@adatechnology/game-shapes-three 0.4.0 → 0.4.1

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 CHANGED
@@ -43,6 +43,7 @@ const geometry = toGeometry(THREE, buildPrimitive({ kind: 'torus', radius: 0.3,
43
43
  | `isMesh(object)` | Type guard for a mesh (or a skinned or instanced one) met while walking a tree with `traverse` |
44
44
  | `coincidentFacesOf(root, { eps, minArea, includeHidden })` | Faces under `root` that z-fight: triangles on the same plane (within 1 mm), facing the same way, that overlap more than 1 cm². Walks every drawn mesh in world space (instances too; decals with `polygonOffset` are skipped) and names both meshes in each hit. Every package's catalog test runs it on each piece (see `CLAUDE.md` §13) |
45
45
  | `markShared(...resources)` | Marks a palette, kit or catalog resource as shared on purpose, so the release never frees it; same as `userData.shared = true` without touching the resource (digests and goldens stay) |
46
+ | `markPositionsWritten(mesh, v0, v1)` / `rangesWrittenSince(attribute, version)` | Declares, right after the one `needsUpdate = true` of a write, which vertex range of a merged mesh it changed, and reads back the ranges written since a `version`. The destruction renderer measures each part's range of a merged mesh as a collider: a declared write re-measures only the parts in that range; a write that flags `needsUpdate` and declares nothing re-measures every part of the mesh |
46
47
 
47
48
  ## Português
48
49
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PrimitiveBuffers, ShapeBatch, ShapePoint, MaterialHint, ShapeBuffers, CoincidentFacesOptions, CoincidentBatch, CoincidentFaceHit } from '@adatechnology/game-shapes';
2
- export { CoincidentFaceHit, describeCoincidentFaces } from '@adatechnology/game-shapes';
2
+ export { CoincidentFaceHit, DepthPrecision, GAME_DEPTH_PRECISION, depthResolution, describeCoincidentFaces } from '@adatechnology/game-shapes';
3
3
  import * as THREE_NS from 'three';
4
4
 
5
5
  type Three = typeof THREE_NS;
@@ -113,10 +113,27 @@ declare function discardObject3D(objects: THREE_NS.Object3D | readonly THREE_NS.
113
113
  /** A mesh (or a subclass: skinned, instanced) found while walking a tree; three marks them with `isMesh`. */
114
114
  declare function isMesh(o: THREE_NS.Object3D | null | undefined): o is THREE_NS.Mesh;
115
115
 
116
+ /**
117
+ * Flags the mesh's positions for upload (`needsUpdate`) and declares that the write changed the vertices `[v0, v1)`: the write and its declaration share one `version`,
118
+ * so call it once per range written instead of setting `needsUpdate` yourself. A drawing that shares a
119
+ * merged mesh with another that measures its ranges (the house collapsing the range of a wall it draws with holes, under the destruction renderer that measures each
120
+ * part's range as a collider) calls it, so only the parts drawn by that range are measured again, not the whole house (`rangesWrittenSince`). A write that sets `needsUpdate` and declares nothing still counts, for every part of the mesh (`CLAUDE.md` §12).
121
+ */
122
+ declare function markPositionsWritten(mesh: THREE_NS.Mesh, v0: number, v1: number): void;
123
+ /** The ranges written after `version` up to the attribute's version now, or null when one of those writes declared no range (or is forgotten). */
124
+ declare function rangesWrittenSince(position: THREE_NS.BufferAttribute, version: number): Array<readonly [number, number]> | null;
125
+
116
126
  interface CoincidentFacesOfOptions extends CoincidentFacesOptions {
117
127
  /** Also check meshes that are hidden now (a piece that only shows when the wall breaks). Default false: only what is drawn. */
118
128
  readonly includeHidden?: boolean;
119
129
  }
130
+ interface MeshBatches {
131
+ readonly batches: CoincidentBatch[];
132
+ /** The mesh each batch came from, at the same index. */
133
+ readonly meshes: THREE_NS.Mesh[];
134
+ }
135
+ /** The triangles of every drawn mesh under `root`, in world space, with the mesh of each batch. */
136
+ declare function meshBatchesOf(root: THREE_NS.Object3D, options?: Pick<CoincidentFacesOfOptions, 'includeHidden'>): MeshBatches;
120
137
  /** The triangles of every drawn mesh under `root`, in world space, ready for `coincidentFaces`. */
121
138
  declare function coincidentBatchesOf(root: THREE_NS.Object3D, options?: Pick<CoincidentFacesOfOptions, 'includeHidden'>): CoincidentBatch[];
122
139
  /**
@@ -125,4 +142,24 @@ declare function coincidentBatchesOf(root: THREE_NS.Object3D, options?: Pick<Coi
125
142
  */
126
143
  declare function coincidentFacesOf(root: THREE_NS.Object3D, options?: CoincidentFacesOfOptions): CoincidentFaceHit[];
127
144
 
128
- export { type CoincidentFacesOfOptions, type ReleaseOptions, type ReleaseReport, SHAPE_GEOMETRY_TYPES, type ShapeGeometriesOptions, type ShapeObject, type Three, type ToGeometryOptions, type ToObjectOptions, catenary, coincidentBatchesOf, coincidentFacesOf, createCord, createMaterials, discardObject3D, isMesh, markShared, mergeByMaterial, releaseObject3D, shapeGeometries, toGeometry, toObject3D };
145
+ interface StandOutOptions {
146
+ /** How far a fighting face of the smaller piece moves out, in metres. Default 0.002 (CLAUDE.md §13). */
147
+ readonly gap?: number;
148
+ /** Rounds of check-and-move; a moved face can meet a third piece. Default 3. */
149
+ readonly rounds?: number;
150
+ }
151
+ interface StandOutReport {
152
+ /** Meshes that were moved out. */
153
+ readonly grown: number;
154
+ /** Face pairs still fighting after the last round (0 when it worked). */
155
+ readonly left: number;
156
+ }
157
+ /**
158
+ * Makes the faces of `root` stop fighting: of each pair of meshes with coincident faces, the face of the smaller one (the label, band, rim
159
+ * or lining) moves `gap` out of the bigger one, the rule of `CLAUDE.md` §13 ("a detail stands out at least 2 mm"). Only the sides that
160
+ * fight move. For pieces ported as they were drawn, where the detail sits flush on its body; a builder of the kit draws the gap itself.
161
+ * Instanced meshes are left alone.
162
+ */
163
+ declare function standOutCoincident(root: THREE_NS.Object3D, options?: StandOutOptions): StandOutReport;
164
+
165
+ export { type CoincidentFacesOfOptions, type MeshBatches, type ReleaseOptions, type ReleaseReport, SHAPE_GEOMETRY_TYPES, type ShapeGeometriesOptions, type ShapeObject, type StandOutOptions, type StandOutReport, type Three, type ToGeometryOptions, type ToObjectOptions, catenary, coincidentBatchesOf, coincidentFacesOf, createCord, createMaterials, discardObject3D, isMesh, markPositionsWritten, markShared, mergeByMaterial, meshBatchesOf, rangesWrittenSince, releaseObject3D, shapeGeometries, standOutCoincident, toGeometry, toObject3D };
@@ -21,19 +21,25 @@ var GameShapesThree = (() => {
21
21
  // src/index.ts
22
22
  var src_exports = {};
23
23
  __export(src_exports, {
24
+ GAME_DEPTH_PRECISION: () => GAME_DEPTH_PRECISION,
24
25
  SHAPE_GEOMETRY_TYPES: () => SHAPE_GEOMETRY_TYPES,
25
26
  catenary: () => catenary,
26
27
  coincidentBatchesOf: () => coincidentBatchesOf,
27
28
  coincidentFacesOf: () => coincidentFacesOf,
28
29
  createCord: () => createCord,
29
30
  createMaterials: () => createMaterials,
31
+ depthResolution: () => depthResolution,
30
32
  describeCoincidentFaces: () => describeCoincidentFaces,
31
33
  discardObject3D: () => discardObject3D,
32
34
  isMesh: () => isMesh,
35
+ markPositionsWritten: () => markPositionsWritten,
33
36
  markShared: () => markShared,
34
37
  mergeByMaterial: () => mergeByMaterial,
38
+ meshBatchesOf: () => meshBatchesOf,
39
+ rangesWrittenSince: () => rangesWrittenSince,
35
40
  releaseObject3D: () => releaseObject3D,
36
41
  shapeGeometries: () => shapeGeometries,
42
+ standOutCoincident: () => standOutCoincident,
37
43
  toGeometry: () => toGeometry,
38
44
  toObject3D: () => toObject3D
39
45
  });
@@ -79,7 +85,7 @@ var GameShapesThree = (() => {
79
85
  return geometry;
80
86
  }
81
87
 
82
- // ../game-shapes/dist/chunk-FZQTELDQ.js
88
+ // ../game-shapes/dist/chunk-E3X7UDDV.js
83
89
  function colorHex(color2, fallback = 16777215) {
84
90
  if (color2 === void 0) return fallback;
85
91
  if (typeof color2 === "number") return Math.floor(color2);
@@ -1624,6 +1630,134 @@ var GameShapesThree = (() => {
1624
1630
  const overlap = polygonAreaAndCenter(polygon);
1625
1631
  return overlap.area < 1e-12 ? void 0 : overlap;
1626
1632
  }
1633
+ var GAME_DEPTH_PRECISION = { viewDistance: 30, near: 0.05, far: 140, depthBits: 24 };
1634
+ function depthResolution(precision = GAME_DEPTH_PRECISION) {
1635
+ const { viewDistance: z, near, far, depthBits } = precision;
1636
+ return z * z * (far - near) / (far * near * 2 ** depthBits);
1637
+ }
1638
+ function boxOf(t) {
1639
+ const xs = [t[0][0], t[1][0], t[2][0]], ys = [t[0][1], t[1][1], t[2][1]], zs = [t[0][2], t[1][2], t[2][2]];
1640
+ return [Math.min(...xs), Math.min(...ys), Math.min(...zs), Math.max(...xs), Math.max(...ys), Math.max(...zs)];
1641
+ }
1642
+ var SAME_COLOUR = 1 / 512;
1643
+ var SAME_UV = 1e-3;
1644
+ var SAME_FACING = 1 - 1e-6;
1645
+ var PARALLEL = Math.cos(2 * Math.PI / 180);
1646
+ var DEFAULT_MAX_PER_PAIR = 3;
1647
+ var kindOf = (label) => label.replace(/\d+(\.\d+)?/g, "#");
1648
+ function facesOf(batches) {
1649
+ const faces = [];
1650
+ batches.forEach((batch, index) => {
1651
+ const label = batch.label ?? `batch ${index}`;
1652
+ const { positions: p, indices } = batch;
1653
+ const count = indices ? indices.length : p.length / 3;
1654
+ const vertex = (i) => [p[i * 3], p[i * 3 + 1], p[i * 3 + 2]];
1655
+ for (let i = 0; i + 2 < count; i += 3) {
1656
+ const corners = indices ? [indices[i], indices[i + 1], indices[i + 2]] : [i, i + 1, i + 2];
1657
+ const triangle = [vertex(corners[0]), vertex(corners[1]), vertex(corners[2])];
1658
+ const n = normalOf(triangle);
1659
+ if (n[0] === 0 && n[1] === 0 && n[2] === 0) continue;
1660
+ const offset = n[0] * triangle[0][0] + n[1] * triangle[0][1] + n[2] * triangle[0][2];
1661
+ faces.push({ triangle, n, offset, label, doubleSided: batch.doubleSided === true, box: boxOf(triangle), batch, batchIndex: index, corners });
1662
+ }
1663
+ });
1664
+ return faces;
1665
+ }
1666
+ function weightsOf(t, n, point) {
1667
+ const area3 = (a, b, c) => {
1668
+ const ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2], vx = c[0] - a[0], vy = c[1] - a[1], vz = c[2] - a[2];
1669
+ return n[0] * (uy * vz - uz * vy) + n[1] * (uz * vx - ux * vz) + n[2] * (ux * vy - uy * vx);
1670
+ };
1671
+ const whole = area3(t[0], t[1], t[2]) || 1;
1672
+ return [area3(point, t[1], t[2]) / whole, area3(t[0], point, t[2]) / whole, area3(t[0], t[1], point) / whole];
1673
+ }
1674
+ function attributeAt(values, size, face, point) {
1675
+ const w = weightsOf(face.triangle, face.n, point);
1676
+ return Array.from({ length: size }, (_, k) => w[0] * values[face.corners[0] * size + k] + w[1] * values[face.corners[1] * size + k] + w[2] * values[face.corners[2] * size + k]);
1677
+ }
1678
+ var close = (a, b, tolerance) => a.every((v, k) => Math.abs(v - b[k]) <= tolerance);
1679
+ function drawAlike(a, b, point) {
1680
+ if (a.batch.look === void 0 || a.batch.look !== b.batch.look) return false;
1681
+ if (a.n[0] * b.n[0] + a.n[1] * b.n[1] + a.n[2] * b.n[2] < SAME_FACING) return false;
1682
+ const ca = a.batch.colors, cb = b.batch.colors;
1683
+ if (ca === void 0 !== (cb === void 0)) return false;
1684
+ if (ca && cb && !close(attributeAt(ca, 3, a, point), attributeAt(cb, 3, b, point), SAME_COLOUR)) return false;
1685
+ const ua = a.batch.uvs, ub = b.batch.uvs;
1686
+ if (ua === void 0 !== (ub === void 0)) return false;
1687
+ return !(ua && ub && !close(attributeAt(ua, 2, a, point), attributeAt(ub, 2, b, point), SAME_UV));
1688
+ }
1689
+ function touch(a, b, slack) {
1690
+ return a[1] <= b[4] + slack && b[1] <= a[4] + slack && a[2] <= b[5] + slack && b[2] <= a[5] + slack && a[0] <= b[3] + slack && b[0] <= a[3] + slack;
1691
+ }
1692
+ function nearHit(a, b, eps, minArea) {
1693
+ const facing = a.n[0] * b.n[0] + a.n[1] * b.n[1] + a.n[2] * b.n[2];
1694
+ if (Math.abs(facing) < PARALLEL) return void 0;
1695
+ if (facing < 0 && !(a.doubleSided || b.doubleSided)) return void 0;
1696
+ const drop = dominantAxis(a.n);
1697
+ const overlap = overlapOfTriangles(projectTriangle(a.triangle, drop), projectTriangle(b.triangle, drop));
1698
+ if (!overlap || overlap.area < minArea) return void 0;
1699
+ const point = unprojectPoint(overlap.center, drop, a);
1700
+ const separation = Math.abs(b.n[0] * point[0] + b.n[1] * point[1] + b.n[2] * point[2] - b.offset);
1701
+ if (separation >= eps) return void 0;
1702
+ if (facing > 0 && drawAlike(a, b, point)) return void 0;
1703
+ return { normal: a.n, offset: a.offset, area: overlap.area, point, labelA: a.label, labelB: b.label, batchA: a.batchIndex, batchB: b.batchIndex, kind: facing > 0 ? "coplanar" : "opposed", separation };
1704
+ }
1705
+ var CELL = 2;
1706
+ var LARGE_CELLS = 64;
1707
+ function nearCoincidentFaces(batches, options) {
1708
+ const eps = depthResolution(options.depth);
1709
+ const minArea = options.minArea ?? 1e-4;
1710
+ const maxHits = options.maxHits ?? 200;
1711
+ const maxPerPair = options.maxPerPair ?? DEFAULT_MAX_PER_PAIR;
1712
+ const faces = facesOf(batches);
1713
+ const perPair = /* @__PURE__ */ new Map();
1714
+ const hits = [];
1715
+ const cells = /* @__PURE__ */ new Map();
1716
+ const large = [];
1717
+ const seen = new Int32Array(faces.length).fill(-1);
1718
+ const cellKey = (x, y, z) => ((x + 4096) * 8192 + (y + 4096)) * 8192 + (z + 4096);
1719
+ const range2 = (lo, hi) => [Math.floor((lo - eps) / CELL), Math.floor((hi + eps) / CELL)];
1720
+ const consider = (index, otherIndex) => {
1721
+ const face = faces[index], other = faces[otherIndex];
1722
+ if (Math.abs(face.n[0] * other.n[0] + face.n[1] * other.n[1] + face.n[2] * other.n[2]) < PARALLEL) return false;
1723
+ if (!touch(other.box, face.box, eps)) return false;
1724
+ const hit = nearHit(other, face, eps, minArea);
1725
+ if (!hit) return false;
1726
+ const [first, second] = [kindOf(other.label), kindOf(face.label)].sort();
1727
+ const key = `${first}|${second}|${hit.kind}`;
1728
+ const count = perPair.get(key) ?? 0;
1729
+ if (count >= maxPerPair) return false;
1730
+ perPair.set(key, count + 1);
1731
+ hits.push(hit);
1732
+ return hits.length >= maxHits;
1733
+ };
1734
+ for (let index = 0; index < faces.length; index++) {
1735
+ const face = faces[index];
1736
+ const [x0, x1] = range2(face.box[0], face.box[3]), [y0, y1] = range2(face.box[1], face.box[4]), [z0, z1] = range2(face.box[2], face.box[5]);
1737
+ const span = (x1 - x0 + 1) * (y1 - y0 + 1) * (z1 - z0 + 1);
1738
+ if (span > LARGE_CELLS) {
1739
+ for (let other = 0; other < index; other++) if (consider(index, other)) return hits;
1740
+ large.push(index);
1741
+ continue;
1742
+ }
1743
+ for (const otherIndex of large) if (consider(index, otherIndex)) return hits;
1744
+ for (let x = x0; x <= x1; x++) for (let y = y0; y <= y1; y++) for (let z = z0; z <= z1; z++) {
1745
+ const key = cellKey(x, y, z);
1746
+ const list2 = cells.get(key);
1747
+ if (!list2) {
1748
+ cells.set(key, [index]);
1749
+ continue;
1750
+ }
1751
+ for (const otherIndex of list2) {
1752
+ if (seen[otherIndex] === index) continue;
1753
+ seen[otherIndex] = index;
1754
+ if (consider(index, otherIndex)) return hits;
1755
+ }
1756
+ list2.push(index);
1757
+ }
1758
+ }
1759
+ return hits;
1760
+ }
1627
1761
  var NORMAL_STEP = 2e-3;
1628
1762
  function trianglesOf(batch) {
1629
1763
  const { positions: p, indices } = batch;
@@ -1638,10 +1772,6 @@ var GameShapesThree = (() => {
1638
1772
  function directionKey(n) {
1639
1773
  return n.map((c) => Math.round(c / NORMAL_STEP)).join(",");
1640
1774
  }
1641
- function boxOf(t) {
1642
- const xs = [t[0][0], t[1][0], t[2][0]], ys = [t[0][1], t[1][1], t[2][1]], zs = [t[0][2], t[1][2], t[2][2]];
1643
- return [Math.min(...xs), Math.min(...ys), Math.min(...zs), Math.max(...xs), Math.max(...ys), Math.max(...zs)];
1644
- }
1645
1775
  function boxesTouch(a, b, slack) {
1646
1776
  return a[0] <= b[3] + slack && b[0] <= a[3] + slack && a[1] <= b[4] + slack && b[1] <= a[4] + slack && a[2] <= b[5] + slack && b[2] <= a[5] + slack;
1647
1777
  }
@@ -1655,7 +1785,7 @@ var GameShapesThree = (() => {
1655
1785
  const offset = n[0] * triangle[0][0] + n[1] * triangle[0][1] + n[2] * triangle[0][2];
1656
1786
  const key = `${directionKey(n)}|${Math.floor(offset / eps)}`;
1657
1787
  const list2 = buckets.get(key) ?? [];
1658
- list2.push({ triangle, n, offset, label, box: boxOf(triangle) });
1788
+ list2.push({ triangle, n, offset, label, batch: index, box: boxOf(triangle) });
1659
1789
  buckets.set(key, list2);
1660
1790
  }
1661
1791
  });
@@ -1666,9 +1796,10 @@ var GameShapesThree = (() => {
1666
1796
  const overlap = overlapOfTriangles(projectTriangle(a.triangle, drop), projectTriangle(b.triangle, drop));
1667
1797
  if (!overlap || overlap.area < minArea) return void 0;
1668
1798
  const point = unprojectPoint(overlap.center, drop, a);
1669
- return { normal: a.n, offset: a.offset, area: overlap.area, point, labelA: a.label, labelB: b.label };
1799
+ return { normal: a.n, offset: a.offset, area: overlap.area, point, labelA: a.label, labelB: b.label, batchA: a.batch, batchB: b.batch };
1670
1800
  }
1671
1801
  function coincidentFaces(batches, options = {}) {
1802
+ if (options.depth) return nearCoincidentFaces(batches, options);
1672
1803
  const eps = options.eps ?? 1e-3;
1673
1804
  const minArea = options.minArea ?? 1e-4;
1674
1805
  const maxHits = options.maxHits ?? 200;
@@ -2079,6 +2210,35 @@ var GameShapesThree = (() => {
2079
2210
  return !!o && o.isMesh === true;
2080
2211
  }
2081
2212
 
2213
+ // src/position-writes.ts
2214
+ var KEPT = 256;
2215
+ var declared = /* @__PURE__ */ new WeakMap();
2216
+ function markPositionsWritten(mesh2, v0, v1) {
2217
+ const position = mesh2.geometry?.getAttribute("position");
2218
+ if (!position) return;
2219
+ position.needsUpdate = true;
2220
+ if (v1 <= v0) return;
2221
+ let log = declared.get(position);
2222
+ if (!log) {
2223
+ log = /* @__PURE__ */ new Map();
2224
+ declared.set(position, log);
2225
+ }
2226
+ const ranges = log.get(position.version);
2227
+ if (ranges) ranges.push([v0, v1]);
2228
+ else log.set(position.version, [[v0, v1]]);
2229
+ if (log.size > KEPT) log.delete(log.keys().next().value);
2230
+ }
2231
+ function rangesWrittenSince(position, version) {
2232
+ const log = declared.get(position);
2233
+ const out = [];
2234
+ for (let v = version + 1; v <= position.version; v++) {
2235
+ const ranges = log?.get(v);
2236
+ if (!ranges) return null;
2237
+ out.push(...ranges);
2238
+ }
2239
+ return out;
2240
+ }
2241
+
2082
2242
  // src/coincident.ts
2083
2243
  function isFartherLevel(o) {
2084
2244
  const lod = o.parent;
@@ -2118,35 +2278,152 @@ var GameShapesThree = (() => {
2118
2278
  }
2119
2279
  return out;
2120
2280
  }
2281
+ var DOUBLE_SIDE = 2;
2282
+ function isDoubleSided(mesh2) {
2283
+ const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];
2284
+ return materials.some((m) => m?.side === DOUBLE_SIDE);
2285
+ }
2286
+ var attributeValues = (attribute, size) => {
2287
+ const out = new Array(attribute.count * size);
2288
+ const read = [(i) => attribute.getX(i), (i) => attribute.getY(i), (i) => attribute.getZ(i)];
2289
+ for (let i = 0; i < attribute.count; i++) for (let k = 0; k < size; k++) out[i * size + k] = read[k](i);
2290
+ return out;
2291
+ };
2292
+ function lookOf(mesh2, geometry) {
2293
+ if (Array.isArray(mesh2.material)) return {};
2294
+ const material = mesh2.material;
2295
+ const color2 = material.vertexColors ? geometry.getAttribute("color") : void 0;
2296
+ const textured = Boolean(material.map || material.normalMap || material.bumpMap || material.alphaMap || material.roughnessMap);
2297
+ const uv = textured ? geometry.getAttribute("uv") : void 0;
2298
+ if (textured && !uv) return {};
2299
+ return { look: material.uuid, ...color2 ? { colors: attributeValues(color2, 3) } : {}, ...uv ? { uvs: attributeValues(uv, 2) } : {} };
2300
+ }
2301
+ function drawnIndices(geometry) {
2302
+ const { start, count } = geometry.drawRange;
2303
+ const index = geometry.index?.array;
2304
+ const total = index ? index.length : geometry.getAttribute("position").count;
2305
+ const end = Math.min(total, start + (Number.isFinite(count) ? count : total));
2306
+ if (index) return start === 0 && end === index.length ? index : Array.from(index).slice(start, end);
2307
+ if (start === 0 && end === total) return void 0;
2308
+ return Array.from({ length: end - start }, (_, i) => start + i);
2309
+ }
2121
2310
  function batchesOfMesh(mesh2, label) {
2311
+ const doubleSided = isDoubleSided(mesh2);
2122
2312
  const geometry = mesh2.geometry;
2123
2313
  const position = geometry?.getAttribute("position");
2124
2314
  if (!geometry || !position) return [];
2125
- const indices = geometry.index?.array;
2315
+ const indices = drawnIndices(geometry);
2126
2316
  const instanced = mesh2;
2127
- if (!instanced.isInstancedMesh) return [{ positions: worldPositions(position, mesh2.matrixWorld), ...indices ? { indices } : {}, label }];
2317
+ const look = lookOf(mesh2, geometry);
2318
+ if (!instanced.isInstancedMesh) return [{ positions: worldPositions(position, mesh2.matrixWorld), ...indices ? { indices } : {}, label, doubleSided, ...look }];
2128
2319
  const batches = [];
2129
2320
  const instance = mesh2.matrixWorld.clone();
2321
+ const tint = instanced.instanceColor;
2130
2322
  for (let i = 0; i < instanced.count; i++) {
2131
2323
  instanced.getMatrixAt(i, instance);
2132
2324
  instance.premultiply(mesh2.matrixWorld);
2133
- batches.push({ positions: worldPositions(position, instance), ...indices ? { indices } : {}, label: `${label} #${i}` });
2325
+ const instanceLook = tint && look.look !== void 0 ? { ...look, look: `${look.look}:${tint.getX(i)},${tint.getY(i)},${tint.getZ(i)}` } : look;
2326
+ batches.push({ positions: worldPositions(position, instance), ...indices ? { indices } : {}, label: `${label} #${i}`, doubleSided, ...instanceLook });
2134
2327
  }
2135
2328
  return batches;
2136
2329
  }
2137
- function coincidentBatchesOf(root, options = {}) {
2330
+ function meshBatchesOf(root, options = {}) {
2138
2331
  root.updateMatrixWorld(true);
2139
2332
  const batches = [];
2333
+ const meshes = [];
2140
2334
  root.traverse((node) => {
2141
2335
  if (!isMesh(node) || node.isSprite) return;
2142
2336
  if (!options.includeHidden && !isDrawn(node, root)) return;
2143
2337
  if (isOffsetDecal(node)) return;
2144
- batches.push(...batchesOfMesh(node, labelOf(node, root)));
2338
+ for (const batch of batchesOfMesh(node, labelOf(node, root))) {
2339
+ batches.push(batch);
2340
+ meshes.push(node);
2341
+ }
2145
2342
  });
2146
- return batches;
2343
+ return { batches, meshes };
2344
+ }
2345
+ function coincidentBatchesOf(root, options = {}) {
2346
+ return meshBatchesOf(root, options).batches;
2147
2347
  }
2148
2348
  function coincidentFacesOf(root, options = {}) {
2149
- return coincidentFaces(coincidentBatchesOf(root, options), options);
2349
+ const { batches, meshes } = meshBatchesOf(root, options);
2350
+ return coincidentFaces(batches, options).filter((hit) => writesDepth(meshes[hit.batchA]) || writesDepth(meshes[hit.batchB]));
2351
+ }
2352
+ function writesDepth(mesh2) {
2353
+ const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];
2354
+ return materials.some((m) => m.depthWrite !== false && m.depthTest !== false);
2355
+ }
2356
+
2357
+ // src/stand-out.ts
2358
+ function localSize(mesh2, out) {
2359
+ const geometry = mesh2.geometry;
2360
+ if (!geometry.boundingBox) geometry.computeBoundingBox();
2361
+ return geometry.boundingBox.getSize(out);
2362
+ }
2363
+ function volumeOf(mesh2) {
2364
+ const size = localSize(mesh2, mesh2.position.clone());
2365
+ const scale = mesh2.getWorldScale(mesh2.position.clone());
2366
+ return Math.max(Math.abs(size.x * scale.x), 1e-4) * Math.max(Math.abs(size.y * scale.y), 1e-4) * Math.max(Math.abs(size.z * scale.z), 1e-4);
2367
+ }
2368
+ function markSide(mesh2, hit, sides, way) {
2369
+ const inverse = mesh2.getWorldQuaternion(mesh2.quaternion.clone()).invert();
2370
+ const n = mesh2.position.clone().set(hit.normal[0], hit.normal[1], hit.normal[2]).applyQuaternion(inverse);
2371
+ const scale = mesh2.getWorldScale(mesh2.position.clone());
2372
+ const local = [n.x * Math.sign(scale.x || 1), n.y * Math.sign(scale.y || 1), n.z * Math.sign(scale.z || 1)];
2373
+ const axis = local.reduce((best, v, i) => Math.abs(v) > Math.abs(local[best]) ? i : best, 0);
2374
+ sides[axis * 2 + (local[axis] > 0 ? 1 : 0)] = way;
2375
+ }
2376
+ function pushSides(mesh2, sides, gap) {
2377
+ const size = localSize(mesh2, mesh2.position.clone());
2378
+ const world = mesh2.getWorldScale(mesh2.position.clone());
2379
+ const shift = mesh2.position.clone().set(0, 0, 0);
2380
+ const scale = [mesh2.scale.x, mesh2.scale.y, mesh2.scale.z];
2381
+ const extent = [size.x, size.y, size.z];
2382
+ const worldScale = [Math.abs(world.x), Math.abs(world.y), Math.abs(world.z)];
2383
+ const centre = mesh2.geometry.boundingBox.getCenter(mesh2.position.clone());
2384
+ const centres = [centre.x, centre.y, centre.z];
2385
+ for (let axis = 0; axis < 3; axis++) {
2386
+ const minus = sides[axis * 2] * gap, plus = sides[axis * 2 + 1] * gap;
2387
+ const s = extent[axis] * worldScale[axis];
2388
+ if (!minus && !plus || s < 1e-6 || s + minus + plus < s / 2) continue;
2389
+ const oldScale = scale[axis];
2390
+ scale[axis] = oldScale * (s + minus + plus) / s;
2391
+ const parentPerWorld = oldScale / worldScale[axis];
2392
+ const outward = (plus - minus) / 2 * parentPerWorld;
2393
+ const recentre = centres[axis] * (oldScale - scale[axis]);
2394
+ shift.setComponent(axis, outward + recentre);
2395
+ }
2396
+ mesh2.scale.set(scale[0], scale[1], scale[2]);
2397
+ mesh2.position.add(shift.applyQuaternion(mesh2.quaternion));
2398
+ mesh2.updateMatrixWorld(true);
2399
+ }
2400
+ function standOutCoincident(root, options = {}) {
2401
+ const gap = options.gap ?? 2e-3;
2402
+ const grown = /* @__PURE__ */ new Set();
2403
+ const volumes = /* @__PURE__ */ new Map();
2404
+ const volume = (mesh2) => volumes.get(mesh2) ?? volumes.set(mesh2, volumeOf(mesh2)).get(mesh2);
2405
+ let left = 0;
2406
+ for (let round = 0; round < (options.rounds ?? 3); round++) {
2407
+ const { batches, meshes } = meshBatchesOf(root);
2408
+ const hits = coincidentFaces(batches, { maxHits: Number.POSITIVE_INFINITY });
2409
+ left = hits.length;
2410
+ if (!left) break;
2411
+ const toPush = /* @__PURE__ */ new Map();
2412
+ for (const hit of hits) {
2413
+ const a = meshes[hit.batchA], b = meshes[hit.batchB];
2414
+ const [smaller, bigger] = volume(a) <= volume(b) ? [a, b] : [b, a];
2415
+ const mesh2 = grown.has(smaller) ? bigger : smaller;
2416
+ if (grown.has(mesh2) || mesh2.isInstancedMesh) continue;
2417
+ const sides = toPush.get(mesh2) ?? [0, 0, 0, 0, 0, 0];
2418
+ markSide(mesh2, hit, sides, 1);
2419
+ toPush.set(mesh2, sides);
2420
+ }
2421
+ for (const [mesh2, sides] of toPush) {
2422
+ pushSides(mesh2, sides, gap);
2423
+ grown.add(mesh2);
2424
+ }
2425
+ }
2426
+ return { grown: grown.size, left };
2150
2427
  }
2151
2428
  return __toCommonJS(src_exports);
2152
2429
  })();