topotopo 0.5.1 → 0.5.3

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.
Files changed (41) hide show
  1. package/dist/cli.js +42 -18
  2. package/dist/core/manifold.d.ts +11 -2
  3. package/dist/core/manifold.js +7 -4
  4. package/dist/core/materials.d.ts +3 -2
  5. package/dist/core/materials.js +3 -2
  6. package/dist/core/tangents.d.ts +11 -1
  7. package/dist/core/tangents.js +87 -14
  8. package/dist/core/texture.d.ts +1 -1
  9. package/dist/core/texture.js +12 -3
  10. package/dist/core/topology.d.ts +5 -1
  11. package/dist/core/topology.js +35 -4
  12. package/dist/graph/engine.d.ts +7 -0
  13. package/dist/graph/engine.js +54 -6
  14. package/dist/io/gltf.js +8 -7
  15. package/dist/io/source.d.ts +2 -0
  16. package/dist/io/source.js +10 -1
  17. package/dist/mcp/docs.js +35 -8
  18. package/dist/mcp/tools.js +35 -10
  19. package/dist/nodes/attributes.js +12 -3
  20. package/dist/nodes/bake.js +2 -2
  21. package/dist/nodes/curves.js +7 -7
  22. package/dist/nodes/material.js +3 -3
  23. package/dist/nodes/solid.js +42 -15
  24. package/dist/nodes/texture.js +16 -9
  25. package/dist/nodes/topology.js +3 -2
  26. package/dist/packages/registry.d.ts +21 -8
  27. package/dist/packages/registry.js +57 -24
  28. package/dist/render/options.js +9 -1
  29. package/dist/render/pbr.d.ts +22 -2
  30. package/dist/render/pbr.js +113 -38
  31. package/dist/render/preview.d.ts +2 -0
  32. package/dist/render/raster.d.ts +13 -1
  33. package/dist/render/raster.js +112 -19
  34. package/dist/session.d.ts +25 -6
  35. package/dist/session.js +98 -43
  36. package/dist/viewer/app/api.js +5 -2
  37. package/dist/viewer/app/cooking.js +9 -3
  38. package/dist/viewer/app/main.js +18 -4
  39. package/dist/viewer/server.js +20 -3
  40. package/integrations/godot/addons/topotopo/plugin.cfg +1 -1
  41. package/package.json +3 -3
@@ -1,10 +1,13 @@
1
1
  import { Image, channelsOf, imageRef, referenceableImages, resizeLayer } from '../core/image.js';
2
- import { DEFAULT_MATERIAL, mergeMaterialTables, primMaterials, readMaterials } from '../core/materials.js';
2
+ import { DEFAULT_MATERIAL, materialAlphaMode, mergeMaterialTables, primMaterials, readMaterials } from '../core/materials.js';
3
3
  import { cornerTangents, loadMikkTSpace, mikkTSpaceReady, shadingFrame, vertexUV } from '../core/tangents.js';
4
4
  import { imageRowOfV } from '../core/texcoord.js';
5
5
  import { resolveVertexNormals } from '../core/topology.js';
6
6
  import { decodePNG } from '../io/png-decode.js';
7
7
  import { imageFromPNG } from '../io/textures.js';
8
+ export const VERTEX_COLOR_MODES = ['auto', 'ignore', 'multiply'];
9
+ /** The base colour of grey renders: 18% reflectance (linear). */
10
+ export const GREY_ALBEDO = 0.18;
8
11
  /** The normals the exporter writes by default (60° cusp): the frame the normal map and TANGENT belong to. */
9
12
  export const PBR_CUSP = 60;
10
13
  /**
@@ -85,6 +88,8 @@ function sampleTri(chain, u, v, lod, out) {
85
88
  if (f > 0 && l0 + 1 < chain.length)
86
89
  bilinear(chain[l0 + 1], u, v, out, f);
87
90
  }
91
+ /** Per-triangle alpha handling (PBRScene.triAlpha). */
92
+ export const ALPHA_OPAQUE = 0, ALPHA_MASK = 1, ALPHA_BLEND = 2;
88
93
  const norm = (v) => { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; };
89
94
  // studio rig in camera space (x right, y up, z towards the viewer): key upper left, fill right, rim behind
