119 lines
6.8 KiB
JavaScript
119 lines
6.8 KiB
JavaScript
const assert = require('node:assert/strict')
|
|
const fs = require('node:fs/promises')
|
|
const http = require('node:http')
|
|
const path = require('node:path')
|
|
const { chromium } = require('playwright')
|
|
|
|
async function main() {
|
|
const project = path.resolve(__dirname, '../..')
|
|
const dist = path.join(project, 'dist')
|
|
const workerFiles = []
|
|
for (const file of await fs.readdir(path.join(dist, 'js'))) {
|
|
if (!file.endsWith('.js.map')) continue
|
|
const map = JSON.parse(await fs.readFile(path.join(dist, 'js', file), 'utf8'))
|
|
if (map.sources.some((source) => /\/mesh-geometry\.worker\.ts(?:\?|$)/.test(source))) workerFiles.push(file.slice(0, -4))
|
|
}
|
|
assert.equal(workerFiles.length, 1, 'Run the production build first; expected exactly one compiled mesh worker')
|
|
const modules = {
|
|
'/three.module.js': path.join(project, 'node_modules/three/build/three.module.js'),
|
|
'/three.core.js': path.join(project, 'node_modules/three/build/three.core.js'),
|
|
'/bvh.js': path.join(project, 'node_modules/three-mesh-bvh/build/index.module.js'),
|
|
}
|
|
const server = http.createServer(async (request, response) => {
|
|
const pathname = new URL(request.url, 'http://localhost').pathname
|
|
if (pathname === '/') {
|
|
response.setHeader('Content-Type', 'text/html')
|
|
response.end('<!doctype html><title>Compiled mesh worker check</title><script type="importmap">{"imports":{"three":"/three.module.js","three-mesh-bvh":"/bvh.js"}}</script>')
|
|
return
|
|
}
|
|
const target = modules[pathname] || path.resolve(dist, `.${pathname}`)
|
|
if (!modules[pathname] && !target.startsWith(`${dist}${path.sep}`)) { response.writeHead(403).end(); return }
|
|
try {
|
|
response.setHeader('Content-Type', 'text/javascript')
|
|
response.end(await fs.readFile(target))
|
|
} catch { response.writeHead(404).end() }
|
|
})
|
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
|
let browser
|
|
try {
|
|
browser = await chromium.launch({ headless: true })
|
|
const page = await browser.newPage()
|
|
const errors = []
|
|
page.on('pageerror', (error) => errors.push(error.message))
|
|
await page.goto(`http://127.0.0.1:${server.address().port}/`)
|
|
const result = await page.evaluate(async (workerFile) => {
|
|
const THREE = await import('/three.module.js')
|
|
const { MeshBVH, acceleratedRaycast } = await import('/bvh.js')
|
|
// Webpack emits this worker as classic code with importScripts for its shared chunks.
|
|
const worker = new Worker(`/js/${workerFile}`)
|
|
const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1])
|
|
const expectedNormals = new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0])
|
|
const attribute = (array, itemSize) => ({ array, itemSize, normalized: false, name: '', usage: THREE.StaticDrawUsage, gpuType: THREE.FloatType })
|
|
const process = (id, recomputeNormals, normal) => {
|
|
const payload = {
|
|
attributes: { position: attribute(positions.slice(), 3) }, index: null,
|
|
groups: [{ start: 0, count: 3, materialIndex: 0 }, { start: 3, count: 3, materialIndex: 1 }],
|
|
drawRange: { start: 0, count: Infinity },
|
|
}
|
|
if (normal) payload.attributes.normal = attribute(normal.slice(), 3)
|
|
const transfer = Object.values(payload.attributes).map((entry) => entry.array.buffer)
|
|
return new Promise((resolve, reject) => {
|
|
const timer = setTimeout(() => reject(new Error('Compiled worker timed out')), 15000)
|
|
worker.onerror = (event) => { clearTimeout(timer); reject(new Error(event.message)) }
|
|
worker.onmessage = ({ data }) => {
|
|
if (data.id !== id) return
|
|
clearTimeout(timer)
|
|
if (data.error) reject(new Error(data.error))
|
|
else resolve({ geometry: data.geometry, inputDetached: payload.attributes.position.array.byteLength === 0 })
|
|
}
|
|
worker.postMessage({ id, geometry: payload, recomputeNormals }, transfer)
|
|
})
|
|
}
|
|
try {
|
|
const first = await process(1, true)
|
|
const authored = expectedNormals.map((value) => -value)
|
|
const second = await process(2, false, authored)
|
|
const geometry = new THREE.BufferGeometry()
|
|
for (const [name, entry] of Object.entries(first.geometry.attributes)) geometry.setAttribute(name, new THREE.BufferAttribute(entry.array, entry.itemSize, entry.normalized))
|
|
if (first.geometry.index) geometry.setIndex(new THREE.BufferAttribute(first.geometry.index.array, 1))
|
|
geometry.groups = first.geometry.groups
|
|
geometry.boundsTree = MeshBVH.deserialize(first.geometry.bvh, geometry, { setIndex: false })
|
|
const reference = new THREE.BufferGeometry()
|
|
reference.setAttribute('position', new THREE.BufferAttribute(positions, 3))
|
|
reference.setAttribute('normal', new THREE.BufferAttribute(expectedNormals, 3))
|
|
reference.groups = first.geometry.groups
|
|
reference.boundsTree = new MeshBVH(reference, { indirect: true })
|
|
const cast = (target) => {
|
|
const hits = []
|
|
const mesh = new THREE.Mesh(target, [new THREE.MeshBasicMaterial({ side: THREE.DoubleSide }), new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })])
|
|
acceleratedRaycast.call(mesh, new THREE.Raycaster(new THREE.Vector3(0.2, 0.2, 2), new THREE.Vector3(0, 0, -1)), hits)
|
|
return hits.map((hit) => ({ distance: hit.distance, point: hit.point.toArray(), faceIndex: hit.faceIndex }))
|
|
}
|
|
return {
|
|
workerFile, inputDetached: first.inputDetached && second.inputDetached,
|
|
normals: [...first.geometry.attributes.normal.array], expectedNormals: [...expectedNormals],
|
|
authoredNormals: [...second.geometry.attributes.normal.array], expectedAuthoredNormals: [...authored],
|
|
bounds: first.geometry.bounds, bvhRootCount: first.geometry.bvh.roots.length,
|
|
workerHits: cast(geometry), mainThreadHits: cast(reference),
|
|
}
|
|
} finally { worker.terminate() }
|
|
}, workerFiles[0])
|
|
assert.equal(result.inputDetached, true)
|
|
assert.deepEqual(result.normals, result.expectedNormals)
|
|
assert.deepEqual(result.authoredNormals, result.expectedAuthoredNormals)
|
|
assert.deepEqual(result.bounds.min, [0, 0, 0])
|
|
assert.deepEqual(result.bounds.max, [1, 1, 1])
|
|
assert(Math.abs(result.bounds.radius - Math.sqrt(3) / 2) < 1e-7)
|
|
assert(result.bvhRootCount > 0)
|
|
assert(result.workerHits.length > 0)
|
|
assert.deepEqual(result.workerHits, result.mainThreadHits)
|
|
assert.deepEqual(errors, [])
|
|
console.log(JSON.stringify({ worker: result.workerFile, transferred: true, normals: 'reconstructed and authored preserved', bounds: 'matched', bvh: 'main-thread raycast parity', pageErrors: errors }))
|
|
} finally {
|
|
if (browser) await browser.close()
|
|
await new Promise((resolve) => server.close(resolve))
|
|
}
|
|
}
|
|
|
|
main().catch((error) => { console.error(error); process.exitCode = 1 })
|