-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathworld.js
325 lines (292 loc) · 10.7 KB
/
world.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
const fs = require('fs')
const { Vec3 } = require('vec3')
const generations = require('../generations')
const playerDat = require('../playerDat')
const spiralloop = require('spiralloop')
const { level } = require('prismarine-provider-anvil')
const nbt = require('prismarine-nbt')
function sleep (ms = 0) {
return new Promise(resolve => setTimeout(resolve, ms))
}
module.exports.server = async function (serv, options = {}) {
const { version, worldFolder, generation = { name: 'diamond_square', options: { worldHeight: 80 } } } = options
const { registry } = serv
const World = require('prismarine-world')(registry)
const Anvil = require('prismarine-provider-anvil').Anvil(registry)
const newSeed = generation.options.seed || Math.floor(Math.random() * Math.pow(2, 31))
let seed
let regionFolder
if (worldFolder) {
regionFolder = worldFolder + '/region'
if (!fs.existsSync(regionFolder)) {
fs.mkdirSync(regionFolder, { recursive: true })
}
try {
const levelData = await level.readLevel(worldFolder + '/level.dat')
seed = levelData.RandomSeed[0]
} catch (err) {
serv.debug?.(err)
serv.debug?.('Creating new level.dat')
seed = newSeed
await level.writeLevel(worldFolder + '/level.dat', {
RandomSeed: [seed, 0],
Version: { Name: options.version },
generatorName: { superflat: 'flat', diamond_square: 'default' }[generation.name] || 'customized'
})
}
} else {
seed = newSeed
}
generation.options.seed = seed
generation.options.version = version
serv.emit('seed', generation.options.seed)
const generationModule = generations[generation.name] ? generations[generation.name] : require(generation.name)
const genOpts = { ...generation.options, registry }
serv.overworld = new World(generationModule(genOpts), regionFolder === undefined ? null : new Anvil(regionFolder))
serv.netherworld = new World(generations.nether(genOpts))
// serv.endworld = new World(generations["end"]({}));
serv.dimensionNames = {
'-1': 'minecraft:nether',
0: 'minecraft:overworld'
// 1: 'minecraft:end'
}
// WILL BE REMOVED WHEN ACTUALLY IMPLEMENTED
serv.overworld.blockEntityData = {}
serv.netherworld.blockEntityData = {}
serv.overworld.portals = []
serv.netherworld.portals = []
/// ///////////
serv.pregenWorld = (world, size = 3) => {
const promises = []
for (let x = -size; x < size; x++) {
for (let z = -size; z < size; z++) {
promises.push(world.getColumn(x, z))
}
}
return Promise.all(promises)
}
// serv.pregenWorld(serv.overworld).then(() => serv.info('Pre-Generated Overworld'));
// serv.pregenWorld(serv.netherworld).then(() => serv.info('Pre-Generated Nether'));
serv.setBlock = async (world, position, stateId) => {
serv.players
.filter(p => p.world === world)
.forEach(player => player.sendBlock(position, stateId))
await world.setBlockStateId(position, stateId)
if (stateId === 0) serv.notifyNeighborsOfStateChange(world, position, serv.tickCount, serv.tickCount, true)
else serv.updateBlock(world, position, serv.tickCount, serv.tickCount, true)
}
if (serv.supportFeature('theFlattening')) {
serv.setBlockType = async (world, position, id) => {
serv.setBlock(world, position, serv.registry.blocks[id].minStateId)
}
} else {
serv.setBlockType = async (world, position, id) => {
serv.setBlock(world, position, id << 4)
}
}
serv.setBlockAction = async (world, position, actionId, actionParam) => {
const location = new Vec3(position.x, position.y, position.z)
const blockType = await world.getBlockType(location)
serv.players
.filter(p => p.world === world)
.forEach(player => player.sendBlockAction(position, actionId, actionParam, blockType))
}
serv.reloadChunks = (world, chunks) => {
serv.players
.filter(player => player.world === world)
.forEach(oPlayer => {
chunks
.filter(({ chunkX, chunkZ }) => oPlayer.loadedChunks[chunkX + ',' + chunkZ] !== undefined)
.forEach(({ chunkX, chunkZ }) => oPlayer._unloadChunk(chunkX, chunkZ))
oPlayer.sendRestMap()
})
}
serv._worldChunksUsed = {}
serv._worldLoadPlayerChunk = (chunkX, chunkZ, player) => {
const id = chunkX + ',' + chunkZ
if (!serv._worldChunksUsed[id]) {
serv._worldChunksUsed[id] = 0
}
serv._worldChunksUsed[id]++
const loaded = player.loadedChunks[id]
if (!loaded) player.loadedChunks[id] = 1
return !loaded
}
serv._worldUnloadPlayerChunk = (chunkX, chunkZ, player) => {
const id = chunkX + ',' + chunkZ
delete player.loadedChunks[id]
if (serv._worldChunksUsed[id] > 0) {
serv._worldChunksUsed[id]--
}
if (!serv._worldChunksUsed[id]) {
player.world.unloadColumn(chunkX, chunkZ)
return true
}
return false
}
serv.commands.add({
base: 'changeworld',
info: 'to change world',
usage: '/changeworld overworld|nether',
onlyPlayer: true,
op: true,
action (world, ctx) {
if (world === 'nether') ctx.player.changeWorld(serv.netherworld, { dimension: -1 })
if (world === 'overworld') ctx.player.changeWorld(serv.overworld, { dimension: 0 })
}
})
}
module.exports.player = function (player, serv, settings) {
player.save = async () => {
await playerDat.save(player, settings.worldFolder, serv.supportFeature('attributeSnakeCase'), serv.supportFeature('theFlattening'))
}
player._unloadChunk = (chunkX, chunkZ, isBecausePlayerLeft) => {
serv._worldUnloadPlayerChunk(chunkX, chunkZ, player)
if (isBecausePlayerLeft) return
if (serv.supportFeature('unloadChunkByEmptyChunk')) {
player._client.write('map_chunk', {
x: chunkX,
z: chunkZ,
groundUp: true,
bitMap: 0x0000,
chunkData: Buffer.alloc(0)
})
} else if (serv.supportFeature('unloadChunkDirect')) {
player._client.write('unload_chunk', {
chunkX,
chunkZ
})
}
}
player.sendChunk = (chunkX, chunkZ, column) => {
return player.behavior('sendChunk', {
x: chunkX,
z: chunkZ,
chunk: column
}, ({ x, z, chunk }) => {
// FIXME: fake heightmap
const heightmaps = nbt.comp({
MOTION_BLOCKING: nbt.longArray(new Array(36).fill([0, 0]))
})
const trustEdges = true // trust edges for lighting updates - should be false when a chunk section is updated instead of the whole chunk being overwritten, do we ever do that?
if (serv.supportFeature('tallWorld')) { // 1.18+ - merged chunk and light data
player._client.write('map_chunk', {
x,
z,
heightmaps,
chunkData: chunk.dump(),
blockEntities: [],
trustEdges,
suppressLightUpdates: trustEdges, // 1.19.2
...chunk.dumpLight()
})
} else {
player._client.write('map_chunk', {
x,
z,
groundUp: true,
bitMap: chunk.getMask(),
biomes: chunk.dumpBiomes(),
ignoreOldData: true, // should be false when a chunk section is updated instead of the whole chunk being overwritten, do we ever do that?
heightmaps,
chunkData: chunk.dump(),
blockEntities: []
})
if (serv.supportFeature('newLightingDataFormat')) { // 1.17+
player._client.write('update_light', {
chunkX: x,
chunkZ: z,
trustEdges,
...chunk.dumpLight()
})
} else if (serv.supportFeature('lightSentSeparately')) { // -1.16.5
player._client.write('update_light', {
chunkX: x,
chunkZ: z,
trustEdges,
skyLightMask: chunk.skyLightMask,
blockLightMask: chunk.blockLightMask,
emptySkyLightMask: 0,
emptyBlockLightMask: 0,
data: chunk.dumpLight()
})
}
}
})
}
function spiral (arr) {
const t = []
spiralloop(arr, (x, z) => {
t.push([x, z])
})
return t
}
async function sendNearbyChunks (view, group) {
player.lastPositionChunkUpdated = player.position
const playerChunkX = Math.floor(player.position.x / 16)
const playerChunkZ = Math.floor(player.position.z / 16)
Object.keys(player.loadedChunks)
.map((key) => key.split(',').map(a => parseInt(a)))
.filter(([x, z]) => Math.abs(x - playerChunkX) > view || Math.abs(z - playerChunkZ) > view)
.forEach(([x, z]) => player._unloadChunk(x, z))
return spiral([view * 2, view * 2])
.map(t => ({
chunkX: playerChunkX + t[0] - view,
chunkZ: playerChunkZ + t[1] - view
}))
.filter(({ chunkX, chunkZ }) => serv._worldLoadPlayerChunk(chunkX, chunkZ, player))
.reduce((acc, { chunkX, chunkZ }) => {
const p = acc
.then(() => player.world.getColumn(chunkX, chunkZ))
.then((column) => player.sendChunk(chunkX, chunkZ, column))
return group ? p.then(() => sleep(5)) : p
}, Promise.resolve())
}
player.worldSendInitialChunks = () => {
return sendNearbyChunks(Math.min(3, settings['view-distance']))
}
player.worldSendRestOfChunks = async () => {
player.sendingChunks = true
await sendNearbyChunks(Math.min(player.view, settings['view-distance']), true)
player.sendingChunks = false
}
player.worldSendAllChunks = player.worldSendRestOfChunks
player.sendSpawnPosition = () => {
player._client.write('spawn_position', {
location: player.spawnPoint
})
}
player.on('playerChangeRenderDistance', (newDistance = player.view, unloadFirst = false) => {
player.view = newDistance
if (unloadFirst) player._unloadAllChunks()
player.worldSendRestOfChunks()
})
player._unloadAllChunks = (isBecausePlayerLeft) => {
if (!player?.loadedChunks) return
Object.keys(player.loadedChunks)
.map((key) => key.split(',').map(a => parseInt(a)))
.forEach(([x, z]) => player._unloadChunk(x, z, isBecausePlayerLeft))
}
player.changeWorld = async (world, opt) => {
if (player.world === world) return Promise.resolve()
opt = opt || {}
player.world = world
player._unloadAllChunks()
if (typeof opt.gamemode !== 'undefined') {
if (opt.gamemode !== player.gameMode) player.prevGameMode = player.gameMode
player.gameMode = opt.gamemode
}
player._sendRespawn(opt.difficulty, opt.gamemode, opt.dimension)
await player.findSpawnPoint()
player.position = player.spawnPoint
player.sendSpawnPosition()
player.updateAndSpawn()
await player.worldSendInitialChunks()
player.sendSelfPosition()
player.emit('change_world')
await player.waitPlayerLogin()
player.worldSendRestOfChunks()
// Prevent player from falling through the world
player.sendSelfPosition(player.spawnPoint)
}
}