90
95
  const RIG = [
@@ -94,12 +99,17 @@ const RIG = [
94
99
  ];
95
100
  // world-up environment for indirect light
96
101
  const SKY = [0.34, 0.37, 0.42], HORIZON = [0.27, 0.27, 0.27], GROUND = [0.08, 0.075, 0.07];
102
+ const ENV = { sky: SKY, horizon: HORIZON, ground: GROUND };
103
+ /** The same light at its luminance (Rec. 709): the neutral rig of grey renders. */
104
+ const neutral = (c) => { const y = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; return [y, y, y]; };
105
+ const GREY_RIG = RIG.map((l) => ({ d: l.d, c: neutral(l.c) }));
106
+ const GREY_ENV = { sky: neutral(SKY), horizon: neutral(HORIZON), ground: neutral(GROUND) };
97
107
  /** Environment radiance along world direction d, widened by roughness (a cheap stand-in for a prefiltered map). */
98
- function env(dy, rough, out) {
108
+ function env(dy, rough, out, { sky, horizon, ground } = ENV) {
99
109
  const w = 0.25 + rough * 0.9;
100
110
  const t = Math.max(-1, Math.min(1, dy / w));
101
111
  for (let c = 0; c < 3; c++)
102
- out[c] = t >= 0 ? HORIZON[c] + (SKY[c] - HORIZON[c]) * t : HORIZON[c] + (GROUND[c] - HORIZON[c]) * -t;
112
+ out[c] = t >= 0 ? horizon[c] + (sky[c] - horizon[c]) * t : horizon[c] + (ground[c] - horizon[c]) * -t;
103
113
  }
104
114
  /** ACES filmic curve (Narkowicz fit). */
105
115
  const acesCurve = (x) => Math.max(0, Math.min(1, (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)));
@@ -117,9 +127,12 @@ function tone(c) {
117
127
  * Build the shading data for g's triangles (tris / triPrim from topology.triangulate). Synchronous: MikkTSpace must be
118
128
  * loaded (preparePBR or loadMikkTSpace) and external textures read into `files`; notes receive what is not evaluated.
119
129
  */
120
- export function pbrScene(g, tris, triPrim, files, exposure, notes) {
130
+ export function pbrScene(g, tris, triPrim, files, exposure, notes, opts = {}) {
121
131
  if (!mikkTSpaceReady())
122
132
  throw new Error('shading "pbr" needs the asynchronous render entry (renderGeometryAsync): MikkTSpace is not loaded');
133
+ const vcMode = opts.vertexColors ?? 'auto', grey = !!opts.grey;
134
+ if (!VERTEX_COLOR_MODES.includes(vcMode))
135
+ throw new Error(`render: cd (vertex colours) expects ${VERTEX_COLOR_MODES.join(', ')}, got ${JSON.stringify(vcMode)}`);
123
136
  const nTri = tris.length / 3;
124
137
  const table = readMaterials(g), pm = primMaterials(g), imgs = referenceableImages(g);
125
138
  const uv = vertexUV(g, 'uv');
@@ -151,7 +164,8 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
151
164
  mipCache.set(key, chain);
152
165
  return chain;
153
166
  };
154
- // vertex colour as glTF COLOR_0: per material, only when Cd is not all white over its prims
167
+ // vertex colour per material name, only when Cd is not all white over its prims: replacing the base colour factor on
168
+ // prims without a named material (glTF COLOR_0), multiplying a named material's base colour with vertexColors 'multiply'
155
169
  const cdF = g.findAttrib('Cd', ['vertex', 'point', 'prim', 'detail']);
156
170
  const cdA = cdF && cdF.attr.type === 'float' ? cdF.attr : null;
157
171
  const cdIndex = (v, p) => (cdF.cls === 'vertex' ? v : cdF.cls === 'point' ? vp[v] : cdF.cls === 'prim' ? p : 0);
@@ -161,8 +175,8 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
161
175
  out[1] = s > 1 ? d[i + 1] : d[i];
162
176
  out[2] = s > 2 ? d[i + 2] : d[i];
163
177
  };
164
- const mats = new Map(), vcol = new Map();
165
- const transparent = [];
178
+ const mats = new Map(), vcol = new Map(); // 0 none, 1 replaces the factor, 2 multiplies
179
+ const opaqueMapAlpha = [];
166
180
  const matOf = (name) => {
167
181
  let m = mats.get(name);
168
182
  if (m)
@@ -177,16 +191,15 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
177
191
  emissive: src.emissive.map((e) => srgbToLinear(Math.max(0, Math.min(1, e / emax))) * emax), unlit: src.unlit,
178
192
  baseMap: mapOf(label, 'base colour', t.baseColor, true), normalMap: mapOf(label, 'normal', t.normal, false),
179
193
  ormMap: mapOf(label, 'orm', t.orm, false), roughMap: t.orm ? null : mapOf(label, 'roughness', t.roughness, false), size: [1, 1],
194
+ alpha: Math.max(0, Math.min(1, src.alpha)), cutoff: src.alphaCutoff ?? 0.5,
180
195
  };
181
196
  for (const c of [m.baseMap, m.normalMap, m.ormMap, m.roughMap])
182
197
  if (c) {
183
198
  m.size[0] = Math.max(m.size[0], c[0].w);
184
199
  m.size[1] = Math.max(m.size[1], c[0].h);
185
200
  }
186
- if (src.alpha < 1)
187
- transparent.push(`material "${label}" alpha ${src.alpha}`);
188
- else if (m.baseMap && m.baseMap[0].ch === 4 && m.baseMap[0].data.some((x, i) => i % 4 === 3 && x < 1))
189
- transparent.push(`material "${label}" base colour map alpha`);
201
+ if (materialAlphaMode(src) === 'OPAQUE' && m.baseMap && m.baseMap[0].ch === 4 && m.baseMap[0].data.some((x, i) => i % 4 === 3 && x < 1))
202
+ opaqueMapAlpha.push(label);
190
203
  mats.set(name, m);
191
204
  return m;
192
205
  };
@@ -207,15 +220,56 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
207
220
  cdWhite.set(name, white);
208
221
  }
209
222
  }
