@selvajs/compute 3.1.0-beta.3 → 3.1.0-beta.4

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 (47) hide show
  1. package/dist/chunk-33753HSV.cjs +2 -0
  2. package/dist/{chunk-JIE3W4KP.cjs.map → chunk-33753HSV.cjs.map} +1 -1
  3. package/dist/chunk-4JNRO7TX.cjs +62 -0
  4. package/dist/chunk-4JNRO7TX.cjs.map +1 -0
  5. package/dist/chunk-6V6SUB4V.js +62 -0
  6. package/dist/chunk-6V6SUB4V.js.map +1 -0
  7. package/dist/chunk-D7A3YIYD.cjs +4 -0
  8. package/dist/chunk-D7A3YIYD.cjs.map +1 -0
  9. package/dist/chunk-EMXDP7KY.js +4 -0
  10. package/dist/chunk-EMXDP7KY.js.map +1 -0
  11. package/dist/chunk-MDFVHHH6.js +2 -0
  12. package/dist/chunk-MDFVHHH6.js.map +1 -0
  13. package/dist/core.cjs +1 -1
  14. package/dist/core.js +1 -1
  15. package/dist/grasshopper.cjs +1 -1
  16. package/dist/grasshopper.d.cts +2 -2
  17. package/dist/grasshopper.d.ts +2 -2
  18. package/dist/grasshopper.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.d.cts +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/{types-B-JygDUF.d.ts → types-BBSF_ISX.d.ts} +32 -3
  24. package/dist/{types-DGeAQnkB.d.cts → types-DxPi5SEx.d.cts} +32 -3
  25. package/dist/visualization-3XYZHAIV.js +2 -0
  26. package/dist/visualization-DEAMRV7R.cjs +2 -0
  27. package/dist/visualization-DEAMRV7R.cjs.map +1 -0
  28. package/dist/visualization.cjs +1 -1
  29. package/dist/visualization.d.cts +44 -7
  30. package/dist/visualization.d.ts +44 -7
  31. package/dist/visualization.js +1 -1
  32. package/package.json +1 -1
  33. package/dist/chunk-CTZ4ZOSM.js +0 -2
  34. package/dist/chunk-CTZ4ZOSM.js.map +0 -1
  35. package/dist/chunk-EUMIGWRX.cjs +0 -4
  36. package/dist/chunk-EUMIGWRX.cjs.map +0 -1
  37. package/dist/chunk-HNG75VAI.js +0 -55
  38. package/dist/chunk-HNG75VAI.js.map +0 -1
  39. package/dist/chunk-JIE3W4KP.cjs +0 -2
  40. package/dist/chunk-L3CNT26S.cjs +0 -55
  41. package/dist/chunk-L3CNT26S.cjs.map +0 -1
  42. package/dist/chunk-QAOHGIFT.js +0 -4
  43. package/dist/chunk-QAOHGIFT.js.map +0 -1
  44. package/dist/visualization-SI2GEY4M.cjs +0 -2
  45. package/dist/visualization-SI2GEY4M.cjs.map +0 -1
  46. package/dist/visualization-UJZN4PJD.js +0 -2
  47. /package/dist/{visualization-UJZN4PJD.js.map → visualization-3XYZHAIV.js.map} +0 -0
@@ -213,8 +213,13 @@ interface GrasshopperComputeResponse extends GrasshopperBaseSchema, GrasshopperD
213
213
  cachesolve: boolean;
214
214
  /** Model units (always present in response) */
215
215
  modelunits: RhinoModelUnit;
216
- /** Base64 encoded algorithm (always present in response) */
217
- algo: string;
216
+ /**
217
+ * The server echoes the request's full base64 definition back as `algo`, but the client strips
218
+ * it before returning — retaining it would pin a multi-MB copy of the definition per response,
219
+ * multiplied by every cache that holds responses. Always `undefined` on client-returned
220
+ * responses (inherited optional field from {@link GrasshopperDefinitionSource}).
221
+ */
222
+ algo?: string | null;
218
223
  /** Filename of the definition (always present in response) */
219
224
  filename: string | null;
220
225
  /** Data version */
@@ -495,6 +500,30 @@ interface MeshBatchParsingOptions {
495
500
  applyTransforms?: boolean;
496
501
  /** Enable performance monitoring in console. Defaults to false. */
497
502
  debug?: boolean;
503
+ /**
504
+ * Appearance dials applied to every material built from this batch. These drive how "rendered"
505
+ * vs "matte technical" the meshes look; they are set once at parse time (materials are rebuilt
506
+ * per solve). Runtime restyling of an already-built scene lives in the viewer's `setRenderStyle`.
507
+ */
508
+ material?: MaterialAppearanceOptions;
509
+ }
510
+ /**
511
+ * How compute meshes read visually. Bundled so a caller can pick a coherent look ('technical' vs
512
+ * 'rendered') by setting all three together rather than dialing each in isolation.
513
+ */
514
+ interface MaterialAppearanceOptions {
515
+ /**
516
+ * Multiplier on the HDR image-based-lighting reflection strength. ~0.5 reads matte/technical,
517
+ * ~1.3 reads glossy/presentation. Default 1 (three.js's own default — unchanged look).
518
+ */
519
+ envMapIntensity?: number;
520
+ /**
521
+ * Cull back faces (`THREE.FrontSide`) instead of rendering both sides (`THREE.DoubleSide`).
522
+ * FrontSide gives cleaner interior shading, a crisper silhouette, and less overdraw on closed
523
+ * solids — but open surfaces (which Rhino also emits) then vanish when viewed from behind.
524
+ * Default false (keep DoubleSide) to stay safe for surface geometry.
525
+ */
526
+ cullBackfaces?: boolean;
498
527
  }
