@pascal-app/geometry-script 1.0.5 → 1.0.7

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/dist/compile.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { union } from '@pascal-app/core/polygon-boolean';
2
- import { GEOMETRY_MANIFEST_MAX_BYTES, GEOMETRY_SCRIPT_MAX_BYTES } from '@pascal-app/core/schema';
2
+ import { GEOMETRY_MANIFEST_MAX_BYTES, GEOMETRY_SCRIPT_MAX_BYTES, LightGlow, } from '@pascal-app/core/schema';
3
3
  import * as THREE from 'three';
4
4
  import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js';
5
5
  import { ConvexGeometry } from 'three/examples/jsm/geometries/ConvexGeometry.js';
@@ -12,13 +12,14 @@ import { ADDITION, Brush, DIFFERENCE, Evaluator, INTERSECTION, SUBTRACTION } fro
12
12
  import { measureCoverage } from './coverage.js';
13
13
  import { cutToRegion, hostRegion } from './cut.js';
14
14
  import { transformModule } from './transform.js';
15
+ import { readUsageShape } from './usage-shape.js';
15
16
  export const GEOMETRY_SCRIPT_LIMITS = {
16
17
  triangles: 300_000,
17
18
  materials: 32,
18
19
  extent: 60,
19
20
  };
20
21
  const csg = { ADDITION, Brush, DIFFERENCE, Evaluator, INTERSECTION, SUBTRACTION };