223
+ // vertex Alpha (glTF COLOR_0 alpha): where vertex colours may be used, per material name when it is below 1 there
224
+ const alF = g.findAttrib('Alpha', ['vertex', 'point', 'prim', 'detail']);
225
+ const alA = alF && alF.attr.type === 'float' && alF.attr.size === 1 ? alF.attr : null;
226
+ const alphaAt = (v, p) => alA.data[alF.cls === 'vertex' ? v : alF.cls === 'point' ? vp[v] : alF.cls === 'prim' ? p : 0];
227
+ const alLow = new Map();
228
+ if (alA) {
229
+ for (let t = 0; t < nTri; t++) {
230
+ const p = triPrim[t], name = pm ? pm[p] : '';
231
+ if (alLow.get(name))
232
+ continue;
233
+ let low = false;
234
+ for (let k = 0; k < 3 && !low; k++)
235
+ if (alphaAt(tris[t * 3 + k], p) < 1)
236
+ low = true;
237
+ if (low || !alLow.has(name))
238
+ alLow.set(name, low);
239
+ }
240
+ }
241
+ const triVcol = new Uint8Array(nTri), triAlpha = new Uint8Array(nTri), triVA = new Uint8Array(nTri);
242
+ const nameAlpha = new Map(); // [mode, vertex alpha used]
243
+ let cdHidden = false, alphaHidden = false;
210
244
  for (let t = 0; t < nTri; t++) {
211
245
  const name = pm ? pm[triPrim[t]] : '';
212
246
  triMat[t] = matOf(name);
213
- if (!vcol.has(name))
214
- vcol.set(name, !!cdA && cdWhite.get(name) === false);
247
+ let v = vcol.get(name), na = nameAlpha.get(name);
248
+ if (v === undefined || na === undefined) {
249
+ const painted = !!cdA && cdWhite.get(name) === false, named = !!(name && table[name]);
250
+ v = !painted || vcMode === 'ignore' ? 0 : !named ? 1 : vcMode === 'multiply' ? 2 : 0;
251
+ if (painted && named && vcMode === 'auto')
252
+ cdHidden = true;
253
+ vcol.set(name, v);
254
+ const vtx = vcMode !== 'ignore' && (!named || vcMode === 'multiply'), lowA = !!alLow.get(name);
255
+ // the mode is the material's own (vertex Alpha is data, as in export); vertex Alpha multiplies the coverage of
256
+ // mask and blend materials where vertex colours are used
257
+ const mode = materialAlphaMode((named && table[name]) || DEFAULT_MATERIAL);
258
+ if (lowA && !vtx && mode !== 'OPAQUE')
259
+ alphaHidden = true;
260
+ na = [mode === 'MASK' ? ALPHA_MASK : mode === 'BLEND' ? ALPHA_BLEND : ALPHA_OPAQUE, vtx && lowA && mode !== 'OPAQUE' ? 1 : 0];
261
+ nameAlpha.set(name, na);
262
+ }
263
+ triVcol[t] = v;
264
+ triAlpha[t] = na[0];
265
+ triVA[t] = na[1];
215
266
  }
216
- const al = g.findAttrib('Alpha', ['vertex', 'point', 'prim', 'detail']);
217
- if (al && al.attr.type === 'float' && al.attr.data.some((x) => x < 1))
218
- transparent.push('Alpha attribute below 1');
267
+ if (cdHidden)
268
+ notes.push('pbr: Cd on prims with a named material is not shown: the material decides their colour, as in glTF export (cd "multiply" tints the material with it)');
269
+ if (alphaHidden)
270
+ notes.push('pbr: the Alpha attribute is not used on prims with a named material: the material\'s alpha decides, as in glTF export (cd "multiply" uses it)');
271
+ for (const label of new Set(opaqueMapAlpha))
272
+ notes.push(`pbr: material "${label}" has a base colour map with alpha below 1 but is opaque (alpha_mode "mask" or "blend" uses that alpha)`);
219
273
  // MikkTSpace frames for normal-mapped triangles (computed once over every triangle: the frames do not depend on the
220
274
  // material, and one call keeps the soup contiguous)
221
275
  const anyNormal = [...mats.values()].some((m) => m.normalMap);
@@ -228,13 +282,13 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
228
282
  }
229
283
  if (!uv && [...mats.values()].some((m) => m.baseMap || m.normalMap || m.ormMap || m.roughMap))
230
284
  problems.push('the geometry has no uv attribute: texture maps are not shown');
231
- if (transparent.length)
232
- notes.push(`pbr: transparency is not evaluated, shaded opaque (${[...new Set(transparent)].join('; ')})`);
233
285
  for (const pr of new Set(problems))
234
286
  notes.push(`pbr: ${pr}`);
235
- let camL = RIG.map((l) => ({ d: l.d, c: l.c }));
287
+ // grey: the rig and environment at their luminance, so a value check carries no hue from the lights either
288
+ const rig = grey ? GREY_RIG : RIG, envC = grey ? GREY_ENV : ENV;
289
+ let camL = rig.map((l) => ({ d: l.d, c: l.c }));
236
290
  const gain = 2 ** exposure;
237
- const n = [0, 0, 0], f = new Float64Array(9), tx = [0, 0, 0, 0], base = [0, 0, 0], e = [0, 0, 0], c3 = [0, 0, 0];
291
+ const n = [0, 0, 0], f = new Float64Array(9), tx = [0, 0, 0, 0], base = [0, 0, 0], e = [0, 0, 0], c3 = [0, 0, 0], vcRGB = [0, 0, 0];
238
292
  const uvAt = (t, w0, w1, w2, out) => {
239
293
  const a = tris[t * 3] * 2, b = tris[t * 3 + 1] * 2, c = tris[t * 3 + 2] * 2;
240
294
  out[0] = uv[a] * w0 + uv[b] * w1 + uv[c] * w2;
@@ -252,31 +306,39 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
252
306
  if (m.roughMap)
253
307
  mapsUsed.add('roughness');
254
308
  }
