oda-engine 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -2
- package/bin/nowhere.mjs +352 -0
- package/lib/account.mjs +57 -0
- package/lib/agentModules.mjs +57 -0
- package/lib/devServer.mjs +351 -0
- package/lib/headless.mjs +231 -0
- package/lib/headlessPreview.mjs +212 -0
- package/lib/keys.mjs +517 -0
- package/lib/make.mjs +855 -0
- package/lib/mcp.mjs +537 -0
- package/lib/open.mjs +22 -0
- package/lib/preview.mjs +87 -0
- package/lib/previewRpc.mjs +134 -0
- package/lib/project.mjs +359 -0
- package/lib/publishFlow.mjs +90 -0
- package/lib/resources.mjs +50 -0
- package/lib/rules.mjs +60 -0
- package/lib/scaffold.mjs +42 -0
- package/lib/setup.mjs +59 -0
- package/lib/tools.mjs +668 -0
- package/package.json +51 -4
- package/template/game.config.json +9 -0
- package/template/scene.json +4 -0
- package/template/src/main.ts +11 -0
- package/vendor/DOCS.md +447 -0
- package/vendor/agent/appRun.mjs +520 -0
- package/vendor/agent/assets/brief.mjs +242 -0
- package/vendor/agent/assets/collider.mjs +531 -0
- package/vendor/agent/assets/environments/index.mjs +12 -0
- package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
- package/vendor/agent/assets/fetch.mjs +168 -0
- package/vendor/agent/assets/footprint.mjs +13 -0
- package/vendor/agent/assets/gltf.mjs +547 -0
- package/vendor/agent/assets/hdr.mjs +269 -0
- package/vendor/agent/assets/imageOps.mjs +171 -0
- package/vendor/agent/assets/images/codex.mjs +307 -0
- package/vendor/agent/assets/images/fal.mjs +75 -0
- package/vendor/agent/assets/images/gemini.mjs +84 -0
- package/vendor/agent/assets/images/index.mjs +25 -0
- package/vendor/agent/assets/images/openai.mjs +75 -0
- package/vendor/agent/assets/images/stability.mjs +71 -0
- package/vendor/agent/assets/images/views.mjs +31 -0
- package/vendor/agent/assets/import.mjs +1352 -0
- package/vendor/agent/assets/inspect.mjs +465 -0
- package/vendor/agent/assets/jobs.mjs +196 -0
- package/vendor/agent/assets/ktx2.mjs +290 -0
- package/vendor/agent/assets/ledger.mjs +466 -0
- package/vendor/agent/assets/net.mjs +254 -0
- package/vendor/agent/assets/prices.json +39 -0
- package/vendor/agent/assets/providers/fal.mjs +115 -0
- package/vendor/agent/assets/providers/index.mjs +22 -0
- package/vendor/agent/assets/providers/meshy.mjs +119 -0
- package/vendor/agent/assets/providers/tripo.mjs +188 -0
- package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
- package/vendor/agent/assets/sources/index.mjs +23 -0
- package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
- package/vendor/agent/assets/sources/polypizza.mjs +121 -0
- package/vendor/agent/assets/splat.mjs +631 -0
- package/vendor/agent/assets/targets.mjs +122 -0
- package/vendor/agent/assets/tile.mjs +261 -0
- package/vendor/agent/assets/unzip.mjs +180 -0
- package/vendor/agent/blender/cleanup.py +360 -0
- package/vendor/agent/blender/convert.py +167 -0
- package/vendor/agent/blender/find.mjs +192 -0
- package/vendor/agent/blender/nw_export.py +104 -0
- package/vendor/agent/blender/nw_rubric.py +426 -0
- package/vendor/agent/blender/run.mjs +193 -0
- package/vendor/agent/blender/runner.py +252 -0
- package/vendor/agent/blender/sheet.py +743 -0
- package/vendor/agent/depth.mjs +134 -0
- package/vendor/agent/director/board.mjs +451 -0
- package/vendor/agent/director/contracts.mjs +663 -0
- package/vendor/agent/director/director.mjs +2365 -0
- package/vendor/agent/director/estimate.mjs +200 -0
- package/vendor/agent/director/gate.mjs +802 -0
- package/vendor/agent/director/limits.json +16 -0
- package/vendor/agent/director/methods.mjs +457 -0
- package/vendor/agent/director/policy.json +33 -0
- package/vendor/agent/director/prompts.mjs +244 -0
- package/vendor/agent/director/reading.mjs +341 -0
- package/vendor/agent/director/router.mjs +184 -0
- package/vendor/agent/director/seams.mjs +243 -0
- package/vendor/agent/director/session.mjs +643 -0
- package/vendor/agent/director/store.mjs +119 -0
- package/vendor/agent/director/taskGate.mjs +110 -0
- package/vendor/agent/director/teamLedger.mjs +118 -0
- package/vendor/agent/director/triage.mjs +63 -0
- package/vendor/agent/downloads.cjs +363 -0
- package/vendor/agent/flow.mjs +78 -0
- package/vendor/agent/guard.mjs +613 -0
- package/vendor/agent/host.mjs +1736 -0
- package/vendor/agent/language.mjs +58 -0
- package/vendor/agent/ledger.mjs +360 -0
- package/vendor/agent/locale.cjs +186 -0
- package/vendor/agent/loop/capacity.mjs +74 -0
- package/vendor/agent/loop/compose.mjs +127 -0
- package/vendor/agent/loop/gate.mjs +205 -0
- package/vendor/agent/loop/judge.mjs +189 -0
- package/vendor/agent/loop/levels.mjs +273 -0
- package/vendor/agent/loop/state.mjs +358 -0
- package/vendor/agent/notes.cjs +278 -0
- package/vendor/agent/pace.mjs +258 -0
- package/vendor/agent/panels.mjs +431 -0
- package/vendor/agent/prompt.mjs +342 -0
- package/vendor/agent/reference/board.mjs +410 -0
- package/vendor/agent/reference/compose.mjs +364 -0
- package/vendor/agent/reference/decode.mjs +56 -0
- package/vendor/agent/reference/facts.mjs +1874 -0
- package/vendor/agent/reference/png.mjs +107 -0
- package/vendor/agent/reference/records.mjs +63 -0
- package/vendor/agent/reference/web.mjs +252 -0
- package/vendor/agent/roles/artist.mjs +69 -0
- package/vendor/agent/roles/builder.mjs +79 -0
- package/vendor/agent/roles/checks.mjs +223 -0
- package/vendor/agent/roles/common.mjs +188 -0
- package/vendor/agent/roles/critic.mjs +171 -0
- package/vendor/agent/roles/index.mjs +39 -0
- package/vendor/agent/roles/modeller.mjs +142 -0
- package/vendor/agent/roles/qa.mjs +58 -0
- package/vendor/agent/roles/rubrics.mjs +79 -0
- package/vendor/agent/roles/sound.mjs +69 -0
- package/vendor/agent/rounds.cjs +333 -0
- package/vendor/agent/shared.mjs +284 -0
- package/vendor/agent/stopGate.mjs +574 -0
- package/vendor/agent/subagents.mjs +129 -0
- package/vendor/agent/tools/assets.mjs +499 -0
- package/vendor/agent/tools/blender.mjs +754 -0
- package/vendor/agent/tools/cards.mjs +479 -0
- package/vendor/agent/tools/choices.mjs +479 -0
- package/vendor/agent/tools/compose.mjs +74 -0
- package/vendor/agent/tools/environment.mjs +488 -0
- package/vendor/agent/tools/eyes.mjs +733 -0
- package/vendor/agent/tools/generate.mjs +338 -0
- package/vendor/agent/tools/guide.mjs +46 -0
- package/vendor/agent/tools/harness.mjs +193 -0
- package/vendor/agent/tools/image.mjs +643 -0
- package/vendor/agent/tools/index.mjs +162 -0
- package/vendor/agent/tools/look.mjs +578 -0
- package/vendor/agent/tools/loop.mjs +858 -0
- package/vendor/agent/tools/others.mjs +123 -0
- package/vendor/agent/tools/pictures.mjs +535 -0
- package/vendor/agent/tools/reference.mjs +366 -0
- package/vendor/agent/transcripts.mjs +118 -0
- package/vendor/agent-loop.mjs +602 -0
- package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
- package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
- package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
- package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
- package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
- package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
- package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
- package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
- package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
- package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
- package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
- package/vendor/auth.cjs +570 -0
- package/vendor/build.cjs +953 -0
- package/vendor/catalog.json +455 -0
- package/vendor/connectors.cjs +688 -0
- package/vendor/eyes.mjs +733 -0
- package/vendor/gameExports.json +1390 -0
- package/vendor/git.cjs +222 -0
- package/vendor/models.json +57 -0
- package/vendor/publish.cjs +1018 -0
- package/vendor/refBoard.cjs +301 -0
- package/vendor/schema/dist/assets.d.ts +335 -0
- package/vendor/schema/dist/assets.js +439 -0
- package/vendor/schema/dist/brief.d.ts +357 -0
- package/vendor/schema/dist/brief.js +302 -0
- package/vendor/schema/dist/common.d.ts +9 -0
- package/vendor/schema/dist/common.js +13 -0
- package/vendor/schema/dist/config.d.ts +406 -0
- package/vendor/schema/dist/config.js +355 -0
- package/vendor/schema/dist/contract.d.ts +599 -0
- package/vendor/schema/dist/contract.js +1146 -0
- package/vendor/schema/dist/index.d.ts +14 -0
- package/vendor/schema/dist/index.js +21 -0
- package/vendor/schema/dist/look.d.ts +463 -0
- package/vendor/schema/dist/look.js +681 -0
- package/vendor/schema/dist/lookStats.d.ts +230 -0
- package/vendor/schema/dist/lookStats.js +768 -0
- package/vendor/schema/dist/pilot.d.ts +32 -0
- package/vendor/schema/dist/pilot.js +44 -0
- package/vendor/schema/dist/publish.d.ts +214 -0
- package/vendor/schema/dist/publish.js +291 -0
- package/vendor/schema/dist/scene.d.ts +75 -0
- package/vendor/schema/dist/scene.js +120 -0
- package/vendor/schema/dist/skyLight.d.ts +141 -0
- package/vendor/schema/dist/skyLight.js +436 -0
- package/vendor/schema/dist/style.d.ts +131 -0
- package/vendor/schema/dist/style.js +155 -0
- package/vendor/schema/package.json +1 -0
- package/vendor/selectionPrompt.mjs +51 -0
- package/vendor/useTools.mjs +195 -0
- package/vendor/userMessage.mjs +26 -0
- package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
- package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
- package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
- package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
- package/web-dist/assets/index-CcjyyQco.css +1 -0
- package/web-dist/assets/index-DMyJcoZJ.js +693 -0
- package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
- package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
- package/web-dist/index.html +34 -0
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
// asset_import's model pipeline: whatever came in, one self-contained GLB the
|
|
2
|
+
// planet can carry, at a real size, standing on its own pivot, inside its
|
|
3
|
+
// class's budget, checked by the Khronos glTF validator.
|
|
4
|
+
//
|
|
5
|
+
// 1. convert glb and gltf read here (every KHR_ and EXT_ extension);
|
|
6
|
+
// fbx, obj, stl, ply, usd, dae through Blender (convert.py)
|
|
7
|
+
// 2. validate gltf-validator on what came in; errors refuse
|
|
8
|
+
// 3. optimise dedup, weld, simplify only over the budget, join, resample,
|
|
9
|
+
// prune, textures to the class's size, quantize all but the
|
|
10
|
+
// positions (they stay metres from the pivot); meshopt and
|
|
11
|
+
// KTX2 where the sides the planet goes to decode them
|
|
12
|
+
// (asset_import's decoders), refused or written plain where
|
|
13
|
+
// they do not
|
|
14
|
+
// 4. size scale to the asked size, or keep plausible metres; pivot at
|
|
15
|
+
// the base (or the centre); both baked into the vertices
|
|
16
|
+
// 5. write one GLB, buffers joined, textures embedded; validated again
|
|
17
|
+
//
|
|
18
|
+
// gltf-transform does the work; this file decides what to ask of it and says
|
|
19
|
+
// what each step did, in numbers, for the agent's answer.
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs'
|
|
22
|
+
import fsp from 'node:fs/promises'
|
|
23
|
+
import path from 'node:path'
|
|
24
|
+
import { Logger, NodeIO, getBounds } from '@gltf-transform/core'
|
|
25
|
+
import { ALL_EXTENSIONS, EXTMeshoptCompression, KHRMeshQuantization, KHRTextureBasisu } from '@gltf-transform/extensions'
|
|
26
|
+
import { center, clearNodeTransform, cloneDocument, dedup, flatten, join, prune, quantize, reorder, resample, simplify, unpartition, weld } from '@gltf-transform/functions'
|
|
27
|
+
import { MeshoptDecoder, MeshoptEncoder, MeshoptSimplifier } from 'meshoptimizer'
|
|
28
|
+
import validator from 'gltf-validator'
|
|
29
|
+
import { DECODERS_LIVE, TEXTURE_BUDGETS, TRIANGLE_BUDGETS } from '../../schema/dist/index.js'
|
|
30
|
+
import { encodePng } from '../reference/png.mjs'
|
|
31
|
+
import { imageSize } from './imageOps.mjs'
|
|
32
|
+
import { decodeKtx2, ktx2Header } from './ktx2.mjs'
|
|
33
|
+
|
|
34
|
+
const MB = 1024 * 1024
|
|
35
|
+
|
|
36
|
+
let ioPromise = null
|
|
37
|
+
/** The role each texture of a model plays, for its codec and its GPU
|
|
38
|
+
* estimate: a normal map, a colour (base colour, emissive), an occlusion
|
|
39
|
+
* map alone, or the rough and metal one (which may carry occlusion too). */
|
|
40
|
+
export function textureRoles(doc) {
|
|
41
|
+
const mats = doc.getRoot().listMaterials()
|
|
42
|
+
const normals = new Set(mats.map((m) => m.getNormalTexture()).filter(Boolean))
|
|
43
|
+
const colours = new Set(mats.flatMap((m) => [m.getBaseColorTexture(), m.getEmissiveTexture()]).filter(Boolean))
|
|
44
|
+
const metalRough = new Set(mats.map((m) => m.getMetallicRoughnessTexture()).filter(Boolean))
|
|
45
|
+
const occlusion = new Set(mats.map((m) => m.getOcclusionTexture()).filter(Boolean))
|
|
46
|
+
return (t) => (normals.has(t) ? 'normal' : colours.has(t) ? 'color' : occlusion.has(t) && !metalRough.has(t) ? 'ao' : 'rough')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Binds a packed _arm map's red channel as occlusion where only its rough
|
|
50
|
+
* and metal are bound: Poly Haven packs ao, rough and metal into one map
|
|
51
|
+
* and its glTFs bind it as metallicRoughness alone, so the ao is lost to
|
|
52
|
+
* the planet and to the baked-shadow check. Only for a source known to
|
|
53
|
+
* pack it so; answers how many materials gained it. */
|
|
54
|
+
export function bindArmOcclusion(doc) {
|
|
55
|
+
let n = 0
|
|
56
|
+
const arm = /_arm(_\d+k)?(\.\w+)?$/i
|
|
57
|
+
for (const m of doc.getRoot().listMaterials()) {
|
|
58
|
+
const t = m.getMetallicRoughnessTexture()
|
|
59
|
+
if (!t || m.getOcclusionTexture() || !(arm.test(t.getName() || '') || arm.test(t.getURI() || ''))) continue
|
|
60
|
+
m.setOcclusionTexture(t)
|
|
61
|
+
const from = m.getMetallicRoughnessTextureInfo()
|
|
62
|
+
const to = m.getOcclusionTextureInfo()
|
|
63
|
+
if (from && to) to.setTexCoord(from.getTexCoord()).setWrapS(from.getWrapS()).setWrapT(from.getWrapT()).setMagFilter(from.getMagFilter()).setMinFilter(from.getMinFilter())
|
|
64
|
+
n++
|
|
65
|
+
}
|
|
66
|
+
return n
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** One NodeIO for the process, with every extension and the meshopt codec. */
|
|
70
|
+
export function gltfIO() {
|
|
71
|
+
ioPromise ??= (async () => {
|
|
72
|
+
await Promise.all([MeshoptDecoder.ready, MeshoptEncoder.ready, MeshoptSimplifier.ready])
|
|
73
|
+
// Warnings only: the answer reports what each step did, and gltf-transform's
|
|
74
|
+
// own info lines (what prune removed) would only be noise in the host's log.
|
|
75
|
+
return new NodeIO()
|
|
76
|
+
.setLogger(QUIET)
|
|
77
|
+
.registerExtensions(ALL_EXTENSIONS)
|
|
78
|
+
.registerDependencies({ 'meshopt.decoder': MeshoptDecoder, 'meshopt.encoder': MeshoptEncoder })
|
|
79
|
+
})()
|
|
80
|
+
return ioPromise
|
|
81
|
+
}
|
|
82
|
+
const QUIET = new Logger(Logger.Verbosity.WARN)
|
|
83
|
+
|
|
84
|
+
// ---------------------------------------------------------------- reading
|
|
85
|
+
|
|
86
|
+
/** The URIs a .gltf names, refused if any could leave its folder. A .gltf
|
|
87
|
+
* that points outside quarantine must not make the reader open that file. */
|
|
88
|
+
export function gltfUris(json) {
|
|
89
|
+
const uris = [...(json?.buffers ?? []), ...(json?.images ?? [])].map((x) => x?.uri).filter((u) => typeof u === 'string')
|
|
90
|
+
for (const uri of uris) {
|
|
91
|
+
if (uri.startsWith('data:')) continue
|
|
92
|
+
let decoded
|
|
93
|
+
try {
|
|
94
|
+
decoded = decodeURIComponent(uri)
|
|
95
|
+
} catch {
|
|
96
|
+
return { error: `it names a file it cannot spell (${uri.slice(0, 80)})` }
|
|
97
|
+
}
|
|
98
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(decoded) || decoded.startsWith('/') || decoded.startsWith('\\') || /^[A-Za-z]:/.test(decoded) || decoded.split(/[\\/]/).includes('..')) {
|
|
99
|
+
return { error: `it points outside its own folder (${uri.slice(0, 80)})` }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return { uris: uris.filter((u) => !u.startsWith('data:')) }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The extensions a glTF needs, from its JSON (a .glb's first chunk). */
|
|
106
|
+
async function requiredExtensions(abs) {
|
|
107
|
+
const buf = await fsp.readFile(abs)
|
|
108
|
+
let json
|
|
109
|
+
if (buf.length >= 20 && buf.readUInt32LE(0) === 0x46546c67) json = buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8')
|
|
110
|
+
else json = buf.toString('utf8')
|
|
111
|
+
try {
|
|
112
|
+
const doc = JSON.parse(json)
|
|
113
|
+
return [...new Set([...(doc.extensionsRequired ?? []), ...(doc.extensionsUsed ?? [])])]
|
|
114
|
+
} catch {
|
|
115
|
+
return []
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Reads a .glb or a .gltf (with its files beside it) into a Document. */
|
|
120
|
+
export async function readGltf(abs) {
|
|
121
|
+
const io = await gltfIO()
|
|
122
|
+
// Draco needs a third decoder nothing here ships (decision D3 took
|
|
123
|
+
// meshopt instead); Blender reads it, so the way out is named.
|
|
124
|
+
if ((await requiredExtensions(abs)).includes('KHR_draco_mesh_compression')) {
|
|
125
|
+
throw new Error('it is Draco-compressed, which the import does not decode; pick another download (glTF, FBX), or open it in Blender and export it again with nw_blender')
|
|
126
|
+
}
|
|
127
|
+
if (/\.gltf$/i.test(abs)) {
|
|
128
|
+
let json
|
|
129
|
+
try {
|
|
130
|
+
json = JSON.parse(await fsp.readFile(abs, 'utf8'))
|
|
131
|
+
} catch (err) {
|
|
132
|
+
throw new Error(`the .gltf is not valid JSON (${err.message})`)
|
|
133
|
+
}
|
|
134
|
+
const uris = gltfUris(json)
|
|
135
|
+
if (uris.error) throw new Error(uris.error)
|
|
136
|
+
for (const uri of uris.uris) {
|
|
137
|
+
if (!fs.existsSync(path.join(path.dirname(abs), decodeURIComponent(uri)))) throw new Error(`it needs ${decodeURIComponent(uri)} beside it, which is not there`)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const doc = await io.read(abs)
|
|
141
|
+
doc.setLogger(QUIET)
|
|
142
|
+
return doc
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The Khronos validator's report on a file as it came in. */
|
|
146
|
+
export async function validateFile(abs) {
|
|
147
|
+
const bytes = new Uint8Array(await fsp.readFile(abs))
|
|
148
|
+
const dir = path.dirname(abs)
|
|
149
|
+
const report = await validator.validateBytes(bytes, {
|
|
150
|
+
uri: path.basename(abs),
|
|
151
|
+
format: /\.glb$/i.test(abs) ? 'glb' : 'gltf',
|
|
152
|
+
maxIssues: 200,
|
|
153
|
+
externalResourceFunction: async (uri) => {
|
|
154
|
+
const plain = decodeURIComponent(uri)
|
|
155
|
+
if (plain.split(/[\\/]/).includes('..') || path.isAbsolute(plain)) throw new Error('outside its folder')
|
|
156
|
+
return new Uint8Array(await fsp.readFile(path.join(dir, plain)))
|
|
157
|
+
},
|
|
158
|
+
})
|
|
159
|
+
return summarise(report)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The validator's report on bytes (the GLB this pipeline wrote). */
|
|
163
|
+
export async function validateGlb(bytes) {
|
|
164
|
+
return summarise(await validator.validateBytes(new Uint8Array(bytes), { format: 'glb', maxIssues: 200 }))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function summarise(report) {
|
|
168
|
+
const messages = report?.issues?.messages ?? []
|
|
169
|
+
const pick = (severity) => messages.filter((m) => m.severity === severity).map((m) => `${m.code}: ${m.message}${m.pointer ? ` (${m.pointer})` : ''}`)
|
|
170
|
+
return { errors: pick(0), warnings: pick(1), numErrors: report?.issues?.numErrors ?? 0, numWarnings: report?.issues?.numWarnings ?? 0 }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---------------------------------------------------------------- measuring
|
|
174
|
+
|
|
175
|
+
/** Triangles a primitive draws. */
|
|
176
|
+
function primitiveTriangles(prim) {
|
|
177
|
+
const count = prim.getIndices()?.getCount() ?? prim.getAttribute('POSITION')?.getCount() ?? 0
|
|
178
|
+
const mode = prim.getMode()
|
|
179
|
+
if (mode === 4) return Math.floor(count / 3)
|
|
180
|
+
if (mode === 5 || mode === 6) return Math.max(0, count - 2)
|
|
181
|
+
return 0
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Triangles drawn by the default scene, counting every instance of a mesh. */
|
|
185
|
+
export function countTriangles(doc) {
|
|
186
|
+
const root = doc.getRoot()
|
|
187
|
+
const scene = root.getDefaultScene() ?? root.listScenes()[0]
|
|
188
|
+
if (!scene) return 0
|
|
189
|
+
let n = 0
|
|
190
|
+
scene.traverse((node) => {
|
|
191
|
+
const mesh = node.getMesh()
|
|
192
|
+
if (mesh) for (const prim of mesh.listPrimitives()) n += primitiveTriangles(prim)
|
|
193
|
+
})
|
|
194
|
+
return n
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function boundsOf(doc) {
|
|
198
|
+
const root = doc.getRoot()
|
|
199
|
+
const scene = root.getDefaultScene() ?? root.listScenes()[0]
|
|
200
|
+
if (!scene) return null
|
|
201
|
+
const { min, max } = getBounds(scene)
|
|
202
|
+
if (!min.every(Number.isFinite) || !max.every(Number.isFinite)) return null
|
|
203
|
+
return { min, max, size: [max[0] - min[0], max[1] - min[1], max[2] - min[2]] }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const round = (v, d = 3) => Math.round(v * 10 ** d) / 10 ** d
|
|
207
|
+
|
|
208
|
+
/** Width (x), height (y) and depth (z) in metres, for the answer. */
|
|
209
|
+
export const sizeText = (s) => `${round(s[0], 2)} x ${round(s[1], 2)} x ${round(s[2], 2)} m (width x height x depth)`
|
|
210
|
+
|
|
211
|
+
/** quantize() decides whether KHR_mesh_quantization is needed by testing
|
|
212
|
+
* every attribute against POSITION's type (gltf-transform 4), so with the
|
|
213
|
+
* positions kept as floats it leaves quantized normals and UVs undeclared,
|
|
214
|
+
* which the validator refuses. Declared here from the attributes themselves. */
|
|
215
|
+
function declareQuantization(doc) {
|
|
216
|
+
const quantized = (semantic, a) => {
|
|
217
|
+
if (a.getComponentSize() >= 4) return false
|
|
218
|
+
if (semantic === 'POSITION' || semantic === 'NORMAL' || semantic === 'TANGENT') return true
|
|
219
|
+
// Normalized unsigned UVs are core glTF; anything else smaller is not.
|
|
220
|
+
return semantic.startsWith('TEXCOORD_') && !(a.getNormalized() && (a.getComponentType() === 5121 || a.getComponentType() === 5123))
|
|
221
|
+
}
|
|
222
|
+
for (const mesh of doc.getRoot().listMeshes()) {
|
|
223
|
+
for (const prim of mesh.listPrimitives()) {
|
|
224
|
+
for (const p of [prim, ...prim.listTargets()]) {
|
|
225
|
+
if (p.listSemantics().some((s) => quantized(s, p.getAttribute(s)))) {
|
|
226
|
+
doc.createExtension(KHRMeshQuantization).setRequired(true)
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Moves every mesh drawn once into the model's own frame: the size
|
|
235
|
+
* wrapper, the pivot and a source's own node scales and rotations (a
|
|
236
|
+
* Sketchfab root, a quantized download) baked into its vertices, so a
|
|
237
|
+
* shader's positionLocal is metres from the base, as a game's own shaders
|
|
238
|
+
* expect. A mesh drawn by several nodes keeps them, and a skinned or
|
|
239
|
+
* animated model is left as it is. Answers how many moved. */
|
|
240
|
+
async function bakeFrames(doc) {
|
|
241
|
+
const root = doc.getRoot()
|
|
242
|
+
if (root.listSkins().length || root.listAnimations().length) return 0
|
|
243
|
+
await doc.transform(flatten())
|
|
244
|
+
const identity = (m) => m.every((v, i) => Math.abs(v - (i % 5 === 0 ? 1 : 0)) < 1e-9)
|
|
245
|
+
let n = 0
|
|
246
|
+
for (const node of root.listNodes()) {
|
|
247
|
+
const mesh = node.getMesh()
|
|
248
|
+
if (!mesh || node.getParentNode() || identity(node.getMatrix())) continue
|
|
249
|
+
if (mesh.listParents().filter((p) => p.propertyType === 'Node').length !== 1) continue
|
|
250
|
+
clearNodeTransform(node)
|
|
251
|
+
n++
|
|
252
|
+
}
|
|
253
|
+
return n
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// ---------------------------------------------------------------- the pipeline
|
|
257
|
+
|
|
258
|
+
/** The classes whose budget simplify may reach past its 0.1% bound for,
|
|
259
|
+
* and the bound then (a share of the model's size). */
|
|
260
|
+
const LOOSE_SIMPLIFY_CLASSES = new Set(['small', 'prop'])
|
|
261
|
+
const LOOSE_SIMPLIFY_ERROR = 0.01
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Turns a Document into the GLB a planet carries.
|
|
265
|
+
*
|
|
266
|
+
* @param {object} opts
|
|
267
|
+
* @param {import('@gltf-transform/core').Document} opts.doc
|
|
268
|
+
* @param {string} opts.className ASSET_CLASSES
|
|
269
|
+
* @param {{ height?: number, width?: number, depth?: number, longest?: number }} [opts.size]
|
|
270
|
+
* @param {'base' | 'center' | 'keep'} [opts.pivot]
|
|
271
|
+
* @param {number} [opts.maxTexture]
|
|
272
|
+
* @param {boolean} [opts.simplify]
|
|
273
|
+
* @param {boolean} [opts.statedMetres] the source says its models are in metres
|
|
274
|
+
* @param {{ resize: Function, ktx2?: Function, ktxCommand?: Function }} opts.imageOps
|
|
275
|
+
* @param {string} opts.workDir inside the project's .nowhere/
|
|
276
|
+
* @param {{ meshopt: boolean, ktx2: boolean, offWhy?: string }} [opts.decoders] DECODERS_LIVE unless a check says otherwise; offWhy when KTX2 is off for this import rather than for the sides
|
|
277
|
+
* @returns {Promise<{ ok: true, glb: Uint8Array, report: object } | { ok: false, error: string }>}
|
|
278
|
+
*/
|
|
279
|
+
export async function optimiseModel(opts) {
|
|
280
|
+
const { doc, imageOps, workDir } = opts
|
|
281
|
+
const className = opts.className ?? 'prop'
|
|
282
|
+
const budget = TRIANGLE_BUDGETS[className] ?? TRIANGLE_BUDGETS.prop
|
|
283
|
+
const maxTexture = opts.maxTexture ?? TEXTURE_BUDGETS[className] ?? 1024
|
|
284
|
+
const decoders = opts.decoders ?? DECODERS_LIVE
|
|
285
|
+
const steps = []
|
|
286
|
+
const step = (op, detail) => steps.push({ op, detail })
|
|
287
|
+
const root = doc.getRoot()
|
|
288
|
+
|
|
289
|
+
// Nothing to place is a refusal now rather than an empty object later.
|
|
290
|
+
if (countTriangles(doc) === 0) return { ok: false, error: 'The model has no triangles to draw (no meshes, or only points and lines).' }
|
|
291
|
+
const before = { triangles: countTriangles(doc), meshes: root.listMeshes().length, materials: root.listMaterials().length, textures: root.listTextures().length }
|
|
292
|
+
|
|
293
|
+
await doc.transform(dedup(), weld())
|
|
294
|
+
step('weld', 'duplicate data merged, vertices welded')
|
|
295
|
+
|
|
296
|
+
if (before.triangles > budget) {
|
|
297
|
+
if (opts.simplify === false) {
|
|
298
|
+
step('simplify', `skipped (simplify: false); ${before.triangles.toLocaleString('en-US')} triangles stay over the ${className} budget of ${budget.toLocaleString('en-US')}`)
|
|
299
|
+
} else {
|
|
300
|
+
const ratio = Math.max(0.001, Math.min(1, budget / before.triangles))
|
|
301
|
+
await doc.transform(simplify({ simplifier: MeshoptSimplifier, ratio, error: 0.001 }))
|
|
302
|
+
let after = countTriangles(doc)
|
|
303
|
+
// A small thing may give more: 1% of a 30 cm lantern is 3 mm, which no
|
|
304
|
+
// visitor sees, and its budget is what keeps a shelf of them cheap. A
|
|
305
|
+
// bigger thing keeps the 0.1% bound (1% of a house is a hand's width).
|
|
306
|
+
const looser = after > budget && LOOSE_SIMPLIFY_CLASSES.has(className)
|
|
307
|
+
if (looser) {
|
|
308
|
+
await doc.transform(simplify({ simplifier: MeshoptSimplifier, ratio: Math.max(0.001, Math.min(1, budget / after)), error: LOOSE_SIMPLIFY_ERROR }))
|
|
309
|
+
after = countTriangles(doc)
|
|
310
|
+
}
|
|
311
|
+
const bound = looser ? `${LOOSE_SIMPLIFY_ERROR * 100}%` : '0.1%'
|
|
312
|
+
step(
|
|
313
|
+
'simplify',
|
|
314
|
+
after <= budget
|
|
315
|
+
? `${before.triangles.toLocaleString('en-US')} to ${after.toLocaleString('en-US')} triangles (${className} budget ${budget.toLocaleString('en-US')}${looser ? `; the surface moved by at most ${bound} of its size` : ''})`
|
|
316
|
+
: `stopped at ${after.toLocaleString('en-US')} triangles, over the ${className} budget of ${budget.toLocaleString('en-US')}: going further would move the surface by more than ${bound} of its size, so the shape was kept. Reduce it in Blender (a Decimate modifier in your script) or pick a lighter model`,
|
|
317
|
+
)
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
await doc.transform(join(), resample(), prune())
|
|
322
|
+
step('join', `${root.listMeshes().length} meshes, ${root.listMaterials().length} materials after joining and pruning`)
|
|
323
|
+
|
|
324
|
+
// Textures to the class's size.
|
|
325
|
+
const textureNotes = []
|
|
326
|
+
const textures = root.listTextures()
|
|
327
|
+
await fsp.mkdir(workDir, { recursive: true })
|
|
328
|
+
const normals = new Set(root.listMaterials().map((m) => m.getNormalTexture()).filter(Boolean))
|
|
329
|
+
for (const [i, tex] of textures.entries()) {
|
|
330
|
+
const image = tex.getImage()
|
|
331
|
+
if (!image) continue
|
|
332
|
+
const mime = tex.getMimeType()
|
|
333
|
+
const buf = Buffer.from(image)
|
|
334
|
+
const size = imageSize(buf)
|
|
335
|
+
const label = tex.getName() || tex.getURI() || `texture ${i + 1}`
|
|
336
|
+
if (mime === 'image/ktx2') {
|
|
337
|
+
// Nothing here turns KTX2 back into a picture, and a side without the
|
|
338
|
+
// decoder would draw the model untextured.
|
|
339
|
+
if (!decoders.ktx2) {
|
|
340
|
+
// Off for this import (asset_import's ktx2 "off"), or off for the sides.
|
|
341
|
+
if (decoders.offWhy) return { ok: false, error: `Its texture ${label} is KTX2 (Basis), and ${decoders.offWhy} Nothing here turns a KTX2 back into a picture, so nothing was written. Leave ktx2 at "auto" to keep it as KTX2, or pick the download with PNG or JPG textures.` }
|
|
342
|
+
return { ok: false, error: `Its texture ${label} is KTX2 (Basis), which the Oda server or player this project publishes to does not decode, so nothing was written. Pick the download with PNG or JPG textures.` }
|
|
343
|
+
}
|
|
344
|
+
textureNotes.push(`${label}: KTX2 kept`)
|
|
345
|
+
continue
|
|
346
|
+
}
|
|
347
|
+
const format = mime === 'image/jpeg' ? 'jpg' : 'png'
|
|
348
|
+
const tooBig = size && Math.max(size.width, size.height) > maxTexture
|
|
349
|
+
const odd = mime === 'image/webp' || !size
|
|
350
|
+
if (tooBig || odd) {
|
|
351
|
+
const from = path.join(workDir, `tex-${i}-in.${format === 'jpg' ? 'jpg' : mime === 'image/webp' ? 'webp' : 'png'}`)
|
|
352
|
+
const to = path.join(workDir, `tex-${i}-out.${format}`)
|
|
353
|
+
await fsp.writeFile(from, buf)
|
|
354
|
+
const r = await imageOps.resize(from, to, { maxSize: maxTexture, format })
|
|
355
|
+
if (r.error) {
|
|
356
|
+
textureNotes.push(`${label}: kept as it is (${r.error})`)
|
|
357
|
+
} else if (r.resized) {
|
|
358
|
+
tex.setImage(new Uint8Array(await fsp.readFile(to)))
|
|
359
|
+
tex.setMimeType(format === 'jpg' ? 'image/jpeg' : 'image/png')
|
|
360
|
+
textureNotes.push(`${label}: ${size ? `${size.width}x${size.height}` : '?'} to ${r.width}x${r.height}`)
|
|
361
|
+
} else {
|
|
362
|
+
textureNotes.push(`${label}: ${size ? `${size.width}x${size.height}` : 'size unknown'}, ${r.how}`)
|
|
363
|
+
}
|
|
364
|
+
} else if (size) {
|
|
365
|
+
textureNotes.push(`${label}: ${size.width}x${size.height}`)
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
if (textures.length) step('textures', `at most ${maxTexture} px (${className}): ${textureNotes.join('; ') || 'none to change'}`)
|
|
369
|
+
|
|
370
|
+
// Each texture as it was before KTX2, for the copy Blender reads (below).
|
|
371
|
+
const pictures = new Map()
|
|
372
|
+
// KTX2 only where the player decodes it and an encoder is here. A colour
|
|
373
|
+
// map (base colour, emissive) or an occlusion map alone may be ETC1S when
|
|
374
|
+
// it holds up; a normal map and the rough and metal one are UASTC.
|
|
375
|
+
if (decoders.ktx2 && textures.length && imageOps.ktx2) {
|
|
376
|
+
const tool = await imageOps.ktxCommand?.()
|
|
377
|
+
if (!tool) step('ktx2', 'not written: no KTX2 encoder (the ktx2-encoder package, or KTX-Software on PATH)')
|
|
378
|
+
else {
|
|
379
|
+
const roleOf = textureRoles(doc)
|
|
380
|
+
let n = 0
|
|
381
|
+
const modes = []
|
|
382
|
+
for (const [i, tex] of root.listTextures().entries()) {
|
|
383
|
+
if (tex.getMimeType() === 'image/ktx2' || !tex.getImage()) continue
|
|
384
|
+
const ext = tex.getMimeType() === 'image/jpeg' ? 'jpg' : 'png'
|
|
385
|
+
const from = path.join(workDir, `ktx-${i}.${ext}`)
|
|
386
|
+
const to = path.join(workDir, `ktx-${i}.ktx2`)
|
|
387
|
+
await fsp.writeFile(from, Buffer.from(tex.getImage()))
|
|
388
|
+
const role = roleOf(tex)
|
|
389
|
+
const r = await imageOps.ktx2(from, to, { normal: role === 'normal', role })
|
|
390
|
+
if (r.ok) {
|
|
391
|
+
pictures.set(tex, { image: tex.getImage(), mime: tex.getMimeType() })
|
|
392
|
+
tex.setImage(new Uint8Array(await fsp.readFile(to)))
|
|
393
|
+
tex.setMimeType('image/ktx2')
|
|
394
|
+
if (r.mode) modes.push(`${tex.getName() || `texture ${i + 1}`} ${r.mode.toUpperCase()}`)
|
|
395
|
+
n++
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
if (n) doc.createExtension(KHRTextureBasisu).setRequired(true)
|
|
399
|
+
step('ktx2', `${n} of ${root.listTextures().length} textures written as KTX2 with ${tool}${modes.length ? ` (${modes.join(', ')})` : ''}`)
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Size and pivot, then baked into the vertices (bakeFrames).
|
|
404
|
+
const scene = root.getDefaultScene() ?? root.listScenes()[0]
|
|
405
|
+
let bounds = boundsOf(doc)
|
|
406
|
+
if (!bounds) return { ok: false, error: 'The model has no measurable size.' }
|
|
407
|
+
const wanted = opts.size ?? {}
|
|
408
|
+
const axis = { width: 0, height: 1, depth: 2 }
|
|
409
|
+
const key = ['height', 'width', 'depth', 'longest'].find((k) => typeof wanted[k] === 'number' && wanted[k] > 0)
|
|
410
|
+
const largest = Math.max(...bounds.size)
|
|
411
|
+
if (key) {
|
|
412
|
+
const current = key === 'longest' ? largest : bounds.size[axis[key]]
|
|
413
|
+
if (!(current > 0)) return { ok: false, error: `The model has no ${key} to scale (it is flat along that axis).` }
|
|
414
|
+
const s = wanted[key] / current
|
|
415
|
+
const wrapper = doc.createNode('asset_root').setScale([s, s, s])
|
|
416
|
+
for (const child of scene.listChildren()) {
|
|
417
|
+
scene.removeChild(child)
|
|
418
|
+
wrapper.addChild(child)
|
|
419
|
+
}
|
|
420
|
+
scene.addChild(wrapper)
|
|
421
|
+
step('size', `scaled by ${round(s, 4)} so its ${key} is ${wanted[key]} m`)
|
|
422
|
+
} else if (opts.statedMetres) {
|
|
423
|
+
step('size', `kept the source's size (it states metres): ${sizeText(bounds.size)}`)
|
|
424
|
+
} else if (largest >= 0.05 && largest <= 200) {
|
|
425
|
+
step('size', `kept the file's size, which is plausible in metres: ${sizeText(bounds.size)}`)
|
|
426
|
+
} else {
|
|
427
|
+
return {
|
|
428
|
+
ok: false,
|
|
429
|
+
error: `The model is ${round(largest, 4)} units across at its largest, which does not look like metres (a source in centimetres or kilometres). Import it again with size, e.g. { "height": 0.9 }.`,
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
const pivot = opts.pivot ?? 'base'
|
|
433
|
+
if (pivot !== 'keep') {
|
|
434
|
+
await doc.transform(center({ pivot: pivot === 'center' ? 'center' : 'below' }))
|
|
435
|
+
step('pivot', pivot === 'center' ? 'the middle of its bounds at the origin' : 'the centre of its footprint at the origin, its lowest point at y = 0')
|
|
436
|
+
}
|
|
437
|
+
const baked = await bakeFrames(doc)
|
|
438
|
+
if (baked) step('bake', `${baked} ${baked === 1 ? 'mesh' : 'meshes'} moved into the model's own frame, so the vertices are metres from its pivot`)
|
|
439
|
+
|
|
440
|
+
// Positions stay float, in metres from the pivot: a game's own shaders
|
|
441
|
+
// read positionLocal as metres from the base, and quantize() would
|
|
442
|
+
// squeeze them into [-1, 1] and move the scale into the node. Normals, UVs and the rest are quantized.
|
|
443
|
+
const keepPositions = { pattern: /^(?!POSITION$).*/ }
|
|
444
|
+
if (decoders.meshopt) {
|
|
445
|
+
await doc.transform(reorder({ encoder: MeshoptEncoder, target: 'size' }), quantize(keepPositions))
|
|
446
|
+
declareQuantization(doc)
|
|
447
|
+
doc.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE })
|
|
448
|
+
step('meshopt', 'geometry compressed with EXT_meshopt_compression (positions kept in metres, the rest quantized)')
|
|
449
|
+
} else {
|
|
450
|
+
// A source that came meshopt-compressed is written plain: a side
|
|
451
|
+
// without the decoder would draw nothing, and say so to no one.
|
|
452
|
+
for (const ext of root.listExtensionsUsed()) if (ext.extensionName === 'EXT_meshopt_compression') ext.dispose()
|
|
453
|
+
await doc.transform(quantize(keepPositions))
|
|
454
|
+
declareQuantization(doc)
|
|
455
|
+
step('quantize', 'normals and UVs quantized (KHR_mesh_quantization, which needs no decoder); positions kept in metres')
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
await doc.transform(prune(), unpartition())
|
|
459
|
+
const io = await gltfIO()
|
|
460
|
+
const glb = await io.writeBinary(doc)
|
|
461
|
+
// What meshopt would make of it, where a side cannot decode it:
|
|
462
|
+
// measured on a copy, so the answer and the ledger can say what turning it
|
|
463
|
+
// on will save.
|
|
464
|
+
let meshoptBytes = null
|
|
465
|
+
if (!decoders.meshopt) {
|
|
466
|
+
try {
|
|
467
|
+
const copy = cloneDocument(doc)
|
|
468
|
+
copy.setLogger(QUIET)
|
|
469
|
+
await copy.transform(reorder({ encoder: MeshoptEncoder, target: 'size' }))
|
|
470
|
+
copy.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE })
|
|
471
|
+
meshoptBytes = (await io.writeBinary(copy)).byteLength
|
|
472
|
+
} catch {
|
|
473
|
+
// the estimate is a nicety; the model is written all the same
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
const check = await validateGlb(glb)
|
|
477
|
+
if (check.numErrors > 0) {
|
|
478
|
+
return { ok: false, error: `The optimised GLB did not pass the glTF validator, so nothing was written:\n${check.errors.slice(0, 5).map((e) => `- ${e}`).join('\n')}` }
|
|
479
|
+
}
|
|
480
|
+
// Blender reads neither meshopt nor KTX2 (its glTF importer refuses both),
|
|
481
|
+
// so the contact sheet is rendered from a copy without them.
|
|
482
|
+
const plainGlb = await blenderCopy(doc, io, pictures)
|
|
483
|
+
bounds = boundsOf(doc)
|
|
484
|
+
const after = {
|
|
485
|
+
triangles: countTriangles(doc),
|
|
486
|
+
meshes: root.listMeshes().length,
|
|
487
|
+
materials: root.listMaterials().length,
|
|
488
|
+
textures: root.listTextures().map((t) => {
|
|
489
|
+
// A texture written as KTX2 says its size in its header.
|
|
490
|
+
const buf = Buffer.from(t.getImage() ?? [])
|
|
491
|
+
const s = imageSize(buf) ?? ktx2Header(buf)
|
|
492
|
+
return { name: t.getName() || t.getURI() || 'texture', mime: t.getMimeType(), ...(s ? { width: s.width, height: s.height } : {}) }
|
|
493
|
+
}),
|
|
494
|
+
}
|
|
495
|
+
return {
|
|
496
|
+
ok: true,
|
|
497
|
+
glb,
|
|
498
|
+
report: {
|
|
499
|
+
className,
|
|
500
|
+
budget,
|
|
501
|
+
maxTexture,
|
|
502
|
+
before,
|
|
503
|
+
after,
|
|
504
|
+
bounds: bounds ? { min: bounds.min.map((v) => round(v)), max: bounds.max.map((v) => round(v)), size: bounds.size.map((v) => round(v)) } : null,
|
|
505
|
+
steps,
|
|
506
|
+
warnings: check.warnings.slice(0, 8),
|
|
507
|
+
bytes: glb.byteLength,
|
|
508
|
+
meshoptBytes,
|
|
509
|
+
mb: round(glb.byteLength / MB, 2),
|
|
510
|
+
},
|
|
511
|
+
...(plainGlb ? { plainGlb } : {}),
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* The same model as a GLB Blender reads, or null when it already is one:
|
|
517
|
+
* the geometry without EXT_meshopt_compression (still quantized, which
|
|
518
|
+
* Blender reads) and each KTX2 texture as the picture it was made from, or,
|
|
519
|
+
* for one that came as KTX2, transcoded back to a PNG. For Blender's eyes
|
|
520
|
+
* only (the contact sheet); never written into assets/.
|
|
521
|
+
*/
|
|
522
|
+
export async function blenderCopy(doc, io, pictures = new Map()) {
|
|
523
|
+
const root = doc.getRoot()
|
|
524
|
+
const packed = root.listExtensionsUsed().filter((e) => e.extensionName === 'EXT_meshopt_compression' || e.extensionName === 'KHR_texture_basisu')
|
|
525
|
+
if (packed.length === 0) return null
|
|
526
|
+
const copy = cloneDocument(doc)
|
|
527
|
+
copy.setLogger(QUIET)
|
|
528
|
+
const from = root.listTextures()
|
|
529
|
+
const to = copy.getRoot().listTextures()
|
|
530
|
+
for (const [i, tex] of to.entries()) {
|
|
531
|
+
if (tex.getMimeType() !== 'image/ktx2') continue
|
|
532
|
+
const before = pictures.get(from[i])
|
|
533
|
+
if (before) {
|
|
534
|
+
tex.setImage(before.image).setMimeType(before.mime)
|
|
535
|
+
continue
|
|
536
|
+
}
|
|
537
|
+
try {
|
|
538
|
+
const back = await decodeKtx2(tex.getImage())
|
|
539
|
+
tex.setImage(new Uint8Array(encodePng(back))).setMimeType('image/png')
|
|
540
|
+
} catch {
|
|
541
|
+
// drawn untextured in the sheet, which says no more than it shows
|
|
542
|
+
tex.dispose()
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
for (const ext of copy.getRoot().listExtensionsUsed()) if (ext.extensionName === 'EXT_meshopt_compression' || ext.extensionName === 'KHR_texture_basisu') ext.dispose()
|
|
546
|
+
return io.writeBinary(copy)
|
|
547
|
+
}
|