forked from PrismarineJS/prismarine-web-client
-
Notifications
You must be signed in to change notification settings - Fork 216
Expand file tree
/
Copy pathmesher.ts
More file actions
215 lines (189 loc) · 6.54 KB
/
Copy pathmesher.ts
File metadata and controls
215 lines (189 loc) · 6.54 KB
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
import { Vec3 } from 'vec3'
import { World } from './world'
import { getSectionGeometry, setBlockStatesData as setMesherData } from './models'
import { BlockStateModelInfo } from './shared'
globalThis.structuredClone ??= (value) => JSON.parse(JSON.stringify(value))
if (module.require) {
// If we are in a node environement, we need to fake some env variables
const r = module.require
const { parentPort } = r('worker_threads')
global.self = parentPort
global.postMessage = (value, transferList) => { parentPort.postMessage(value, transferList) }
global.performance = r('perf_hooks').performance
}
let workerIndex = 0
let world: World
let dirtySections = new Map<string, number>()
let allDataReady = false
function sectionKey (x, y, z) {
return `${x},${y},${z}`
}
const batchMessagesLimit = 100
let queuedMessages = [] as any[]
let queueWaiting = false
const postMessage = (data, transferList = []) => {
queuedMessages.push({ data, transferList })
if (queuedMessages.length > batchMessagesLimit) {
drainQueue(0, batchMessagesLimit)
}
if (queueWaiting) return
queueWaiting = true
setTimeout(() => {
queueWaiting = false
drainQueue(0, queuedMessages.length)
})
}
function drainQueue (from, to) {
const messages = queuedMessages.slice(from, to)
global.postMessage(messages.map(m => m.data), messages.flatMap(m => m.transferList) as unknown as string)
queuedMessages = queuedMessages.slice(to)
}
function setSectionDirty (pos, value = true) {
const x = Math.floor(pos.x / 16) * 16
const y = Math.floor(pos.y / 16) * 16
const z = Math.floor(pos.z / 16) * 16
const key = sectionKey(x, y, z)
if (!value) {
dirtySections.delete(key)
postMessage({ type: 'sectionFinished', key, workerIndex })
return
}
const chunk = world.getColumn(x, z)
if (chunk?.getSection(pos)) {
dirtySections.set(key, (dirtySections.get(key) || 0) + 1)
} else {
postMessage({ type: 'sectionFinished', key, workerIndex })
}
}
const softCleanup = () => {
// clean block cache and loaded chunks
world = new World(world.config.version)
globalThis.world = world
}
const handleMessage = data => {
const globalVar: any = globalThis
if (data.type === 'mcData') {
globalVar.mcData = data.mcData
}
if (data.config) {
if (data.type === 'mesherData' && world) {
// reset models
world.blockCache = {}
world.erroredBlockModel = undefined
}
world ??= new World(data.config.version)
world.config = { ...world.config, ...data.config }
globalThis.world = world
globalThis.Vec3 = Vec3
}
switch (data.type) {
case 'mesherData': {
setMesherData(data.blockstatesModels, data.blocksAtlas, data.config.outputFormat === 'webgpu')
allDataReady = true
workerIndex = data.workerIndex
break
}
case 'dirty': {
const loc = new Vec3(data.x, data.y, data.z)
setSectionDirty(loc, data.value)
break
}
case 'chunk': {
world.addColumn(data.x, data.z, data.chunk)
if (data.lightData) {
world.lightHolder.loadChunk(data.lightData)
}
if (data.customBlockModels) {
const chunkKey = `${data.x},${data.z}`
world.customBlockModels.set(chunkKey, data.customBlockModels)
}
break
}
case 'unloadChunk': {
world.removeColumn(data.x, data.z)
world.customBlockModels.delete(`${data.x},${data.z}`)
if (Object.keys(world.columns).length === 0) softCleanup()
break
}
case 'blockUpdate': {
const loc = new Vec3(data.pos.x, data.pos.y, data.pos.z).floored()
if (data.stateId !== undefined && data.stateId !== null) {
world?.setBlockStateId(loc, data.stateId)
}
const chunkKey = `${Math.floor(loc.x / 16) * 16},${Math.floor(loc.z / 16) * 16}`
if (data.customBlockModels) {
world?.customBlockModels.set(chunkKey, data.customBlockModels)
}
break
}
case 'reset': {
world = undefined as any
// blocksStates = null
dirtySections = new Map()
// todo also remove cached
globalVar.mcData = null
allDataReady = false
break
}
case 'getCustomBlockModel': {
const pos = new Vec3(data.pos.x, data.pos.y, data.pos.z)
const chunkKey = `${Math.floor(pos.x / 16) * 16},${Math.floor(pos.z / 16) * 16}`
const customBlockModel = world.customBlockModels.get(chunkKey)?.[`${pos.x},${pos.y},${pos.z}`]
global.postMessage({ type: 'customBlockModel', chunkKey, customBlockModel })
break
}
// No default
}
}
// eslint-disable-next-line no-restricted-globals -- TODO
self.onmessage = ({ data }) => {
if (Array.isArray(data)) {
// eslint-disable-next-line unicorn/no-array-for-each
data.forEach(handleMessage)
return
}
handleMessage(data)
}
setInterval(() => {
if (world === null || !allDataReady) return
if (dirtySections.size === 0) return
// console.log(sections.length + ' dirty sections')
// const start = performance.now()
for (const key of dirtySections.keys()) {
const [x, y, z] = key.split(',').map(v => parseInt(v, 10))
const chunk = world.getColumn(x, z)
let processTime = 0
if (chunk?.getSection(new Vec3(x, y, z))) {
const start = performance.now()
const geometry = getSectionGeometry(x, y, z, world)
const transferable = [geometry.positions?.buffer, geometry.normals?.buffer, geometry.colors?.buffer, geometry.uvs?.buffer].filter(Boolean)
//@ts-expect-error
postMessage({ type: 'geometry', key, geometry, workerIndex }, transferable)
processTime = performance.now() - start
} else {
// console.info('[mesher] Missing section', x, y, z)
}
const dirtyTimes = dirtySections.get(key)
if (!dirtyTimes) throw new Error('dirtySections.get(key) is falsy')
for (let i = 0; i < dirtyTimes; i++) {
postMessage({ type: 'sectionFinished', key, workerIndex, processTime })
processTime = 0
}
dirtySections.delete(key)
}
// Send new block state model info if any
if (world.blockStateModelInfo.size > 0) {
const newBlockStateInfo: Record<string, BlockStateModelInfo> = {}
for (const [cacheKey, info] of world.blockStateModelInfo) {
if (!world.sentBlockStateModels.has(cacheKey)) {
newBlockStateInfo[cacheKey] = info
world.sentBlockStateModels.add(cacheKey)
}
}
if (Object.keys(newBlockStateInfo).length > 0) {
postMessage({ type: 'blockStateModelInfo', info: newBlockStateInfo })
}
}
// const time = performance.now() - start
// console.log(`Processed ${sections.length} sections in ${time} ms (${time / sections.length} ms/section)`)
}, 50)