255
- const summary = `${mats.size} material${mats.size === 1 ? '' : 's'}${mapsUsed.size ? `, maps ${[...mapsUsed].join('/')}` : ''}`;
309
+ const alphaUsed = [...new Set(triAlpha)].filter((x) => x !== ALPHA_OPAQUE).sort().map((x) => (x === ALPHA_MASK ? 'cutout' : 'blend'));
310
+ const summary = `${mats.size} material${mats.size === 1 ? '' : 's'}${mapsUsed.size ? `, maps ${[...mapsUsed].join('/')}` : ''}${alphaUsed.length ? `, alpha ${alphaUsed.join('/')}` : ''}`;
256
311
  return {
257
- summary, hasUV: !!uv, uvAt,
258
- camera(r, u, fw) { camL = RIG.map((l) => ({ d: [0, 1, 2].map((k) => r[k] * l.d[0] + u[k] * l.d[1] - fw[k] * l.d[2]), c: l.c })); },
312
+ summary, hasUV: !!uv, uvAt, triAlpha,
313
+ cutoff: (t) => triMat[t].cutoff,
314
+ camera(r, u, fw) { camL = rig.map((l) => ({ d: [0, 1, 2].map((k) => r[k] * l.d[0] + u[k] * l.d[1] - fw[k] * l.d[2]), c: l.c })); },
259
315
  shade(t, w0, w1, w2, dudx, dvdx, dudy, dvdy, view, back, out) {
260
316
  const m = triMat[t], a = tris[t * 3], b = tris[t * 3 + 1], c = tris[t * 3 + 2];
261
317
  if (uv)
262
318
  uvAt(t, w0, w1, w2, uvp);
263
319
  const lod = (sz) => 0.5 * Math.log2(Math.max(1e-30, Math.max((dudx * sz[0].w) ** 2 + (dvdx * sz[0].h) ** 2, (dudy * sz[0].w) ** 2 + (dvdy * sz[0].h) ** 2)));
264
320
  // base colour
265
- if (vcol.get(pm ? pm[triPrim[t]] : '')) {
321
+ const vc = triVcol[t];
322
+ if (vc) {
266
323
  cdOf(a, triPrim[t], c3);
267
- base[0] = c3[0] * w0;
268
- base[1] = c3[1] * w0;
269
- base[2] = c3[2] * w0;
324
+ vcRGB[0] = c3[0] * w0;
325
+ vcRGB[1] = c3[1] * w0;
326
+ vcRGB[2] = c3[2] * w0;
270
327
  cdOf(b, triPrim[t], c3);
271
- base[0] += c3[0] * w1;
272
- base[1] += c3[1] * w1;
273
- base[2] += c3[2] * w1;
328
+ vcRGB[0] += c3[0] * w1;
329
+ vcRGB[1] += c3[1] * w1;
330
+ vcRGB[2] += c3[2] * w1;
274
331
  cdOf(c, triPrim[t], c3);
275
- base[0] += c3[0] * w2;
276
- base[1] += c3[1] * w2;
277
- base[2] += c3[2] * w2;
332
+ vcRGB[0] += c3[0] * w2;
333
+ vcRGB[1] += c3[1] * w2;
334
+ vcRGB[2] += c3[2] * w2;
278
335
  for (let k = 0; k < 3; k++)
279
- base[k] = srgbToLinear(Math.max(0, Math.min(1, base[k])));
336
+ vcRGB[k] = srgbToLinear(Math.max(0, Math.min(1, vcRGB[k])));
337
+ }
338
+ if (vc === 1) {
339
+ base[0] = vcRGB[0];
340
+ base[1] = vcRGB[1];
341
+ base[2] = vcRGB[2];
280
342
  }
281
343
  else if (m.baseMap && uv) {
282
344
  base[0] = base[1] = base[2] = 1;
@@ -286,12 +348,25 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
286
348
  base[1] = m.base[1];
287
349
  base[2] = m.base[2];
288
350
  }
351
+ let cov = triAlpha[t] === ALPHA_OPAQUE ? 1 : m.alpha;
289
352
  if (m.baseMap && uv) {
290
353
  sampleTri(m.baseMap, uvp[0], uvp[1], lod(m.baseMap), tx);
291
354
  base[0] *= tx[0];
292
355
  base[1] *= tx[1];
293
356
  base[2] *= tx[2];
357
+ if (triAlpha[t] !== ALPHA_OPAQUE)
358
+ cov *= tx[3];
359
+ }
360
+ if (triVA[t])
361
+ cov *= alphaAt(a, triPrim[t]) * w0 + alphaAt(b, triPrim[t]) * w1 + alphaAt(c, triPrim[t]) * w2;
362
+ out[3] = Math.max(0, Math.min(1, cov));
363
+ if (vc === 2) {
364
+ base[0] *= vcRGB[0];
365
+ base[1] *= vcRGB[1];
366
+ base[2] *= vcRGB[2];
294
367
  }
368
+ if (grey)
369
+ base[0] = base[1] = base[2] = GREY_ALBEDO;
295
370
  if (m.unlit) {
296
371
  out[0] = linearToSrgb(Math.min(1, base[0]));
297
372
  out[1] = linearToSrgb(Math.min(1, base[1]));
@@ -302,8 +377,8 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
302
377
  if (m.ormMap && uv) {
303
378
  sampleTri(m.ormMap, uvp[0], uvp[1], lod(m.ormMap), tx);
304
379
  ao = tx[0];
305
- rough = tx[1];
306
- metal = tx[2];
380
+ rough = tx[1] * m.roughness;
381
+ metal = tx[2] * m.metallic;
307
382
  }
308
383
  else if (m.roughMap && uv) {
309
384
  sampleTri(m.roughMap, uvp[0], uvp[1], lod(m.roughMap), tx);
@@ -359,10 +434,10 @@ export function pbrScene(g, tris, triPrim, files, exposure, notes) {
359
434
  }
360
435
  }
361
436
  // indirect: sky/ground irradiance (diffuse) and the environment along the reflection (specular), both occluded
362
- env(n[1], 1, e);
437
+ env(n[1], 1, e, envC);
363
438
  const ir = [e[0], e[1], e[2]];
364
439
  const RdotN = 2 * NoV, ry = RdotN * n[1] - view[1];
365
- env(ry, rough, e);
440
+ env(ry, rough, e, envC);
366
441
  // Karis' analytic environment BRDF
367
442
  const c0 = [-1, -0.0275, -0.572, 0.022], c1 = [1, 0.0425, 1.04, -0.04];
368
443
  const q = [rough * c0[0] + c1[0], rough * c0[1] + c1[1], rough * c0[2] + c1[2], rough * c0[3] + c1[3]];
@@ -51,6 +51,8 @@ export declare function thumbOptions(g: GraphSpec, size?: number): {
51
51
  shading?: import("./raster.ts").ShadingMode;
52
52
  exposure?: number;
53
53
  pbrTextures?: import("./pbr.ts").PBRTextures;
54
+ vertexColors?: import("./pbr.ts").VertexColorMode;
55
+ grey?: boolean;
54
56
  aoRadius?: number;
55
57
  orthoScale?: number;
56
58
  scale?: number;
@@ -1,6 +1,6 @@
1
1
  import { Geometry } from '../core/geometry.ts';
2
2
  import type { Vec3 } from '../core/math.ts';
3
- import type { PBRTextures } from './pbr.ts';
3
+ import type { PBRTextures, VertexColorMode } from './pbr.ts';
4
4
  /**
5
5
  * 3D views, 'persp@<azimuth>' (a persp view at that azimuth), 'section' (the cut through the section plane,
6
6
  * looking along its axis), plus 'uv': the 0..1 UV square (UDIM tiles) with every polygon drawn at its uv.
@@ -138,6 +138,18 @@ export interface RenderOptions {
138
138
  exposure?: number;
139
139
  /** shading 'pbr': texture files read by renderGeometryAsync (preparePBR); image volumes need none */
140
140
  pbrTextures?: PBRTextures;
141
+ /**
142
+ * shading 'pbr': how vertex colour Cd enters the base colour. 'auto' (default, the glTF export rule): a named
143
+ * material's base colour (factor or map) wins and Cd colours only prims without a material; 'ignore': Cd is never
144
+ * used; 'multiply': Cd also multiplies a named material's base colour (vertex paint as a tint)
145
+ */
146
+ vertexColors?: VertexColorMode;
147
+ /**
148
+ * value check: shading 'pbr' (implied when shading is not given) with every base colour replaced by a neutral 18%
149
+ * grey (linear 0.18); base colour maps and Cd give no colour, while alpha, roughness, metallic, normal and orm maps,
150
+ * emissive and unlit still apply
151
+ */
152
+ grey?: boolean;
141
153
  /** ao sample radius in output pixels (default 10) */
142
154
  aoRadius?: number;
143
155
  /** ortho and section views: world width in metres visible across a view (default: fit the bounds) */
@@ -25,7 +25,8 @@ import { heightfieldPreviewStep, isHeightfield, layerStats, withHeightfieldPrevi
25
25
  import { withSdfGridPreview } from '../core/sdfgrid.js';
26
26
  import { drawTextureView, textureSampler, withMaterialPreview } from './texview.js';
27
27
  import { EMPTY_ATTRIB } from '../core/scene.js';
28
- import { pbrScene, preparePBR } from './pbr.js';
28
+ import { ALPHA_BLEND, ALPHA_MASK, pbrScene, preparePBR } from './pbr.js';
29
+ import { loadMikkTSpace } from '../core/tangents.js';
29
30
  import { decodePNG } from '../io/png-decode.js';
30
31
  /**
31
32
  * Named three-quarter views: persp views at these azimuths (degrees; 0 = the camera on +Z looking at the front, 90 =
@@ -68,6 +69,8 @@ const SHADING_MODES = ['default', 'flat', 'matcap', 'ao', 'pbr'];
68
69
  /** The automatic wireframe draws polygon edges up to this many polygons. */
69
70
  export const AUTO_WIRE_MAX = 6000;
70
71
  const CUT_C = [0.93, 0.4, 0.3], CUT_FLIP_C = [0.25, 0.38, 0.9], SOCKET_C = [0.35, 1, 0.72];
72
+ /** Barycentric tolerance of the blend pass's shared-edge rule. */
73
+ const EDGE_EPS = 1e-9;
71
74
  /** Margins of the fit: the bounds fill this fraction of a view's width and height (room for the label and gizmo). */
72
75
  const FIT_W = 0.9, FIT_H = 0.84;
73
76
  /** Whether a zoom above 1 may crop the bounds: only when the person framed the view (look_at or ortho_scale). */
@@ -207,10 +210,14 @@ function makeCam(name, bmin, bmax, W, H, o, kind = name, azDeg, secAxis, pts) {
207
210
  * Host.readFile); every other mode renders exactly as renderGeometry does.
208
211
  */
209
212
  export async function renderGeometryAsync(g, o = {}, readFile) {
213
+ o = greyShading(o);
210
214
  if (o.shading === 'pbr' && !o.pbrTextures)
211
215
  o = { ...o, pbrTextures: await preparePBR(g, readFile) };
212
216
  if (o.underlay && !o.underlayImage)
213
217
  o = { ...o, underlayImage: await readUnderlay(o.underlay, readFile) };
218
+ // last, so no other task replaces the MikkTSpace instance between this and the synchronous render
219
+ if (o.shading === 'pbr')
220
+ await loadMikkTSpace();
214
221
  return renderGeometry(g, o);
215
222
  }
216
223
  /** A reference image for the underlay option: a PNG read through readFile (errors say what to pass instead). */
@@ -246,8 +253,17 @@ export async function readUnderlay(p, readFile) {
246
253
  }
247
254
  return { width: img.width, height: img.height, rgba };
248
255
  }
256
+ /** grey is a pbr value check: it implies shading 'pbr' and refuses another shading. */
257
+ function greyShading(o) {
258
+ if (!o.grey || o.shading === 'pbr')
259
+ return o;
260
+ if (o.shading && o.shading !== 'default')
261
+ throw new Error(`render: grey is a value check of shading "pbr" (given shading "${o.shading}"); leave shading out or set it to "pbr"`);
262
+ return { ...o, shading: 'pbr' };
263
+ }
249
264
  /** Render the geometry; returns RGBA pixels. Shading 'pbr' needs renderGeometryAsync first (or MikkTSpace loaded). */
250
265
  export function renderGeometry(g, o = {}) {
266
+ o = greyShading(o);
251
267
  // packed instances are drawn expanded (within a triangle budget), spline curves as polylines, see core/packed.ts
252
268
  if (g.hasPacked() || g.hasSplines()) {
253
269
  const budget = o.maxTriangles !== undefined && o.maxTriangles > 0 ? Math.min(o.maxTriangles, 50_000_000) : undefined;
@@ -439,7 +455,8 @@ export function renderGeometry(g, o = {}) {
439
455
  if (f.cls === 'point')
440
456
  pointColorOf = (p) => get(p);
441
457
  }
442
- // material base colours where there is no colour (no Cd, or Houdini's default white), as glTF export does
458
+ // material base colours where there is no colour (no Cd, or Houdini's default white); an inspection view, so Cd
459
+ // stays visible here (shading 'pbr' follows the export rule: a named material wins)
443
460
  const pm = primMaterials(g), table = pm ? readMaterials(g) : null;
444
461
  if (pm && table && Object.keys(table).length) {
445
462
  const cd = colorOf, hasCd = !!(f && f.attr.type === 'float');
@@ -589,15 +606,29 @@ export function renderGeometry(g, o = {}) {
589
606
  const flatN = shadingMode === 'flat' && nTri ? primNormals(g) : null;
590
607
  const matcap = shadingMode === 'matcap';
591
608
  let pbrS = null;
609
+ const pbrBlend = [];
592
610
  if (shadingMode === 'pbr' && nTri) {
593
611
  const ev = o.exposure ?? 0;
594
612
  if (!Number.isFinite(ev))
595
613
  throw new Error(`render: exposure expects a number of stops, got ${o.exposure}`);
596
- pbrS = pbrScene(g, tris, triPrim, o.pbrTextures, ev, notes);
614
+ pbrS = pbrScene(g, tris, triPrim, o.pbrTextures, ev, notes, { vertexColors: o.vertexColors, grey: !!o.grey });
597
615
  // color_by and highlight tint the shaded material (their colour, lit by its brightness); the checker is not shown
598
616
  if (o.checker)
599
617
  notes.push('pbr: checker is not shown under shading "pbr" (color_by and highlight tint the material)');
600
- ovDesc.push(`SHADING PBR STUDIO EV ${fmtNum(ev)} (${pbrS.summary.toUpperCase()})`);
618
+ const cdMode = o.vertexColors && o.vertexColors !== 'auto' ? ` CD ${o.vertexColors.toUpperCase()}` : '';
619
+ ovDesc.push(`SHADING PBR${o.grey ? ' GREY 18%' : ''} STUDIO EV ${fmtNum(ev)}${cdMode} (${pbrS.summary.toUpperCase()})`);
620
+ // blend triangles grouped by prim, for the back-to-front pass of each view
621
+ const byPrim = new Map();
622
+ for (let t = 0; t < nTri; t++)
623
+ if (pbrS.triAlpha[t] === ALPHA_BLEND) {
624
+ const p = triPrim[t];
625
+ let l = byPrim.get(p);
626
+ if (!l)
627
+ byPrim.set(p, (l = []));
628
+ l.push(t);
629
+ }
630
+ for (const [prim, ts] of byPrim)
631
+ pbrBlend.push({ prim, tris: ts });
601
632
  }
602
633
  else if (shadingMode)
603
634
  ovDesc.push(`SHADING ${shadingMode.toUpperCase()}`);
@@ -990,7 +1021,7 @@ export function renderGeometry(g, o = {}) {
990
1021
  // downsample a finished tile into the output, draw the output-resolution overlays (post), label it. Transparent
991
1022
  // 3D views (zb given): alpha = the covered fraction of each pixel's samples and the colour of those samples alone;
992
1023
  // whatever post and the label draw is opaque
993
- const blit = (label, post, zb) => {
1024
+ const blit = (label, post, zb, bA) => {
994
1025
  const inv = 1 / (ss * ss);
995
1026
  const cover = !!(outA && zb);
996
1027
  for (let y = 0; y < TH; y++)
@@ -1008,6 +1039,12 @@ export function renderGeometry(g, o = {}) {
1008
1039
  cg += col[k + 1];
1009
1040
  cb += col[k + 2];
1010
1041
  }
1042
+ else if (cover && bA && bA[zi] > 0) {
1043
+ n += bA[zi];
1044
+ cr += col[k];
1045
+ cg += col[k + 1];
1046
+ cb += col[k + 2];
1047
+ } // premultiplied
1011
1048
  }
1012
1049
  const o1 = (ty + y) * outW + tx + x, k = o1 * 3;
1013
1050
  if (!cover) {
@@ -1178,13 +1215,19 @@ export function renderGeometry(g, o = {}) {
1178
1215
  const na = [0, 0, 0], nb = [0, 0, 0], nc = [0, 0, 0];
1179
1216
  const tn = [0, 0, 0];
1180
1217
  const chk = [0, 0, 0];
1181
- const pbrUV0 = [0, 0], pbrUV1 = [0, 0], pbrUV2 = [0, 0], pbrV = [0, 0, 0], pbrRGB = [0, 0, 0];
1218
+ const pbrUV0 = [0, 0], pbrUV1 = [0, 0], pbrUV2 = [0, 0], pbrV = [0, 0, 0], pbrRGB = [0, 0, 0, 1];
1182
1219
  const bf = vi === backView ? new Uint8Array(W * H) : null, bfPrim = bf ? new Int32Array(W * H) : null;
1183
- for (let t = 0; t < nTri; t++) {
1220
+ // shading 'pbr' blend materials: drawn after the opaque pass (blendPass), depth-tested without writing depth and
1221
+ // composited over what is behind; on a transparent background, bA holds their coverage of empty samples (col
1222
+ // premultiplied there)
1223
+ const bA = pbrBlend.length && transparent ? new Float32Array(W * H) : null;
1224
+ const drawTri = (t, blendPass) => {
1225
+ if (pbrS && (pbrS.triAlpha[t] === ALPHA_BLEND) !== blendPass)
1226
+ return;
1184
1227
  const va = tris[t * 3], vb = tris[t * 3 + 1], vc = tris[t * 3 + 2];
1185
1228
  const a = g.vertexPoint[va], b = g.vertexPoint[vb], c = g.vertexPoint[vc];
1186
1229
  if (cam.persp && (vz[a] < 1e-4 || vz[b] < 1e-4 || vz[c] < 1e-4))
1187
- continue;
1230
+ return;
1188
1231
  let partial = false, qa = 0, qb = 0, qc = 0;
1189
1232
  if (clipOn) {
1190
1233
  qa = Pd[a * 3 + cK];
@@ -1192,17 +1235,17 @@ export function renderGeometry(g, o = {}) {
1192
1235
  qc = Pd[c * 3 + cK];
1193
1236
  const ra = (qa - cC) * cS > 0, rb = (qb - cC) * cS > 0, rc = (qc - cC) * cS > 0;
1194
1237
  if (ra && rb && rc)
1195
- continue;
1238
+ return;
1196
1239
  partial = ra || rb || rc;
1197
1240
  }
1198
1241
  const ax = sx[a], ay = sy[a], bx = sx[b], by = sy[b], cx = sx[c], cy = sy[c];
1199
1242
  const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
1200
1243
  if (Math.abs(area) < 1e-12)
1201
- continue;
1244
+ return;
1202
1245
  let minX = Math.max(0, Math.floor(Math.min(ax, bx, cx))), maxX = Math.min(W - 1, Math.ceil(Math.max(ax, bx, cx)));
1203
1246
  let minY = Math.max(0, Math.floor(Math.min(ay, by, cy))), maxY = Math.min(H - 1, Math.ceil(Math.max(ay, by, cy)));
1204
1247
  if (minX > maxX || minY > maxY)
1205
- continue;
1248
+ return;
1206
1249
  // facing (world space)
1207
1250
  const e1 = [Pd[b * 3] - Pd[a * 3], Pd[b * 3 + 1] - Pd[a * 3 + 1], Pd[b * 3 + 2] - Pd[a * 3 + 2]];
1208
1251
  const e2 = [Pd[c * 3] - Pd[a * 3], Pd[c * 3 + 1] - Pd[a * 3 + 1], Pd[c * 3 + 2] - Pd[a * 3 + 2]];
@@ -1210,7 +1253,9 @@ export function renderGeometry(g, o = {}) {
1210
1253
  const toCam = cam.persp ? [cam.eye[0] - Pd[a * 3], cam.eye[1] - Pd[a * 3 + 1], cam.eye[2] - Pd[a * 3 + 2]] : [-cam.f[0], -cam.f[1], -cam.f[2]];
1211
1254
  const back = dot3(fnw, toCam) < 0;
1212
1255
  const material = materialNames ? materialTable[materialNames[triPrim[t]]] : undefined;
1213
- const alphaMask = material?.alphaMode === 'MASK';
1256
+ // shading 'pbr' evaluates its own coverage (base colour maps of any source, vertex Alpha as exported)
1257
+ const alphaMask = !pbrS && material?.alphaMode === 'MASK';
1258
+ const pbrMask = !!pbrS && pbrS.triAlpha[t] === ALPHA_MASK, pbrCut = pbrMask ? pbrS.cutoff(t) : 0;
1214
1259
  const suspicious = back && !material?.doubleSided && solid !== null && closedPiece[pieceOf[triPrim[t]]] === 1;
1215
1260
  if (flatN) {
1216
1261
  const p = triPrim[t] * 3;
@@ -1238,6 +1283,17 @@ export function renderGeometry(g, o = {}) {
1238
1283
  colC = tint(colC);
1239
1284
  }
1240
1285
  const za = cz[a], zb2 = cz[b], zc = cz[c];
1286
+ // blend pass: a pixel centre on an edge shared by two triangles is drawn by exactly one of them (the one whose
1287
+ // opposite vertex lies on a fixed side of the edge), so shared edges are not composited twice
1288
+ const owns = (p0x, p0y, p1x, p1y, rx, ry) => {
1289
+ let nx = p0y - p1y, ny = p1x - p0x;
1290
+ if (nx < 0 || (nx === 0 && ny < 0)) {
1291
+ nx = -nx;
1292
+ ny = -ny;
1293
+ }
1294
+ return nx * (rx - p0x) + ny * (ry - p0y) > 0;
1295
+ };
1296
+ const own0 = blendPass && owns(bx, by, cx, cy, ax, ay), own1 = blendPass && owns(cx, cy, ax, ay, bx, by), own2 = blendPass && owns(ax, ay, bx, by, cx, cy);
1241
1297
  const inv = 1 / area;
1242
1298
  // shading 'pbr': screen-space gradients of the affine weights (uv derivatives for the texture level of detail)
1243
1299
  const g0x = (by - cy) * inv, g0y = (cx - bx) * inv, g1x = (cy - ay) * inv, g1y = (ax - cx) * inv;
@@ -1255,7 +1311,13 @@ export function renderGeometry(g, o = {}) {
1255
1311
  let w0 = ((bx - xx) * (cy - yy) - (by - yy) * (cx - xx)) * inv;
1256
1312
  let w1 = ((cx - xx) * (ay - yy) - (cy - yy) * (ax - xx)) * inv;
1257
1313
  let w2 = 1 - w0 - w1;
1258
- if (w0 < 0 || w1 < 0 || w2 < 0)
1314
+ if (blendPass) {
1315
+ if (w0 < -EDGE_EPS || w1 < -EDGE_EPS || w2 < -EDGE_EPS)
1316
+ continue;
1317
+ if ((w0 < EDGE_EPS && !own0) || (w1 < EDGE_EPS && !own1) || (w2 < EDGE_EPS && !own2))
1318
+ continue;
1319
+ }
1320
+ else if (w0 < 0 || w1 < 0 || w2 < 0)
1259
1321
  continue;
1260
1322
  const depth = w0 * za + w1 * zb2 + w2 * zc;
1261
1323
  const zi = py * W + px;
@@ -1289,11 +1351,6 @@ export function renderGeometry(g, o = {}) {
1289
1351
  if (alpha < (material.alphaCutoff ?? 0.5))
1290
1352
  continue;
1291
1353
  }
1292
- zb[zi] = depth;
1293
- if (bf) {
1294
- bf[zi] = suspicious ? 1 : 0;
1295
- bfPrim[zi] = triPrim[t];
1296
- }
1297
1354
  if (pbrS) {
1298
1355
  let dudx = 0, dvdx = 0, dudy = 0, dvdy = 0;
1299
1356
  if (pbrS.hasUV) {
@@ -1327,6 +1384,15 @@ export function renderGeometry(g, o = {}) {
1327
1384
  pbrV[2] = -cam.f[2];
1328
1385
  }
1329
1386
  pbrS.shade(t, w0, w1, w2, dudx, dvdx, dudy, dvdy, pbrV, back, pbrRGB);
1387
+ if (pbrMask && pbrRGB[3] < pbrCut)
1388
+ continue;
1389
+ if (!blendPass) {
1390
+ zb[zi] = depth;
1391
+ if (bf) {
1392
+ bf[zi] = suspicious ? 1 : 0;
1393
+ bfPrim[zi] = triPrim[t];
1394
+ }
1395
+ }
1330
1396
  const ci = zi * 3;
1331
1397
  if (pbrTint) {
1332
1398
  // the attribute colour lit by the material's brightness, over a third of the material itself
@@ -1339,11 +1405,27 @@ export function renderGeometry(g, o = {}) {
1339
1405
  pbrRGB[1] = pbrRGB[1] * 0.35 + 0.22;
1340
1406
  pbrRGB[2] = pbrRGB[2] * 0.35 + 0.6;
1341
1407
  }
1408
+ if (blendPass) {
1409
+ const al = pbrRGB[3];
1410
+ if (bA && zb[zi] === -Infinity) {
1411
+ if (bA[zi] === 0)
1412
+ col[ci] = col[ci + 1] = col[ci + 2] = 0;
1413
+ bA[zi] = al + bA[zi] * (1 - al);
1414
+ }
1415
+ for (let k = 0; k < 3; k++)
1416
+ col[ci + k] = pbrRGB[k] * al + col[ci + k] * (1 - al);
1417
+ continue;
1418
+ }
1342
1419
  col[ci] = pbrRGB[0];
1343
1420
  col[ci + 1] = pbrRGB[1];
1344
1421
  col[ci + 2] = pbrRGB[2];
1345
1422
  continue;
1346
1423
  }
1424
+ zb[zi] = depth;
1425
+ if (bf) {
1426
+ bf[zi] = suspicious ? 1 : 0;
1427
+ bfPrim[zi] = triPrim[t];
1428
+ }
1347
1429
  tn[0] = ca[0] * w0 + cb[0] * w1 + cc[0] * w2;
1348
1430
  tn[1] = ca[1] * w0 + cb[1] * w1 + cc[1] * w2;
1349
1431
  tn[2] = ca[2] * w0 + cb[2] * w1 + cc[2] * w2;
@@ -1407,6 +1489,17 @@ export function renderGeometry(g, o = {}) {
1407
1489
  col[ci + 2] = aces(fb * k + spec + rim);
1408
1490
  }
1409
1491
  }
1492
+ };
1493
+ for (let t = 0; t < nTri; t++)
1494
+ drawTri(t, false);
1495
+ if (pbrBlend.length) {
1496
+ // blend prims from back to front by their centroid's depth along the view axis
1497
+ const pc = centroids();
1498
+ const depthOf = (p) => (pc[p * 3] - cam.eye[0]) * cam.f[0] + (pc[p * 3 + 1] - cam.eye[1]) * cam.f[1] + (pc[p * 3 + 2] - cam.eye[2]) * cam.f[2];
1499
+ const order = pbrBlend.map((b) => ({ b, d: depthOf(b.prim) })).sort((x, y) => y.d - x.d || x.b.prim - y.b.prim);
1500
+ for (const { b } of order)
1501
+ for (const t of b.tris)
1502
+ drawTri(t, true);
1410
1503
  }
1411
1504
  if (bf)
1412
1505
  for (let i = 0; i < W * H; i++)
@@ -1777,7 +1870,7 @@ export function renderGeometry(g, o = {}) {
1777
1870
  for (let y = 0; y < TH; y++)
1778
1871
  out.set(tb.subarray(y * TW * 3, (y + 1) * TW * 3), ((ty + y) * outW + tx) * 3);
1779
1872
  };
1780
- blit(viewLabel, post, zb);
1873
+ blit(viewLabel, post, zb, bA);
1781
1874
  });
1782
1875
  // footer
1783
1876
  const fy = outH - footerH + 4 * ui;