499
528
  /**
500
529
  * Options for extracting and processing meshes from compute responses.
@@ -515,4 +544,4 @@ interface MeshExtractionOptions {
515
544
  debug?: boolean;
516
545
  }
517
546
 
518
- export type { BooleanInputType as B, DataItem as D, FileInputType as F, GeometryInputType as G, InnerTreeData as I, MeshExtractionOptions as M, NumericInputType as N, OutputParamSchema as O, TextInputType as T, ValueListInputType as V, DataTree as a, DataTreeDefault as b, DataTreePath as c, DefaultValue as d, GrasshopperComputeConfig as e, GrasshopperComputeResponse as f, GrasshopperParsedIO as g, GrasshopperParsedIORaw as h, GrasshopperRequestSchema as i, InputParam as j, InputParamSchema as k, OutputType as l, MeshBatchParsingOptions as m, DisplayBatch as n, DisplayItem as o, DisplayCurve as p, DisplayIdentity as q, DisplayItemBase as r, DisplayPoint as s, DisplayPosition as t, MeshBatch as u };
547
+ export type { BooleanInputType as B, DataItem as D, FileInputType as F, GeometryInputType as G, InnerTreeData as I, MaterialAppearanceOptions as M, NumericInputType as N, OutputParamSchema as O, TextInputType as T, ValueListInputType as V, DataTree as a, DataTreeDefault as b, DataTreePath as c, DefaultValue as d, GrasshopperComputeConfig as e, GrasshopperComputeResponse as f, GrasshopperParsedIO as g, GrasshopperParsedIORaw as h, GrasshopperRequestSchema as i, InputParam as j, InputParamSchema as k, OutputType as l, MeshExtractionOptions as m, MeshBatchParsingOptions as n, DisplayBatch as o, DisplayItem as p, DisplayCurve as q, DisplayIdentity as r, DisplayItemBase as s, DisplayPoint as t, DisplayPosition as u, MeshBatch as v };
@@ -0,0 +1,2 @@
1
+ import{A as S,B as _,C as G,D as L,E as R,F as u,G as T,a as e,b as r,c as t,d as o,e as a,f as p,g as s,h as i,i as n,j as l,k as m,l as y,m as f,n as d,o as x,p as h,q as C,r as c,s as g,t as M,u as E,v as A,w as O,x as B,y as j,z as D}from"./chunk-6V6SUB4V.js";import"./chunk-EMXDP7KY.js";export{A as BINARY_MESH_MAGIC,O as BINARY_MESH_VERSION,i as EDGE_USERDATA_KIND,j as FLAG_DELTA_ENCODED,B as FLAG_FLOAT32,D as FLAG_HAS_UVS,S as FLAG_HAS_VERTEX_COLORS,M as Materials,u as SCALE_FACTORS,n as addEdges,t as applyOffset,C as clearTextureCache,o as computeCombinedBoundingBox,a as createCameraController,p as createGrid,f as createLabelLayer,x as createMeasureTool,y as createRenderPipeline,s as createViewGizmo,T as getThreeMeshesFromComputeResponse,g as initThree,l as isEdgeOverlay,c as materialAppearanceForStyle,_ as parseBinaryMeshBatch,r as parseColor,E as parseDisplayItems,G as parseMeshBatch,R as parseMeshBatchBlob,L as parseMeshBatchObject,m as removeEdges,h as setTextureAnisotropy,d as snapToVertex,e as updateScene};
2
+ //# sourceMappingURL=visualization-3XYZHAIV.js.map
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk4JNRO7TXcjs = require('./chunk-4JNRO7TX.cjs');require('./chunk-D7A3YIYD.cjs');exports.BINARY_MESH_MAGIC = _chunk4JNRO7TXcjs.v; exports.BINARY_MESH_VERSION = _chunk4JNRO7TXcjs.w; exports.EDGE_USERDATA_KIND = _chunk4JNRO7TXcjs.h; exports.FLAG_DELTA_ENCODED = _chunk4JNRO7TXcjs.y; exports.FLAG_FLOAT32 = _chunk4JNRO7TXcjs.x; exports.FLAG_HAS_UVS = _chunk4JNRO7TXcjs.z; exports.FLAG_HAS_VERTEX_COLORS = _chunk4JNRO7TXcjs.A; exports.Materials = _chunk4JNRO7TXcjs.t; exports.SCALE_FACTORS = _chunk4JNRO7TXcjs.F; exports.addEdges = _chunk4JNRO7TXcjs.i; exports.applyOffset = _chunk4JNRO7TXcjs.c; exports.clearTextureCache = _chunk4JNRO7TXcjs.q; exports.computeCombinedBoundingBox = _chunk4JNRO7TXcjs.d; exports.createCameraController = _chunk4JNRO7TXcjs.e; exports.createGrid = _chunk4JNRO7TXcjs.f; exports.createLabelLayer = _chunk4JNRO7TXcjs.m; exports.createMeasureTool = _chunk4JNRO7TXcjs.o; exports.createRenderPipeline = _chunk4JNRO7TXcjs.l; exports.createViewGizmo = _chunk4JNRO7TXcjs.g; exports.getThreeMeshesFromComputeResponse = _chunk4JNRO7TXcjs.G; exports.initThree = _chunk4JNRO7TXcjs.s; exports.isEdgeOverlay = _chunk4JNRO7TXcjs.j; exports.materialAppearanceForStyle = _chunk4JNRO7TXcjs.r; exports.parseBinaryMeshBatch = _chunk4JNRO7TXcjs.B; exports.parseColor = _chunk4JNRO7TXcjs.b; exports.parseDisplayItems = _chunk4JNRO7TXcjs.u; exports.parseMeshBatch = _chunk4JNRO7TXcjs.C; exports.parseMeshBatchBlob = _chunk4JNRO7TXcjs.E; exports.parseMeshBatchObject = _chunk4JNRO7TXcjs.D; exports.removeEdges = _chunk4JNRO7TXcjs.k; exports.setTextureAnisotropy = _chunk4JNRO7TXcjs.p; exports.snapToVertex = _chunk4JNRO7TXcjs.n; exports.updateScene = _chunk4JNRO7TXcjs.a;
2
+ //# sourceMappingURL=visualization-DEAMRV7R.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/visualization-DEAMRV7R.cjs"],"names":[],"mappings":"AAAA,iIAAwQ,gCAA6B,ujDAAsuB","file":"/home/runner/work/selva-compute/selva-compute/dist/visualization-DEAMRV7R.cjs"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkL3CNT26Scjs = require('./chunk-L3CNT26S.cjs');require('./chunk-EUMIGWRX.cjs');exports.EDGE_USERDATA_KIND = _chunkL3CNT26Scjs.h; exports.Materials = _chunkL3CNT26Scjs.q; exports.SCALE_FACTORS = _chunkL3CNT26Scjs.D; exports.addEdges = _chunkL3CNT26Scjs.i; exports.applyOffset = _chunkL3CNT26Scjs.c; exports.computeCombinedBoundingBox = _chunkL3CNT26Scjs.d; exports.createCameraController = _chunkL3CNT26Scjs.e; exports.createGrid = _chunkL3CNT26Scjs.f; exports.createLabelLayer = _chunkL3CNT26Scjs.m; exports.createMeasureTool = _chunkL3CNT26Scjs.o; exports.createRenderPipeline = _chunkL3CNT26Scjs.l; exports.createViewGizmo = _chunkL3CNT26Scjs.g; exports.getThreeMeshesFromComputeResponse = _chunkL3CNT26Scjs.E; exports.initThree = _chunkL3CNT26Scjs.p; exports.isEdgeOverlay = _chunkL3CNT26Scjs.j; exports.parseColor = _chunkL3CNT26Scjs.b; exports.parseDisplayItems = _chunkL3CNT26Scjs.r; exports.parseMeshBatchBlob = _chunkL3CNT26Scjs.C; exports.parseMeshBatchObject = _chunkL3CNT26Scjs.B; exports.removeEdges = _chunkL3CNT26Scjs.k; exports.snapToVertex = _chunkL3CNT26Scjs.n; exports.updateScene = _chunkL3CNT26Scjs.a;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk4JNRO7TXcjs = require('./chunk-4JNRO7TX.cjs');require('./chunk-D7A3YIYD.cjs');exports.EDGE_USERDATA_KIND = _chunk4JNRO7TXcjs.h; exports.Materials = _chunk4JNRO7TXcjs.t; exports.SCALE_FACTORS = _chunk4JNRO7TXcjs.F; exports.addEdges = _chunk4JNRO7TXcjs.i; exports.applyOffset = _chunk4JNRO7TXcjs.c; exports.computeCombinedBoundingBox = _chunk4JNRO7TXcjs.d; exports.createCameraController = _chunk4JNRO7TXcjs.e; exports.createGrid = _chunk4JNRO7TXcjs.f; exports.createLabelLayer = _chunk4JNRO7TXcjs.m; exports.createMeasureTool = _chunk4JNRO7TXcjs.o; exports.createRenderPipeline = _chunk4JNRO7TXcjs.l; exports.createViewGizmo = _chunk4JNRO7TXcjs.g; exports.getThreeMeshesFromComputeResponse = _chunk4JNRO7TXcjs.G; exports.initThree = _chunk4JNRO7TXcjs.s; exports.isEdgeOverlay = _chunk4JNRO7TXcjs.j; exports.parseColor = _chunk4JNRO7TXcjs.b; exports.parseDisplayItems = _chunk4JNRO7TXcjs.u; exports.parseMeshBatchBlob = _chunk4JNRO7TXcjs.E; exports.parseMeshBatchObject = _chunk4JNRO7TXcjs.D; exports.removeEdges = _chunk4JNRO7TXcjs.k; exports.snapToVertex = _chunk4JNRO7TXcjs.n; exports.updateScene = _chunk4JNRO7TXcjs.a;
2
2
  //# sourceMappingURL=visualization.cjs.map
@@ -1,9 +1,9 @@
1
1
  import * as THREE from 'three';
2
2
  import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
3
+ import { M as MaterialAppearanceOptions, f as GrasshopperComputeResponse, m as MeshExtractionOptions, n as MeshBatchParsingOptions, o as DisplayBatch, p as DisplayItem } from './types-DxPi5SEx.cjs';
4
+ export { q as DisplayCurve, r as DisplayIdentity, s as DisplayItemBase, t as DisplayPoint, u as DisplayPosition, v as MeshBatch } from './types-DxPi5SEx.cjs';
3
5
  import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
4
6
  import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
5
- import { f as GrasshopperComputeResponse, M as MeshExtractionOptions, m as MeshBatchParsingOptions, n as DisplayBatch, o as DisplayItem } from './types-DGeAQnkB.cjs';
6
- export { p as DisplayCurve, q as DisplayIdentity, r as DisplayItemBase, s as DisplayPoint, t as DisplayPosition, u as MeshBatch } from './types-DGeAQnkB.cjs';
7
7
  import { RhinoModule } from 'rhino3dm';
8
8
  import './types-V7G83j5m.cjs';
9
9
 
@@ -53,6 +53,16 @@ type RenderConfig = {
53
53
  /** AO strength 0–1 when {@link RenderConfig.ambientOcclusion} is on. Default 1. */