21
- const MODULES = {
22
+ export const MODULES = {
22
23
  three: THREE,
23
24
  'three-bvh-csg': csg,
24
25
  BufferGeometryUtils: BufferGeometryUtils,
@@ -28,7 +29,7 @@ const MODULES = {
28
29
  ParametricFunctions: ParametricFunctions,
29
30
  RoundedBoxGeometry: { RoundedBoxGeometry },
30
31
  };
31
- const LIB = {
32
+ export const LIB = {
32
33
  BufferGeometryUtils,
33
34
  ConvexGeometry,
34
35
  LoftGeometry,
@@ -164,6 +165,62 @@ function unmeasurable(root) {
164
165
  }
165
166
  return new Error('The object cannot be measured: its size is not a finite number.');
166
167
  }
168
+ /**
169
+ * Every InstancedMesh as a group of plain meshes, one per drawn instance: the bounds, the cut to a
170
+ * host's floor or face, the coverage, the triangle count and the merge read each mesh's own
171
+ * geometry and matrixWorld, so an instanced mesh would count as one copy at its own origin. The
172
+ * group takes its place with its uuid, name, transform, userData and children, so part names and
173
+ * clip targets hold; `instanceColor` becomes a vertex colour, on a vertex-coloured copy of the
174
+ * material (times the geometry's own vertex colours when the material already drew them).
175
+ */
176
+ function expandInstances(root) {
177
+ const instanced = [];
178
+ root.traverse((object) => {
179
+ if (object.isInstancedMesh)
180
+ instanced.push(object);
181
+ });
182
+ const matrix = new THREE.Matrix4();
183
+ const color = new THREE.Color();
184
+ for (const source of instanced) {
185
+ const group = THREE.Object3D.prototype.copy.call(new THREE.Group(), source, false);
186
+ group.uuid = source.uuid;
187
+ for (const child of [...source.children])
188
+ group.add(child);
189
+ const authored = Array.isArray(source.material) ? source.material : [source.material];
190
+ const tint = source.instanceColor;
191
+ const own = authored.some((m) => m.vertexColors) ? source.geometry.getAttribute('color') : null;
192
+ const materials = tint
193
+ ? authored.map((m) => Object.assign(m.clone(), { vertexColors: true }))
194
+ : authored;
195
+ const material = materials.length === 1 ? materials[0] : materials;
196
+ for (let i = 0; i < source.count; i++) {
197
+ let geometry = source.geometry;
198
+ if (tint) {
199
+ source.getColorAt(i, color);
200
+ geometry = source.geometry.clone();
201
+ const count = geometry.getAttribute('position').count;
202
+ const size = own?.itemSize ?? 3;
203
+ const values = new Float32Array(count * size);
204
+ for (let v = 0; v < count; v++) {
205
+ values[v * size] = color.r * (own ? own.getX(v) : 1);
206
+ values[v * size + 1] = color.g * (own ? own.getY(v) : 1);
207
+ values[v * size + 2] = color.b * (own ? own.getZ(v) : 1);
208
+ if (own && size === 4)
209
+ values[v * 4 + 3] = own.getW(v);
210
+ }
211
+ geometry.setAttribute('color', new THREE.BufferAttribute(values, size));
212
+ }
213
+ const mesh = new THREE.Mesh(geometry, material);
214
+ // A helper stays one: each copy of an instanced cutout or collider is one too.
215
+ if (isHelper(source))
216
+ mesh.name = source.name;
217
+ source.getMatrixAt(i, matrix);
218
+ matrix.decompose(mesh.position, mesh.quaternion, mesh.scale);
219
+ group.add(mesh);
220
+ }
221
+ source.parent?.add(group).remove(source);
222
+ }
223
+ }
167
224
  /** The meshes that draw: helpers (cutout, collider), and anything under one, do not. */
168
225
  function visibleMeshes(root) {
169
226
  const meshes = [];
@@ -200,6 +257,40 @@ function originFor(box, mount) {
200
257
  }
201
258
  const round = (v) => Math.round(v * 1e6) / 1e6;
202
259
  const vec = (v) => [round(v.x), round(v.y), round(v.z)];
260
+ /**
261
+ * A SpotLight's beam in the artifact frame. A target the script never added to the scene is a
262
+ * point in the script's own frame, as three.js reads an unparented target in world space.
263
+ */
264
+ function readSpot(light, root, id) {
265
+ const from = light.getWorldPosition(new THREE.Vector3());
266
+ let to;
267
+ if (light.target.parent)
268
+ to = light.target.getWorldPosition(new THREE.Vector3());
269
+ else {
270
+ let frame = light;
271
+ while (frame.parent && frame.parent !== root)
272
+ frame = frame.parent;
273
+ to = frame.parent ? frame.localToWorld(light.target.position.clone()) : light.target.position;
274
+ }
275
+ const direction = to.sub(from);
276
+ if (direction.lengthSq() < 1e-12)
277
+ throw new Error(`Spot light "${id}" targets its own position`);
278
+ direction.normalize();
279
+ return {
280
+ direction: vec(direction),
281
+ angle: Math.min(179, Math.max(1, round(THREE.MathUtils.radToDeg(light.angle * 2)))),
282
+ softness: Math.min(1, Math.max(0, round(light.penumbra))),
283
+ };
284
+ }
285
+ /** `userData.glow = { size, strength }` (strength defaults to 1). */
286
+ function readGlow(value, id) {
287
+ if (value === undefined)
288
+ return undefined;
289
+ const glow = LightGlow.safeParse(value);
290
+ if (!glow.success)
291
+ throw new Error(`Light "${id}": glow must be { size: metres across (0–5), strength: 0–10 }, got ${JSON.stringify(value)}`);
292
+ return glow.data;
293
+ }
203
294
  /**
204
295
  * Reads the naming conventions into the manifest and rewrites the output so
205
296
  * they survive glTF: GLTFLoader strips ':' from node names, so convention ids
@@ -267,6 +358,15 @@ function readConventions(root) {
267
358
  color,
268
359
  intensity,
269
360
  distance,
361
+ spot: light.isSpotLight
362
+ ? readSpot(light, root, lightId)
363
+ : undefined,
364
+ shadows: typeof userData.shadows === 'boolean'
365
+ ? userData.shadows
366
+ : light.isLight && light.castShadow
367
+ ? true
368
+ : undefined,
369
+ glow: readGlow(userData.glow, lightId),
270
370
  });
271
371
  toRemove.push(object);
272
372
  return;
@@ -511,23 +611,41 @@ function flipWinding(source) {
511
611
  * so a double-sided plane shows nothing from behind. The back face is baked into
512
612
  * the geometry instead: the triangles again, wound the other way with their
513
613
  * normals negated; a back-side material keeps only that copy. Runs before the
514
- * triangle count and the merge, so both see what is exported.
614
+ * triangle count and the merge, so both see what is exported. Materials turn
615
+ * front-side only once every mesh is baked: a material shared by several
616
+ * meshes (a pair of curtains) must still read as double-sided on the last one.
515
617
  */
516
618
  function bakeBackFaces(root) {
619
+ const sided = [];
517
620
  root.traverse((object) => {
518
621
  const mesh = object;
519
622
  if (!mesh.isMesh || isHelper(mesh) || Array.isArray(mesh.material))
520
623
  return;
521
- const { side } = mesh.material;
522
- if (side === THREE.FrontSide)
523
- return;
624
+ if (mesh.material.side !== THREE.FrontSide)
625
+ sided.push(mesh);
626
+ });
627
+ for (const mesh of sided) {
524
628
  const back = flipWinding(mesh.geometry);
525
629
  mesh.geometry =
526
- side === THREE.BackSide
630
+ mesh.material.side === THREE.BackSide
527
631
  ? back
528
632
  : (BufferGeometryUtils.mergeGeometries([mesh.geometry.toNonIndexed(), back]) ??
529
633
  mesh.geometry);
634
+ }
635
+ for (const mesh of sided)
530
636
  mesh.material.side = THREE.FrontSide;
637
+ }
638
+ /**
639
+ * The bake and the merge leave every triangle with its own three vertices, three
640
+ * times what a smooth surface needs: an 82k-triangle bed was a 6 MB GLB.
641
+ * Vertices equal in every attribute are shared again, so hard edges (their
642
+ * normals differ) stay split and the exported shape is the same.
643
+ */
644
+ function weldVertices(root) {
645
+ root.traverse((object) => {
646
+ const mesh = object;
647
+ if (mesh.isMesh && !isHelper(mesh) && !mesh.geometry.index)
648
+ mesh.geometry = BufferGeometryUtils.mergeVertices(mesh.geometry);
531
649
  });
532
650
  }
533
651
  /**
@@ -797,10 +915,13 @@ async function digest(bytes) {
797
915
  * floor or face they describe and measures how much of it the build covers), reads the conventions into the manifest,
798
916
  * samples its clips and exports the GLB. `built.animations` holds its clips.
799
917
  */
800
- export async function finishBuild({ built, mount, specs, params, code, language, inputs, }) {
918
+ export async function finishBuild({ built, mount, specs, params, code, language, inputs, usageShape, }) {
801
919
  const root = new THREE.Group();
802
920
  root.name = 'pascal_script_root';
803
921
  root.add(built);
922
+ expandInstances(root);
923
+ // A build that is itself an InstancedMesh has given its place to its group.
924
+ const model = root.children[0];
804
925
  const box = visibleBounds(root);
805
926
  if (box.isEmpty())
806
927
  throw new Error('build() returned no visible meshes');
@@ -812,9 +933,9 @@ export async function finishBuild({ built, mount, specs, params, code, language,
812
933
  throw new Error(`The object is ${vec(size).join(' × ')} m; the limit is ${GEOMETRY_SCRIPT_LIMITS.extent} m per side. Units are metres.`);
813
934
  }
814
935
  if (!inputs)
815
- built.position.sub(originFor(box, mount));
936
+ model.position.sub(originFor(box, mount));
816
937
  root.updateWorldMatrix(true, true);
817
- const read = readAnimations(built, root);
938
+ const read = readAnimations(model, root);
818
939
  const clips = sampleTransformClips(root, read.clips);
819
940
  const animated = read.animated;
820
941
  const region = inputs && hostRegion(inputs);
@@ -835,7 +956,9 @@ export async function finishBuild({ built, mount, specs, params, code, language,
835
956
  throw new Error(`${conventions.materialCount} materials exceeds the ${GEOMETRY_SCRIPT_LIMITS.materials} limit`);
836
957
  }
837
958
  const { surfaces, undersides } = analyseGeometry(root, conventions.parts);
959
+ const shape = usageShape ? readUsageShape(visibleMeshes(root)) : null;
838
960
  mergeByPartAndMaterial(root, animated);
961
+ weldVertices(root);
839
962
  const bounds = visibleBounds(root);
840
963
  const glb = await exportGlb(root, clips);
841
964
  return {
@@ -862,12 +985,13 @@ export async function finishBuild({ built, mount, specs, params, code, language,
862
985
  cutout: conventions.cutout,
863
986
  collider: conventions.collider,
864
987
  triangles: conventions.triangles,
988
+ ...(shape ? { shape } : {}),
865
989
  ...coverage,
866
990
  }),
867
991
  };
868
992
  }
869
993
  // A deterrent, not the isolation boundary: hosts run this in a locked-down worker or process.
870
- const SOURCE_GUARD = /\bimport\s*\(|\beval\s*\(|\bFunction\s*\(|\.constructor\s*\(|\bprocess\b|\brequire\s*\(/;
994
+ export const SOURCE_GUARD = /\bimport\s*\(|\beval\s*\(|\bFunction\s*\(|\.constructor\s*\(|\bprocess\b|\brequire\s*\(/;
871
995
  export function assertScriptSize(code) {
872
996
  if (new TextEncoder().encode(code).byteLength > GEOMETRY_SCRIPT_MAX_BYTES) {
873
997
  throw new Error(`The script is longer than ${GEOMETRY_SCRIPT_MAX_BYTES / 1024} KiB`);
@@ -908,5 +1032,6 @@ export async function compileGeometryScript(input) {
908
1032
  code: input.code,
909
1033
  language: 'three',
910
1034
  inputs: input.inputs,
1035
+ usageShape: input.usageShape,
911
1036
  });
912
1037
  }
package/dist/cut.d.ts CHANGED
@@ -11,14 +11,16 @@ export type HostRegion = {
11
11
  };
12
12
  /**
13
13
  * The region a build for these inputs is cut to: a floor's `polygon` less its `holes`, or a wall
14
- * face's `outline` less its `holes` (rectangles); null when the inputs describe neither.
14
+ * face's `outline` less its `holes` (rectangles, each grown by OPENING_MARGIN); null when the
15
+ * inputs describe neither.
15
16
  */
16
17
  export declare function hostRegion(inputs: Record<string, unknown>): HostRegion | null;
17
18
  /**
18
19
  * Cuts each visible mesh of a host's build to its region: whole inside, it is kept untouched;
19
20
  * whole outside or in a hole, it is dropped; across the boundary, it is intersected with the
20
21
  * region's prism (a closed mesh gains the cut faces, an open one is trimmed), keeping its
21
- * material, and dropped if nothing is left. `extent` is the build's visible bounds.
22
+ * material, and dropped if nothing is left. A mesh under another is cut to the region inset by
23
+ * its layer steps. `extent` is the build's visible bounds.
22
24
  */
23
25
  export declare function cutToRegion(meshes: THREE.Mesh[], region: HostRegion, extent: THREE.Box3): void;
24
26
  //# sourceMappingURL=cut.d.ts.map
package/dist/cut.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cut.d.ts","sourceRoot":"","sources":["../src/cut.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAAK,YAAY,EAAa,MAAM,kCAAkC,CAAA;AAC3F,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAG9B;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG;IAAE,IAAI,EAAE,GAAG,GAAG,GAAG,CAAC;IAAC,IAAI,EAAE,YAAY,CAAA;CAAE,CAAA;AAsBhE;;;GAGG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,GAAG,IAAI,CAU7E;AAiID;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,IAAI,QA0CvF"}
1
+ {"version":3,"file":"cut.d.ts","sourceRoot":"","sources":["../src/cut.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAAK,YAAY,EAAoB,MAAM,kCAAkC,CAAA;AAClG,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAG9B;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG;IAAE,IAAI,EAAE,GAAG,GAAG,GAAG,CAAC;IAAC,IAAI,EAAE,YAAY,CAAA;CAAE,CAAA;AA6BhE;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,GAAG,IAAI,CAiB7E;AAiMD;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,IAAI,QAmEvF"}
package/dist/cut.js CHANGED
@@ -1,4 +1,4 @@
1
- import { difference } from '@pascal-app/core/polygon-boolean';
1
+ import { difference, union } from '@pascal-app/core/polygon-boolean';
2
2
  import * as THREE from 'three';
3
3
  import { Brush, Evaluator, HOLLOW_INTERSECTION, INTERSECTION } from 'three-bvh-csg';
4
4
  const isPoint = (point) => Array.isArray(point) && Number.isFinite(point[0]) && Number.isFinite(point[1]);
@@ -13,9 +13,16 @@ const rectRing = ({ x0, y0, x1, y1 }) => [
13
13
  [x0, y1],
14
14
  ];
15
15
  const pieces = (rings) => rings.map((outer) => ({ outer, holes: [] }));
16
+ /**
17
+ * How far a face's finish stops short of each door and window, all round. The frame, its sill, a
18
+ * casing and the wall's reveal stand on the opening's edges: a finish cut exactly there would close
19
+ * with faces in their planes, and two faces in one plane flicker.
20
+ */
21
+ const OPENING_MARGIN = 0.001;
16
22
  /**
17
23
  * The region a build for these inputs is cut to: a floor's `polygon` less its `holes`, or a wall
18
- * face's `outline` less its `holes` (rectangles); null when the inputs describe neither.
24
+ * face's `outline` less its `holes` (rectangles, each grown by OPENING_MARGIN); null when the
25
+ * inputs describe neither.
19
26
  */
20
27
  export function hostRegion(inputs) {
21
28
  const holes = Array.isArray(inputs.holes) ? inputs.holes : [];
@@ -23,7 +30,12 @@ export function hostRegion(inputs) {
23
30
  return { axis: 'y', area: difference(inputs.polygon, pieces(holes.filter(isRing))) };
24
31
  }
25
32
  if (isRect(inputs.outline)) {
26
- const rings = holes.filter(isRect).map(rectRing);
33
+ const rings = holes.filter(isRect).map(({ x0, y0, x1, y1 }) => rectRing({
34
+ x0: x0 - OPENING_MARGIN,
35
+ y0: y0 - OPENING_MARGIN,
36
+ x1: x1 + OPENING_MARGIN,
37
+ y1: y1 + OPENING_MARGIN,
38
+ }));
27
39
  return { axis: 'z', area: difference(rectRing(inputs.outline), pieces(rings)) };
28
40
  }
29
41
  return null;
@@ -101,8 +113,64 @@ function placement(area, span) {
101
113
  }
102
114
  return regionHolds(area, [(u0 + u1) / 2, (v0 + v1) / 2]) ? 'inside' : 'outside';
103
115
  }
104
- /** The region as a closed prism spanning `extent` (plus MARGIN) along its axis, in the build's frame. */
105
- function regionPrism({ axis, area }, extent) {
116
+ /**
117
+ * How much farther from the cut each layer of a finish stops than the layer over it (a grout bed
118
+ * under its tiles, mortar behind brick slips). Cut at one edge, both would close with a face in one
119
+ * plane, which flickers; a step apart, the one behind closes inside the one in front. 1 mm, as a
120
+ * face script stands off its wall: the views resolve it.
121
+ */
122
+ const LAYER_STEP = 0.001;
123
+ /** A layer deeper than this stops with the last: finishes are a few layers deep. */
124
+ const MAX_LAYER_STEPS = 4;
125
+ /** Fronts this close are one layer: tiles laid a hair proud of their neighbours are not stacked. */
126
+ const LAYER_TOLERANCE = 1e-4;
127
+ const overlaps = (a, b) => a.u0 < b.u1 - EDGE && b.u0 < a.u1 - EDGE && a.v0 < b.v1 - EDGE && b.v0 < a.v1 - EDGE;
128
+ /**
129
+ * How many steps back from the cut each mesh near it stops: none with nothing over it, else one
130
+ * more than the farthest-stopped mesh over it (their bounds overlap in the plane and its front
131
+ * stands farther out along the axis). A mesh away from the cut has no cut face to keep apart.
132
+ */
133
+ function layerSteps(near) {
134
+ const steps = new Map();
135
+ const outermostFirst = [...near].sort((a, b) => b.front - a.front);
136
+ outermostFirst.forEach((layer, index) => {
137
+ let step = 0;
138
+ for (let k = 0; k < index; k++) {
139
+ const over = outermostFirst[k];
140
+ if (over.front > layer.front + LAYER_TOLERANCE && overlaps(over.span, layer.span)) {
141
+ step = Math.max(step, Math.min(MAX_LAYER_STEPS, steps.get(over.mesh) + 1));
142
+ }
143
+ }
144
+ steps.set(layer.mesh, step);
145
+ });
146
+ return steps;
147
+ }
148
+ /** The area less a band `by` wide inside its boundary: each edge's band, squared off past its ends. */
149
+ function insetArea(area, by) {
150
+ const bands = [];
151
+ for (const { outer, holes } of area) {
152
+ for (const ring of [outer, ...holes]) {
153
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
154
+ const [au, av] = ring[j];
155
+ const [bu, bv] = ring[i];
156
+ const length = Math.hypot(bu - au, bv - av);
157
+ if (length === 0)
158
+ continue;
159
+ const tu = ((bu - au) / length) * by;
160
+ const tv = ((bv - av) / length) * by;
161
+ bands.push([
162
+ [au - tu + tv, av - tv - tu],
163
+ [bu + tu + tv, bv + tv - tu],
164
+ [bu + tu - tv, bv + tv + tu],
165
+ [au - tu - tv, av - tv + tu],
166
+ ]);
167
+ }
168
+ }
169
+ }
170
+ return difference(area, union(bands));
171
+ }
172
+ /** The area as a closed prism spanning `extent` (plus MARGIN) along `axis`, in the build's frame. */
173
+ function regionPrism(axis, area, extent) {
106
174
  // A floor's plan v is world z; the shape is drawn at -z so turning it up (-90° about x) lands it at +z.
107
175
  const flip = axis === 'y' ? -1 : 1;
108
176
  const shapes = area.map(({ outer, holes }) => {
@@ -153,25 +221,41 @@ const triangles = (geometry) => Math.floor((geometry.index?.count ?? geometry.ge
153
221
  * Cuts each visible mesh of a host's build to its region: whole inside, it is kept untouched;
154
222
  * whole outside or in a hole, it is dropped; across the boundary, it is intersected with the
155
223
  * region's prism (a closed mesh gains the cut faces, an open one is trimmed), keeping its
156
- * material, and dropped if nothing is left. `extent` is the build's visible bounds.
224
+ * material, and dropped if nothing is left. A mesh under another is cut to the region inset by
225
+ * its layer steps. `extent` is the build's visible bounds.
157
226
  */
158
227
  export function cutToRegion(meshes, region, extent) {
159
- const box = new THREE.Box3();
160
- let prism;
161
- const brushes = new Map();
162
- const evaluator = new Evaluator();
163
- for (const mesh of meshes) {
228
+ const reach = LAYER_STEP * MAX_LAYER_STEPS;
229
+ const layers = meshes.map((mesh) => {
164
230
  mesh.geometry.computeBoundingBox();
165
- box.copy(mesh.geometry.boundingBox).applyMatrix4(mesh.matrixWorld);
166
- const where = placement(region.area, planeSpan(box, region.axis));
231
+ const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);
232
+ return { mesh, span: planeSpan(box, region.axis), front: box.max[region.axis] };
233
+ });
234
+ const steps = layerSteps(layers.filter(({ span }) => placement(region.area, {
235
+ u0: span.u0 - reach,
236
+ u1: span.u1 + reach,
237
+ v0: span.v0 - reach,
238
+ v1: span.v1 + reach,
239
+ }) === 'boundary'));
240
+ const cuts = new Map();
241
+ const evaluator = new Evaluator();
242
+ for (const { mesh, span } of layers) {
243
+ const step = steps.get(mesh) ?? 0;
244
+ let cut = cuts.get(step);
245
+ if (!cut) {
246
+ const area = step ? insetArea(region.area, step * LAYER_STEP) : region.area;
247
+ cut = { area, brushes: new Map() };
248
+ cuts.set(step, cut);
249
+ }
250
+ const where = placement(cut.area, span);
167
251
  if (where === 'inside')
168
252
  continue;
169
253
  if (where === 'outside') {
170
254
  mesh.removeFromParent();
171
255
  continue;
172
256
  }
173
- prism ??= regionPrism(region, extent);
174
- const target = prismBrush(prism, mesh.geometry, brushes);
257
+ cut.prism ??= regionPrism(region.axis, cut.area, extent);
258
+ const target = prismBrush(cut.prism, mesh.geometry, cut.brushes);
175
259
  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
176
260
  target.material = materials[0];
177
261
  const source = new Brush(mesh.geometry.clone(), mesh.material);
@@ -196,7 +280,9 @@ export function cutToRegion(meshes, region, extent) {
196
280
  else
197
281
  mesh.material = kept;
198
282
  }
199
- prism?.dispose();
200
- for (const brush of brushes.values())
201
- brush.geometry.dispose();
283
+ for (const { prism, brushes } of cuts.values()) {
284
+ prism?.dispose();
285
+ for (const brush of brushes.values())
286
+ brush.geometry.dispose();
287
+ }
202
288
  }
@@ -0,0 +1,17 @@
1
+ import * as THREE from 'three';
2
+ /** A design module is a whole building, so it is allowed far more than an object's 48 KB. */
3
+ export declare const DESIGN_MODULE_MAX_BYTES: number;
4
+ /** A design built: its scene, world matrices updated. */
5
+ export type BuiltDesign = {
6
+ scene: THREE.Scene;
7
+ /** `addons.<name>` the design asked for that Pascal's compiler does not carry. */
8
+ missingAddons: string[];
9
+ };
10
+ /** A model's module, with its imports bound to what the compiler carries; `what` names it in errors. */
11
+ export declare function loadModule(code: string, what: string): (ctx: unknown) => unknown;
12
+ /**
13
+ * Builds the design as Pascal runs it: its `build`, by name or as its default, is called with
14
+ * `{ THREE, scene, addons }`; it adds to the scene, or returns a group, which is added.
15
+ */
16
+ export declare function buildDesign(code: string): Promise<BuiltDesign>;
17
+ //# sourceMappingURL=design.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"design.d.ts","sourceRoot":"","sources":["../src/design.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAI9B,6FAA6F;AAC7F,eAAO,MAAM,uBAAuB,QAAa,CAAA;AAEjD,yDAAyD;AACzD,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,EAAE,KAAK,CAAC,KAAK,CAAA;IAClB,kFAAkF;IAClF,aAAa,EAAE,MAAM,EAAE,CAAA;CACxB,CAAA;AAWD,wGAAwG;AACxG,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAgB1B,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CACnD;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAgBpE"}
package/dist/design.js ADDED
@@ -0,0 +1,52 @@
1
+ // Runs a whole design written as free three.js (a house: walls, windows, rooms, a roof) where every
2
+ // other three.js module runs: in the isolated compiler, never in a host process, for the adapter
3
+ // that converts it (`adapter.ts`). Nothing is compiled to a GLB here.
4
+ import * as THREE from 'three';
5
+ import { LIB, MODULES, SOURCE_GUARD } from './compile.js';
6
+ import { transformModule } from './transform.js';
7
+ /** A design module is a whole building, so it is allowed far more than an object's 48 KB. */
8
+ export const DESIGN_MODULE_MAX_BYTES = 400 * 1024;
9
+ /** What `addons` holds: the three.js addons Pascal's compiler carries. */
10
+ const ADDONS = {
11
+ ...LIB.BufferGeometryUtils,
12
+ ...LIB.ParametricFunctions,
13
+ ConvexGeometry: LIB.ConvexGeometry,
14
+ ParametricGeometry: LIB.ParametricGeometry,
15
+ RoundedBoxGeometry: LIB.RoundedBoxGeometry,
16
+ };
17
+ /** A model's module, with its imports bound to what the compiler carries; `what` names it in errors. */
18
+ export function loadModule(code, what) {
19
+ if (code.length > DESIGN_MODULE_MAX_BYTES)
20
+ throw new Error(`The ${what} module exceeds ${DESIGN_MODULE_MAX_BYTES / 1024} KB`);
21
+ if (SOURCE_GUARD.test(code))
22
+ throw new Error(`The ${what} module cannot use dynamic import, eval, Function constructors, process or require`);
23
+ // Evaluating the model's module is this function's job; callers run it in a locked-down process.
24
+ const factory = new Function('__modules', 'THREE', 'lib', transformModule(code, MODULES));
25
+ const exported = factory(MODULES, THREE, LIB);
26
+ if (typeof exported.build !== 'function')
27
+ throw new Error(`The ${what} module must export its function as default (or named build)`);
28
+ return exported.build;
29
+ }
30
+ /**
31
+ * Builds the design as Pascal runs it: its `build`, by name or as its default, is called with
32
+ * `{ THREE, scene, addons }`; it adds to the scene, or returns a group, which is added.
33
+ */
34
+ export async function buildDesign(code) {
35
+ const build = loadModule(code, 'design');
36
+ const missing = new Set();
37
+ const addons = new Proxy(ADDONS, {
38
+ get(target, name) {
39
+ if (typeof name === 'string' && name !== 'then' && !(name in target))
40
+ missing.add(name);
41
+ return typeof name === 'string' ? target[name] : undefined;
42
+ },
43
+ });
44
+ const scene = new THREE.Scene();
45
+ const built = await build({ THREE, scene, addons, lib: LIB, params: {} });
46
+ if (built instanceof THREE.Object3D && built !== scene && !built.parent)
47
+ scene.add(built);
48
+ if (!scene.children.length)
49
+ throw new Error('build() added nothing to the scene and returned nothing');
50
+ scene.updateMatrixWorld(true);
51
+ return { scene, missingAddons: [...missing] };
52
+ }
@@ -40,9 +40,9 @@ for (const name of BLOCKED) {
40
40
  }
41
41
  }
42
42
  self.addEventListener('message', async (event) => {
43
- const { id, code, params, inputs } = event.data;
43
+ const { id, code, params, inputs, usageShape } = event.data;
44
44
  try {
45
- const output = await compileGeometryScript({ code, params, inputs });
45
+ const output = await compileGeometryScript({ code, params, inputs, usageShape });
46
46
  post({ id, ok: true, output }, [output.glb]);
47
47
  }
48
48
  catch (error) {