54
54
  aoIntensity?: number;
55
55
  };
56
+ /**
57
+ * A coherent visual look. Seeds the initial render defaults (tone mapping, AO, edges, grid, IBL
58
+ * strength) at construction and can be re-applied live via `setRenderStyle`.
59
+ *
60
+ * - 'technical': matte, drawing-like — neutral tone mapping, low IBL, edges + grid on, AO on.
61
+ * Reads like a CAD shaded view (Rhino/Onshape).
62
+ * - 'rendered': presentation — ACES-filmic tone mapping, stronger IBL, edges off, AO on. Reads
63
+ * like a Keyshot/Fusion render.
64
+ */
65
+ type RenderStyle = 'technical' | 'rendered';
56
66
  /** Crisp boundary/crease edge overlays on meshes. See `addEdges`. */
57
67
  type EdgesConfig = {
58
68
  /** Auto-attach edge overlays to meshes as they load. Default false (opt-in). */
@@ -122,6 +132,13 @@ type MeasureConfig = {
122
132
  };
123
133
  type ThreeInitializerOptions = {
124
134
  sceneScale?: 'mm' | 'cm' | 'm' | 'inches' | 'feet';
135
+ /**
136
+ * Pick a coherent look up front — seeds sensible defaults for tone mapping, AO, edges, grid, and
137
+ * IBL strength (see {@link RenderStyle}). Individual `render`/`edges`/`grid` options still win
138
+ * when set explicitly, so this only fills in what you leave unspecified. Omit for the plain
139
+ * per-field defaults (no style applied). Re-apply later via the init result's `setRenderStyle`.
140
+ */
141
+ renderStyle?: RenderStyle;
125
142
  camera?: CameraConfig;
126
143
  lighting?: LightingConfig;
127
144
  environment?: EnvironmentConfig;
@@ -412,6 +429,19 @@ declare const initThree: (canvas: HTMLCanvasElement, options?: ThreeInitializerO
412
429
  applyEdges: (root: THREE.Object3D) => void;
413
430
  /** Toggle ambient occlusion at runtime — builds or tears down the postprocessing pipeline. */
414
431
  setAmbientOcclusion: (enabled: boolean) => void;
432
+ /**
433
+ * Apply a coherent look to the already-loaded scene: 'technical' (matte/CAD — edges, grid, low
434
+ * IBL, neutral tone mapping) or 'rendered' (presentation — stronger IBL, ACES tone mapping, no
435
+ * edges). Retunes viewer-owned dials only; per-material parse choices are set via the batch
436
+ * parser's `material` option. Handy for comparing the two looks in a live viewer.
437
+ */
438
+ setRenderStyle: (style: "technical" | "rendered") => void;
439
+ /**
440
+ * The parse-time material options (backface culling, IBL strength) matching the active render
441
+ * style — feed into the batch parser's `material` option so freshly-loaded meshes are built to
442
+ * match the look. Returns undefined when no style is active. See `setRenderStyle`.
443
+ */
444
+ getMaterialAppearance: () => MaterialAppearanceOptions | undefined;
415
445
  /**
416
446
  * Refit the sun's shadow frustum to the current scene content for crisp shadows. Call after
417
447
  * loading or replacing geometry (e.g. after `updateScene`). No-op when sunlight/shadows are off.
@@ -526,11 +556,18 @@ declare function removeEdges(root: THREE.Object3D): number;
526
556
  * this when `render.ambientOcclusion` is enabled, and otherwise renders with a plain
527
557
  * `renderer.render` so the cheap path stays cheap (the chosen tradeoff — see cad-viewer-plan.md).
528
558
  *
529
- * Pipeline: RenderPass → GTAOPass → OutputPass. GTAO (ground-truth AO) is the modern replacement for
530
- * SSAO/SAO — better contact shadows in crevices, the "engineered" depth cue. `screenSpaceRadius` is
531
- * on so the AO radius is in screen space, which keeps it scale-robust across the viewer's mm→m
532
- * scenes without per-scene tuning. OutputPass applies tone mapping + color space (taking over the
533
- * roles the renderer did directly in the non-composer path).
559
+ * Pipeline: RenderPass → GTAOPass → SMAAPass → OutputPass. GTAO (ground-truth AO) is the modern
560
+ * replacement for SSAO/SAO — better contact shadows in crevices, the "engineered" depth cue.
561
+ * `screenSpaceRadius` is on so the AO radius is in screen space, which keeps it scale-robust across
562
+ * the viewer's mm→m scenes without per-scene tuning.
563
+ *
564
+ * SMAA restores antialiasing on this path. The EffectComposer renders into an offscreen target, so
565
+ * the WebGLRenderer's own MSAA (`antialias: true`) does nothing here — without a dedicated AA pass,
566
+ * enabling AO would visibly *worsen* edge quality. SMAA is chosen over TAA because TAA's temporal
567
+ * jitter smears during OrbitControls drags; SMAA is single-frame, cheap, and stable while orbiting.
568
+ *
569
+ * OutputPass applies tone mapping + color space last (taking over the roles the renderer did
570
+ * directly in the non-composer path), so SMAA operates on the pre-tonemapped image as intended.
534
571
  *
535
572
  * Camera swaps: the active camera can flip perspective↔ortho. Rather than rebuild the composer, we
536
573
  * retarget the passes' `camera` each render via {@link setCamera}.
@@ -1,9 +1,9 @@
1
1
  import * as THREE from 'three';
2
2
  import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
3
+ import { M as MaterialAppearanceOptions, f as GrasshopperComputeResponse, m as MeshExtractionOptions, n as MeshBatchParsingOptions, o as DisplayBatch, p as DisplayItem } from './types-BBSF_ISX.js';
4
+ export { q as DisplayCurve, r as DisplayIdentity, s as DisplayItemBase, t as DisplayPoint, u as DisplayPosition, v as MeshBatch } from './types-BBSF_ISX.js';
3
5
  import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
4
6
  import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
5
- import { f as GrasshopperComputeResponse, M as MeshExtractionOptions, m as MeshBatchParsingOptions, n as DisplayBatch, o as DisplayItem } from './types-B-JygDUF.js';
6
- export { p as DisplayCurve, q as DisplayIdentity, r as DisplayItemBase, s as DisplayPoint, t as DisplayPosition, u as MeshBatch } from './types-B-JygDUF.js';
7
7
  import { RhinoModule } from 'rhino3dm';
8
8
  import './types-V7G83j5m.js';
9
9
 
@@ -53,6 +53,16 @@ type RenderConfig = {
53
53
  /** AO strength 0–1 when {@link RenderConfig.ambientOcclusion} is on. Default 1. */
54
54
  aoIntensity?: number;
55
55
  };
56
+ /**
57
+ * A coherent visual look. Seeds the initial render defaults (tone mapping, AO, edges, grid, IBL
58
+ * strength) at construction and can be re-applied live via `setRenderStyle`.
59
+ *
60
+ * - 'technical': matte, drawing-like — neutral tone mapping, low IBL, edges + grid on, AO on.
61
+ * Reads like a CAD shaded view (Rhino/Onshape).
62
+ * - 'rendered': presentation — ACES-filmic tone mapping, stronger IBL, edges off, AO on. Reads
63
+ * like a Keyshot/Fusion render.
64
+ */
65
+ type RenderStyle = 'technical' | 'rendered';
56
66
  /** Crisp boundary/crease edge overlays on meshes. See `addEdges`. */
57
67
  type EdgesConfig = {
58
68
  /** Auto-attach edge overlays to meshes as they load. Default false (opt-in). */
@@ -122,6 +132,13 @@ type MeasureConfig = {
122
132
  };
123
133
  type ThreeInitializerOptions = {
124
134
  sceneScale?: 'mm' | 'cm' | 'm' | 'inches' | 'feet';
135
+ /**
136
+ * Pick a coherent look up front — seeds sensible defaults for tone mapping, AO, edges, grid, and
137
+ * IBL strength (see {@link RenderStyle}). Individual `render`/`edges`/`grid` options still win
138
+ * when set explicitly, so this only fills in what you leave unspecified. Omit for the plain
139
+ * per-field defaults (no style applied). Re-apply later via the init result's `setRenderStyle`.
140
+ */
141
+ renderStyle?: RenderStyle;
125
142
  camera?: CameraConfig;
126
143
  lighting?: LightingConfig;
127
144
  environment?: EnvironmentConfig;
@@ -412,6 +429,19 @@ declare const initThree: (canvas: HTMLCanvasElement, options?: ThreeInitializerO
412
429
  applyEdges: (root: THREE.Object3D) => void;
413
430
  /** Toggle ambient occlusion at runtime — builds or tears down the postprocessing pipeline. */
414
431
  setAmbientOcclusion: (enabled: boolean) => void;
432
+ /**
433
+ * Apply a coherent look to the already-loaded scene: 'technical' (matte/CAD — edges, grid, low
434
+ * IBL, neutral tone mapping) or 'rendered' (presentation — stronger IBL, ACES tone mapping, no
435
+ * edges). Retunes viewer-owned dials only; per-material parse choices are set via the batch
436
+ * parser's `material` option. Handy for comparing the two looks in a live viewer.
437
+ */
438
+ setRenderStyle: (style: "technical" | "rendered") => void;
439
+ /**
440
+ * The parse-time material options (backface culling, IBL strength) matching the active render
441
+ * style — feed into the batch parser's `material` option so freshly-loaded meshes are built to
442
+ * match the look. Returns undefined when no style is active. See `setRenderStyle`.
443
+ */
444
+ getMaterialAppearance: () => MaterialAppearanceOptions | undefined;
415
445
  /**
416
446
  * Refit the sun's shadow frustum to the current scene content for crisp shadows. Call after
417
447
  * loading or replacing geometry (e.g. after `updateScene`). No-op when sunlight/shadows are off.
@@ -526,11 +556,18 @@ declare function removeEdges(root: THREE.Object3D): number;
526
556
  * this when `render.ambientOcclusion` is enabled, and otherwise renders with a plain
527
557
  * `renderer.render` so the cheap path stays cheap (the chosen tradeoff — see cad-viewer-plan.md).
528
558
  *
529
- * Pipeline: RenderPass → GTAOPass → OutputPass. GTAO (ground-truth AO) is the modern replacement for
530
- * SSAO/SAO — better contact shadows in crevices, the "engineered" depth cue. `screenSpaceRadius` is
531
- * on so the AO radius is in screen space, which keeps it scale-robust across the viewer's mm→m
532
- * scenes without per-scene tuning. OutputPass applies tone mapping + color space (taking over the
533
- * roles the renderer did directly in the non-composer path).
559
+ * Pipeline: RenderPass → GTAOPass → SMAAPass → OutputPass. GTAO (ground-truth AO) is the modern
560
+ * replacement for SSAO/SAO — better contact shadows in crevices, the "engineered" depth cue.
561
+ * `screenSpaceRadius` is on so the AO radius is in screen space, which keeps it scale-robust across
562
+ * the viewer's mm→m scenes without per-scene tuning.
563
+ *
564
+ * SMAA restores antialiasing on this path. The EffectComposer renders into an offscreen target, so
565
+ * the WebGLRenderer's own MSAA (`antialias: true`) does nothing here — without a dedicated AA pass,
566
+ * enabling AO would visibly *worsen* edge quality. SMAA is chosen over TAA because TAA's temporal
567
+ * jitter smears during OrbitControls drags; SMAA is single-frame, cheap, and stable while orbiting.
568
+ *
569
+ * OutputPass applies tone mapping + color space last (taking over the roles the renderer did
570
+ * directly in the non-composer path), so SMAA operates on the pre-tonemapped image as intended.
534
571
  *
535
572
  * Camera swaps: the active camera can flip perspective↔ortho. Rather than rebuild the composer, we
536
573
  * retarget the passes' `camera` each render via {@link setCamera}.
@@ -1,2 +1,2 @@
1
- import{B as h,C as c,D as v,E as j,a as e,b as r,c as t,d as o,e as i,f as a,g as s,h as p,i as n,j as l,k as f,l as m,m as y,n as u,o as d,p as x,q as C,r as g}from"./chunk-HNG75VAI.js";import"./chunk-QAOHGIFT.js";export{p as EDGE_USERDATA_KIND,C as Materials,v as SCALE_FACTORS,n as addEdges,t as applyOffset,o as computeCombinedBoundingBox,i as createCameraController,a as createGrid,y as createLabelLayer,d as createMeasureTool,m as createRenderPipeline,s as createViewGizmo,j as getThreeMeshesFromComputeResponse,x as initThree,l as isEdgeOverlay,r as parseColor,g as parseDisplayItems,c as parseMeshBatchBlob,h as parseMeshBatchObject,f as removeEdges,u as snapToVertex,e as updateScene};
1
+ import{D as h,E as c,F as v,G as j,a as e,b as r,c as t,d as o,e as i,f as a,g as s,h as p,i as n,j as l,k as f,l as m,m as y,n as u,o as d,s as x,t as C,u as g}from"./chunk-6V6SUB4V.js";import"./chunk-EMXDP7KY.js";export{p as EDGE_USERDATA_KIND,C as Materials,v as SCALE_FACTORS,n as addEdges,t as applyOffset,o as computeCombinedBoundingBox,i as createCameraController,a as createGrid,y as createLabelLayer,d as createMeasureTool,m as createRenderPipeline,s as createViewGizmo,j as getThreeMeshesFromComputeResponse,x as initThree,l as isEdgeOverlay,r as parseColor,g as parseDisplayItems,c as parseMeshBatchBlob,h as parseMeshBatchObject,f as removeEdges,u as snapToVertex,e as updateScene};
2
2
  //# sourceMappingURL=visualization.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selvajs/compute",
3
- "version": "3.1.0-beta.3",
3
+ "version": "3.1.0-beta.4",
4
4
  "description": "TypeScript library for Rhino Compute Server - Grasshopper and RhinoCommon",
5
5
  "author": "VektorNode",
6
6
  "license": "MIT",
@@ -1,2 +0,0 @@
1
- import{b as l,c as h,d as f,e as d,h as U,i as z,k as $,l as A,m as _,n as q,r as N}from"./chunk-QAOHGIFT.js";function p(t,e){if(!t||typeof t!="object")return;let r=t;if(e in r)return r[e];let n=J(r).get(e.toLowerCase());return n===void 0?void 0:r[n]}function L(t,e){if(!t||typeof t!="object")return!1;let r=t;return e in r?!0:J(r).has(e.toLowerCase())}var H=new WeakMap;function J(t){let e=H.get(t);if(!e){e=new Map;for(let r of Object.keys(t)){let n=r.toLowerCase();e.has(n)||e.set(n,r)}H.set(t,e)}return e}function C(t,e){e||typeof window<"u"&&d().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`)}var Ie="Unable to load grasshopper definition";function xe(t){return t instanceof f?t.code===h.DEFINITION_NOT_CACHED||t.message.includes(Ie):!1}function Y(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let a=p(o,"innerTree");(!a||Object.keys(a).length===0)&&n.push(p(o,"paramName")??"<unnamed>")}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;d().warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function D(t,e,r){r.debug&&C("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let{response:n}=await O(P(e,t),r);return n}async function Q(t,e,r){return r.debug&&C("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning),O(P(e,t),r)}async function X(t,e,r,n){n.debug&&C("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let s={algo:null,pointer:e,values:t};try{return{...await O(s,n),missed:!1}}catch(o){if(!xe(o))throw o;return{...await O(P(r,t),n),missed:!0}}}async function O(t,e){De(t,e);let r=await A("grasshopper",t,e);if("pointer"in r){let{pointer:n,...s}=r,o=s;return Y(o,e.debug),{response:o,cacheKey:typeof n=="string"?n:null}}return Y(r,e.debug),{response:r,cacheKey:null}}function P(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=$(t):/^https?:\/\//i.test(t)?r.pointer=t:z(t)?r.algo=t:r.algo=U(t),r}function De(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function Pe(t){let e=new WeakSet,r=n=>{if(n==null)return JSON.stringify(n);if(typeof n=="number")return Number.isFinite(n)?String(n):JSON.stringify(null);if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return JSON.stringify(n.toString());if(n instanceof Uint8Array){let s=n.length>64?Array.from(n.slice(0,32)).concat(Array.from(n.slice(-32))):Array.from(n);return JSON.stringify({__u8:!0,len:n.length,sample:s})}return Array.isArray(n)?`[${n.map(r).join(",")}]`:typeof n=="object"?e.has(n)?JSON.stringify("[Circular]"):(e.add(n),`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`):JSON.stringify(null)};return r(t)}function Z(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function ee(t){return Z(t.length,e=>t.charCodeAt(e))}function Re(t){return Z(t.length,e=>t[e])}function te(t,e){return ee(`${W(t)}|${Pe(e)}`)}function W(t){return typeof t=="string"?`s:${t.length}:${ee(t)}`:`u8:${t.length}:${Re(t)}`}var we=100;function Ee(t){return t instanceof Uint8Array?!0:!/^https?:\/\//i.test(t)}var S=class{constructor(e,r,n={},s){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheTtl");l(this,"cache",new Map);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.timeoutMs=n.timeoutMs,this.retry=n.retry;let o=n.cache;this.cacheEnabled=o!==void 0&&o!==!1;let a=typeof o=="object"?o:{};this.cacheMax=a.maxEntries??50,this.cacheTtl=a.ttlMs??0,this.reuseServerDefinitionCache=!!s&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){d().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new f("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let s=te(e,r),o={key:s,enqueuedAt:Date.now(),startedAt:null};if(this.cacheEnabled){let a=this.readCache(s);if(a){let i={status:"success",response:a,durationMs:0,fromCache:!0};return this._lastResult=a,this._lastError=null,this._lastDurationMs=0,this.runHook(this.onStart,o),this.runHook(this.onSettle,o,i),this.notify(),Promise.resolve(a)}}return new Promise((a,i)=>{let u={definition:e,dataTree:r,ctx:o,resolve:a,reject:i,externalSignal:n?.signal};if(u.externalSignal?.aborted){this.settleError(u,this.makeAbortError(o));return}this.enqueue(u)})}enqueue(e){switch(this.mode){case"latest-wins":{this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let r of this.inFlight)this.supersede(r),r.controller.abort();this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.fifoQueue.push(e);break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now();let s=()=>r.abort();e.externalSignal?.addEventListener("abort",s,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let o=performance.now();try{let a={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:i,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,a),c=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,i),!this.settleSuccess(e,i))return;this._lastResult=i,this._lastError=null,this._lastDurationMs=c,this.runHook(this.onSettle,e.ctx,{status:"success",response:i,durationMs:c,fromCache:!1,definitionReuploaded:u})}catch(a){let i=performance.now()-o,u=this.normalizeExecutionError(a,n);this._lastError=u,this._lastDurationMs=i,this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:i})}finally{e.externalSignal?.removeEventListener("abort",s),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!Ee(e))return{response:await this.executor(e,r,n)};let s=W(e),o=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,o,n);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>we;){let i=this.serverCacheKeys.keys().next().value;if(i===void 0)break;this.serverCacheKeys.delete(i)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.missed}}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new f("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new f("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},e.resolve(r),!0)}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof f?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new f(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?performance.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){this.settleError(e,this.makeAbortError(e.ctx))}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.cache.delete(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(this.cacheEnabled)for(this.cache.set(e,{response:r,insertedAt:Date.now()});this.cache.size>this.cacheMax;){let n=this.cache.keys().next().value;if(n===void 0)break;this.cache.delete(n)}}clearCache(){this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.cache.clear())}runHook(e,...r){if(e)try{e(...r)}catch(n){d().error("[SolveScheduler] hook threw:",n)}}};var R=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new q(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(e.retry?.attempts??2)+1),s=e.retry?.baseDelayMs??250,o=e.retry?.maxDelayMs??1e3;for(let a=0;a<n;a++){if(await r.serverStats.isServerOnline())return r;if(a<n-1){let i=Math.min(s*2**a,o);await new Promise(u=>setTimeout(u,i))}}throw await r.dispose(),new f("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),F(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),w(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new f("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new f("Definition content is empty",h.INVALID_INPUT);let s={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},o=await D(r,e,s);if(o?.errors&&o.errors.length>0)throw new f(o.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r,errors:o.errors,warnings:o.warnings}});return o}catch(s){throw this.config.debug&&d().error("Compute failed:",s),s instanceof f?s:new f(s instanceof Error?s.message:String(s),h.COMPUTATION_ERROR,{context:{definition:typeof e=="string"&&e.length<200?e:"...content...",inputs:r},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,a)=>D(o,s,a),n=(s,o,a,i)=>a===null?Q(o,s,i).then(u=>({...u,missed:!1})):X(o,a,s,i);return new S(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new f("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var G=new Map;function re(t,e){G.set(t,e)}re("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});re("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function ve(t){if(G.has(t))return G.get(t);for(let[e,r]of G)if(t.startsWith(e))return r}function Ae(t){return!t||typeof t!="object"?null:t.data??t.value??null}function ne(t,e,r){let n=ve(e);if(n)try{return n(r,t)}catch(s){d().warn(`Failed to decode Rhino type ${e}:`,s)}try{let s=Ae(t);if(s)return r.CommonObject.decode(s)}catch(s){return d().warn(`Failed to decode ${e} with CommonObject:`,s),{__decodeError:!0,type:e,raw:t}}return t}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ne="Rhino.Geometry.",Oe=["WebDisplay"],Fe="FileData";function se(t){return Oe.some(e=>t.includes(e))}function oe(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Ge(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ne)?ne(t,e,r):t}}function ae(t,e,r,n){if(typeof t!="string")return t;let s=r?oe(t):t;return Ge(s,e,n)}function ke(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function k(t,e){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)e(n)}function ie(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a={},i=new Set;for(let u of t.values)k(u.InnerTree,c=>{if(se(c.type)||o&&c.type!==I.STRING)return;let m=e?c.id:u.ParamName;if(!m)return;let y=ae(c.data,c.type,n,s);m in a?i.has(m)?a[m].push(y):(a[m]=[a[m],y],i.add(m)):a[m]=y});return{values:a}}function ue(t){let e=[];for(let r of t.values)k(r.InnerTree,n=>{if(!n.type.includes(Fe))return;let s=oe(n.data);ke(s)&&e.push(s)});return e}function pe(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,a;if("byName"in e?a=t.values.find(u=>u.ParamName===e.byName):a=t.values.find(u=>{let c=!1;return k(u.InnerTree,m=>{m.id===e.byId&&(c=!0)}),c}),!a)return;let i=[];if(k(a.InnerTree,u=>{if("byId"in e&&u.id!==e.byId||se(u.type)||o&&u.type!==I.STRING)return;let c=ae(u.data,u.type,n,s);i.push(c)}),i.length!==0)return i.length===1?i[0]:i}var E=class{constructor(e,r=!1){this.response=e;this.debug=r}getValues(e=!1,r={}){return ie(this.response,e,r)}getValue(e,r){return pe(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-UJZN4PJD.js"))}catch(s){throw new f("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:s instanceof Error?s.message:String(s)}})}return n(this.response,r)}getFileData(){return ue(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await N(n,e,r)}};function le(t){return p(t,"data")}function Me(t){return p(t,"type")}function ce(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(!L(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return d().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={};for(let[s,o]of Object.entries(e))n[s]=o.map(a=>{let i=le(a),u=Me(a);if(typeof i=="string"){if(u==="System.Double"||u==="System.Int32"){let c=Number(i);return Number.isNaN(c)?i:c}if(u==="System.Boolean")return i.toLowerCase()==="true";if(u?.startsWith("Rhino.Geometry"))try{return JSON.parse(i)}catch{return i}}return i});return{schema:{...t,default:n}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&L(s,"data")&&r.push(le(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var B=/^\{(\d+(?:;\d+)*)?\}$/;function v(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>B.test(r)&&Array.isArray(n))}function x(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var Ve=t=>{if(typeof t=="number")return t;if(typeof t=="string"){let e=t.trim();if(e==="")return null;let r=Number(e);return Number.isNaN(r)?null:r}return null},Le=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.toLowerCase();if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean string: "${t}"`)}return null},We=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,Be=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function me(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(d().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return d().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function fe(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function je(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),T=Math.pow(10,-b),K=Number(T.toFixed(b));return Math.abs(K-T)<e?K:T}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let y=Number(s[1]);if(y<0||n.toLowerCase().includes("e-")){let g=Math.abs(y),b=Math.pow(10,-g),T=Number(b.toFixed(g));return Math.abs(T-b)<e?T:b}return .1}let o=12,i=r.toFixed(o).replace(/0+$/,""),u=Math.min((i.split(".")[1]||"").length,o);if(u===0)return .1;let c=Math.pow(10,-u),m=Number(c.toFixed(u));return Math.abs(m-c)<e?m:c}function Ke(t,e=1e-8){let r=t.paramType==="Integer";if(v(t.default))return{default:t.default,stepSize:r?1:.1};let n=x(t.default,Ve,!0);if(r)return Array.isArray(n)?n=n.map(m=>typeof m=="number"?Math.round(m):m):typeof n=="number"&&(n=Math.round(n)),{default:n,stepSize:1};let s=Array.isArray(n)?n[0]:n,o;typeof s=="number"&&Number.isFinite(s)&&s!==0?o=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?o=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(o=t.maximum);let a=o!==void 0?je(o,e):.1,i=0,u=String(a),c=u.toLowerCase().match(/e(-?\d+)/);if(c?i=Math.abs(Number(c[1])):i=u.split(".")[1]?.length??0,i===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let m=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(m)&&m>0&&(i=m)}return i=Math.min(Math.max(i,0),12),Array.isArray(n)?n=n.map(m=>typeof m=="number"?fe(m,i,e):m):typeof n=="number"&&(n=fe(n,i,e)),{default:n,stepSize:a}}var Ue={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=Ke(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,default:r?[0]:0}}},ze={types:["Boolean"],parse(t,e){let r;try{r=x(t.default,Le,!1)}catch(n){throw n instanceof Error?new f(n.message):n}return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},$e={types:["Text"],parse(t,e){let r=x(t.default,We,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},_e={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw f.missingValues(t.nickname||"unnamed","ValueList");if(t.default!==void 0&&t.default!==null){let r=String(t.default).toLowerCase();Object.keys(t.values).some(s=>s.toLowerCase()===r)||d().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:t.default}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"ValueList",values:t.values??{},default:r?[t.default]:t.default}}},de={types:["Geometry"],parse(t,e){let r=x(t.default,me(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},qe={types:["File"],parse(t,e){let r=x(t.default,me(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},He={types:["Color"],parse(t,e){let r=x(t.default,Be,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},Je=[Ue,ze,$e,_e,de,qe,He],j=new Map(Je.flatMap(t=>t.types.map(e=>[e,t]))),he=de;var Ye=new Map([...j.keys()].map(t=>[t.toLowerCase(),t]));function Qe(t){return Ye.get(t?.toLowerCase())??t}function ye(t){return ge(t).input}function ge(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??"",id:t.id},r=Qe(t.paramType),{schema:n,warning:s}=ce({...t,paramType:r}),o=s&&{inputName:t.name||"unknown",paramType:r,message:s.message,code:s.code},a=j.get(r);try{if(!a)throw f.unknownParamType(r,t.name);return{input:a.parse(n,e),error:o}}catch(i){if(i instanceof f)return d().error(`Validation error for input ${t.name||"unknown"}:`,i.message),{input:(a??he).fallback(n,e),error:{inputName:t.name||"unknown",paramType:r,message:i.message,code:i.code}};throw new f(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function be(t){return M(t).inputs}function M(t){let e=[],r=[];for(let n of t){let{input:s,error:o}=ge(n);e.push(s),o&&r.push(o)}return{inputs:e,parseErrors:r}}function Te(t){return{id:p(t,"id"),name:p(t,"name"),nickname:p(t,"nickname")??null,description:p(t,"description"),paramType:p(t,"paramType"),treeAccess:p(t,"treeAccess"),minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast"),atMost:p(t,"atMost"),stepSize:p(t,"stepSize"),default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??""}}function Ce(t){return{name:p(t,"name"),nickname:p(t,"nickname")??null,paramType:p(t,"paramType"),id:p(t,"id")}}async function w(t,e){let r=P(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new f("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let s=await A("io",n,e);if(!s||typeof s!="object")throw new f("Invalid IO response structure",h.INVALID_INPUT,{context:{response:s,definition:t}});let o=Se(p(s,"warnings")),a=Se(p(s,"errors")),i=p(s,"inputs"),u=p(s,"outputs");return{inputs:Array.isArray(i)?i.map(Te):[],outputs:Array.isArray(u)?u.map(Ce):[],...o&&{loadWarnings:o},...a&&{loadErrors:a}}}function Se(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}async function F(t,e){C("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await w(t,e),{inputs:a,parseErrors:i}=M(r);return{inputs:a,outputs:n,...i.length>0&&{parseErrors:i},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}var V=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let s=t.parsePathString(r);this.append(s,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(s=>t.deserializeValue(s.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),s=r.default;if(r.treeAccess&&v(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],a=t.processValues(o,r);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let c=e,m=c.findIndex(y=>y.getParamName()===r);return m!==-1?c[m]=o:c.push(o),c}let a=e,i=o.toComputeFormat(),u=a.findIndex(c=>c.ParamName===r);return u!==-1?a[u]=i:a.push(i),a}static buildFromValue(e,r){let n=new t(e);return v(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(a=>a.ParamName===r);if(!n?.InnerTree)return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(a=>a?.data!==void 0?t.deserializeValue(a.data):null).filter(a=>a!==null):o?.data!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(B);return r?r[1]?r[1].split(";").map(Number):[]:(d().warn(`Invalid TreeBuilder path format: ${e}, using [0]`),[0])}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let a=t.deserializeValue(o.data);if(typeof a=="number"){let i=t.clampValue(a,e,r,n);o.data=t.serializeValue(i)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}return e.trim()!==""&&!isNaN(Number(e))?Number(e):e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,s){let o=e;return r!=null&&o<r&&(d().warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(d().warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};export{D as a,S as b,R as c,E as d,ye as e,be as f,w as g,F as h,V as i};
2
- //# sourceMappingURL=chunk-CTZ4ZOSM.js.map