diff --git a/.github/architecture/rendering-and-shadows.md b/.github/architecture/rendering-and-shadows.md index e6db67c4e..8c22c254e 100644 --- a/.github/architecture/rendering-and-shadows.md +++ b/.github/architecture/rendering-and-shadows.md @@ -1,84 +1,154 @@ # PolyCSS Rendering, Shadows, Lighting & Meshing Reference -> Linked from [AGENTS.md](../../AGENTS.md). Read before changing render strategies, cast/receiver shadows, lighting modes, meshing, or animation paths. +> Linked from [AGENTS.md](../../AGENTS.md). Read before changing — or proposing deletions/simplifications to — render strategies, cast/receiver shadows, lighting modes, meshing, or animation paths. ## Rendering model — the mental model **One visible `Polygon` → one leaf DOM element.** Leaves use canonical CSS primitives where possible and move scale into `matrix3d`; clipped solids use fixed primitives because their paint geometry becomes unstable when collapsed to 1px. Atlas-backed textured polygons pack their local-2D bounding rect (`canvasW × canvasH`) into atlas pages; source-exact textured polygons may instead carry `textureImageSource` + `texturePresentation.backend="image"` and render as direct image leaves without atlas rasterisation. The HTML tag *is* the render strategy — the renderer picks one tag per polygon based on its shape and material. -Raw MagicaVoxel `.vox` sources have a narrower baked-mode fast path: `parseVox` still returns the polygon mesh for bounds, fallback rendering, and public handles, but also preserves a `PolyVoxelSource` marker. Eligible vanilla, React, and Vue meshes render visible voxel quads as `` leaves inside persistent signed-face wrappers (`t`, `b`, `fl`, `br`, `fr`, `bl`), with canonical `matrix3d(...)` transforms and projected tile4 scanline order inside each mounted face. Camera-facing culling mounts/removes those face wrappers instead of removing thousands of live brush children from the mesh root. `.vox` normalization snaps to the nearest integer CSS cell size so direct voxel matrices use integer pixel coordinates without any scale wrapper; same-color shared voxel edges get a tiny matrix-space overscan to hide compositor seams without fattening exterior silhouette edges. Brush colors still receive baked Lambert shading from the scene lights. Callers may opt into lossy `.vox` palette merging and small local face-region cleanup before greedy meshing when authored palettes contain visually redundant colors; gallery and builder route this through Mesh resolution so `Lossy` may simplify palettes while `Lossless` keeps palette colors exact. Dynamic lighting, shadows, stable DOM animation, non-exact voxel geometry, and geometry replaced via `setPolygons` fall back to the polygon renderer. +### Voxel fast path & camera-facing culling -Voxel-shaped meshes are the exception to "all polygons stay mounted": meshes with at most the six axis-aligned face normals, excluding helpers/auto-center-exempt meshes, automatically mount only camera-facing leaves and patch the mounted set when the camera or mesh rotation crosses a visible-normal boundary. Non-voxel meshes keep the full leaf DOM mounted; broad camera-dependent DOM culling is not worth the mutation cost. +- **Raw MagicaVoxel `.vox` baked fast path:** `parseVox` still returns the polygon mesh for bounds, fallback rendering, and public handles, while preserving a `PolyVoxelSource` marker. Eligible vanilla, React, and Vue meshes render visible voxel quads as `` leaves inside persistent signed-face wrappers (`t`, `b`, `fl`, `br`, `fr`, `bl`), with canonical `matrix3d(...)` transforms and projected tile4 scanline order inside each mounted face. + - Camera-facing culling mounts/removes those ≤ 6 face wrappers instead of mutating thousands of brush children. + - `.vox` normalization snaps to the nearest integer CSS cell size so direct voxel matrices use integer pixel coordinates without any scale wrapper; same-color shared voxel edges get a tiny matrix-space overscan to hide compositor seams without fattening exterior silhouettes. + - Desktop-class documents use a canonical `1px` primitive; mobile-class documents (`pointer: coarse` or `hover: none`) use an `8px` primitive and divide the in-plane matrix scale by 8 to preserve identical CSS-space geometry while avoiding large GPU filtering gaps. + - Brush colors receive baked Lambert shading from the scene lights. Callers may opt into lossy `.vox` palette merging and small local face-region cleanup before greedy meshing (Gallery and Builder route this through Mesh resolution: `Lossy` simplifies palettes while `Lossless` keeps colors exact). + - Dynamic lighting, shadows, stable DOM animation, non-exact voxel geometry, and geometry replaced via `setPolygons` fall back to the polygon renderer. +- **General voxel-shaped culling exception:** Meshes with at most the six axis-aligned face normals (excluding helpers/auto-center-exempt meshes) automatically mount only camera-facing leaves and patch the mounted set when camera or mesh rotation crosses a visible-normal boundary. Non-voxel meshes keep the full leaf DOM mounted; broad camera-dependent DOM culling is not worth the mutation cost. ### Tag-as-strategy table | Tag | Strategy | When chosen | Paint mechanism | Atlas memory | |---|---|---|---|---| -| `` | **Quads** | Axis-aligned rectangle, or untextured convex quad when the homography passes stability guards on non-Safari engines | `background: currentColor` on a fixed 64px rectangle; affine and projective quads normalize their `matrix3d` to that primitive, with tiny solid bleed on projective quads to overlap antialias seams. Safari-family browsers skip the projective quad path and fall through because transformed projective rectangles composite incorrectly there. | None | -| `` | **Border-shape clipped solid** | Untextured non-rect not caught by the exact corner-shape solid path, on browsers with CSS `border-shape` (Chromium + `pointer:fine` + `hover:hover`) | `border-color: currentColor` on a fixed 16px border-shape primitive, clipped by `border-shape: polygon(...)`; polygon bbox scale and tiny solid bleed are folded into `matrix3d` | None | -| `` | **Texture slice / atlas fallback** | Atlas-backed textured polygons, direct `textureImageSource` polygons, or untextured non-rect on browsers without `border-shape` | Atlas leaves use a packed bitmap slice on an auto-budgeted primitive (128px for desktop-class `textureQuality="auto"`, 64px for mobile-class `auto` and explicit numeric quality by default; `textureLeafSizing` can switch to local or raster dimensions). Direct image leaves use the caller's source URL and source rect directly, keep source lighting, and may use guarded affine or projective matrices for exact quad mapping. Atlas position/size, image position/size, filtering (`textureImageRendering`), readiness, projection, and source rect are emitted as PolyCSS-owned metadata so callers do not parse private style strings. | Atlas: bounding-rect area; direct image: none | -| `` | **Stable solid triangle / corner-shape solid** | Triangles on non-WebKit engines; or untextured non-triangle polygons whose normalized outline is exactly a rectangle with one or more beveled corners on browsers with CSS `corner-shape` | Triangles use a 32px box with two beveled top corners and `background: currentColor` when CSS `corner-shape` support is present, progressively falling back to the CSS border-color triangle trick. Firefox uses a 96px border-triangle primitive to avoid large-perspective compositor banding. Exact corner-shape solids use a fixed 16px classed box with inline per-corner radii + `corner-*-shape: bevel` and `background: currentColor`. Tiny solid bleed is folded into `matrix3d`. WebKit/Safari falls through to `` for border triangles because transformed CSS border triangles composite incorrectly there. | None | +| `` | **Quads** | Axis-aligned rectangle, or untextured convex quad when the homography passes stability guards on non-Safari engines | `background: currentColor` on a fixed `64px` rectangle; affine and projective quads normalize their `matrix3d` to that primitive, with tiny solid bleed on projective quads to overlap antialias seams. Safari-family browsers skip the projective quad path and fall through because transformed projective rectangles composite incorrectly there. | None | +| `` | **Solid triangle / corner-shape solid** | Triangles (`corner-shape: bevel` primary everywhere; CSS border-trick fallback on non-WebKit); or untextured non-triangle polygons whose normalized outline is an exact rectangle with 1–4 beveled corners on browsers with CSS `corner-shape` | Triangles use a `32px` box with two beveled top corners and `background: currentColor` when CSS `corner-shape` support is present (our best triangle), progressively falling back to the CSS border-color triangle trick (`32px`; Firefox uses `96px` to avoid large-perspective compositor banding). Exact corner-shape solids use a fixed `16px` classed box (`u.polycss-corner-shape-solid`) with inline per-corner radii + `corner-*-shape: bevel` and `background: currentColor`. Tiny solid bleed is folded into `matrix3d`. WebKit/Safari falls through to `` for border triangles because transformed CSS border triangles composite incorrectly there. | None | +| `` | **Border-shape clipped solid** | Untextured non-rect not caught by the exact corner-shape solid path, on browsers with CSS `border-shape` (Chromium + `pointer:fine` + `hover:hover`) | `border-color: currentColor` on a fixed `16px` border-shape primitive, clipped by `border-shape: polygon(...)`; polygon bbox scale and tiny solid bleed are folded into `matrix3d`. | None | +| `` | **Texture slice / atlas fallback** | Atlas-backed textured polygons, direct `textureImageSource` polygons, or untextured non-rect on browsers without `border-shape` | Atlas leaves use a packed bitmap slice on an auto-budgeted primitive (`128px` for desktop-class `textureQuality="auto"`, `64px` for mobile-class `auto` and explicit numeric quality by default; `textureLeafSizing` can switch to `local` or `raster`). Direct image leaves use the caller's source URL and source rect directly, keep source lighting, and may use guarded affine or projective matrices for exact quad mapping. Atlas position/size, image position/size, filtering (`textureImageRendering`), readiness, projection, and source rect are emitted as PolyCSS-owned metadata. | Atlas: bounding-rect area; direct image: none | -Strategies are ordered cheapest → most expensive. The mesher's job is to maximise `` / `` / `` and minimise `` (see "Meshing implications" below). +Strategies are ordered cheapest → most expensive (`` → `` → `` → ``). The mesher's job is to maximise `` / `` / `` and minimise `` (see "Meshing implications" below). -Callers can opt out of specific strategies via `strategies: { disable: ["b" | "i" | "u"] }` on `RenderTextureAtlasOptions`. Disabled or unsupported strategies fall through the chain (`b → i → s`, `u → i → s`, `i → s`). Disabling `"i"` also disables the exact corner-shape solid branch even though that branch emits a bare ``, because it belongs to the non-triangle clipped-solid family. `` is the universal fallback and cannot be disabled. Solid seam bleed gives detected shared solid edges a per-edge overscan, fitted to the polygon plan, rather than inflating every side of each participating polygon. It IS exposed: `seamBleed` is a scene option in all three renderers plus a React/Vue per-mesh prop, though not a custom-element attribute. Semantics are unified and owned by core (`resolveSeamBleedPx` / `seamBleedPrimitiveRatio` in `packages/core/src/atlas/constants.ts`; renderers pass the raw option through): `undefined`/`"auto"` → the `1.5` px default (`DEFAULT_SEAM_BLEED`); a finite number ≥ 0 is the requested overscan in CSS px with no upper clamp (the per-edge geometric fit still bounds each edge); negative/non-finite values fall back to the default. The same option scales the per-strategy primitive bleeds (`SOLID_TRIANGLE_BLEED`, `BORDER_SHAPE_BLEED`, `TEXTURE_TRIANGLE_BLEED`, and the projective-quad guard bleed) by `clamp(px / 1.5, 0, 1)` — so `0` disables every bleed, sub-`1.5` values shrink primitives proportionally, and larger values keep primitives at full strength while the seam overscan uses the raw px. All three renderers also honor the `window.__polycssProjectiveQuadGuards` debug override for projective-quad guards, merged over the seam-scaled default. +### Strategy opt-out & unified seam bleed -Cast shadows are not a render-strategy leaf tag. Meshes with `castShadow: true` project casting polygons on the CPU into SVG shadow surfaces onto scene-level receiver surfaces where `receiveShadow` is enabled. All three renderers share the single shadow orchestrator in `@layoutit/polycss/runtime` (`shadowOrchestrator.ts` / `receiverShadow.ts`). **No-receiver ground fallback:** vanilla defaults to `groundShadowFallback: false` (Three.js parity — a caster with no receiver draws nothing), while React/Vue pass `groundShadowFallback: true` to emit a compound ground-plane shadow SVG when a nonzero-intensity directional light exists and drop it as soon as any receiver mounts. EVERY polygon casts — shadow casters are NOT filtered to the camera-rendered set (atlas plan), because a polygon casts a shadow regardless of whether it's painted for the camera; filtering left camera-dependent holes in imported-mesh shadows. Coincident/back-to-back duplicate faces ARE pre-dropped via `findOverlappingPolygonDuplicates` (`dedupByCaster`). Remaining overlapping projections are merged into one compound path per caster under `fill-rule: nonzero` so they don't alpha-stack, rather than being dropped. The directional light projects in parallel; each `pointLights` entry with `castShadow: true` casts an additional **radial** shadow (each vertex projected along its own ray from the light position), and point-light passes always project the caster *silhouette* — projecting individual back-faces leaves the contact footprint unshadowed under radial divergence. Shadows are **shaded, not flat black**: each light's shadow is filled with the receiver lit by every OTHER light (the blocked light removed), so a region shadowed from one colored light still shows the remaining lights' color (Three.js colored shadows). A lone directional light reduces this to the ambient-only fill (unchanged). All of a receiver FACE's lights are merged into **one SVG per face** so overlapping shadows composite correctly: a single-light SOLID face normally paints one path filled with the remaining-light color at `shadow.opacity`, and switches to the PRE-BLENDED color `blend(fullLitFill, remaining, shadow.opacity)` at alpha 1 only when that face actually bled a crease (see below) — the identical pixel over the lit receiver (the blend is exact at antialiased coverage too), but idempotent under overlap, which is what makes the crease bleed safe. The opaque form is NOT free elsewhere: `shadow.lift` floats the SVG above its face, and at grazing camera angles that parallax hangs part of the card past the receiver's silhouette, where opaque paint deviates from the backdrop about 4× as much as 25% alpha did (measured headlessly: mean Δ 54 → 209 of 255 over ~580 off-surface px on a lit cube; `lift=0` removes 99% of those px, confirming parallax as the cause). So the pre-blend is paid only where it buys the seam fix. `MergedShadowFace.layers[].opacity` therefore carries `shadow.opacity` for an ordinary single-light solid face and `1` for a crease-bled one — callers must read the field, never assume either; a multi-light solid face paints a base = full-lit color `C` then each light as a `mix-blend-mode: multiply` layer with factor `remaining/C`, so the both-blocked overlap becomes `C·∏factor` (ambient only). `mix-blend-mode` works *within* one SVG but NOT across SVGs (`preserve-3d` isolates each SVG against a transparent backdrop — verified), which is why the merge is per-face rather than per-light. Textured receivers (per-pixel base, no uniform multiply) fall back to per-pass alpha layers that cumulatively darken. The per-face color uses the face CENTROID direction (matching the baked per-polygon shading) so the base leaves no visible color box. The per-face merge is the shared core helper `computeMergedReceiverShadows` (runs every light pass + aggregates each face into one SVG descriptor); the runtime shadow emitter turns those descriptors into ``/`` nodes. Moving a light or changing caster/receiver geometry re-emits the shadow SVGs; this is DOM/SVG work only and does not redraw texture atlases. +- **Strategy disabling:** Callers opt out via `strategies: { disable: ["b" | "i" | "u"] }` on `RenderTextureAtlasOptions`. Disabled or unsupported strategies fall through (`b → i → s`, `u → i → s`, `i → s`). Disabling `"i"` also disables the exact corner-shape solid branch even though it emits ``, because it belongs to the non-triangle clipped-solid family. `` is the universal fallback and cannot be disabled. +- **Unified `seamBleed` option:** Solid seam bleed gives detected shared solid edges a per-edge overscan fitted to the polygon plan rather than inflating every side. Exposed as a scene option in all three renderers plus a React/Vue per-mesh prop (not a custom-element attribute). Semantics are owned by core (`resolveSeamBleedPx` / `seamBleedPrimitiveRatio` in `packages/core/src/atlas/constants.ts`): + - `undefined` / `"auto"` / negative / non-finite → `1.5` px default (`DEFAULT_SEAM_BLEED`). + - Finite number ≥ 0 → requested overscan in CSS px with no upper clamp (the per-edge geometric fit still bounds each edge). + - Scales per-strategy primitive bleeds (`SOLID_TRIANGLE_BLEED`, `BORDER_SHAPE_BLEED`, `TEXTURE_TRIANGLE_BLEED`, and projective-quad guard bleed) by `clamp(px / 1.5, 0, 1)` — so `0` disables every bleed, sub-`1.5` values shrink primitives proportionally, and larger values keep primitives at full strength while seam overscan uses raw px. +- **Projective quad debug override:** All three renderers honor `window.__polycssProjectiveQuadGuards`, merged over the seam-scaled default. -**Receiver-clip seam bleed (the pale-hairline classes).** Each receiver face group clips its shadow to the union of its member polygons, and two abutting antialiased clip edges do not sum to full coverage — so every receiver edge that a shadow crosses can show as a pale hairline. `prepareReceiverFacePlanes` therefore carries two per-member edge sets, and `computeReceiverShadowFaces` unions them into ONE outward clip expansion of `SHADOW_CLIP_SEAM_BLEED`: `memberSharedEdges` (neighbour is another member of the SAME coplanar group — the subpaths land in one nonzero compound path, so this is always on) and `memberCreaseEdges` (neighbour is a member of a DIFFERENT, non-coplanar group — a crease, and by far the dominant class on imported architecture). Crease adjacency is matched in WORLD space, since crease neighbours are not coplanar and the 2D `planarEdgesShareLine` predicate does not apply: matching runs on `memberPolysWorld` — each member's TRUE world vertices, carried alongside the (u, v) outline — via an exact quantized endpoint-pair hash, then `spatialEdgesShareLine` (the world-space sibling of the 2D predicate, same tolerances) over a uniform spatial hash restricted to edges the exact pass left unmatched. It must NOT lift the (u, v) outline back to 3D: that lift is exact only for members perfectly coplanar with their group plane, and imported architecture routinely is not (the castle has quads whose vertices sit ~0.3 CSS px off their own plane). Projecting drops that offset, so two groups snap the SAME shared vertex to two different points and push an exactly-shared crease past `RECEIVER_EDGE_PERP_EPS` (0.25) — which silently hid 272 of the castle's creases and left exactly the hairlines the pass exists to close. Edges already in `memberSharedEdges` stay in the candidate pool AND record their crease neighbours like any other edge. The mark cannot change their own clip expansion (an edge gets one bleed amount whether it is shared, crease, or both), but it is what flips the face to its opaque pre-blend, and it is the direction `qualifiesCrease`'s reciprocity condition reads. Suppressing it was a real bug: on a floor grouped from two coplanar quads with a wall standing on their shared edge — tessellated/greedy-merged architecture, the castle's dominant interior-partition shape — the exact hash recorded wall→floor but never floor→wall, so BOTH sides refused to bleed and the hairline came back. It also left the wall's opaque strip lying over a floor still painting at alpha, which composites by SVG paint order. True mesh-boundary edges have no neighbour in either set and are never bled, so shadow can never be pushed off the model's silhouette. Crease bleed makes two SVGs' shadow regions OVERLAP, which only composites correctly under the opaque pre-blend, so it is enabled only where that pre-blend is BOTH available and exact — and that is decided from the resolved colors BEFORE any clip is expanded, because expanded clips painted at fractional alpha are precisely the double-darkening the design exists to avoid. Three conditions, all checked per face per pass: a solid receiver; exactly ONE light pass; and every member of the group painting exactly `fullLitFill` — verified by re-shading each member from its OWN normal and centroid (`groupMembersShareLitColor`), not assumed from a shared base color. Those make a face ELIGIBLE; they say nothing about the neighbour it would bleed into, and eligibility alone is not licence to expand. `memberCreaseEdges` therefore stores the neighbouring PLANE INDICES (not bare normals), and `qualifiesCrease` requires four things of the neighbour across a given edge: it faces the camera (otherwise the crease is the camera silhouette and the expansion hangs in free space past the model outline); it EMITS a layer in this same pass (a camera-facing neighbour need not be a shadowed one — under a vertical light a side face fails `L·n` and emits no SVG, and bleeding into it paints shadow onto lit surface with nothing to fuse with); its resolved opaque pre-blend is the SAME colour (each face's pre-blend derives from its own lit colour, and crease neighbours are non-coplanar by construction, so the two usually differ — overlapping two different opaque fills is not idempotent, it just paints one over the other, a seam of the wrong colour, measured `rgb(79,79,79)` over `rgb(69,69,69)` on the standard L fixture); and it bleeds BACK toward this face, so neither side is left painting at alpha under the other's opaque strip. Answering "does the neighbour emit?" needs emission before expansion, so `computeReceiverShadowFaces` runs in two phases: phase 1 computes every face with crease bleed off (emission is crease-independent — a bleed only ever GROWS a member clip), phase 2 re-runs only the planes that end up with a qualifying neighbour. Where nothing qualifies — the common case, since differing lit colours are the norm at a crease — phase 2 does no work and the face keeps the alpha form and unexpanded clips. A group is formed by plane + adjacency, so neither one material nor one normal follows from membership: `RECEIVER_NORMAL_TOL` admits members ~2.5° apart, and over that spread the residual `(leaf − fullLitFill)·(1 − opacity)` was measured up to 11/255 at the default opacity 0.25 (bright base, low ambient, grazing light) — visible, so those groups keep the alpha form. On the castle the check costs 7 of 2286 groups and zero mounted shadow faces. The pre-blend must also be REPRESENTABLE: `blendShadowOverLitBase` returns null for a non-opaque-hex color, which a translucent receiver always produces (`shadePolygon` preserves alpha as `rgba(...)`), and such a face keeps unexpanded clips at its own alpha. Textured receivers, multi-light merged faces, multi-colored coplanar groups, groups with non-uniform member shading, and translucent receivers all keep the alpha form and get no crease bleed. `ReceiverFacePlane` carries `memberPolysWorld`, `memberSharedEdges`, and `memberCreaseEdges` as OPTIONAL fields — `prepareReceiverFacePlanes` always fills them, and a hand-built plane passed straight to `computeReceiverShadowFaces` still type-checks and simply gets no seam bleed, no crease bleed, and no pre-blend (its members' shading cannot be verified). That degradation is deliberate: it is the safe answer, not a silent approximation. The shadow clip applies the group's convex outline BEFORE the per-member clips, so the stored `RECEIVER_OUTLINE_EXPAND` (0.5) would cap the per-edge amount wherever a crease sits on the hull — 91% of the castle's crease edges, held to 0.5 px of the 0.75 px they were granted. `computeReceiverShadowFaces` therefore widens its own COPY of the hull by the shortfall (`CLIP_OUTLINE_EXTRA`), and only where crease bleed is already active. The stored outline keeps its 0.5, because it also sizes each face plane's `minU/minV/width/height/matrixCss`: widening it unconditionally shifts emitted geometry on multi-light and textured receivers, which get no crease bleed at all (measured — it moved 40 SVGs on a multi-light castle). The hull is not the surface boundary, the member clips are, and they still bound every edge, so widening the clip copy cannot push shadow past a member outline. +--- -Receiver shadows re-emit on camera motion only when the camera crosses a receiver-face VISIBILITY BOUNDARY, in all three renderers. Shadow output genuinely depends on the camera in two places — `computeReceiverShadowFaces` culls back-facing receiver faces, and a crease bleeds only toward a camera-facing neighbour (which also flips that face between the opaque pre-blend and the alpha form) — so a frozen orbit shows stale geometry that then pops on the next unrelated light or geometry change. Re-emitting per frame is the other failure. The gate between them is `receiverShadowCameraSignature`: one `normalFacesCamera` bit per receiver face plane, packed base-32 behind the count of contributing planes, which is the complete camera dependence because both decisions reduce to that same per-plane boolean. The count is not decoration — the final bit group is zero-padded to five, so without it every all-back-facing receiver of one to five planes packs to the same `"0"` and a plane-set change between two such states reads as "camera unchanged". Planes no light can reach are omitted — they emit nothing at any camera angle, so their bits would invent crossings; all three renderers pass the pass lights (`ReceiverShadowSignatureLights`), and omitting them (as React and Vue did) re-ran the whole pipeline on every horizon crossing of an unlit wall. Mesh rotation is deliberately NOT in the signature, because `plane.n` is already in world frame — which makes the key meaningless against planes built at a different mesh rotation, so every renderer must rebuild its planes and re-emit on a transform change BEFORE comparing keys (vanilla's `setTransform` gate therefore covers rotation alongside position and scale; React/Vue get it from `receiverPlanes` depending on `rotation`). Vanilla folds the signature into the emit short-circuit next to the light key and calls `syncShadowsForCameraChange` from `applyCamera`; React and Vue subscribe to the camera store, mirror the signature into state (`cameraShadowKey`, seeded from the store so the first render already holds the true key), and let the shadow memo/computed depend on it — a signature-gated subscription, never a per-frame recompute. An unchanged signature costs one per-plane facing sweep and returns. Measured on the bench castle (self-shadow + floor, parametric def 48): a full 360° orbit in 1° steps re-emits 71 times, ~one per 5° of azimuth, median step 0 ms and mean 2.2 ms; before this it re-emitted 0 times and the output was stale for the whole sweep. Projection (`merge`) is ~98% of each re-emit, so making crossings cheaper would mean caching specs per plane and recomputing only flipped planes — not done. All three renderers also share the same per-caster memoization: cached caster world-space items (vanilla `casterItemsCache`, React/Vue module WeakMaps keyed on polygon-array identity + transform), a per-caster parametric-override cache (at most two variants — self/cross — reused across every receiver), and a shared O(n²) overlap-dedup cache keyed on polygon-array identity + option set. +## Cast & receiver shadows -Receiver-shadow geometry has two caster paths. The default per-mesh **silhouette fast path** (caster ≠ receiver, ≥40 polys) projects one outline per caster instead of every front-facing triangle — but only when the caster's silhouette under the current light is a clean union of simple closed loops (every silhouette vertex shared by exactly two silhouette edges). Meshes whose silhouette has non-manifold / T-junction / open-boundary vertices (imported architecture like the castle) fall back to the **per-polygon union**, which is gap-free for any topology. Light-back-facing caster polygons are normally culled (single-sided casting, correct for clean closed meshes); the per-poly path casts **double-sided** (skips that cull) for two cases — cross-mesh casters whose silhouette is unreliable, and ALL self-shadow casters (caster = receiver) — so badly-wound / single-sided interior walls don't leave holes. Closed meshes are unaffected by double-siding: their far back-faces sit below each lit receiver plane and get above-plane-culled, adding no spurious shadow. +Cast shadows are CPU-projected SVG overlays under `.polycss-shadows`, not render-strategy leaf tags. All three renderers share the single shadow orchestrator in `@layoutit/polycss/runtime` (`shadowOrchestrator.ts` / `receiverShadow.ts`) and core `computeMergedReceiverShadows`. -**Parametric shadows (all three renderers, opt-in via `shadow.parametric` + `shadow.definition`).** A lightweight approximation that replaces a caster's per-poly/silhouette projection with low-resolution coverage-contour loops, so a complex caster emits far fewer shadow-path vertices. Per caster the light-perpendicular coverage is rasterised into a mask (resolution scales with `definition`), traced with marching squares, simplified, and lifted back to 3D for the normal receiver projector. Cross-mesh casting uses ONE flat proxy outline slid toward the light so it clears receivers below the caster (footprint is depth-invariant under directional projection); self-shadow uses depth-stratified bands, each biased to its far-from-light edge so a face is only shadowed by geometry genuinely in front of it. The approximation is governed by named geometric invariants (flat casters route to the exact path; convex casters skip self-shadow; self-shadow depth-bias prevents over-darkening; coverage holes — courtyards, the coliseum arena — are emitted with opposite winding by nesting depth so they subtract under the receiver's `fill-rule: nonzero`, while the exact path keeps per-loop CCW). Higher `definition` trades DOM weight for fidelity and is the knob for resolving fine concave holes. **Point lights** are supported: each shadow-casting point light gets its own RADIAL override silhouette built from the caster-centroid → light direction (the small-object approximation point shading already uses), stored per-light in `overridePointSilhouettes` and selected per pass; the directional override is the wrong outline for a finite-distance light, so point passes never reuse it. Parametric does not change the exact path, which remains the default. **Render style** is selectable via `shadow.style`: `"vector"` (default) traces the smooth concave contour; `"pixel"` greedy-meshes the coverage mask into axis-aligned rectangles for a blocky/voxel shadow — holes (courtyards, the coliseum arena) fall out for free as absent cells (no winding/`fill-rule` work), and `definition` becomes the pixel-grid resolution (lower → chunkier; the block size is the aesthetic). Both styles share the per-mesh def, point-light, and progressive machinery. The override builder (`buildParametricCasterOverride` + `isFlatCaster`/`isConvexCaster`) lives in **core** so all three renderers produce byte-identical loops — vanilla `receiverShadow.ts`, React `PolyMesh.tsx`, and Vue `PolyMesh.ts` each just call it in their caster loop and drop the result on the `ReceiverCasterInput`. Per-mesh `shadowDefinition` is a `PolyMeshTransform` field (vanilla), a `` prop (React), and a `shadow-definition` prop (Vue). The ONE intentional asymmetry: **progressive `dragDefinition` is vanilla-only**, because it's a `createPolyScene` orchestration concern (auto-detect a light-direction change → emit at the drag def → debounced full-def refine). React/Vue are declarative and re-render on prop change, so an app gets the same effect idiomatically by lowering `shadow.definition` in its own state during a drag and restoring it at rest. **Animated shadows** (`shadow.followAnimation`, all three renderers): a caster's shadow normally FREEZES during a same-topology deform — re-projecting every frame is expensive — so the default is frozen and `followAnimation` opts into tracking the pose (pair with a low parametric `definition`). All three renderers throttle the follow re-emit to the same 80ms window (~12fps, leading + trailing edge so a paused animation still lands its final pose): vanilla in `setPolygons` (`maybeEmitAnimationShadow`), React/Vue by gating + throttling the caster re-registration (a same-topology polygon change is skipped unless `followAnimation`, so the receiver re-emits only when following). Topology changes (different polygon count) always re-emit regardless. +### Core shadow rules -**Cost + the laggless levers.** Cross-mesh/floor cast shadows are cheap (one outline, ~1 receiver face) and follow a moving light at 60fps+; camera orbit is nearly free (shadows ride the scene transform; a re-emit happens only when the camera crosses a receiver-face visibility boundary — see the signature gate above). SELF-shadow is the expensive case: it projects every depth band onto every one of the mesh's own coplanar faces, so the recompute is O(faces × bands × points) and that work is irreducible by spatial culling (the depth-band proxies span the whole mesh, so their AABBs overlap nearly every face — a broad-phase cull was measured to reject nothing). The lever for smooth interaction is therefore reducing *quality during motion*, not a faster projector. Two knobs make this configurable: -- **Per-mesh `PolyMeshTransform.shadowDefinition`** overrides the scene `shadow.definition` for one mesh's cast/self shadow — a detailed caster stays sharp while a simple prop runs cheap in the same scene. -- **`shadow.dragDefinition`** is the library's built-in progressive refinement: when set (and `parametric`), a light-DIRECTION change emits at `min(definition, dragDefinition)` for a laggless drag (castle ~100fps at 16 vs 36fps at 96), then a debounced pass re-emits at full `definition` once the light settles — the same atlas-rebake-at-rest escape hatch. It's auto-detected in `setOptions` (direction change = motion; an appearance edit like the `definition` slider renders full immediately). Per-mesh def composes: motion caps each mesh at `min(its def, dragDefinition)`. +- **No-receiver ground fallback:** Vanilla defaults to `groundShadowFallback: false` (Three.js parity — a caster with no receiver draws nothing). React/Vue pass `groundShadowFallback: true` to emit a compound ground-plane shadow SVG when a nonzero directional light exists and drop it as soon as any receiver mounts. +- **Every polygon casts:** Shadow casters are NOT filtered to the camera-rendered set (atlas plan); filtering left camera-dependent holes in imported-mesh shadows. Coincident/back-to-back duplicate faces are pre-dropped via `findOverlappingPolygonDuplicates` (`dedupByCaster`) for ground fallback; remaining overlapping projections merge into one compound path per caster under `fill-rule: nonzero` so they never alpha-stack. +- **Directional + point lights:** Directional lights project in parallel; each `pointLights` entry with `castShadow: true` casts an additional **radial** shadow (always projecting the caster silhouette, because individual back-faces leave the contact footprint unshadowed under radial divergence). +- **Shaded, per-face merged SVGs:** Shadows are shaded, not flat black — each light's shadow is filled with the receiver lit by every *other* light (the blocked light removed). All lights affecting a receiver face merge into **one SVG per face** (`computeMergedReceiverShadows`) because `preserve-3d` isolates separate SVGs and breaks `mix-blend-mode` across SVGs: + - **Multi-light solid face:** paints base = full-lit color `C`, then each light as a `mix-blend-mode: multiply` layer with factor `remaining / C` so both-blocked overlaps evaluate to `C · ∏ factor` (ambient only). Face color uses the face centroid direction (matching baked shading). + - **Single-light solid face:** normally paints one path filled with `remaining` at `shadow.opacity`; switches to the **opaque pre-blend** `blend(fullLitFill, remaining, shadow.opacity)` at alpha `1` *only* when that face actually bleeds a crease (see below). Paying the opaque form everywhere is not free: `shadow.lift` floats the SVG above its face, and at grazing angles that parallax hangs part of the card past the receiver silhouette where opaque paint deviates ~4× more from the backdrop than 25% alpha (measured: mean Δ 54 → 209 of 255 over ~580 off-surface px on a lit cube; `lift=0` removes 99%). Callers must read `MergedShadowFace.layers[].opacity` and never assume either value. + - **Textured receivers:** no uniform multiply base; fall back to per-pass alpha layers that cumulatively darken. +- **No atlas redraw:** Moving a light or changing caster/receiver geometry re-emits shadow SVGs only (DOM/SVG work, never redraws texture atlases). + +### Receiver-clip seam bleed (closing pale hairlines) + +Two abutting antialiased SVG clip edges do not sum to 100% coverage, leaving pale hairlines where a shadow crosses a receiver edge. `prepareReceiverFacePlanes` records two edge sets per member, unioned by `computeReceiverShadowFaces` into one outward clip expansion of `SHADOW_CLIP_SEAM_BLEED` (`0.75` px): + +- **`memberSharedEdges`:** neighbour is another member of the *same* coplanar group (subpaths live in one `nonzero` compound path, so always enabled). +- **`memberCreaseEdges`:** neighbour is a member of a *different*, non-coplanar group (dominant class on imported architecture). + - Matched in **world space** on unsnapped `memberPolysWorld` (exact quantized endpoint hash, then `spatialEdgesShareLine` over a 3D spatial hash for unmatched edges). Lifting `(u, v)` back to 3D snaps ~0.3px non-planar quads to different points and pushed 272 castle creases past `RECEIVER_EDGE_PERP_EPS` (`0.25`). + - Edges already in `memberSharedEdges` still record their crease neighbours so floor-meets-wall partitions satisfy reciprocity on both sides. + - True mesh-boundary edges have no neighbour in either set and are never bled (shadows never push past silhouettes). +- **Eligibility & two-phase reciprocity:** Because overlapping fractional-alpha SVGs double-darken, crease bleed is gated on the **opaque pre-blend** being both available and exact: + 1. Solid receiver, exactly 1 light pass. + 2. Every group member paints exact `fullLitFill` when re-shaded from its own normal and centroid (`groupMembersShareLitColor` — groups admit ~2.5° spread via `RECEIVER_NORMAL_TOL`, where residual `(leaf − fullLitFill)·(1 − opacity)` reached 11/255; on castle this check costs 7 of 2,286 groups and 0 mounted faces). + 3. `blendShadowOverLitBase` returns opaque hex (`null` for translucent `rgba(...)` receivers). + 4. `qualifiesCrease` checks 4 neighbour conditions: neighbour faces the camera, emits a layer in this pass, has the exact same opaque pre-blend color, and bleeds back toward this face. + - **Phase 1** computes all faces with crease bleed off (emission is crease-independent); **Phase 2** re-runs only planes with a qualifying neighbour, widening a local *copy* of the convex hull clip by `CLIP_OUTLINE_EXTRA` (`0.25` px, keeping stored `RECEIVER_OUTLINE_EXPAND = 0.5` untouched so multi-light/textured SVG geometry never shifts). + - `memberPolysWorld`, `memberSharedEdges`, and `memberCreaseEdges` are optional on `ReceiverFacePlane` so hand-built planes degrade safely to no bleed / no pre-blend. + +### Camera visibility boundary gate & memoization + +- Receiver shadows depend on camera angle in two places (back-face culling and camera-facing crease bleed), so orbits re-emit only when crossing a receiver-face visibility boundary — gated by `receiverShadowCameraSignature` (one `normalFacesCamera` bit per light-reachable plane, packed 5 bits per base-32 digit prefixed with contributing plane count). +- Unlit planes are omitted via `ReceiverShadowSignatureLights` so horizon crossings of unlit walls never trigger re-emits. Mesh rotation is omitted because `plane.n` is already world-frame (transform changes rebuild planes before comparing keys). +- Measured on bench castle (self-shadow + floor, parametric def 48): 360° orbit in 1° steps re-emits 71 times (~once per 5° azimuth, median 0 ms, mean 2.2 ms; projection/merge is ~98% of each re-emit). +- All three renderers share per-caster memoization: cached world-space caster items, per-caster parametric overrides (at most `self`/`cross`), and a shared overlap-dedup cache. + +### Exact caster paths (silhouette vs per-polygon) + +- **Silhouette fast path (default for cross-mesh casters ≥ 40 polys):** projects clean closed silhouette loops when `silhouetteReliable` holds (every silhouette vertex has degree exactly 2). +- **Per-polygon union fallback:** used for non-manifold / T-junction / open-boundary casters (imported architecture) and **all** self-shadow passes. Casts double-sided (skips light backface cull) so single-sided interior walls don't leave holes; closed-mesh far backfaces sit below each lit receiver plane and get half-space clipped away. + +### Parametric & pixel shadows (`shadow.parametric`, `shadow.style`, `shadow.definition`) + +Opt-in lightweight proxy replacing per-poly/silhouette projection with rasterized coverage-contour loops: + +- **Invariants:** flat casters (`isFlatCaster`) route to the exact path; convex casters (`isConvexCaster`) skip self-shadow; cross-mesh uses 1 flat proxy slid toward the light; self-shadow uses depth-stratified bands biased to their far-from-light edge. +- **Styles (`shadow.style`):** + - `"vector"` (default): marching squares + Douglas–Peucker; nested holes (courtyards, arenas) emit opposite winding by depth so they subtract under `fill-rule: nonzero`. + - `"pixel"`: greedy-meshes the coverage mask into axis-aligned rectangles for a blocky/voxel shadow; holes drop out naturally as empty cells. +- **Point lights:** each shadow-casting point light gets its own radial override built along `casterCentroid → lightPosition` (`overridePointSilhouettes`), never reusing the directional override. +- **Shared core builder:** `buildParametricCasterOverride` lives in `core` so vanilla, React, and Vue emit byte-identical loops. +- **Cost & smooth-interaction knobs:** Cross-mesh shadows follow moving lights at 60fps+; self-shadow is O(faces × bands × points) and irreducible by broad-phase AABB culling. Two knobs control interactive cost: + - Per-mesh `shadowDefinition` (`PolyMeshTransform.shadowDefinition`, ``, `shadow-definition`). + - Progressive `shadow.dragDefinition` (**vanilla-only**, intentional asymmetry — React/Vue apps lower `shadow.definition` in state during drag): light-direction changes emit at `min(def, dragDefinition)` (castle ~100fps at 16 vs 36fps at 96), then a debounced pass refines at full `definition` once settled. +- **Animated shadows (`shadow.followAnimation`, all three renderers):** frozen by default during same-topology deforms; opting in throttles re-emits to an 80ms leading + trailing window (~12fps) so paused animations land on their final pose. Topology changes always re-emit. The fps↔definition curve and per-phase breakdown can be profiled with `bench/perf-vanilla.html` and the `chrome-trace` skill. -The `.vox` fast path emits plain `` elements inside `.polycss-voxel-face` wrappers. They intentionally reuse the cheap quad tag; each visible quad has one `matrix3d(...)`, with same-color shared-edge overscan folded into the local left/top/width/height before matrix generation. The face wrappers are grouping nodes for cheap add/remove and are not render-strategy leaves. Desktop-class documents use a canonical 1px primitive for the cheapest transform shape; mobile-class documents (`pointer: coarse` or `hover: none`) use an 8px primitive and divide the in-plane matrix scale by 8 to preserve identical CSS-space geometry while avoiding large GPU filtering gaps. +--- + +## Lights & lighting modes ### Lights -The scene takes one `directionalLight`, one `ambientLight`, and zero or more `pointLights` (`PolyPointLight[]`). Directional light `direction` is the unit source vector from the surface toward the distant light. Point lights are **direction-only** — no distance falloff. Per polygon the contribution is `color · intensity · max(0, n · L̂)`, where `L̂` is the unit direction from the surface to the light position; multiple colored lights accumulate per-channel alongside the directional + ambient terms. This deliberately omits CSS gradients: point lights shade flat-per-face (an accepted approximation vs three.js's per-fragment `PointLight(distance:0, decay:0)`; exact for small faces / distant lights). Point lights are **baked-mode only** — the dynamic mode's zero-JS light move can't express a per-face direction that varies with position, so dynamic scenes ignore `pointLights` entirely: not for surface shading, and not for shadows. (A point light casting a shadow onto a floor those same lights never lit would read as broken, so dynamic shadows are directional-only — see the lighting modes below.) +The scene takes one `directionalLight`, one `ambientLight`, and zero or more `pointLights` (`PolyPointLight[]`). + +- `directionalLight.direction` is the unit source vector from the surface toward the distant light. +- `pointLights` are **direction-only** (no distance falloff — flat per-face from centroid toward light, matching `THREE.PointLight(color, intensity, 0, 0)` for small faces/distant lights) and **baked-mode only** (ignored for both surface shading and shadows in dynamic mode because per-face direction varies with position). ### Lighting modes (`PolyTextureLightingMode = "baked" | "dynamic"`) -- **Baked.** Lambert (directional + each point light + ambient) is computed once on the CPU per polygon, multiplied into the inline `color` (for ``/``/``) or into the rasterised atlas pixels (for atlas-backed ``). Direct image `` leaves preserve source pixels and use `texturePresentation.lighting="source"`; scene-lit direct images fall back to the atlas path. Moving a light requires explicit re-rasterising of affected lit atlas polys via `mesh.rebakeAtlas()` — the atlas bake (canvas raster + async `toBlob`) is the one expensive step, so the vanilla imperative API does NOT auto-rebake the lit surface on a `setOptions({directionalLight})` change; that keeps high-frequency light drags fast (the caller rebakes, typically debounced to drag-end). Cast shadows ARE cheap (CPU-projected SVG paths) so they re-emit automatically on any light change — direction, intensity, or color (intensity 0 removes the shadow) — and follow the light interactively even while the baked lit side stays frozen. **Renderer asymmetry:** the declarative React/Vue components re-render → auto-rebake the lit surface on any light prop change; vanilla freezes it until an explicit `rebakeAtlas()`. This is intentional (vanilla keeps the fast-drag escape hatch); for live/animated lights prefer dynamic mode. Left as-is by design — do not "fix" the asymmetry by making vanilla auto-rebake without explicit approval. **Exception:** a `setOptions({pointLights})` change DOES re-render every mesh in vanilla (`createPolyScene.ts` `pointLightsChanged` → `renderEntry`), so the freeze applies to the directional light only. -- **Dynamic.** Scene root carries the directional + ambient setup as custom properties (`--plx/y/z`, `--plr/g/b`, `--pli`, `--par/g/b`, `--pai`). Each leaf embeds its surface normal (`--pnx/y/z`) and base color (`--psr/g/b`) inline. CSS `calc()` resolves the Lambert dot product and per-channel tint at paint time. Moving a light mutates scene-root vars for surface lighting — zero JS, no atlas redraw. Point lights are not represented in dynamic mode at all — neither surface shading nor shadows (see above). Cast shadows are **directional-only** in dynamic mode (CPU-projected SVG paths, ambient fill) and re-emit when the directional light changes. +- **Baked:** Lambert (directional + each point light + ambient, linear-space `/ π` matching Three.js `MeshLambertMaterial`) is computed once on the CPU per polygon into inline `color` (``/``/``) or rasterised atlas pixels (``). + - Direct image `` leaves preserve source pixels (`texturePresentation.lighting="source"`); scene-lit direct images fall back to the atlas path. + - **Intentional renderer asymmetry:** Vanilla defaults `bakedLightPolicy: "manual"`, freezing baked lit surfaces on `setOptions({ directionalLight })` until explicit `mesh.rebakeAtlas()` so high-frequency light drags stay fast (cast shadows still follow live, and `setOptions({ pointLights })` does re-render). React and Vue pass `bakedLightPolicy: "auto"` to auto-rebake on light prop changes. Do not "fix" this asymmetry without explicit approval. +- **Dynamic:** Scene root carries directional + ambient setup as `@property`-registered custom properties (`--plx/y/z`, `--plr/g/b`, `--pli`, `--par/g/b`, `--pai`). Leaves carry `--pnx/y/z` and `--psr/g/b` (or inherit hoisted `--plam` from `.polycss-bucket`). CSS `calc()` resolves linear-space Lambert at paint time — zero JS, no atlas redraw. Point lights are ignored; cast shadows are directional-only. + +All solid and atlas-backed tags work in both modes. Direct image `` leaves are source-lit only. The `.vox` direct-matrix fast path is baked-only (dynamic mode uses the polygon path). The full CSS coverage matrix lives in `packages/polycss/src/styles/styles.ts`. + +--- -All solid and atlas-backed tags work in both modes. Direct image `` leaves are source-lit only; callers that need scene lighting use the atlas backend. The `.vox` direct-matrix fast path is baked-only for now; dynamic mode uses the polygon path so lighting semantics stay correct. The full coverage matrix is in each renderer's `styles.ts`. +## Meshing implications (what generators must respect) -### Meshing implications (what generators must respect) +- **Polygon count is the dominant cost.** Each polygon is one DOM node, one `matrix3d`, one paint. Halving polygon count is almost always worth a smarter mesher. +- **Lossy optimization favors low DOM render cost.** Default `"lossy"` `loadMesh` bakes uniform solid texture swatches, merges visually redundant baked swatch colors, tries endpoint-preserving static QEM triangle simplification (relaxed seam-key pass + strict source-vertex fallback, accepted only when final DOM leaf count beats baseline), and scores exact + approximate isolated triangle-pair merge candidates inside the boundary displacement budget (accepting aggressive variants only on material cost win with non-worsening seam/topology diagnostics). + - **STL conservative exception:** STL parse results force `"lossless"` and skip ray-based interior culling because public CAD/STL corpora often have open/non-manifold shells where false-positive culling causes visible data loss. + - Import uses read-only `seamOverlapSafetyDiagnostics` to gate aggressive lossy candidates without mutating seam geometry. +- **Fill ratio matters for atlas `` leaves.** An atlas slice equals its local-2D bounding rect (`area / bboxArea`: axis-aligned rect = `1.0`, right-isosceles triangle = `0.5`, skinny triangle ≪ `0.5`). +- **Regular grids are not a constraint.** Any crack-free planar tiling without T-junctions is valid; break grids to fit larger axis-aligned rects. +- **Coplanarity is a hard requirement at render time.** Non-triangular polygons must have all vertices on one plane within epsilon, or the renderer opens seams. Snap-and-propagate shared vertices to a common plane within the cumulative per-vertex displacement budget. -- **Polygon count is the dominant cost.** Each polygon is one DOM node, one `matrix3d`, one paint. Halving the polygon count is almost always worth a more complex mesher. -- **Lossy optimization favors low DOM render cost.** The default `"lossy"` `loadMesh` / core import path first bakes solid texture swatches, merges visually redundant baked swatch colors, and tries endpoint-preserving static triangle simplification for eligible non-animated meshes. It then scores exact and approximate merge candidates by estimated render cost and keeps the cheapest direct candidate. Static simplification has a relaxed seam-key pass plus a stricter source-vertex fallback, and is accepted only when the final optimized DOM leaf count is lower than the baseline optimizer result. The polygon optimizer can also try a more aggressive triangle-pair merge candidate inside the same boundary displacement budget, but accepts it only when the render-cost win is material and whole-mesh seam diagnostics do not get worse. STL parse results are the conservative exception: they keep the lossless optimizer path and skip ray-based interior culling because public CAD/STL corpora frequently contain shell, winding, or topology quirks where false-positive culling is a visible data-loss bug. It avoids per-candidate seam-repair passes in the import path; targeted seam repair remains a lower-level helper for explicit repair workflows. -- **Fill ratio matters.** An atlas-backed textured polygon's atlas slice equals its local-2D bounding rect. Empty space inside that slice is wasted bitmap pixels. Direct image leaves avoid atlas memory, but only for source-exact surfaces with preserved source metadata and source lighting. Prefer atlas shapes with high `area / boundingRect.area`: - - axis-aligned rectangle = 1.0 (and hits the fastest path) - - right-isosceles triangle = 0.5 - - skinny/long triangle ≪ 0.5 (worst case — many such triangles balloon atlas memory) -- **Regular grids are not a constraint.** Vertices may sit anywhere on the surface. Any planar tiling whose edges match across neighbours (no T-junctions, no cracks) is valid. Break the grid where it lets you fit larger axis-aligned rects to flat regions. -- **Coplanarity is a hard requirement at render time, but the mesher can engineer it.** A non-triangular polygon must have all vertices on a common plane within a small epsilon, or the renderer snaps the offending vertex in isolation and opens a visible seam with adjacent polygons. The mesher avoids this either by (a) only merging when natural coplanarity holds, or (b) deliberately snapping shared vertices to a common plane and propagating the new position to *every* polygon that references them. Snap-and-propagate is preferred when it widens the merge opportunity, subject to the budget below. -- **Vertex displacement budget.** Every snap consumes budget on the moved vertex and on all polygons that reference it. Track cumulative displacement from the original DEM-sampled position per vertex; reject any merge that would push a vertex past the user's height tolerance. Errors compound across merges, so the bound is per-vertex cumulative drift, not per-merge. +--- ## The "no JS in the render loop" principle -This is the load-bearing constraint behind the whole engine. **JavaScript should not run per-frame to paint polygons when the motion can be expressed as a scene, mesh, camera, or light update.** Once the scene is built and the atlas is rasterised, the browser drives most rendering through CSS — `matrix3d` transforms, `calc()`-driven custom properties, `background-blend-mode`, `border-shape`, etc. +**JavaScript must not run per-frame to paint polygons when motion can be expressed as a scene, mesh, camera, or light update.** Once built and rasterised, the browser drives rendering via CSS (`matrix3d`, `@property` `calc()`, `background-blend-mode`, `corner-shape`, `border-shape`). -The renderer exception is imported skeletal animation. glTF/GLB skinning changes each polygon independently, so the vanilla stable-DOM animation path samples the active clip in JS, keeps the leaf set mounted, caches baked stable-triangle transform frames, and pins each mounted triangle's baked color while transforms animate. Recomputing Lambert from every deformed low-poly face normal creates visible color pumping, so color refresh is internal opt-in rather than the default animation behavior. On WebKit/Safari, where stable CSS triangles fall through to solid atlas `` leaves, same-topology animation updates keep the existing atlas elements and bitmap URLs mounted, cache transform frames once warmed, and hide briefly degenerate atlas triangles only until the next valid frame. That optimized path is the default; do not add a user-facing "baseline vs optimized" toggle or maintain a legacy slow path in product UI. +### The two closed exceptions -The domformat reference mount has one separate, closed exception: it may schedule validated prepared playback and interaction tables. The scheduler sleeps on a deadline timer and requests one paint-aligned animation frame only when a bounded-rate, exact rational-microsecond, or prepared timeline deadline is due; it does not poll display frames continuously. It may write only declared sinks on retained targets, never reconstruct topology or evaluate producer code, expressions, renderer internals, or arbitrary network resources, and is disabled by `animate: false`. The binding selects bounded catch-up (up to eight ordered ticks, then one suspension tick), single-step deadline reset, or animation-only collapsed elapsed reconstruction. Prepared effects and interaction simulate every admitted tick because their state is history-dependent, so they cannot use collapsed elapsed catch-up. Closed compositor timing may instead give a retained model cycle to viewer-owned WAAPI or add viewer-owned linear transform transitions for fixed cadence only; seek, catch-up, restart, pause, and wrap synchronously snap prepared state. This is a reference implementation of an already-lowered wire profile, not a PolyCSS renderer loop. +1. **Imported skeletal animation:** glTF/GLB skinning deforms each polygon independently. The vanilla stable-DOM path samples the active clip in JS via zero-allocation `Float64Array` frames (`updateStableTriangleFrame`), keeps leaves mounted, caches baked transform frames, and pins baked triangle colors while transforms animate (recomputing Lambert per deformed low-poly normal causes color pumping, so color refresh is internal opt-in only). On WebKit/Safari where triangles fall back to solid atlas `` leaves, `updatePolygonsWithStableTopology` keeps atlas elements and blob URLs mounted, caches transform frames, and hides briefly degenerate triangles until the next valid frame. Do not add a user-facing "baseline vs optimized" toggle. +2. **Closed `domformat` reference mount:** May schedule validated prepared playback and interaction tables via deadline timers (`setTimeout` → single paint-aligned rAF, no continuous display polling), writing only declared sinks on retained targets (disabled by `animate: false`). Supports bounded catch-up (≤ 8 ticks + 1 suspension tick), single-step deadline reset, or animation-only collapsed elapsed reconstruction (effects/interaction simulate every admitted tick). Closed compositor timing may hand fixed-cadence cycles to viewer-owned WAAPI or linear CSS transitions, snapping synchronously on seek/catch-up/restart/pause/wrap. | Where JS runs | Where JS does NOT run | |---|---| | Scene construction (`createPolyScene`, mesh ops, vertex snapping) | Per-frame polygon paint | -| OBJ/STL/glTF/GLB import, mesh optimisation, coplanar merging | Per-frame Lambert evaluation (dynamic mode is pure CSS) | +| OBJ/STL/glTF/GLB/VOX import, mesh optimisation, coplanar merging | Per-frame Lambert evaluation (dynamic mode is pure CSS) | | Atlas planning + rasterisation (one-shot to ``, then `toBlob`) | Per-frame atlas redraw (only on baked-mode light changes) | -| Control input handling (`PolyOrbitControls`, `PolyMapControls`, `PolyTransformControls`) | Per-frame transform recomputation of every polygon for camera/mesh motion — only the scene-root or mesh-root transform changes | +| Control input handling (`PolyOrbitControls`, `PolyMapControls`, `PolyTransformControls`) | Per-frame transform recomputation of every polygon for camera/mesh motion | | Camera math (matrix4 product → scene-root `transform` CSS var) | Per-polygon JS in any hot path | | Hover/selection raycasting (only on pointer events, not per frame) | Continuous renderer re-rendering "ticks" | -If you find yourself wanting a `requestAnimationFrame` loop to update many renderer DOM nodes outside skeletal animation or the closed domformat prepared-runtime exception, stop. Find the CSS variable that should be carrying the change, and update that single variable on a single ancestor. Cascading + `@property`-registered custom properties do the rest. +If you find yourself wanting a `requestAnimationFrame` loop to update many renderer DOM nodes outside skeletal animation or the closed `domformat` prepared-runtime exception, stop. Find the CSS variable that should carry the change, and update that single variable on a single ancestor. diff --git a/.github/architecture/repo-map.md b/.github/architecture/repo-map.md index 0da0195e5..e7b39b8eb 100644 --- a/.github/architecture/repo-map.md +++ b/.github/architecture/repo-map.md @@ -1,20 +1,20 @@ # PolyCSS Repository Map -Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **512 files**, **99,750 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. +Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **507 files**, **97,247 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. ## 1. Packages & Entry Points | Package | Visibility | Exports | Workspace deps | Src files | Src lines | Test files | |---|---|---|---|---:|---:|---:| -| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 104 | 27,402 | 58 | +| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 100 | 25,369 | 57 | | `packages/domformat` (`@layoutit/polycss-domformat`) | private | `., ./browser` | — | 36 | 13,165 | 0 | | `packages/fonts` (`@layoutit/polycss-fonts`) | npm | `.` | `@layoutit/polycss-core` | 7 | 1,656 | 4 | | `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 54 | 7,826 | 14 | -| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./internal, ./elements, ./three` | `@layoutit/polycss-core` | 95 | 17,300 | 42 | -| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,651 | 31 | +| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./internal, ./elements, ./three` | `@layoutit/polycss-core` | 94 | 16,912 | 43 | +| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,635 | 31 | | `packages/skills` (`@layoutit/polycss-skills`) | npm | `.` | — | 1 | 415 | 1 | -| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,437 | 29 | +| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,365 | 29 | ## 2. Canonical Workspace Source Aliases @@ -45,18 +45,18 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | Fan-in | Lines | File | |---:|---:|---| -| 127 | 528 | `packages/core/src/index.ts` | -| 92 | 248 | `packages/core/src/types.ts` | -| 46 | 301 | `packages/react/src/index.ts` | +| 126 | 537 | `packages/core/src/index.ts` | +| 87 | 247 | `packages/core/src/types.ts` | +| 46 | 289 | `packages/react/src/index.ts` | | 44 | 119 | `website/src/components/types.ts` | -| 29 | 148 | `packages/polycss/src/runtime.ts` | -| 25 | 220 | `packages/polycss/src/index.ts` | +| 30 | 145 | `packages/polycss/src/runtime.ts` | +| 25 | 217 | `packages/polycss/src/index.ts` | | 23 | 88 | `website/src/components/GalleryWorkbench/types.ts` | -| 20 | 57 | `packages/polycss/src/internal.ts` | -| 17 | 49 | `packages/core/src/math/vec3.ts` | -| 17 | 385 | `packages/polycss/src/api/createPolyScene.ts` | -| 16 | 366 | `packages/core/src/atlas/types.ts` | -| 16 | 45 | `packages/polycss/src/render/textureAtlas.ts` | +| 20 | 59 | `packages/polycss/src/internal.ts` | +| 17 | 414 | `packages/polycss/src/api/createPolyScene.ts` | +| 16 | 350 | `packages/core/src/atlas/types.ts` | +| 16 | 49 | `packages/core/src/math/vec3.ts` | +| 16 | 42 | `packages/polycss/src/render/textureAtlas.ts` | ### Largest production source files diff --git a/.github/mirror-waivers.json b/.github/mirror-waivers.json index 0967ef424..dfd37f9a0 100644 --- a/.github/mirror-waivers.json +++ b/.github/mirror-waivers.json @@ -1 +1,26 @@ -{} +{ + "scene-components": { + "reason": "Vue-only SSR guard in usePolyMesh watch({ immediate: true }); React useEffect never executes during Node SSR.", + "files": ["packages/vue/src/scene/useMesh.ts"], + "expectedLanes": ["vue"], + "baseHashes": { + "packages/vue/src/scene/useMesh.ts": "4f82d0614571ca4c9ae0a8850d49aa64083c599d23ec34aa3b1a1eec592f46ce" + } + }, + "shapes": { + "reason": "Vue PolyShapes catches up to React PolyShapes by forwarding all PolyMesh props, events, class/style, and slots via definePolyShape.", + "files": ["packages/vue/src/shapes/PolyShapes.ts"], + "expectedLanes": ["vue"], + "baseHashes": { + "packages/vue/src/shapes/PolyShapes.ts": "41bb795fc4997da06c58a4d68a2dc13699069d0c27e6aed51c0be7a1add42314" + } + }, + "store": { + "reason": "React-only getServerSnapshot argument to useSyncExternalStore for Node SSR; Vue store does not use useSyncExternalStore.", + "files": ["packages/react/src/store/sceneStore.ts"], + "expectedLanes": ["react"], + "baseHashes": { + "packages/react/src/store/sceneStore.ts": "5e334d78a77d02d2a93fdbb14809997f969145991e3813d036646054f61fc0d1" + } + } +} diff --git a/.github/scripts/bump-versions.mjs b/.github/scripts/bump-versions.mjs index a499c9d84..558fa1989 100644 --- a/.github/scripts/bump-versions.mjs +++ b/.github/scripts/bump-versions.mjs @@ -3,14 +3,17 @@ * Bump every publishable package under `packages/*` in lockstep. * * Usage: - * node .github/scripts/bump-versions.mjs + * node .github/scripts/bump-versions.mjs [--dry-run] * * Reads the current version from every non-private package (refusing to bump - * if they have drifted out of lockstep), applies the requested semver bump, - * writes the new version back with a regex (preserving formatting), and prints - * the new version to stdout (also exporting NEXT_VERSION / version when + * if they have drifted out of lockstep), fails closed if previously exported + * public symbols were removed since `v` on a non-breaking bump + * (`patch` on 0.x, or `patch`/`minor` on >=1.0), applies the requested semver + * bump, writes the new version back with a regex (preserving formatting), and + * prints the new version to stdout (also exporting NEXT_VERSION / version when * GITHUB_ENV / GITHUB_OUTPUT are set). */ +import { execFileSync } from "node:child_process"; import { appendFileSync, existsSync, @@ -20,16 +23,130 @@ import { } from "node:fs"; import { resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; +import { extractBarrelExports } from "./check-exports.mjs"; import { isDirectRun } from "./is-direct-run.mjs"; const __dirname = dirname(fileURLToPath(import.meta.url)); -const defaultPackagesRoot = resolve(__dirname, "..", "..", "packages"); +const defaultRepoRoot = resolve(__dirname, "..", ".."); +const defaultPackagesRoot = resolve(defaultRepoRoot, "packages"); const VERSION_RE = /^(\s*"version":\s*")(\d+)\.(\d+)\.(\d+)(")/m; +export const PUBLIC_EXPORT_BARRELS = [ + "packages/core/src/index.ts", + "packages/core/src/three/index.ts", + "packages/polycss/src/index.ts", + "packages/polycss/src/runtime.ts", + "packages/polycss/src/three.ts", + "packages/react/src/index.ts", + "packages/react/src/three/index.ts", + "packages/vue/src/index.ts", + "packages/vue/src/three/index.ts", + "packages/fonts/src/index.ts", + "packages/morph/src/index.ts", + "packages/morph/src/prepare/index.ts", +]; + +function gitShow(repoRoot, refSpec) { + try { + return execFileSync("git", ["show", refSpec], { + cwd: repoRoot, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }); + } catch { + return null; + } +} + +function gitTagExists(repoRoot, tag) { + try { + execFileSync("git", ["rev-parse", "--verify", "--quiet", `refs/tags/${tag}`], { + cwd: repoRoot, + stdio: ["ignore", "ignore", "ignore"], + }); + return true; + } catch { + return false; + } +} + +export function findRemovedExportsSinceTag({ + repoRoot = defaultRepoRoot, + baseTag, + barrels = PUBLIC_EXPORT_BARRELS, + readAtTag = (relPath) => gitShow(repoRoot, `${baseTag}:${relPath}`), + readCurrent = (relPath) => { + const abs = resolve(repoRoot, relPath); + return existsSync(abs) ? readFileSync(abs, "utf8") : null; + }, +} = {}) { + const removals = []; + for (const barrel of barrels) { + const baseSrc = readAtTag(barrel); + if (baseSrc === null) continue; + const baseExp = extractBarrelExports(baseSrc); + const curSrc = readCurrent(barrel); + const curExp = curSrc !== null + ? extractBarrelExports(curSrc) + : { values: new Set(), types: new Set() }; + const removedValues = [...baseExp.values].filter((v) => !curExp.values.has(v)).sort(); + const removedTypes = [...baseExp.types].filter((t) => !curExp.types.has(t)).sort(); + if (removedValues.length > 0 || removedTypes.length > 0) { + removals.push({ barrel, removedValues, removedTypes }); + } + } + return removals; +} + +export function assertSemverCompatibleWithExports({ + repoRoot = defaultRepoRoot, + previousVersion, + bump, + baseTag = `v${previousVersion}`, + barrels = PUBLIC_EXPORT_BARRELS, + readAtTag, + readCurrent, +} = {}) { + const major = Number(String(previousVersion).split(".")[0]); + const allowsBreaking = major === 0 ? bump !== "patch" : bump === "major"; + if (allowsBreaking) return []; + if (!readAtTag && !gitTagExists(repoRoot, baseTag)) return []; + + const removals = findRemovedExportsSinceTag({ + repoRoot, + baseTag, + barrels, + ...(readAtTag ? { readAtTag } : {}), + ...(readCurrent ? { readCurrent } : {}), + }); + if (removals.length > 0) { + const requiredBump = major === 0 ? "minor" : "major"; + const summary = removals + .map((r) => { + const parts = []; + if (r.removedValues.length > 0) { + parts.push(`values(${r.removedValues.length}): ${r.removedValues.slice(0, 6).join(", ")}${r.removedValues.length > 6 ? ", ..." : ""}`); + } + if (r.removedTypes.length > 0) { + parts.push(`types(${r.removedTypes.length}): ${r.removedTypes.slice(0, 6).join(", ")}${r.removedTypes.length > 6 ? ", ..." : ""}`); + } + return ` - ${r.barrel}: ${parts.join("; ")}`; + }) + .join("\n"); + throw new Error( + `Cannot run "${bump}" release from ${previousVersion}: public exports were removed since ${baseTag} (requires "${requiredBump}" bump):\n${summary}`, + ); + } + return []; +} + export function bumpVersions({ packagesRoot = defaultPackagesRoot, + repoRoot = defaultRepoRoot, bump, env = process.env, + dryRun = false, + checkExports = packagesRoot === defaultPackagesRoot, } = {}) { if (!["patch", "minor", "major"].includes(bump)) { throw new Error(`Invalid bump "${bump}" (expected patch, minor, or major)`); @@ -69,29 +186,42 @@ export function bumpVersions({ ); } + if (checkExports) { + assertSemverCompatibleWithExports({ + repoRoot, + previousVersion: base.version, + bump, + }); + } + const next = bump === "major" ? `${base.maj + 1}.0.0` : bump === "minor" ? `${base.maj}.${base.min + 1}.0` : `${base.maj}.${base.min}.${base.pat + 1}`; - for (const p of parsed) { - writeFileSync(p.file, p.src.replace(VERSION_RE, `$1${next}$5`)); - } + if (!dryRun) { + for (const p of parsed) { + writeFileSync(p.file, p.src.replace(VERSION_RE, `$1${next}$5`)); + } - if (env.GITHUB_ENV) { - appendFileSync(env.GITHUB_ENV, `NEXT_VERSION=${next}\n`); - } - if (env.GITHUB_OUTPUT) { - appendFileSync(env.GITHUB_OUTPUT, `version=${next}\n`); + if (env.GITHUB_ENV) { + appendFileSync(env.GITHUB_ENV, `NEXT_VERSION=${next}\n`); + } + if (env.GITHUB_OUTPUT) { + appendFileSync(env.GITHUB_OUTPUT, `version=${next}\n`); + } } - return { previous: base.version, next, updated: packages }; + return { previous: base.version, next, updated: packages, dryRun }; } if (isDirectRun(import.meta.url)) { try { - const res = bumpVersions({ bump: process.argv[2] }); - console.log(`bumped ${res.previous} -> ${res.next}`); + const args = process.argv.slice(2); + const dryRun = args.includes("--dry-run"); + const bump = args.find((a) => !a.startsWith("--")); + const res = bumpVersions({ bump, dryRun }); + console.log(`${dryRun ? "[dry-run] " : ""}bumped ${res.previous} -> ${res.next}`); } catch (err) { console.error(err?.message ?? err); process.exit(1); diff --git a/.github/scripts/bump-versions.test.mjs b/.github/scripts/bump-versions.test.mjs index 277f7d7ce..beb259132 100644 --- a/.github/scripts/bump-versions.test.mjs +++ b/.github/scripts/bump-versions.test.mjs @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { bumpVersions } from "./bump-versions.mjs"; +import { assertSemverCompatibleWithExports, bumpVersions } from "./bump-versions.mjs"; function makeWorkspace(pkgs) { const dir = mkdtempSync(join(tmpdir(), "polycss-bump-test-")); @@ -69,3 +69,57 @@ test("bumpVersions fails closed on invalid bump or drifted package versions", () rmSync(dir, { recursive: true, force: true }); } }); + +test("assertSemverCompatibleWithExports fails closed on removed exports for patch on 0.x and minor on 1.x+", () => { + const barrels = ["packages/core/src/index.ts"]; + const readAtTag = () => 'export { keep, removedFn } from "./a";\nexport type { RemovedType } from "./a";\n'; + const readCurrent = () => 'export { keep } from "./a";\n'; + + assert.throws( + () => + assertSemverCompatibleWithExports({ + previousVersion: "0.2.11", + bump: "patch", + barrels, + readAtTag, + readCurrent, + }), + /requires "minor" bump[\s\S]*removedFn[\s\S]*RemovedType/, + ); + + // 0.x minor bump allows breaking export removals. + assert.deepEqual( + assertSemverCompatibleWithExports({ + previousVersion: "0.2.11", + bump: "minor", + barrels, + readAtTag, + readCurrent, + }), + [], + ); + + // 1.x+ requires major bump for removed exports. + assert.throws( + () => + assertSemverCompatibleWithExports({ + previousVersion: "1.2.0", + bump: "minor", + barrels, + readAtTag, + readCurrent, + }), + /requires "major" bump/, + ); + + assert.deepEqual( + assertSemverCompatibleWithExports({ + previousVersion: "1.2.0", + bump: "major", + barrels, + readAtTag, + readCurrent, + }), + [], + ); +}); diff --git a/.github/scripts/check-elements-observed-attrs.test.mjs b/.github/scripts/check-elements-observed-attrs.test.mjs new file mode 100644 index 000000000..8c58e8209 --- /dev/null +++ b/.github/scripts/check-elements-observed-attrs.test.mjs @@ -0,0 +1,136 @@ +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repoRoot = resolve(__dirname, "../.."); + +function collectStringLiterals(block) { + const out = []; + for (const m of block.matchAll(/"([^"]+)"/g)) out.push(m[1]); + return out; +} + +function collectAttributeReads(src) { + const reads = new Set(); + for (const m of src.matchAll( + /(?:getAttribute|hasAttribute|numAttr|strAttr|parseVec3Attr)\(\s*(?:this|el)?\s*,?\s*"([^"]+)"/g, + )) { + reads.add(m[1]); + } + return [...reads].sort(); +} + +test("every custom element observes every attribute it reads (per-file and per-shape-class)", () => { + const elementsDir = join(repoRoot, "packages/polycss/src/elements"); + const files = readdirSync(elementsDir) + .filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts")) + .sort(); + + const missing = []; + for (const file of files) { + const src = readFileSync(join(elementsDir, file), "utf8"); + const reads = collectAttributeReads(src); + if (reads.length === 0) continue; + + // Resolve top-level const string arrays referenced via `...CONST_NAME`. + const constArrays = new Map(); + for (const m of src.matchAll(/const\s+([A-Z0-9_]+)\s*=\s*\[([\s\S]*?)\]\s*(?:as\s+const)?;/g)) { + constArrays.set(m[1], collectStringLiterals(m[2])); + } + + const expandArrayExpr = (expr) => { + const out = new Set(collectStringLiterals(expr)); + for (const spread of expr.matchAll(/\.\.\.([A-Z0-9_]+)/g)) { + for (const item of constArrays.get(spread[1]) ?? []) out.add(item); + } + return out; + }; + + const classMatches = [...src.matchAll(/export\s+class\s+(\w+)\s+extends\s+(\w+)\s*\{/g)]; + if (classMatches.length > 1) { + // Multi-class file (e.g. PolyShapeElements.ts): check each concrete class + // against both base-class attribute reads and its own body reads. + const firstClassStart = classMatches[0].index; + const baseClassReads = collectAttributeReads(src.slice(0, firstClassStart)); + for (let i = 0; i < classMatches.length; i += 1) { + const clsName = classMatches[i][1]; + const start = classMatches[i].index; + const end = i + 1 < classMatches.length ? classMatches[i + 1].index : src.length; + const body = src.slice(start, end); + const obsMatch = body.match(/observedAttributes[\s\S]*?return\s*\[([\s\S]*?)\]/); + const observed = obsMatch ? expandArrayExpr(obsMatch[1]) : new Set(); + const classReads = [...new Set([...baseClassReads, ...collectAttributeReads(body)])]; + for (const attr of classReads) { + if (!observed.has(attr)) { + missing.push(`${file} (${clsName}): reads "${attr}" without observing it`); + } + } + } + continue; + } + + const observed = new Set(); + for (const m of src.matchAll(/observedAttributes[\s\S]*?return\s*\[([\s\S]*?)\]/g)) { + for (const item of expandArrayExpr(m[1])) observed.add(item); + } + for (const [name, items] of constArrays) { + if (name.includes("OBSERVED")) { + for (const item of items) observed.add(item); + } + } + for (const attr of reads) { + if (!observed.has(attr)) { + missing.push(`${file}: reads "${attr}" without observing it`); + } + } + } + + assert.deepEqual(missing, [], `Unobserved custom-element attributes:\n${missing.join("\n")}`); +}); + +test("packages/core/src/index.ts Part 2 morph-pin comment matches packages/morph/src runtime imports", () => { + const morphSrcDir = join(repoRoot, "packages/morph/src"); + const morphRuntimeImports = new Set(); + + const walk = (dir) => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + if (entry.isDirectory()) { + walk(full); + } else if (entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) { + const src = readFileSync(full, "utf8"); + for (const m of src.matchAll(/import\s*\{([^}]*)\}\s*from\s*["']@layoutit\/polycss-core["']/g)) { + for (const rawSpec of m[1].split(",")) { + const spec = rawSpec.trim(); + if (!spec || spec.startsWith("type ")) continue; + const imported = spec.split(/\s+as\s+/)[0].trim(); + if (imported) morphRuntimeImports.add(imported); + } + } + } + } + }; + walk(morphSrcDir); + + const coreIndex = readFileSync(join(repoRoot, "packages/core/src/index.ts"), "utf8"); + const pinMatch = coreIndex.match( + /\/\/ Morph-pinned runtime imports:\n((?:\/\/[^\n]*\n)+)/, + ); + assert.ok(pinMatch, "packages/core/src/index.ts must list Morph-pinned runtime imports in Part 2"); + const documented = new Set( + pinMatch[1] + .replace(/\/\//g, "") + .split(/[,\s]+/) + .map((s) => s.trim()) + .filter(Boolean), + ); + + assert.deepEqual( + [...documented].sort(), + [...morphRuntimeImports].sort(), + "Part 2 morph-pinned runtime imports comment drifted from packages/morph/src", + ); +}); diff --git a/AGENTS.md b/AGENTS.md index 18cd7a515..1d0eeb221 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,11 +25,11 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ ## Rendering model & core invariants -**Before editing render strategies, lighting, meshing, cast/receiver shadows, or animation paths, read [.github/architecture/rendering-and-shadows.md](.github/architecture/rendering-and-shadows.md).** +**Before editing — or proposing deletions/simplifications to — render strategies, lighting, meshing, cast/receiver shadows, or animation paths, read [.github/architecture/rendering-and-shadows.md](.github/architecture/rendering-and-shadows.md) and the implementation.** - **One visible `Polygon` → one leaf DOM element.** Tag = render strategy, cheapest → most expensive: - `` — Quads (axis-aligned rects; guarded projective quads on non-Safari; `.vox` direct fast path inside `.polycss-voxel-face` wrappers). Zero atlas memory. - - `` — Solid triangles (non-WebKit; `corner-shape` bevel or CSS border trick) and exact corner-shape beveled solids. Zero atlas memory. + - `` — Solid triangles (`corner-shape: bevel` primary — our best triangle; falls back to CSS border trick on non-WebKit) and exact `corner-shape` beveled solids. Zero atlas memory. - `` — Border-shape clipped solids (Chromium + `pointer:fine` + `hover:hover`). Zero atlas memory. - `` — Atlas texture slices, direct `textureImageSource` image leaves, and universal fallback (cannot be disabled). - **No JS in the render loop.** Never run `requestAnimationFrame` to paint or update per-polygon DOM nodes when a scene/mesh/camera/light CSS variable can carry the change. The only exceptions are imported glTF/GLB skeletal skinning and the closed `domformat` prepared-runtime scheduler. @@ -86,7 +86,7 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ - `pnpm bench:gate:lifecycle` — fail-closed Node SSR + Chromium lifecycle gate (`bench/lifecycle-gate.mjs`): verifies pure Node SSR (zero DOM globals), React `` remounts and textured `` blob URLs, `setOptions` / 3× rebake / `undefined` clears, real `.vox` class updates, stable-topology overrides, dynamic shadow emits, Vue async `src` single-mount, and controls interaction. - Shared browser and `ffmpeg` discovery lives in `bench/browser-discovery.mjs`. Gate fail-closed invariants are unit-tested in `bench/{visual,perf,lifecycle}-gate.test.mjs` (`pnpm test:scripts`). - **CI (`.github/workflows/ci.yml`)** runs `test-and-build` (`check:guards`, unified `test:coverage`, `build:packages`, `typecheck`, `check:packs`, `check:ir`, `test:website`, website/bench/examples typecheck & builds), path-filtered PR `visual-gate` (Chromium + Firefox), `perf-gate` (paired A/B on Chromium), `lifecycle-gate` (Node SSR + Chromium), and `certify-domformat-browser` / `certify-gallery-domformat-corpus` (path-filtered on PRs, unconditional on `push: main`). `.github/workflows/publish-packages.yml` runs `check:guards`, `test`, `build:packages`, `typecheck`, `check:ir`, `check:packs`, and `morph test:package` before publishing. -- **Pre-push & dead-code hygiene:** Check `.github/workflows/ci.yml` path filters before editing peripheral packages (`packages/domformat` triggers the 45-minute `certify-domformat-browser` job; `packages/morph` is tested against npm-published `@layoutit/polycss-core` by `test:package:registry`). Always grep the entire repo including `.agents/` (e.g., `.agents/skills/chrome-trace/scripts/`) before deleting any export. +- **Pre-push & dead-code hygiene:** Check `.github/workflows/ci.yml` path filters before editing peripheral packages (`packages/domformat` triggers the 45-minute `certify-domformat-browser` job; `packages/morph` is tested against npm-published `@layoutit/polycss-core` by `test:package:registry`). Always grep the entire repo including `.agents/` (e.g., `.agents/skills/chrome-trace/scripts/`) and `website/` (including DOM tag selectors like `:scope > u, :scope > s` in `VanillaScene/stableAnimationCache.ts`) before deleting any export or changing leaf tags. ## Style / process diff --git a/bench/lifecycle-gate.mjs b/bench/lifecycle-gate.mjs index 68a2c3c07..4b6211b75 100644 --- a/bench/lifecycle-gate.mjs +++ b/bench/lifecycle-gate.mjs @@ -227,48 +227,65 @@ function runSsrCases(selectedSsr) { const out = {}; try { - const reactSceneHtml = ReactDOMServer.renderToString( - React.createElement( - reactMod.PolyPerspectiveCamera, { rotX: 30, rotY: 45 }, + let fetchCalls = 0; + const origFetch = globalThis.fetch; + globalThis.fetch = async () => { + fetchCalls += 1; + throw new Error("SSR must not call fetch"); + }; + try { + const reactSceneHtml = ReactDOMServer.renderToString( React.createElement( - reactMod.PolyScene, { directionalLight: { direction: [0.4, -0.7, 0.59], intensity: 1 } }, - React.createElement(reactMod.PolyMesh, { - id: "ssr-box", - polygons: [{ vertices: [[0,0,0],[1,0,0],[1,1,0],[0,1,0]], color: "#f00" }], - castShadow: true, - }) + reactMod.PolyPerspectiveCamera, { rotX: 30, rotY: 45 }, + React.createElement( + reactMod.PolyScene, { directionalLight: { direction: [0.4, -0.7, 0.59], intensity: 1 } }, + React.createElement(reactMod.PolyMesh, { + id: "ssr-box", + polygons: [{ vertices: [[0,0,0],[1,0,0],[1,1,0],[0,1,0]], color: "#f00" }], + castShadow: true, + }), + React.createElement(reactMod.PolyTransformControls, { object: null }), + ) ) - ) - ); - const vueSceneApp = Vue.createSSRApp({ - render: () => - Vue.h(vueMod.PolyPerspectiveCamera, { rotX: 30, rotY: 45 }, () => - Vue.h( - vueMod.PolyScene, - { directionalLight: { direction: [0.4, -0.7, 0.59], intensity: 1 } }, - () => - Vue.h(vueMod.PolyMesh, { - id: "ssr-box", - polygons: [{ vertices: [[0,0,0],[1,0,0],[1,1,0],[0,1,0]], color: "#f00" }], - castShadow: true, - }), + ); + const vueSceneApp = Vue.createSSRApp({ + render: () => + Vue.h(vueMod.PolyPerspectiveCamera, { rotX: 30, rotY: 45 }, () => + Vue.h( + vueMod.PolyScene, + { directionalLight: { direction: [0.4, -0.7, 0.59], intensity: 1 } }, + () => [ + Vue.h(vueMod.PolyMesh, { + id: "ssr-box", + polygons: [{ vertices: [[0,0,0],[1,0,0],[1,1,0],[0,1,0]], color: "#f00" }], + castShadow: true, + }), + Vue.h(vueMod.PolyMesh, { + id: "ssr-async", + src: "/nonexistent-ssr.obj", + }), + ], + ), ), - ), - }); - const vueSceneHtml = await VueSSR.renderToString(vueSceneApp); - const ok = - !hasDom && - typeof rt.createPolyScene === "function" && - reactSceneHtml.includes("polycss-scene") && - reactSceneHtml.includes("polycss-mesh") && - vueSceneHtml.includes("polycss-scene") && - vueSceneHtml.includes("polycss-mesh"); - out["ssr-node-imports-and-scene"] = { - ok, - detail: ok - ? "domGlobals=false, reactSceneLen=" + reactSceneHtml.length + ", vueSceneLen=" + vueSceneHtml.length - : "Invalid SSR scene output (hasDom=" + hasDom + ", reactLen=" + reactSceneHtml.length + ", vueLen=" + vueSceneHtml.length + ")", - }; + }); + const vueSceneHtml = await VueSSR.renderToString(vueSceneApp); + const ok = + !hasDom && + fetchCalls === 0 && + typeof rt.createPolyScene === "function" && + reactSceneHtml.includes("polycss-scene") && + reactSceneHtml.includes("polycss-mesh") && + vueSceneHtml.includes("polycss-scene") && + vueSceneHtml.includes("polycss-mesh"); + out["ssr-node-imports-and-scene"] = { + ok, + detail: ok + ? "domGlobals=false, fetchCalls=0, reactSceneLen=" + reactSceneHtml.length + ", vueSceneLen=" + vueSceneHtml.length + : "Invalid SSR scene output (hasDom=" + hasDom + ", fetchCalls=" + fetchCalls + ", reactLen=" + reactSceneHtml.length + ", vueLen=" + vueSceneHtml.length + ")", + }; + } finally { + globalThis.fetch = origFetch; + } } catch (err) { out["ssr-node-imports-and-scene"] = { ok: false, detail: String(err) }; } diff --git a/packages/core/README.md b/packages/core/README.md index fc3550e82..d64d23b18 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -71,14 +71,13 @@ already-loaded input. `BASE_TILE`. - **Transforms** — `buildPolyMeshTransform`, `buildPolySceneTransform`, rotation and quaternion helpers. -- **Color + lighting** — `parseColor`, `parsePureColor`, `shadeColor`, - `computeShapeLighting`. +- **Color + lighting** — `parseColor`, `parsePureColor`, `shadePolygon`. - **Primitives** — `boxPolygons`, `planePolygons`, `spherePolygons`, `cylinderPolygons`, `conePolygons`, `torusPolygons`, `ringPolygons`, `axesHelperPolygons`, and the Platonic solids. - **Mesh optimization** — `optimizeMeshPolygons`, `mergePolygons`, `dedupeOverlappingPolygons`, `cullInteriorPolygons`, - `simplifyTriangleMeshPolygons`, `repairMeshSeams`. + `simplifyTriangleMeshPolygons`, `seamOverlapDiagnostics`. - **Culling** — `polygonFacesCamera`, `polygonCssSurfaceNormal`, `cameraCullNormalGroups`, and the voxel camera-cull helpers. - **Shadow projection** — `buildParametricCasterOverride`, diff --git a/packages/core/src/animation/animation.test.ts b/packages/core/src/animation/animation.test.ts index 63999dca6..70fe39309 100644 --- a/packages/core/src/animation/animation.test.ts +++ b/packages/core/src/animation/animation.test.ts @@ -699,3 +699,34 @@ describe("paused", () => { expect(action.time).toBeCloseTo(0.8); }); }); + +describe("multi-action blending metadata", () => { + it("takes non-positional polygon fields from the highest-weight clip", () => { + const clips: ParseAnimationClip[] = [ + makeClip(0, "low", 1), + makeClip(1, "high", 1), + ]; + const ctrl: ParseAnimationController = { + clips, + sample(clip) { + const isHigh = clip === "high" || clip === 1; + return [{ + vertices: isHigh + ? [[10, 0, 0], [11, 0, 0], [10, 1, 0]] + : [[0, 0, 0], [1, 0, 0], [0, 1, 0]], + color: isHigh ? "#00ff00" : "#ff0000", + }]; + }, + }; + const target = makeTarget(); + const mixer = createPolyAnimationMixer(target, ctrl); + const low = mixer.clipAction("low"); + const high = mixer.clipAction("high"); + low.setEffectiveWeight(0.2).play(); + high.setEffectiveWeight(0.8).play(); + mixer.update(0.1); + const last = target.calls[target.calls.length - 1]; + expect(last[0].color).toBe("#00ff00"); + expect(last[0].vertices[0][0]).toBeCloseTo(8, 5); + }); +}); diff --git a/packages/core/src/animation/index.ts b/packages/core/src/animation/index.ts index c8367e7bf..d1de7f89f 100644 --- a/packages/core/src/animation/index.ts +++ b/packages/core/src/animation/index.ts @@ -429,7 +429,13 @@ export function createPolyAnimationMixer( weight: internal.weight / totalWeight, })); - const refPolygons = frames[0].polygons; + let dominantFrame = frames[0]; + for (let i = 1; i < frames.length; i++) { + if (frames[i].weight > dominantFrame.weight) { + dominantFrame = frames[i]; + } + } + const refPolygons = dominantFrame.polygons; if (refPolygons.length === 0) return; // Build blended polygon array. For each polygon, blend each vertex diff --git a/packages/core/src/atlas/constants.ts b/packages/core/src/atlas/constants.ts index 43464ac95..89a1a1e76 100644 --- a/packages/core/src/atlas/constants.ts +++ b/packages/core/src/atlas/constants.ts @@ -26,10 +26,6 @@ export const AUTO_ATLAS_MAX_DECODED_BYTES_DESKTOP = 16 * 1024 * 1024; export const AUTO_ATLAS_SCALE_GUARD = 0.995; export const COLOR_PARSE_CACHE_MAX = 512; -// Budget for the internal async atlas planner used by large imperative -// scene updates. Keep comfortably under the 50ms long-task threshold. -export const ASYNC_RENDER_BUDGET_MS = 12; - export const RECT_EPS = 1e-3; export const BASIS_EPS = 1e-9; export const SURFACE_NORMAL_EPS = 1e-4; diff --git a/packages/core/src/atlas/plan/lighting.ts b/packages/core/src/atlas/plan/lighting.ts index 1a216d7d1..37a423af7 100644 --- a/packages/core/src/atlas/plan/lighting.ts +++ b/packages/core/src/atlas/plan/lighting.ts @@ -89,12 +89,7 @@ export function computePlanLighting( const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; // Decoupled: directional and ambient sum independently. No (1 - ambient) // budget — matches three.js's lighting model. - const occluded = options.lightOccludedPolyIndices?.has(index) ?? false; - const directScale = occluded - ? 0 - : lightIntensity * Math.max(0, normal[0] * lx + normal[1] * ly + normal[2] * lz); - // Point lights are occlusion-shaded the same as directional: a polygon the - // directional light can't reach (occluded) still gets point-light + ambient. + const directScale = lightIntensity * Math.max(0, normal[0] * lx + normal[1] * ly + normal[2] * lz); const pointContribs = computePointContribs(options.pointLights, pts, normal, tile, elev); const textureTint = textureTintFactors(directScale, lightColor, ambientColor, ambientIntensity, pointContribs); const shadedColor = shadePolygon(polygon.color ?? "#cccccc", directScale, lightColor, ambientColor, ambientIntensity, pointContribs); diff --git a/packages/core/src/atlas/solidTrianglePlan.ts b/packages/core/src/atlas/solidTrianglePlan.ts index 367e76424..66f632bc4 100644 --- a/packages/core/src/atlas/solidTrianglePlan.ts +++ b/packages/core/src/atlas/solidTrianglePlan.ts @@ -90,10 +90,7 @@ export function computeSolidTriangleColorPlanFromNormal( const ambientIntensity = Math.max(0, ambientCfg?.intensity ?? DEFAULT_AMBIENT_INTENSITY); const lLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; - const occluded = options.lightOccludedPolyIndices?.has(index) ?? false; - const directScale = occluded - ? 0 - : lightIntensity * Math.max(0, nx * lx + ny * ly + nz * lz); + const directScale = lightIntensity * Math.max(0, nx * lx + ny * ly + nz * lz); const ptTile = options.tileSize ?? DEFAULT_TILE; const ptElev = options.layerElevation ?? ptTile; const pointContribs = computePointContribs( diff --git a/packages/core/src/atlas/types.ts b/packages/core/src/atlas/types.ts index 501d5e1e0..0facf8bb2 100644 --- a/packages/core/src/atlas/types.ts +++ b/packages/core/src/atlas/types.ts @@ -324,15 +324,6 @@ export interface SolidTrianglePlanOptions { strategies?: PolyRenderStrategiesOption; seamBleed?: PolySeamBleed; seamEdges?: Set; - /** - * Indices (into the polygon array being planned) of polygons that the - * directional light cannot physically reach because another polygon of - * the same mesh is between them and the light source. Per-polygon - * directScale is forced to 0 for indices in this set, so they receive - * ambient lighting only — matching what a shadow-map-equivalent pass - * would produce. - */ - lightOccludedPolyIndices?: ReadonlySet; } /** Internal solid-triangle plan options (extends SolidTrianglePlanOptions). */ @@ -356,11 +347,4 @@ export interface ComputeTextureAtlasPlanOptions { textureEdgeRepairEdges?: Set; seamBleed?: PolySeamBleed; seamEdges?: Set; - /** Indices of polygons that the directional light cannot reach because - * another polygon of the same mesh occludes them (precomputed via - * {@link import("../cull/lightVisibility").computeLightVisibility}). When - * `index ∈ lightOccludedPolyIndices`, the polygon's direct lighting term - * is forced to zero and only ambient remains. Matches the vanilla - * renderer's self-shadow path. */ - lightOccludedPolyIndices?: ReadonlySet; } diff --git a/packages/core/src/camera/camera.test.ts b/packages/core/src/camera/camera.test.ts index 061e7c477..bc063804b 100644 --- a/packages/core/src/camera/camera.test.ts +++ b/packages/core/src/camera/camera.test.ts @@ -2,7 +2,6 @@ import { describe, it, expect } from "vitest"; import { capturePolyCameraSnapshot, createIsometricCamera, - normalizeInvertMultiplier, buildPolyCameraSceneTransform, polyCameraTargetToCss, resolvePolyCameraAppliedPerspectiveStyle, @@ -18,32 +17,6 @@ describe("DEFAULT_CAMERA_STATE", () => { }); }); -describe("normalizeInvertMultiplier", () => { - it("returns -1 for true", () => { - expect(normalizeInvertMultiplier(true)).toBe(-1); - }); - - it("returns 1 for false", () => { - expect(normalizeInvertMultiplier(false)).toBe(1); - }); - - it("returns undefined for undefined", () => { - expect(normalizeInvertMultiplier(undefined)).toBeUndefined(); - }); - - it("returns 1 for positive number", () => { - expect(normalizeInvertMultiplier(5)).toBe(1); - }); - - it("returns -1 for negative number", () => { - expect(normalizeInvertMultiplier(-3)).toBe(-1); - }); - - it("returns undefined for 0", () => { - expect(normalizeInvertMultiplier(0)).toBeUndefined(); - }); -}); - describe("createIsometricCamera", () => { describe("initial state", () => { it("uses default values when no overrides given", () => { diff --git a/packages/core/src/camera/camera.ts b/packages/core/src/camera/camera.ts index 277feee73..f7c34c590 100644 --- a/packages/core/src/camera/camera.ts +++ b/packages/core/src/camera/camera.ts @@ -80,17 +80,6 @@ export type PolyCameraSnapshotSource = CameraHandle & { readonly perspectiveStyle?: string; }; -export function normalizeInvertMultiplier(value: number | boolean | undefined): number | undefined { - if (typeof value === "number") { - if (value === 0) return undefined; - return value < 0 ? -1 : 1; - } - if (typeof value === "boolean") { - return value ? -1 : 1; - } - return undefined; -} - export const DEFAULT_CAMERA_STATE: CameraState = { target: [0, 0, 0], rotX: 65, diff --git a/packages/core/src/color/lighting.test.ts b/packages/core/src/color/lighting.test.ts index 7d0bb684b..3cff869f8 100644 --- a/packages/core/src/color/lighting.test.ts +++ b/packages/core/src/color/lighting.test.ts @@ -1,6 +1,5 @@ import { describe, it, expect } from "vitest"; -import { parseColor, shadeColor, computeShapeLighting } from "./lighting"; -import { DEFAULT_LIGHT_DIR } from "../atlas/constants"; +import { parseColor } from "./lighting"; describe("parseColor", () => { it("parses 6-digit hex", () => { @@ -42,114 +41,3 @@ describe("parseColor", () => { expect(a).toBe(b); }); }); - -describe("shadeColor", () => { - it("returns original color when delta is 0", () => { - expect(shadeColor("#808080", 0)).toBe("rgb(128, 128, 128)"); - }); - - it("applies positive delta", () => { - expect(shadeColor("#808080", 20)).toBe("rgb(148, 148, 148)"); - }); - - it("applies negative delta", () => { - expect(shadeColor("#808080", -20)).toBe("rgb(108, 108, 108)"); - }); - - it("clamps at 255", () => { - expect(shadeColor("#ffffff", 50)).toBe("rgb(255, 255, 255)"); - }); - - it("clamps at 0", () => { - expect(shadeColor("#000000", -50)).toBe("rgb(0, 0, 0)"); - }); - - it("falls back to default gray for unparseable input", () => { - // default = rgb(204,204,204), delta +10 - expect(shadeColor("notacolor12345", 10)).toBe("rgb(214, 214, 214)"); - }); -}); - -describe("computeShapeLighting", () => { - it("face pointing toward light is fully lit (lambert = 1)", () => { - // Light source is above along [0,0,1]. A face whose normal is [0,0,1] (up) - // catches the light fully. With ambient intensity 0, only the - // directional contribution applies. - const result = computeShapeLighting( - [0, 0, 1], - "#808080", - { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, - { color: "#ffffff", intensity: 0 }, - ); - expect(result).toBe("rgb(128, 128, 128)"); - }); - - it("face pointing away from light gets ambient only", () => { - const result = computeShapeLighting( - [0, 0, -1], - "#808080", - { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, - { color: "#ffffff", intensity: 0.5 }, - ); - // ambient * base = 0.5 * 128 = 64 - expect(result).toBe("rgb(64, 64, 64)"); - }); - - it("perpendicular face gets ambient only", () => { - const result = computeShapeLighting( - [1, 0, 0], - "#808080", - { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, - { color: "#ffffff", intensity: 0.4 }, - ); - // perpendicular: lambert = 0; only ambient applies → 0.4 * 128 = 51 - expect(result).toBe("rgb(51, 51, 51)"); - }); - - it("uses default lights when args are omitted (atlas DEFAULT_LIGHT_DIR sun)", () => { - // Defaults: white directional along the atlas pipeline's - // DEFAULT_LIGHT_DIR with intensity 1 + white ambient intensity 0.4 — - // core has ONE default sun. Pinned by equality with the explicit args. - const result = computeShapeLighting([0, 0, 1], "#808080"); - const explicit = computeShapeLighting( - [0, 0, 1], - "#808080", - { direction: DEFAULT_LIGHT_DIR, color: "#ffffff", intensity: 1 }, - { color: "#ffffff", intensity: 0.4 }, - ); - expect(result).toBe(explicit); - // Not the old [0,0,1] top-down default: a face tilted toward - // DEFAULT_LIGHT_DIR shades brighter than the up-facing one. - const towardSun = computeShapeLighting(DEFAULT_LIGHT_DIR, "#808080"); - expect(towardSun).not.toBe(result); - }); - - it("directional intensity scales the lit contribution independently of ambient", () => { - const half = computeShapeLighting( - [0, 0, 1], - "#808080", - { direction: [0, 0, 1], color: "#ffffff", intensity: 0.5 }, - { color: "#ffffff", intensity: 0 }, - ); - // tint = 0 + 0.5*1 = 0.5 → 128 * 0.5 = 64 - expect(half).toBe("rgb(64, 64, 64)"); - }); - - it("returns shaded color string", () => { - const result = computeShapeLighting([0, 1, 0], "#ff0000"); - expect(result).toMatch(/^rgb\(/); - }); - - it("normalizes the input normal", () => { - // Same direction, different magnitude — same shading. - const a = computeShapeLighting([0, 0, 1], "#808080"); - const b = computeShapeLighting([0, 0, 5], "#808080"); - expect(a).toBe(b); - }); - - it("handles zero-length normal gracefully", () => { - const result = computeShapeLighting([0, 0, 0], "#808080"); - // Degenerate normal → lambert = 0 → ambient-only - expect(result).toMatch(/^rgb\(/); - }); -}); diff --git a/packages/core/src/color/lighting.ts b/packages/core/src/color/lighting.ts index 79a780fce..f0006a473 100644 --- a/packages/core/src/color/lighting.ts +++ b/packages/core/src/color/lighting.ts @@ -1,23 +1,10 @@ -/* Shared lighting helpers for PolyCSS polygons. +/* Cached CSS color parsing helper for PolyCSS polygons. * Pure module — zero DOM dependencies. - * - * `computeShapeLighting(normal, baseColor, light?)` is a per-polygon Lambert - * shader. Renderers may keep Lambert math inline for performance, but this - * helper supports users who shade polygons outside the renderer, such as SSR, - * validators, or alternate backends. */ -import type { PolyAmbientLight, PolyDirectionalLight, Vec3 } from "../types"; -import { - type ParsedColor, - parsePureColor, - clampChannel, - formatColor -} from "./color"; -import { DEFAULT_LIGHT_DIR } from "../atlas/constants"; +import { type ParsedColor, parsePureColor } from "./color"; export type { ParsedColor }; -const defaultColor: ParsedColor = { rgb: [204, 204, 204], alpha: 1 }; const colorCache = new Map(); export function parseColor(input: string): ParsedColor | null { @@ -34,84 +21,3 @@ export function parseColor(input: string): ParsedColor | null { return null; } - -/** - * Lighten/darken a color by a flat per-channel delta. Used by the framework - * wrappers for tinted-overlay debug renderers; per-polygon Lambert shading - * goes through `computeShapeLighting` instead. - */ -export function shadeColor(base: string, delta: number): string { - const parsed = parseColor(base) ?? defaultColor; - const rgb: [number, number, number] = [ - clampChannel(parsed.rgb[0] + delta), - clampChannel(parsed.rgb[1] + delta), - clampChannel(parsed.rgb[2] + delta) - ]; - return formatColor({ rgb, alpha: parsed.alpha }); -} - -// Default sun shared with the atlas pipeline (`DEFAULT_LIGHT_DIR`) so core -// has ONE default light direction everywhere. -const DEFAULT_DIRECTIONAL: Required = { - direction: DEFAULT_LIGHT_DIR, - color: "#ffffff", - intensity: 1, -}; - -const DEFAULT_AMBIENT: Required = { - color: "#ffffff", - intensity: 0.4, -}; - -function normalizeVec3(v: Vec3): Vec3 { - const len = Math.hypot(v[0], v[1], v[2]); - if (len < 1e-12) return [0, 0, 0]; - return [v[0] / len, v[1] / len, v[2] / len]; -} - -function tintChannel(base: number, tintHex: string, channel: 0 | 1 | 2): number { - const tint = parseColor(tintHex) ?? defaultColor; - // Per-channel multiply, normalized to 0..1, with the tint scaled into 0..1. - return base * (tint.rgb[channel] / 255); -} - -/** - * Per-polygon Lambert shading. Given a polygon's outward normal and the - * scene's lights, returns the shaded color as a CSS rgb string. - * - * Math (decoupled, three.js convention): - * tint = ambient.color · ambient.intensity - * + directional.color · directional.intensity · max(0, n · L) - * final = baseColor × tint - * - * Pass `directional` and/or `ambient` undefined to fall back to defaults - * (white directional along the atlas pipeline's `DEFAULT_LIGHT_DIR` with - * intensity 1, white ambient with intensity 0.4) — useful for static - * SSR/validator renders. - */ -export function computeShapeLighting( - normal: Vec3, - baseColor: string, - directional?: PolyDirectionalLight, - ambient?: PolyAmbientLight, -): string { - const base = parseColor(baseColor) ?? defaultColor; - const dir = normalizeVec3(directional?.direction ?? DEFAULT_DIRECTIONAL.direction); - const lightHex = directional?.color ?? DEFAULT_DIRECTIONAL.color; - const lightIntensity = Math.max(0, directional?.intensity ?? DEFAULT_DIRECTIONAL.intensity); - const ambientHex = ambient?.color ?? DEFAULT_AMBIENT.color; - const ambientIntensity = Math.max(0, ambient?.intensity ?? DEFAULT_AMBIENT.intensity); - - const n = normalizeVec3(normal); - const lambert = Math.max(0, n[0] * dir[0] + n[1] * dir[1] + n[2] * dir[2]); - const directionalScale = lightIntensity * lambert; - - const out: [number, number, number] = [0, 0, 0]; - for (let c = 0 as 0 | 1 | 2; c < 3; c = (c + 1) as 0 | 1 | 2) { - const baseC = base.rgb[c]; - const ambContrib = tintChannel(baseC, ambientHex, c) * ambientIntensity; - const dirContrib = tintChannel(baseC, lightHex, c) * directionalScale; - out[c] = clampChannel(ambContrib + dirContrib); - } - return formatColor({ rgb: out, alpha: base.alpha }); -} diff --git a/packages/core/src/cull/bvh.ts b/packages/core/src/cull/bvh.ts index 6402cf787..429b97cf6 100644 --- a/packages/core/src/cull/bvh.ts +++ b/packages/core/src/cull/bvh.ts @@ -1,8 +1,7 @@ /** * Shared flat-array SAH BVH and Möller–Trumbore ray-triangle intersection. * - * Used by `cullInteriorPolygons` and `computeLightVisibility` for fast any-hit - * ray occlusion queries. + * Used by `cullInteriorPolygons` for fast any-hit ray occlusion queries. */ export const BVH_PARALLEL_EPS = 1e-9; diff --git a/packages/core/src/cull/lightVisibility.test.ts b/packages/core/src/cull/lightVisibility.test.ts deleted file mode 100644 index b886e4a5d..000000000 --- a/packages/core/src/cull/lightVisibility.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { computeLightVisibility } from "./lightVisibility"; -import type { Polygon, Vec3 } from "../types"; - -// Axis-aligned quad facing +Z (top), at z=cz, size×size. Vertices CCW -// when viewed from +Z so the cross-product normal points +Z. -function topQuad(cx: number, cy: number, cz: number, size = 2): Polygon { - const h = size / 2; - return { - vertices: [ - [cx - h, cy - h, cz], - [cx + h, cy - h, cz], - [cx + h, cy + h, cz], - [cx - h, cy + h, cz], - ], - }; -} - -describe("computeLightVisibility", () => { - // Sanity: a single polygon is never occluded — no other geometry to - // block the ray, so the returned set is empty. - it("returns empty set when there is nothing to occlude", () => { - const polys: Polygon[] = [topQuad(0, 0, 0)]; - const lightDir: Vec3 = [0, 0, 1]; - expect(computeLightVisibility(polys, lightDir).size).toBe(0); - }); - - // Two parallel quads stacked along the light direction: the LOWER - // quad's ray toward the light hits the upper quad → lower flagged. - // The upper quad's ray escapes → not flagged. - it("flags the lower of two stacked quads", () => { - const polys: Polygon[] = [ - topQuad(0, 0, 0), // index 0 — lower, blocked - topQuad(0, 0, 5), // index 1 — upper, escapes - ]; - const lightDir: Vec3 = [0, 0, 1]; - const occluded = computeLightVisibility(polys, lightDir); - expect(occluded.has(0)).toBe(true); - expect(occluded.has(1)).toBe(false); - }); - - // skipIndices excludes a polygon from being raytraced AND from being - // a candidate occluder. With the upper quad skipped, the lower quad's - // ray finds no blocker → not flagged. - it("skipIndices excludes both as source and as occluder", () => { - const polys: Polygon[] = [ - topQuad(0, 0, 0), - topQuad(0, 0, 5), - ]; - const lightDir: Vec3 = [0, 0, 1]; - const skip = new Set([1]); - const occluded = computeLightVisibility(polys, lightDir, skip); - expect(occluded.has(0)).toBe(false); - expect(occluded.has(1)).toBe(false); - }); - - // The skipped index never appears in the result even when it WOULD - // have been occluded — it's excluded from the source-iteration loop. - it("skipped polygon is never in the returned set", () => { - const polys: Polygon[] = [ - topQuad(0, 0, 0), - topQuad(0, 0, 5), - topQuad(0, 0, 10), // blocks index 1 - ]; - const lightDir: Vec3 = [0, 0, 1]; - const skip = new Set([0, 1]); - const occluded = computeLightVisibility(polys, lightDir, skip); - // Index 0 + 1 in skip → never in output. - expect(occluded.has(0)).toBe(false); - expect(occluded.has(1)).toBe(false); - // Index 2 is the topmost, escapes. - expect(occluded.has(2)).toBe(false); - }); - - // Regression: the cottage false-positive case. Two near-coincident - // parallel walls (e.g. an OBJ exporter doubling the outer face slightly - // outside the inner) would self-occlude — the outer wall's ray hits - // the duplicate outer wall and gets flagged as occluded. With dedup- - // before-raytrace passing the duplicate index in skipIndices, the - // outer wall escapes correctly. - it("dedup-skip prevents self-occlusion from near-coincident duplicates", () => { - const polys: Polygon[] = [ - topQuad(0, 0, 0), // outer wall - topQuad(0, 0, 0.08), // near-coincident duplicate ~0.08 above - ]; - const lightDir: Vec3 = [0, 0, 1]; - // Without skipIndices the lower quad is occluded by its near twin. - expect(computeLightVisibility(polys, lightDir).has(0)).toBe(true); - // With the duplicate marked for skip, the outer wall escapes. - const occluded = computeLightVisibility(polys, lightDir, new Set([1])); - expect(occluded.has(0)).toBe(false); - }); - - // Back-facing-to-light polygons (n·L <= 0) are never iterated as - // sources — they can't be lit, occlusion is irrelevant. Their - // omission must not depend on the skipIndices set. - it("never flags back-facing-to-light polygons even without skip", () => { - const polys: Polygon[] = [ - topQuad(0, 0, 0), // faces +Z - topQuad(0, 0, 5), - ]; - // Light direction is -Z — both quads face away from it. - const lightDir: Vec3 = [0, 0, -1]; - const occluded = computeLightVisibility(polys, lightDir); - expect(occluded.size).toBe(0); - }); -}); diff --git a/packages/core/src/cull/lightVisibility.ts b/packages/core/src/cull/lightVisibility.ts deleted file mode 100644 index 958a38f42..000000000 --- a/packages/core/src/cull/lightVisibility.ts +++ /dev/null @@ -1,134 +0,0 @@ -/** - * computeLightVisibility — for each polygon of a mesh, determines whether - * direct light from a given direction physically reaches it (ray from the - * polygon's centroid toward the light source is unblocked) or is occluded - * by other geometry of the same mesh. - * - * This is the CPU equivalent of one shadow-map sample per polygon from the - * light's POV. Used by the baked atlas pipeline so polygons in shadow get - * lit with ambient-only color, matching Three.js's depth-pass occlusion. - * - * Algorithm: Möller-Trumbore ray-triangle intersection per candidate, with - * a flat-array BVH for any-hit traversal. Cost: O(F log F) per mesh per - * light direction. Cottage at ~240 polys: ~5-10 ms. Caller should cache by - * (mesh geometry version, lightDir hash) and only recompute on change. - */ -import type { Polygon, Vec3 } from "../types"; -import { - BVH_PARALLEL_EPS as PARALLEL_EPS, - buildBVH, - rayHitsAnyInBVH, -} from "./bvh"; - -const RAY_ORIGIN_OFFSET = 1e-3; -const LIGHT_VISIBILITY_SAH_BUCKETS = 12; - -interface PolyMeta { - triFlat: Float64Array; - centroid: Vec3; - normal: Vec3; - bcx: number; bcy: number; bcz: number; br2: number; - minX: number; minY: number; minZ: number; - maxX: number; maxY: number; maxZ: number; -} - -function precompute(p: Polygon): PolyMeta | null { - const verts = p.vertices; - if (!verts || verts.length < 3) return null; - let cx = 0, cy = 0, cz = 0; - for (const [x, y, z] of verts) { cx += x; cy += y; cz += z; } - const inv = 1 / verts.length; - cx *= inv; cy *= inv; cz *= inv; - const v0 = verts[0], v1 = verts[1], v2 = verts[2]; - const e1x = v1[0] - v0[0], e1y = v1[1] - v0[1], e1z = v1[2] - v0[2]; - const e2x = v2[0] - v0[0], e2y = v2[1] - v0[1], e2z = v2[2] - v0[2]; - let nx = e1y * e2z - e1z * e2y; - let ny = e1z * e2x - e1x * e2z; - let nz = e1x * e2y - e1y * e2x; - const nLen = Math.hypot(nx, ny, nz); - if (nLen < PARALLEL_EPS) return null; - nx /= nLen; ny /= nLen; nz /= nLen; - const nTri = verts.length - 2; - const triFlat = new Float64Array(nTri * 9); - let ti = 0; - for (let i = 1; i < verts.length - 1; i++) { - const a = verts[0], b = verts[i], c = verts[i + 1]; - triFlat[ti++] = a[0]; triFlat[ti++] = a[1]; triFlat[ti++] = a[2]; - triFlat[ti++] = b[0]; triFlat[ti++] = b[1]; triFlat[ti++] = b[2]; - triFlat[ti++] = c[0]; triFlat[ti++] = c[1]; triFlat[ti++] = c[2]; - } - let br2 = 0; - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (const [x, y, z] of verts) { - const ddx = x - cx, ddy = y - cy, ddz = z - cz; - const d2 = ddx * ddx + ddy * ddy + ddz * ddz; - if (d2 > br2) br2 = d2; - if (x < minX) minX = x; if (x > maxX) maxX = x; - if (y < minY) minY = y; if (y > maxY) maxY = y; - if (z < minZ) minZ = z; if (z > maxZ) maxZ = z; - } - return { - centroid: [cx, cy, cz], normal: [nx, ny, nz], - triFlat, bcx: cx, bcy: cy, bcz: cz, br2, - minX, minY, minZ, maxX, maxY, maxZ, - }; -} - -/** - * Returns a Set of polygon indices that are OCCLUDED from the light - * (a ray from the polygon's centroid in the +lightDir direction hits - * another polygon of the same mesh before escaping to infinity). - * - * `lightDir` is the direction TO the light source (matching the - * convention used by `shadePolygon`'s caller — points from the - * surface toward the light). - * - * Caller should cache by mesh-geometry version + lightDir hash; - * recompute only when either changes. - */ -export function computeLightVisibility( - polygons: readonly Polygon[], - lightDir: Vec3, - skipIndices?: ReadonlySet, -): Set { - const occluded = new Set(); - if (polygons.length < 2) return occluded; - const lLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]); - if (lLen < PARALLEL_EPS) return occluded; - const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; - const meta: Array = polygons.map(precompute); - // skipIndices: caller-supplied set of polygon indices to exclude from BOTH - // being raytraced AND from being raytrace candidates. Used to drop - // overlapping/duplicate polygons (e.g. back-to-back inner/outer wall - // pairs on imported OBJ meshes) that would otherwise self-occlude and - // false-positive a fully-lit outer face as shadowed. - if (skipIndices && skipIndices.size > 0) { - for (const i of skipIndices) meta[i] = null; - } - const bvh = buildBVH(meta, LIGHT_VISIBILITY_SAH_BUCKETS); - const stack = new Int32Array(Math.max(64, bvh.nodeCount)); - for (let i = 0; i < polygons.length; i++) { - const p = meta[i]; - if (!p) continue; - // Push origin slightly along the OUTWARD NORMAL so the ray doesn't - // immediately self-hit the polygon's own plane (Möller-Trumbore is - // sensitive to t close to 0). The offset is in mesh units; geometry - // at parser scale typically spans ~1-10 units, so 1e-3 = 0.001 units - // is safely sub-feature-size. - const ox = p.centroid[0] + p.normal[0] * RAY_ORIGIN_OFFSET; - const oy = p.centroid[1] + p.normal[1] * RAY_ORIGIN_OFFSET; - const oz = p.centroid[2] + p.normal[2] * RAY_ORIGIN_OFFSET; - // Back-facing-to-light polys can never be lit (n·L <= 0). Don't - // call them occluded — that's a different concept handled by the - // standard Lambert formula. Mark them as "no direct light" via - // the front-face dot test outside; here we only care about - // front-facing polys that are blocked by other geometry. - const ndotL = p.normal[0] * lx + p.normal[1] * ly + p.normal[2] * lz; - if (ndotL <= 0) continue; - if (rayHitsAnyInBVH(ox, oy, oz, lx, ly, lz, i, bvh, stack)) { - occluded.add(i); - } - } - return occluded; -} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 995fad378..2a39c52b0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,7 +1,16 @@ // @layoutit/polycss-core — Pure-math polygon rendering engine (zero browser globals). // -// Public exports define the supported core package surface. Anything not -// exported here is implementation detail. +// Organized into two tiers so callers and agents can distinguish user-facing +// headless APIs from internal renderer/morph plumbing without changing import paths: +// - PART 1: Public User & Headless API (types, parsers, mesh ops, helpers, camera, animation, stats) +// - PART 2: Renderer & Morph Contract (atlas/strategy planning, controls math, shadows, transforms) +// +// WARNING: @layoutit/polycss-morph pins core exports against the npm-published version +// (checked by `pnpm check:packs`). Never remove or rename morph-pinned symbols in Part 2. + +// ═══════════════════════════════════════════════════════════════════ +// PART 1 — PUBLIC USER & HEADLESS API +// ═══════════════════════════════════════════════════════════════════ // ── Types ───────────────────────────────────────────────────────── export type { @@ -26,7 +35,6 @@ export type { PolyTextureLightingMode, MeshResolution, } from "./types"; -export { DEFAULT_PROJECTION } from "./types"; // ── Scene context + normalization ──────────────────────────────── export { @@ -43,15 +51,9 @@ export type { NormalizeResult, } from "./scene/context"; -// ── Polygon geometry helper ────────────────────────────────────── -export { polygonFaces, computeTexturePaintMetrics } from "./scene/polygonGeometry"; -export type { - PolygonFace, - TexturePaintMetrics, - TexturePaintMetricsOptions, -} from "./scene/polygonGeometry"; - -// ── Rotation math ──────────────────────────────────────────────── +// ── Polygon geometry & rotation math ───────────────────────────── +export { polygonFaces } from "./scene/polygonGeometry"; +export type { PolygonFace } from "./scene/polygonGeometry"; export { rotateVec3, inverseRotateVec3, rotateVec3InWrapperCssFrame } from "./math/rotation"; export { quatFromAxisAngle, @@ -65,7 +67,6 @@ export type { Quat } from "./math/quaternion"; // ── Camera ──────────────────────────────────────────────────────── export { createIsometricCamera, - normalizeInvertMultiplier, buildPolyCameraSceneTransform, polyCameraTargetToCss, resolvePolyCameraAppliedPerspectiveStyle, @@ -88,14 +89,9 @@ export type { export { screenToWorldRay, screenToWorldOnSphere } from "./camera/unproject"; export type { ScreenToWorldOptions } from "./camera/unproject"; -// ── Color & lighting ───────────────────────────────────────────── -export { - parseColor, - shadeColor, - computeShapeLighting, -} from "./color/lighting"; +// ── Color ───────────────────────────────────────────────────────── +export { parseColor } from "./color/lighting"; export type { ParsedColor } from "./color/lighting"; - export { parsePureColor, parseHexColor, @@ -105,7 +101,34 @@ export { normalizeSolidColorKey, } from "./color/color"; -// ── Mesh post-processing ────────────────────────────────────────── +// ── Parsers ─────────────────────────────────────────────────────── +export type { + ParseAnimationClip, + ParseAnimationController, + PolyVoxelCell, + PolyVoxelFace, + PolyVoxelSource, + ParseStlColor, + ParseStlSolid, + ParseStlTopology, + ParseResult, +} from "./parser/types"; +export { parseObj } from "./parser/parseObj"; +export type { ObjParseOptions } from "./parser/parseObj"; +export { parseMtl } from "./parser/parseMtl"; +export type { MtlParseResult } from "./parser/parseMtl"; +export { parseGltf } from "./parser/parseGltf"; +export type { GltfParseOptions } from "./parser/parseGltf"; +export { bakeSolidTextureSamples } from "./parser/solidTextureSamples"; +export type { SolidTextureSampleOptions } from "./parser/solidTextureSamples"; +export { parseVox } from "./parser/parseVox"; +export type { VoxParseOptions } from "./parser/parseVox"; +export { parseStl } from "./parser/parseStl"; +export type { StlParseOptions } from "./parser/parseStl"; +export { loadMesh } from "./parser/loadMesh"; +export type { LoadMeshOptions } from "./parser/loadMesh"; + +// ── Mesh post-processing & culling ─────────────────────────────── export { mergePolygons } from "./merge/mergePolygons"; export { dedupeOverlappingPolygons, @@ -115,40 +138,21 @@ export type { DedupeOverlappingPolygonsOptions } from "./merge/dedupeOverlapping export { coverPlanarPolygons } from "./merge/coverPlanarPolygons"; export type { CoverPlanarPolygonsOptions } from "./merge/coverPlanarPolygons"; export { optimizeMeshPolygons } from "./merge/optimizePolygons"; -export type { - OptimizeMeshPolygonsOptions, -} from "./merge/optimizePolygons"; +export type { OptimizeMeshPolygonsOptions } from "./merge/optimizePolygons"; export { optimizeMeshParseResult } from "./parser/optimizeMeshParseResult"; -export type { - OptimizeMeshParseResultOptions, -} from "./parser/optimizeMeshParseResult"; +export type { OptimizeMeshParseResultOptions } from "./parser/optimizeMeshParseResult"; export { simplifyTriangleMeshPolygons } from "./merge/simplifyTriangleMesh"; -export type { - SimplifyTriangleMeshPolygonsOptions, -} from "./merge/simplifyTriangleMesh"; +export type { SimplifyTriangleMeshPolygonsOptions } from "./merge/simplifyTriangleMesh"; export { - DEFAULT_SEAM_FACET_SPLIT_OPTIONS, DEFAULT_SEAM_OVERLAP_OPTIONS, - repairMeshSeams, - seamFacetSplitPolygons, - seamFacetSplitReport, seamOverlapDiagnostics, - seamOverlapPolygons, - seamOverlapReport, } from "./merge/seamRepair"; export type { - SeamFacetSplitCandidate, - SeamFacetSplitCandidateReason, - SeamFacetSplitOptions, - SeamFacetSplitReport, - SeamOverlapCandidate, - SeamOverlapCandidateKind, SeamOverlapDiagnostics, SeamOverlapOptions, } from "./merge/seamRepair"; export { cullInteriorPolygons } from "./cull/cullInteriorPolygons"; export type { CullInteriorOptions } from "./cull/cullInteriorPolygons"; -export { computeLightVisibility } from "./cull/lightVisibility"; export { CAMERA_BACKFACE_CULL_EPS, VOXEL_CAMERA_CULL_AXIS_EPS, @@ -169,9 +173,88 @@ export type { CameraCullRotation, } from "./cull/cameraBackfaceCulling"; -// ── Helper geometry (boxes, axes, light marker, transform arrows / rings) ─ -export { axesHelperPolygons, boxPolygons, arrowPolygons, ringPolygons, ringQuadPolygons, planePolygons, octahedronPolygons, spherePolygons, tetrahedronPolygons, icosahedronPolygons, dodecahedronPolygons, cylinderPolygons, conePolygons, torusPolygons } from "./helpers"; -export type { AxesHelperOptions, BoxFace, BoxFaceOptions, BoxPolygonsOptions, ArrowPolygonsOptions, RingPolygonsOptions, RingQuadPolygonsOptions, PlanePolygonsOptions, OctahedronPolygonsOptions, SpherePolygonsOptions, TetrahedronPolygonsOptions, IcosahedronPolygonsOptions, DodecahedronPolygonsOptions, CylinderPolygonsOptions, ConePolygonsOptions, TorusPolygonsOptions } from "./helpers"; +// ── Helper geometry (boxes, axes, primitives, gizmo shapes) ────── +export { + axesHelperPolygons, + boxPolygons, + arrowPolygons, + ringPolygons, + ringQuadPolygons, + planePolygons, + octahedronPolygons, + spherePolygons, + tetrahedronPolygons, + icosahedronPolygons, + dodecahedronPolygons, + cylinderPolygons, + conePolygons, + torusPolygons, +} from "./helpers"; +export type { + AxesHelperOptions, + BoxFace, + BoxFaceOptions, + BoxPolygonsOptions, + ArrowPolygonsOptions, + RingPolygonsOptions, + RingQuadPolygonsOptions, + PlanePolygonsOptions, + OctahedronPolygonsOptions, + SpherePolygonsOptions, + TetrahedronPolygonsOptions, + IcosahedronPolygonsOptions, + DodecahedronPolygonsOptions, + CylinderPolygonsOptions, + ConePolygonsOptions, + TorusPolygonsOptions, +} from "./helpers"; + +// ── Animation ───────────────────────────────────────────────────── +export { + createPolyAnimationMixer, + LoopOnce, + LoopRepeat, + LoopPingPong, +} from "./animation"; +export { optimizeAnimatedMeshPolygons } from "./animation/optimizeAnimatedMeshPolygons"; +export type { OptimizeAnimatedMeshPolygonsOptions } from "./animation/optimizeAnimatedMeshPolygons"; +export type { + PolyAnimationClip, + PolyAnimationAction, + PolyAnimationMixer, + PolyAnimationTarget, + LoopMode, +} from "./animation"; + +// ── Render stats & diagnostics ─────────────────────────────────── +export { + collectPolyRenderStats, + collectPolyTextureReadiness, + queryPolyLeaves, +} from "./render/renderStats"; +export type { + PolyLeafInfo, + PolyRenderLeafStrategy, + PolyRenderStats, + PolyRenderStatsElement, + PolyRenderStatsOptions, + PolyRenderStatsRoot, + PolyRenderSurfaceLeafCounts, + PolyCameraSnapshotStats, + PolySnapshotRenderStats, + PolyTextureRenderStats, + PolyTextureReadiness, +} from "./render/renderStats"; + +// ═══════════════════════════════════════════════════════════════════ +// PART 2 — RENDERER & MORPH CONTRACT (@layoutit/polycss, @layoutit/polycss-morph) +// ═══════════════════════════════════════════════════════════════════ + +// ── Transforms (CSS scene / mesh / iframe) ─────────────────────── +export { buildPolyIframeTransform, buildPolyMeshTransform } from "./transform/meshTransform"; +export type { PolyMeshTransformInput } from "./transform/meshTransform"; +export { buildPolySceneTransform } from "./transform/sceneTransform"; +export type { PolySceneTransformInput } from "./transform/sceneTransform"; // ── Controls math (orbit / map, first-person, transform gizmo) ──── export { @@ -234,22 +317,16 @@ export { } from "./controls/gizmo"; export type { GizmoScreenAxis } from "./controls/gizmo"; -// ── Shadow ──────────────────────────────────────────────────────── +// ── Cast & receiver shadows ────────────────────────────────────── export { - buildBakedShadowProjectionMatrix, convexHull2D, ensureCcw2D, - isBakedShadowCaster, - isPointShadowCaster, projectCssVertexToGround, - projectCssVertexToGroundFromPoint, } from "./shadow/projection"; export { computeParametricShadowSilhouette } from "./shadow/parametricSilhouette"; export { computeCoverageShadowSilhouette } from "./shadow/coverageSilhouette"; export { buildParametricCasterOverride, - isFlatCaster, - isConvexCaster, type ParametricOverrideInput, type ParametricOverrideResult, } from "./shadow/parametricOverride"; @@ -276,10 +353,6 @@ export { worldPositionToPolyCss, } from "./shadow/receiverFaceGroups"; export type { ReceiverPlaneGroup } from "./shadow/receiverFaceGroups"; -export { buildPolyIframeTransform, buildPolyMeshTransform } from "./transform/meshTransform"; -export type { PolyMeshTransformInput } from "./transform/meshTransform"; -export { buildPolySceneTransform } from "./transform/sceneTransform"; -export type { PolySceneTransformInput } from "./transform/sceneTransform"; export { buildSharedEdgeMap, computeMergedReceiverShadows, @@ -310,54 +383,11 @@ export { } from "./shadow/silhouette"; export type { EdgeOwners } from "./shadow/silhouette"; -// ── Animation ───────────────────────────────────────────────────── -export { - createPolyAnimationMixer, - LoopOnce, - LoopRepeat, - LoopPingPong, -} from "./animation"; -export { optimizeAnimatedMeshPolygons } from "./animation/optimizeAnimatedMeshPolygons"; -export type { OptimizeAnimatedMeshPolygonsOptions } from "./animation/optimizeAnimatedMeshPolygons"; -export type { - PolyAnimationClip, - PolyAnimationAction, - PolyAnimationMixer, - PolyAnimationTarget, - LoopMode, -} from "./animation"; - -// ── Parsers ─────────────────────────────────────────────────────── -export type { - ParseAnimationClip, - ParseAnimationController, - PolyVoxelCell, - PolyVoxelFace, - PolyVoxelSource, - ParseStlColor, - ParseStlSolid, - ParseStlTopology, - ParseResult, -} from "./parser/types"; -export { parseObj } from "./parser/parseObj"; -export type { ObjParseOptions } from "./parser/parseObj"; -export { parseMtl } from "./parser/parseMtl"; -export type { MtlParseResult } from "./parser/parseMtl"; -export { parseGltf } from "./parser/parseGltf"; -export type { GltfParseOptions } from "./parser/parseGltf"; -export { - bakeSolidTextureSamples, - bakeSolidTextureSampledPolygons, -} from "./parser/solidTextureSamples"; -export type { SolidTextureSampleOptions } from "./parser/solidTextureSamples"; -export { parseVox } from "./parser/parseVox"; -export type { VoxParseOptions } from "./parser/parseVox"; -export { parseStl } from "./parser/parseStl"; -export type { StlParseOptions } from "./parser/parseStl"; -export { loadMesh } from "./parser/loadMesh"; -export type { LoadMeshOptions } from "./parser/loadMesh"; - -// ── Atlas (pure math) ──────────────────────────────────────────── +// ── Atlas & render-strategy math (pinned by @layoutit/polycss + @layoutit/polycss-morph) ── +// Morph-pinned runtime imports: +// SOLID_TRIANGLE_CANONICAL_SIZE, computeSolidTrianglePlanFromCssPoints, +// computeProjectiveQuadCoefficients, resolveProjectiveQuadGuards, +// computeTextureAtlasPlanPublic, packTextureAtlasPlansWithScaleCore, crossVec export { DEFAULT_TILE, DEFAULT_LIGHT_DIR, @@ -365,7 +395,6 @@ export { DEFAULT_LIGHT_INTENSITY, DEFAULT_AMBIENT_COLOR, DEFAULT_AMBIENT_INTENSITY, - ASYNC_RENDER_BUDGET_MS, BASIS_EPS, TEXTURE_TRIANGLE_BLEED, TEXTURE_EDGE_REPAIR_ALPHA_MIN, @@ -374,7 +403,7 @@ export { SOLID_TRIANGLE_BLEED, DEFAULT_MATRIX_DECIMALS, SOLID_QUAD_CANONICAL_SIZE, - SOLID_TRIANGLE_CANONICAL_SIZE, + SOLID_TRIANGLE_CANONICAL_SIZE, // pinned by @layoutit/polycss-morph BORDER_SHAPE_BLEED, PROJECTIVE_QUAD_DENOM_EPS, PROJECTIVE_QUAD_MAX_WEIGHT_RATIO, @@ -392,7 +421,7 @@ export type { UvAffine, UvSampleRect, TextureTrianglePlan, - TextureAtlasPlan, + TextureAtlasPlan, // pinned by @layoutit/polycss-morph BorderShapeBounds, CornerShapeCorner, CornerShapeRadius, @@ -405,10 +434,10 @@ export type { SolidTrianglePrimitive, PolyRenderStrategiesOption, SeamBleedInsets, - PackedTextureAtlasEntry, + PackedTextureAtlasEntry, // pinned by @layoutit/polycss-morph PackedPage, PackedAtlas, - SolidTriangleBasis, + SolidTriangleBasis, // pinned by @layoutit/polycss-morph SolidTriangleColorPlan, SolidTrianglePlan, SolidTriangleComputeOptions, @@ -481,17 +510,17 @@ export { export { computeSolidTriangleColorPlan, computeSolidTrianglePlan, - computeSolidTrianglePlanFromCssPoints, + computeSolidTrianglePlanFromCssPoints, // pinned by @layoutit/polycss-morph } from "./atlas/solidTrianglePlan"; export { - resolveProjectiveQuadGuards, - computeProjectiveQuadCoefficients, + resolveProjectiveQuadGuards, // pinned by @layoutit/polycss-morph + computeProjectiveQuadCoefficients, // pinned by @layoutit/polycss-morph computeProjectiveQuadMatrix, - crossVec, + crossVec, // pinned by @layoutit/polycss-morph buildBasisHints, isFullRectBasis, computeTextureAtlasPlan, - computeTextureAtlasPlanPublic, + computeTextureAtlasPlanPublic, // pinned by @layoutit/polycss-morph } from "./atlas/plan"; export { resolvePolyTextureLeafGeometry, @@ -504,25 +533,5 @@ export { } from "./atlas/textureSource"; export { atlasCanonicalSizeForEntry, - packTextureAtlasPlansWithScaleCore, + packTextureAtlasPlansWithScaleCore, // pinned by @layoutit/polycss-morph } from "./atlas/packing"; - -// ── Render stats ───────────────────────────────────────────────── -export { - collectPolyRenderStats, - collectPolyTextureReadiness, - queryPolyLeaves, -} from "./render/renderStats"; -export type { - PolyLeafInfo, - PolyRenderLeafStrategy, - PolyRenderStats, - PolyRenderStatsElement, - PolyRenderStatsOptions, - PolyRenderStatsRoot, - PolyRenderSurfaceLeafCounts, - PolyCameraSnapshotStats, - PolySnapshotRenderStats, - PolyTextureRenderStats, - PolyTextureReadiness, -} from "./render/renderStats"; diff --git a/packages/core/src/merge/optimize/geometry.ts b/packages/core/src/merge/optimize/geometry.ts index cc6968fc6..c9cc89895 100644 --- a/packages/core/src/merge/optimize/geometry.ts +++ b/packages/core/src/merge/optimize/geometry.ts @@ -208,34 +208,6 @@ export function averagedVertexPositionMoves(moves: VertexPositionMove[]): Map { - const plane = planeOfPolygon(polygon); - if (!plane) return null; - return { - polygon, - normal: plane.normal, - area: plane.area, - materialKey: materialKeyForPolygon(polygon), - }; - }); - const adjacency = buildMergeAdjacency(snapped, metas); - const assigned = new Set(); - const output: Array = Array(snapped.length); - const vertexMoves: VertexPositionMove[] = []; - const writeOutput = (index: number, polygon: Polygon): void => { - output[index] = polygon; - }; - - for (let i = 0; i < snapped.length; i++) { - const meta = metas[i]; - if (assigned.has(i)) continue; - if (!meta) { - writeOutput(i, snapped[i]); - continue; - } - - const group = growPlaneGroup(i, metas, adjacency, assigned, planeEpsilon, options); - for (const index of group) assigned.add(index); - if (group.length < 2) { - writeOutput(i, snapped[i]); - continue; - } - - const replacements = choosePlaneGroupReplacements(group, snapped, metas, adjacency, planeEpsilon, options); - vertexMoves.push(...replacements.vertexMoves); - for (const index of group) { - writeOutput(index, replacements.polygons.get(index) ?? snapped[index]); - } - } - - const projected = output.flatMap((polygon) => polygon ? [polygon] : []); - const moved = vertexMoves.length > 0 - ? applyVertexPositionMoves(projected, averagedVertexPositionMoves(vertexMoves)) - : projected; - return snapGeometryForMerge(moved); -} - -function choosePlaneGroupReplacements( - group: number[], - polygons: Polygon[], - metas: Array, - adjacency: Map>, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): PlaneGroupReplacements { - const fullGroup = projectedPlanePatchCandidate(group, polygons, metas, planeEpsilon, options); - if (fullGroup) return replacementsForPlanePatch(fullGroup); - return splitPlaneGroupIntoWinningPatches(group, polygons, metas, adjacency, planeEpsilon, options); -} - -function splitPlaneGroupIntoWinningPatches( - group: number[], - polygons: Polygon[], - metas: Array, - adjacency: Map>, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): PlaneGroupReplacements { - const groupSet = new Set(group); - const candidates: PlanePatchCandidate[] = []; - for (const a of group) { - for (const b of adjacency.get(a) ?? []) { - if (a >= b || !groupSet.has(b)) continue; - const candidate = projectedPlanePatchCandidate([a, b], polygons, metas, planeEpsilon, options); - if (candidate) candidates.push(candidate); - } - } - - candidates.sort((a, b) => b.score - a.score); - const used = new Set(); - const replacements = new Map(); - const vertexMoves: VertexPositionMove[] = []; - for (const candidate of candidates) { - if (candidate.indices.some((index) => used.has(index))) continue; - vertexMoves.push(...candidate.vertexMoves); - for (let i = 0; i < candidate.indices.length; i++) { - const index = candidate.indices[i]; - used.add(index); - replacements.set(index, polygons[index]); - } - } - return { polygons: replacements, vertexMoves }; -} - -function replacementsForPlanePatch(candidate: PlanePatchCandidate): PlaneGroupReplacements { - const replacements = new Map(); - for (let i = 0; i < candidate.indices.length; i++) { - replacements.set(candidate.indices[i], candidate.source[i]); - } - return { polygons: replacements, vertexMoves: candidate.vertexMoves }; -} - -function projectedPlanePatchCandidate( - group: number[], - polygons: Polygon[], - metas: Array, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): PlanePatchCandidate | null { - const fit = fitPlaneForGroup(group, metas); - if (!fit || !groupWithinPlaneBudget(group, metas, fit, planeEpsilon, options)) return null; - - const source = group.map((index) => polygons[index]); - const projected = source.map((polygon) => projectPolygonToPlane(polygon, fit)); - const sourceCost = polygonRenderCost(mergePolygons(source)); - const projectedCost = polygonRenderCost(mergePolygons(projected)); - if (projectedCost >= sourceCost) return null; - return { - indices: group, - source, - projected, - vertexMoves: vertexPositionMovesForProjection(source, projected), - score: sourceCost - projectedCost, - }; -} - -function planeFitEpsilon( - polygons: Polygon[], - options: ResolvedGeometryNormalizeOptions, -): number { - const geometryEpsilon = geometrySnapEpsilon(polygons); - if (geometryEpsilon <= 0) return 0; - return options.maxPlaneDisplacement; -} - -function buildMergeAdjacency( - polygons: Polygon[], - metas: Array, -): Map> { - const edgeOwners = new Map(); - const adjacency = new Map>(); - - for (let i = 0; i < polygons.length; i++) { - const polygon = polygons[i]; - if (!metas[i] || polygon.vertices.length < 3) continue; - for (let j = 0; j < polygon.vertices.length; j++) { - const key = edgeKey(polygon.vertices[j], polygon.vertices[(j + 1) % polygon.vertices.length]); - const owners = edgeOwners.get(key); - if (owners) owners.push(i); - else edgeOwners.set(key, [i]); - } - } - - for (const owners of edgeOwners.values()) { - for (let a = 0; a < owners.length; a++) { - for (let b = a + 1; b < owners.length; b++) { - const ai = owners[a]; - const bi = owners[b]; - if (canShareMergePatch(polygons[ai], polygons[bi], metas[ai], metas[bi])) { - addAdjacency(adjacency, ai, bi); - addAdjacency(adjacency, bi, ai); - } - } - } - } - - return adjacency; -} - -function canShareMergePatch( - a: Polygon, - b: Polygon, - aMeta: PlaneNormalizeMeta | null, - bMeta: PlaneNormalizeMeta | null, -): boolean { - if (!aMeta || !bMeta) return false; - if (aMeta.materialKey !== bMeta.materialKey) return false; - if (!!a.uvs !== !!b.uvs) return false; - if (hasTextureMergeState(a) || hasTextureMergeState(b)) return canUseTexturedLossyMerge(a, b); - if (!a.uvs || !b.uvs) return true; - - const shared = sharedEdgeIndices(a, b); - if (!shared) return false; - const [ai0, ai1, bi0, bi1] = shared; - return eqUv(a.uvs[ai0], b.uvs[bi0]) && eqUv(a.uvs[ai1], b.uvs[bi1]); -} - -function addAdjacency(adjacency: Map>, from: number, to: number): void { - const values = adjacency.get(from); - if (values) values.add(to); - else adjacency.set(from, new Set([to])); -} - -function growPlaneGroup( - seed: number, - metas: Array, - adjacency: Map>, - assigned: Set, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): number[] { - const group = [seed]; - const queued = new Set([seed]); - const queue = [seed]; - - while (queue.length > 0) { - const current = queue.shift()!; - for (const next of adjacency.get(current) ?? []) { - if (assigned.has(next) || queued.has(next)) continue; - const nextMeta = metas[next]; - const seedMeta = metas[seed]; - if (!nextMeta || !seedMeta) continue; - if (nextMeta.materialKey !== seedMeta.materialKey) continue; - if (!canJoinPlaneGroup([...group, next], metas, planeEpsilon, options)) continue; - group.push(next); - queued.add(next); - queue.push(next); - } - } - - return group; -} - -function canJoinPlaneGroup( - group: number[], - metas: Array, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): boolean { - const fit = fitPlaneForGroup(group, metas); - return !!fit && groupWithinPlaneBudget(group, metas, fit, planeEpsilon, options); -} - -function fitPlaneForGroup( - group: number[], - metas: Array, -): PlaneFit | null { - const seed = metas[group[0]]; - if (!seed) return null; - - let nx = 0; - let ny = 0; - let nz = 0; - let px = 0; - let py = 0; - let pz = 0; - let weightSum = 0; - - for (const index of group) { - const meta = metas[index]; - if (!meta) return null; - const direction = dotVec(seed.normal, meta.normal) < 0 ? -1 : 1; - const weight = Math.max(meta.area, 1e-6); - nx += meta.normal[0] * direction * weight; - ny += meta.normal[1] * direction * weight; - nz += meta.normal[2] * direction * weight; - for (const vertex of meta.polygon.vertices) { - px += vertex[0]; - py += vertex[1]; - pz += vertex[2]; - weightSum += 1; - } - } - - const normal = normalizeVec([nx, ny, nz]); - if (!normal || weightSum === 0) return null; - const boundaryVertices = groupBoundaryVertexKeys(group, metas); - const boundaryD = planeOffsetRangeForVertices(group, metas, normal, boundaryVertices); - if (boundaryD) { - const d = (boundaryD.min + boundaryD.max) / 2; - return { - normal, - point: [normal[0] * d, normal[1] * d, normal[2] * d], - boundaryVertexKeys: boundaryVertices, - }; - } - - return { - normal, - point: [px / weightSum, py / weightSum, pz / weightSum], - boundaryVertexKeys: boundaryVertices, - }; -} - -function planeOffsetRangeForVertices( - group: number[], - metas: Array, - normal: Vec3, - vertexKeys: Set, -): { min: number; max: number } | null { - let min = Infinity; - let max = -Infinity; - - for (const index of group) { - const meta = metas[index]; - if (!meta) continue; - for (const vertex of meta.polygon.vertices) { - if (!vertexKeys.has(vertexKey(vertex))) continue; - const d = dotVec(vertex, normal); - min = Math.min(min, d); - max = Math.max(max, d); - } - } - - return Number.isFinite(min) && Number.isFinite(max) ? { min, max } : null; -} - -function groupWithinPlaneBudget( - group: number[], - metas: Array, - fit: PlaneFit, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): boolean { - const normalDotMin = Math.cos((options.maxAngleDeg * Math.PI) / 180); - const boundaryVertices = fit.boundaryVertexKeys ?? groupBoundaryVertexKeys(group, metas); - for (const index of group) { - const meta = metas[index]; - if (!meta) return false; - if (Math.abs(dotVec(meta.normal, fit.normal)) < normalDotMin) return false; - for (const vertex of meta.polygon.vertices) { - const limit = boundaryVertices.has(vertexKey(vertex)) - ? options.maxBoundaryDisplacement - : planeEpsilon; - if (Math.abs(signedPlaneDistance(vertex, fit)) > limit) return false; - } - } - return true; -} - -function groupBoundaryVertexKeys( - group: number[], - metas: Array, -): Set { - const edgeCounts = new Map(); - - for (const index of group) { - const meta = metas[index]; - if (!meta) continue; - const vertices = meta.polygon.vertices; - for (let i = 0; i < vertices.length; i++) { - const a = vertices[i]; - const b = vertices[(i + 1) % vertices.length]; - const key = edgeKey(a, b); - const current = edgeCounts.get(key); - if (current) current.count += 1; - else edgeCounts.set(key, { count: 1, a, b }); - } - } - - const boundary = new Set(); - for (const edge of edgeCounts.values()) { - if (edge.count !== 1) continue; - boundary.add(vertexKey(edge.a)); - boundary.add(vertexKey(edge.b)); - } - return boundary; -} - -function projectPolygonToPlane(polygon: Polygon, fit: PlaneFit): Polygon { - const projectVertex = (vertex: Vec3): Vec3 => projectVecToPlane(vertex, fit); - const textureTriangles = mapTextureTriangleVertices(polygon.textureTriangles, projectVertex); - return { - ...polygon, - vertices: polygon.vertices.map(projectVertex), - ...(textureTriangles ? { textureTriangles } : {}), - }; -} diff --git a/packages/core/src/merge/optimize/preprocess.ts b/packages/core/src/merge/optimize/preprocess.ts index 93797c826..f0c60cb78 100644 --- a/packages/core/src/merge/optimize/preprocess.ts +++ b/packages/core/src/merge/optimize/preprocess.ts @@ -6,7 +6,6 @@ import { mergePolygons } from "../mergePolygons"; import { simplifyTriangleMeshPolygons } from "../simplifyTriangleMesh"; import { edgeKey, snappedPolygonsForMerge } from "./geometry"; import { mergeIsolatedTrianglePairs } from "./pairMerge"; -import { normalizeGeometryForMerge } from "./planeNormalize"; import type { IndexFilter, LossyApproximateOptions, @@ -25,7 +24,6 @@ const DEFAULT_NORMALIZE_OPTIONS: ResolvedGeometryNormalizeOptions = { maxAngleDeg: NORMALIZE_MAX_ANGLE_DEG, maxPlaneDisplacement: NORMALIZE_MAX_PLANE_DISPLACEMENT, maxBoundaryDisplacement: NORMALIZE_MAX_BOUNDARY_DISPLACEMENT, - isolatedPairs: false, }; const AUTOMATIC_RECT_COVER_MAX_POLYGONS = 1800; @@ -265,27 +263,21 @@ export function preprocessModelPolygons( const options = normalizeGeometry === true ? DEFAULT_NORMALIZE_OPTIONS : resolveNormalizeOptions(normalizeGeometry); - if (options.isolatedPairs) { - const paired = mergeIsolatedTrianglePairs(snappedInteriorPolygonsForMerge(deduped, cache), options, cache); - let mergedPaired = mergePolygons(paired); - if ( - cache?.snappedInteriorUsesBaselineFilter && - shouldRecheckSnappedInteriorCull(baseline, mergedPaired) - ) { - const exactPaired = mergeIsolatedTrianglePairs( - snappedInteriorPolygonsForMerge(deduped, cache, true), - options, - cache, - ); - const exactMergedPaired = mergePolygons(exactPaired); - if (exactMergedPaired.length < mergedPaired.length) mergedPaired = exactMergedPaired; - } - return mergedPaired.length < baseline.length ? mergedPaired : baseline; + const paired = mergeIsolatedTrianglePairs(snappedInteriorPolygonsForMerge(deduped, cache), options, cache); + let mergedPaired = mergePolygons(paired); + if ( + cache?.snappedInteriorUsesBaselineFilter && + shouldRecheckSnappedInteriorCull(baseline, mergedPaired) + ) { + const exactPaired = mergeIsolatedTrianglePairs( + snappedInteriorPolygonsForMerge(deduped, cache, true), + options, + cache, + ); + const exactMergedPaired = mergePolygons(exactPaired); + if (exactMergedPaired.length < mergedPaired.length) mergedPaired = exactMergedPaired; } - const normalizedGeometry = normalizeGeometryForMerge(deduped, options, cache); - const normalizedInterior = cullInteriorPolygons(normalizedGeometry); - const normalized = mergePolygons(normalizedInterior); - return normalized.length < baseline.length ? normalized : baseline; + return mergedPaired.length < baseline.length ? mergedPaired : baseline; } function snappedInteriorPolygonsForMerge( @@ -346,6 +338,5 @@ function resolveNormalizeOptions(options: LossyApproximateOptions): ResolvedGeom maxAngleDeg: options.maxAngleDeg ?? DEFAULT_NORMALIZE_OPTIONS.maxAngleDeg, maxPlaneDisplacement: options.maxPlaneDisplacement ?? DEFAULT_NORMALIZE_OPTIONS.maxPlaneDisplacement, maxBoundaryDisplacement: options.maxBoundaryDisplacement ?? DEFAULT_NORMALIZE_OPTIONS.maxBoundaryDisplacement, - isolatedPairs: options.isolatedPairs ?? DEFAULT_NORMALIZE_OPTIONS.isolatedPairs, }; } diff --git a/packages/core/src/merge/optimize/types.ts b/packages/core/src/merge/optimize/types.ts index 65440a9ba..ed0f77573 100644 --- a/packages/core/src/merge/optimize/types.ts +++ b/packages/core/src/merge/optimize/types.ts @@ -7,7 +7,6 @@ export interface LossyApproximateOptions { maxAngleDeg?: number; maxPlaneDisplacement?: number; maxBoundaryDisplacement?: number; - isolatedPairs?: boolean; } export interface OptimizeMeshPolygonsOptions { @@ -30,7 +29,6 @@ export interface ResolvedGeometryNormalizeOptions { maxAngleDeg: number; maxPlaneDisplacement: number; maxBoundaryDisplacement: number; - isolatedPairs: boolean; } export interface PlaneNormalizeMeta { @@ -65,19 +63,6 @@ export interface PairCandidateRank { index: number; } -export interface PlanePatchCandidate { - indices: number[]; - source: Polygon[]; - projected: Polygon[]; - vertexMoves: VertexPositionMove[]; - score: number; -} - -export interface PlaneGroupReplacements { - polygons: Map; - vertexMoves: VertexPositionMove[]; -} - export interface TrianglePairSourceCache { polygons: Polygon[]; metas: Array; diff --git a/packages/core/src/merge/optimizePolygons.ts b/packages/core/src/merge/optimizePolygons.ts index 25c5b0fab..8dc871076 100644 --- a/packages/core/src/merge/optimizePolygons.ts +++ b/packages/core/src/merge/optimizePolygons.ts @@ -47,7 +47,6 @@ const DEFAULT_LOSSY_APPROXIMATE_OPTIONS: Required = { maxAngleDeg: 15, maxPlaneDisplacement: 0.35, maxBoundaryDisplacement: 0.04, - isolatedPairs: true, }; const AGGRESSIVE_LOSSY_APPROXIMATE_VARIANTS: ReadonlyArray> = [ diff --git a/packages/core/src/merge/seamRepair.ts b/packages/core/src/merge/seamRepair.ts index f92cc0c52..580799d12 100644 --- a/packages/core/src/merge/seamRepair.ts +++ b/packages/core/src/merge/seamRepair.ts @@ -1,31 +1,18 @@ import type { Polygon } from "../types"; import type { - SeamFacetSplitOptions as SplitOptions, - SeamFacetSplitReport as SplitReport, - SeamOverlapCandidate as OverlapCandidate, SeamOverlapDiagnostics as OverlapDiagnostics, SeamOverlapOptions as OverlapOptions, } from "./seamRepairTypes"; import { - DEFAULT_SEAM_SPLIT_BUDGET, DEFAULT_TRUE_GAP_OVERLAP_PX, MAX_NEAR_SEAM_GAP_PX, - resolveSeamFacetSplitOptions, resolveSeamOverlapOptions, seamOverlapEnabled, } from "./seamRepair/geometry"; import { buildSeamEdgeAmounts, emptyDiagnostics, - patchPolygon, } from "./seamRepair/nearSeam"; -import { - applySeamFacetSplitSelection, - seamFacetSplitPlan, - seamFacetSplitPublicCandidate, - splitPlanFollowUpContext, -} from "./seamRepair/facetSplit"; -import type { FollowUp } from "./seamRepair/facetSplit"; export type * from "./seamRepairTypes"; @@ -35,88 +22,13 @@ export const DEFAULT_SEAM_OVERLAP_OPTIONS = { capacityScale: 1, } as const satisfies OverlapOptions; -export const DEFAULT_SEAM_FACET_SPLIT_OPTIONS = { - budget: DEFAULT_SEAM_SPLIT_BUDGET, -} as const satisfies SplitOptions; - -export function seamFacetSplitPolygons( - polygons: Polygon[], - seamOptions?: number | OverlapOptions, - splitOptions?: SplitOptions, -) { - const resolved = resolveSeamOverlapOptions(seamOptions); - const split = resolveSeamFacetSplitOptions(splitOptions); - if (!seamOverlapEnabled(resolved, seamOptions) || polygons.length === 0) return polygons; - let current = polygons; - let followUpContext: FollowUp | undefined; - let remainingBudget = split.budget; - for (let pass = 0; pass < split.passes; pass += 1) { - const plan = seamFacetSplitPlan(current, resolved, split, remainingBudget, followUpContext); - if (pass === 0) remainingBudget = Math.min(remainingBudget, plan.budgetLimit); - if (plan.selected.size === 0) break; - const next = applySeamFacetSplitSelection(current, plan.selected); - if (next.length === current.length) break; - remainingBudget -= plan.selected.size; - if (remainingBudget <= 0) { - current = next; - break; - } - followUpContext = splitPlanFollowUpContext(plan.candidates); - current = next; - } - return current; -} - -export function seamFacetSplitReport( - polygons: Polygon[], - seamOptions?: number | OverlapOptions, - splitOptions?: SplitOptions, -): SplitReport { - const resolved = resolveSeamOverlapOptions(seamOptions); - const split = resolveSeamFacetSplitOptions(splitOptions); - if (!seamOverlapEnabled(resolved, seamOptions) || polygons.length === 0) { - return { candidates: [], selectedPolygons: 0, selectedEdges: 0, addedPolygons: 0 }; - } - - const plan = seamFacetSplitPlan(polygons, resolved, split, split.budget); - let selectedEdges = 0; - for (const edges of plan.selected.values()) selectedEdges += edges.size; - return { - candidates: plan.candidates.map(seamFacetSplitPublicCandidate), - selectedPolygons: plan.selected.size, - selectedEdges, - addedPolygons: plan.selected.size, - }; -} - -export function seamOverlapPolygons( - polygons: Polygon[], - options?: number | OverlapOptions, -) { - const resolved = resolveSeamOverlapOptions(options); - if (!seamOverlapEnabled(resolved, options) || polygons.length === 0) return polygons; - const { edgeRepairs } = buildSeamEdgeAmounts(polygons, resolved); - if (!edgeRepairs.some((edges) => edges.size > 0)) return polygons; - return polygons.map((polygon, index) => patchPolygon(polygon, edgeRepairs[index], resolved.capacityScale)); -} - -export function repairMeshSeams( - polygons: Polygon[], - seamOptions: number | OverlapOptions = DEFAULT_SEAM_OVERLAP_OPTIONS, - splitOptions: SplitOptions = DEFAULT_SEAM_FACET_SPLIT_OPTIONS, -) { - if (polygons.length === 0) return polygons; - const split = seamFacetSplitPolygons(polygons, seamOptions, splitOptions); - return seamOverlapPolygons(split, seamOptions); -} - export function seamOverlapDiagnostics( polygons: Polygon[], options?: number | OverlapOptions, ): OverlapDiagnostics { const resolved = resolveSeamOverlapOptions(options); if (!seamOverlapEnabled(resolved, options) || polygons.length === 0) return emptyDiagnostics(); - return buildSeamEdgeAmounts(polygons, resolved).diagnostics; + return buildSeamEdgeAmounts(polygons, resolved, false).diagnostics; } export function seamOverlapSafetyDiagnostics( @@ -125,20 +37,5 @@ export function seamOverlapSafetyDiagnostics( ): OverlapDiagnostics { const resolved = resolveSeamOverlapOptions(options); if (!seamOverlapEnabled(resolved, options) || polygons.length === 0) return emptyDiagnostics(); - return buildSeamEdgeAmounts(polygons, resolved, false, true).diagnostics; -} - -export function seamOverlapReport( - polygons: Polygon[], - options?: number | OverlapOptions, -): { diagnostics: OverlapDiagnostics; candidates: OverlapCandidate[] } { - const resolved = resolveSeamOverlapOptions(options); - if (!seamOverlapEnabled(resolved, options) || polygons.length === 0) { - return { diagnostics: emptyDiagnostics(), candidates: [] }; - } - const result = buildSeamEdgeAmounts(polygons, resolved, true); - return { - diagnostics: result.diagnostics, - candidates: result.candidates ?? [], - }; + return buildSeamEdgeAmounts(polygons, resolved, true).diagnostics; } diff --git a/packages/core/src/merge/seamRepair/facetSplit.ts b/packages/core/src/merge/seamRepair/facetSplit.ts deleted file mode 100644 index 196ae2620..000000000 --- a/packages/core/src/merge/seamRepair/facetSplit.ts +++ /dev/null @@ -1,550 +0,0 @@ -import { rotateVec3 as rotateCssVec3 } from "../../math/rotation"; -import type { Polygon } from "../../types"; -import type { SeamFacetSplitCandidateReason as SplitReason } from "../seamRepairTypes"; -import { - buildEdgeRecords, - buildPolygonMetas, - compatibleRepairMaterials, - dot, - EPS, - pointKey, -} from "./geometry"; -import type { Edge, Meta, Overlap, Split } from "./geometry"; -import { - isRefinableSeamQuad, - quadShapeRisk, - splitQuadIntoTriangles, -} from "./quadSplit"; - -type Cand = { - key: string; - e: [string, string]; - o: Edge[]; - r: Edge[]; - len: number; - rank: number; - proj: number; - s: number; - nr: number; - sr: number; - vr: number; - comp: number; - sel: boolean; - why: SplitReason; - cost: number; -}; - -export type FollowUp = { endpoints: ReadonlySet }; - -type SplitMode = "primary" | "follow-up"; - -type Dist = { - q1: number; - median: number; - q3: number; - p70: number; - p80: number; - p88: number; - p95: number; - p97: number; - max: number; -}; - -function numericDistribution(values: number[]) { - if (values.length === 0) { - return { - q1: Infinity, - median: Infinity, - q3: Infinity, - p70: Infinity, - p80: Infinity, - p88: Infinity, - p95: Infinity, - p97: Infinity, - max: Infinity, - }; - } - const sorted = [...values].sort((a, b) => a - b); - const at = (ratio: number) => sorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * ratio))] ?? 0; - return { - q1: at(0.25), - median: at(0.5), - q3: at(0.75), - p70: at(0.7), - p80: at(0.8), - p88: at(0.88), - p95: at(0.95), - p97: at(0.97), - max: sorted[sorted.length - 1] ?? 0, - }; -} - -function unionFindRoot(parents: number[], index: number): number { - const parent = parents[index]; - if (parent === index) return index; - const root = unionFindRoot(parents, parent); - parents[index] = root; - return root; -} - -export function splitPlanFollowUpContext(candidates: Cand[]) { - const endpoints = new Set(); - const components = new Set(); - for (const candidate of candidates) { - if (!candidate.sel) continue; - components.add(candidate.comp); - } - for (const candidate of candidates) { - if (!components.has(candidate.comp)) continue; - for (const endpoint of candidate.e) endpoints.add(endpoint); - } - return { endpoints }; -} - -function splitCandidateTouchesFollowUp( - candidate: Cand, - context: FollowUp | undefined, -) { - if (!context) return true; - return candidate.e.some((endpoint) => context.endpoints.has(endpoint)); -} - -function buildSeamFacetSplitCandidates( - polygons: Polygon[], - metas: Meta[], - edgeOwners: ReadonlyMap, - splitOptions: Split, -) { - const candidates: Cand[] = []; - for (const [key, owners] of edgeOwners) { - if (owners.length !== 2) continue; - const [a, b] = owners; - if (!compatibleRepairMaterials(a, b)) continue; - const refinable = owners.filter((record) => isRefinableSeamQuad(polygons[record.polygon])); - if (refinable.length === 0) continue; - const firstRefinable = refinable[0]; - - const normalRisk = 1 - Math.min(1, Math.abs(dot(a.normal, b.normal))); - const seamLength = Math.max(a.length, b.length); - if (normalRisk < 0.01 && seamLength < 64) continue; - - const shapeRisk = Math.max(...refinable.map((record) => quadShapeRisk(metas[record.polygon]))); - const bothSidesRefinable = refinable.length === 2 ? 1.18 : 1; - const seamRisk = Math.max(0.08, normalRisk); - const projected = splitOptions.viewAware - ? splitCandidateViewMetrics(a, b, splitOptions.rotX, splitOptions.rotY) - : { proj: seamLength, vr: 1 }; - const rankLength = splitOptions.viewAware ? Math.max(projected.proj, seamLength * 0.12) : seamLength; - const viewWeight = splitOptions.viewAware ? 0.18 + projected.vr * 1.82 : 1; - candidates.push({ - key, - e: [pointKey(firstRefinable.a), pointKey(firstRefinable.b)], - o: owners, - r: refinable, - len: seamLength, - rank: rankLength, - proj: projected.proj, - s: rankLength * (0.58 + seamRisk * 2.8) * shapeRisk * bothSidesRefinable * viewWeight, - nr: normalRisk, - sr: shapeRisk, - vr: projected.vr, - comp: -1, - sel: false, - why: "below-threshold", - cost: refinable.length, - }); - } - - const parents = Array.from({ length: candidates.length }, (_, index) => index); - const byEndpoint = new Map(); - for (let index = 0; index < candidates.length; index += 1) { - for (const endpoint of candidates[index].e) { - const previous = byEndpoint.get(endpoint); - if (previous === undefined) { - byEndpoint.set(endpoint, index); - } else { - const rootA = unionFindRoot(parents, previous); - const rootB = unionFindRoot(parents, index); - if (rootA !== rootB) parents[rootB] = rootA; - } - } - } - - const componentIds = new Map(); - for (let index = 0; index < candidates.length; index += 1) { - const root = unionFindRoot(parents, index); - let component = componentIds.get(root); - if (component === undefined) { - component = componentIds.size; - componentIds.set(root, component); - } - candidates[index].comp = component; - } - - return candidates; -} - -function splitCandidateViewMetrics( - a: Edge, - b: Edge, - rotX: number, - rotY: number, -) { - const p0 = rotateCssVec3(a.a, rotX, 0, rotY); - const p1 = rotateCssVec3(a.b, rotX, 0, rotY); - const projectedLength = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]); - const depthA = rotateCssVec3(a.normal, rotX, 0, rotY)[2]; - const depthB = rotateCssVec3(b.normal, rotX, 0, rotY)[2]; - const frontness = Math.max(0, depthA, depthB); - const silhouette = Math.min(1, Math.abs(depthA - depthB)); - return { - proj: projectedLength, - vr: Math.max(0.04, Math.min(1, frontness * 0.85 + silhouette * 0.45)), - }; -} - -function strongestCandidatesByComponent( - candidates: Cand[], -) { - const strongest = new Map(); - for (const candidate of candidates) { - const current = strongest.get(candidate.comp); - if (!current || candidate.s > current.s || (candidate.s === current.s && candidate.len > current.len)) { - strongest.set(candidate.comp, candidate); - } - } - return new Set(strongest.values()); -} - -function splitCandidateBudgetPriority(candidate: Cand) { - const coplanar = Math.max(0, 1 - Math.min(1, candidate.nr)); - const coplanarWeight = 0.35 + coplanar * coplanar * coplanar * 3.65; - const oneSidedWeight = candidate.r.length === 1 ? 1.08 : 1; - return (candidate.rank * coplanarWeight * oneSidedWeight) / Math.sqrt(Math.max(1, candidate.r.length)); -} - -function splitCandidateLikelyCrackPriority(candidate: Cand) { - const coplanar = Math.max(0, 1 - Math.min(1, candidate.nr)); - const visibleWeight = 0.35 + Math.min(1, candidate.vr) * 1.65; - const shapeWeight = 0.7 + Math.min(2.6, candidate.sr) * 0.3; - const oneSidedWeight = candidate.r.length === 1 ? 1.1 : 1; - const visiblePriority = ( - candidate.rank * - (0.6 + coplanar * coplanar * 1.4) * - visibleWeight * - shapeWeight * - oneSidedWeight - ) / Math.sqrt(Math.max(1, candidate.r.length)); - return Math.max(visiblePriority, splitCandidateBudgetPriority(candidate) * 0.75); -} - -function uniqueSplitPolygonCost(candidates: Cand[]) { - const polygons = new Set(); - for (const candidate of candidates) { - for (const record of candidate.r) polygons.add(record.polygon); - } - return polygons.size; -} - -function splitCandidateLikelyCrack(candidate: Cand, lengthStats: Dist) { - return candidate.nr <= 0.25 && - candidate.rank >= lengthStats.median * 1.08 && - candidate.proj >= 24; -} - -function splitCandidateGlobalSeed( - candidate: Cand, - strongScore: number, - strongLength: number, -) { - return candidate.s >= strongScore || candidate.rank >= strongLength; -} - -function seamFacetSplitBudgetPlan( - candidates: Cand[], - mode: SplitMode, - maxBudget: number, - scoreStats: Dist, - lengthStats: Dist, - strongScore: number, - strongLength: number, -) { - const budgetLimit = Math.max(0, Math.floor(maxBudget)); - if (budgetLimit <= 0 || candidates.length === 0 || mode === "follow-up") { - return { budgetLimit, componentBudgets: null }; - } - - const byComponent = new Map(); - for (const candidate of candidates) { - const group = byComponent.get(candidate.comp); - if (group) group.push(candidate); - else byComponent.set(candidate.comp, [candidate]); - } - - const componentBudgets = new Map(); - const scoreSpread = Math.max(EPS, scoreStats.q3 - scoreStats.q1); - const fallbackSeedScore = Math.min(scoreStats.max, Math.max(scoreStats.p95, scoreStats.q3 + scoreSpread)); - let total = 0; - for (const [component, group] of byComponent) { - const primary = group.filter((candidate) => - splitCandidateGlobalSeed(candidate, strongScore, strongLength) || - candidate.s >= fallbackSeedScore - ); - if (primary.length === 0) continue; - - const likely = group.filter((candidate) => splitCandidateLikelyCrack(candidate, lengthStats)); - const primaryCost = uniqueSplitPolygonCost(primary); - const likelyCost = uniqueSplitPolygonCost(likely); - const followUpAllowance = Math.ceil(Math.sqrt(Math.max(0, likelyCost - primaryCost)) * 3); - const componentBudget = Math.min( - uniqueSplitPolygonCost(group), - primaryCost + followUpAllowance, - ); - if (componentBudget <= 0) continue; - componentBudgets.set(component, componentBudget); - total += componentBudget; - } - - if (componentBudgets.size === 0) return { budgetLimit: 0, componentBudgets }; - return { - budgetLimit: Math.min(budgetLimit, total), - componentBudgets, - }; -} - -function selectSeamFacetSplitCandidates( - candidates: Cand[], - mode: SplitMode, - budget: number, -) { - const selected = new Map>(); - if (candidates.length === 0 || budget <= 0) return { selected, budgetLimit: 0 }; - - const scoreStats = numericDistribution(candidates.map((candidate) => candidate.s)); - const lengthStats = numericDistribution(candidates.map((candidate) => candidate.rank)); - const scoreSpread = Math.max(EPS, scoreStats.q3 - scoreStats.q1); - const strongScore = Math.min(scoreStats.max, Math.max(scoreStats.p95, scoreStats.q3 + scoreSpread * 0.85)); - const anchorScore = Math.min(scoreStats.max, Math.max(scoreStats.p80, scoreStats.q3 + scoreSpread * 0.15)); - const sharedPolygonScore = Math.min(scoreStats.max, Math.max(scoreStats.p70, scoreStats.q3)); - const strongLength = Math.max(lengthStats.p97, lengthStats.median * 1.8); - const anchorLength = Math.max(lengthStats.p88, lengthStats.median * 1.35); - const budgetPlan = seamFacetSplitBudgetPlan( - candidates, - mode, - budget, - scoreStats, - lengthStats, - strongScore, - strongLength, - ); - let remainingBudget = budgetPlan.budgetLimit; - if (remainingBudget <= 0) return { selected, budgetLimit: 0 }; - - const anchors = strongestCandidatesByComponent(candidates); - const alreadySplit = new Set(); - const selectedEndpoints = new Set(); - const selectedComponents = new Set(); - const componentSpend = new Map(); - const localReserve = mode === "primary" - ? Math.min(Math.max(0, budgetPlan.budgetLimit - 1), Math.max(2, Math.floor(budgetPlan.budgetLimit * 0.28))) - : 0; - - const sorted = [...candidates].sort((a, b) => - splitCandidateBudgetPriority(b) - splitCandidateBudgetPriority(a) || - (b.s / Math.max(1, b.r.length)) - (a.s / Math.max(1, a.r.length)) || - b.len - a.len - ); - const likelyCrackSorted = [...candidates].sort((a, b) => - splitCandidateLikelyCrackPriority(b) - splitCandidateLikelyCrackPriority(a) || - splitCandidateBudgetPriority(b) - splitCandidateBudgetPriority(a) || - b.len - a.len - ); - - const selectCandidate = (candidate: Cand, reason: SplitReason) => { - candidate.sel = true; - candidate.why = reason; - selectedComponents.add(candidate.comp); - for (const endpoint of candidate.e) selectedEndpoints.add(endpoint); - for (const record of candidate.r) { - alreadySplit.add(record.polygon); - const edges = selected.get(record.polygon); - if (edges) edges.add(record.edge); - else selected.set(record.polygon, new Set([record.edge])); - } - }; - - const withinComponentBudget = (candidate: Cand, marginalCost: number) => { - const componentBudgets = budgetPlan.componentBudgets; - if (marginalCost <= 0 || !componentBudgets) return true; - const componentBudget = componentBudgets.get(candidate.comp) ?? 0; - return (componentSpend.get(candidate.comp) ?? 0) + marginalCost <= componentBudget; - }; - - const recordComponentSpend = (candidate: Cand, marginalCost: number) => { - if (marginalCost <= 0 || !budgetPlan.componentBudgets) return; - componentSpend.set(candidate.comp, (componentSpend.get(candidate.comp) ?? 0) + marginalCost); - }; - - for (const candidate of likelyCrackSorted) { - const marginalCost = candidate.r.reduce( - (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), - 0, - ); - candidate.cost = marginalCost; - if (marginalCost > remainingBudget) continue; - if (!withinComponentBudget(candidate, marginalCost)) continue; - if (marginalCost > 0 && remainingBudget - marginalCost < localReserve) continue; - const isLikelyCrack = splitCandidateLikelyCrack(candidate, lengthStats); - if (!isLikelyCrack) continue; - selectCandidate(candidate, "global-outlier"); - recordComponentSpend(candidate, marginalCost); - remainingBudget -= marginalCost; - if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; - } - - for (const candidate of sorted) { - if (candidate.sel) continue; - const marginalCost = candidate.r.reduce( - (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), - 0, - ); - candidate.cost = marginalCost; - if (marginalCost > remainingBudget) continue; - if (!withinComponentBudget(candidate, marginalCost)) continue; - if (marginalCost > 0 && remainingBudget - marginalCost < localReserve) continue; - - const twoSided = candidate.r.length === 2; - const isAnchor = anchors.has(candidate) && ( - mode === "primary" || - (mode === "follow-up" && candidate.s >= anchorScore * 1.08 && candidate.rank >= anchorLength) - ) && ( - twoSided - ? candidate.s >= anchorScore || candidate.rank >= anchorLength - : candidate.s >= anchorScore * 1.18 || candidate.rank >= anchorLength * 1.12 - ); - const isGlobalOutlier = twoSided - ? candidate.s >= strongScore || candidate.rank >= strongLength - : candidate.s >= strongScore * 1.35 || candidate.rank >= strongLength * 1.2; - const isSharedPolygonFollowUp = marginalCost === 0 && ( - twoSided - ? candidate.s >= sharedPolygonScore || candidate.rank >= anchorLength - : candidate.s >= sharedPolygonScore * 1.25 || candidate.rank >= anchorLength * 1.12 - ); - if (!isAnchor && !isGlobalOutlier && !isSharedPolygonFollowUp) continue; - - selectCandidate(candidate, isAnchor - ? "component-anchor" - : isGlobalOutlier - ? "global-outlier" - : "shared-polygon"); - recordComponentSpend(candidate, marginalCost); - remainingBudget -= marginalCost; - if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; - } - - for (const candidate of sorted) { - if (candidate.sel) continue; - const marginalCost = candidate.r.reduce( - (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), - 0, - ); - candidate.cost = marginalCost; - if (marginalCost > 1 || marginalCost > remainingBudget) continue; - if (!withinComponentBudget(candidate, marginalCost)) continue; - const touchesSelectedPolygon = candidate.r.some((record) => alreadySplit.has(record.polygon)); - const touchesSelectedEndpoint = candidate.e.some((endpoint) => selectedEndpoints.has(endpoint)); - const isOneSidedTail = mode === "primary" && - candidate.r.length === 1 && - marginalCost === 1 && - (selectedComponents.has(candidate.comp) || touchesSelectedEndpoint || touchesSelectedPolygon) && - candidate.rank >= anchorLength * 1.05 && - candidate.nr >= 0.16 && - candidate.vr <= 0.32; - if (isOneSidedTail) { - selectCandidate(candidate, "local-follow-up"); - recordComponentSpend(candidate, marginalCost); - remainingBudget -= marginalCost; - if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; - continue; - } - if (candidate.r.length !== 2) continue; - const isProjectedNeighbor = touchesSelectedPolygon && - marginalCost === 1 && - candidate.proj >= anchorLength * 1.45 && - candidate.vr <= 0.18; - if (!touchesSelectedEndpoint && !isProjectedNeighbor) continue; - const isLocalFollowUp = ( - candidate.s >= sharedPolygonScore * 0.42 || - candidate.rank >= anchorLength * 0.62 - ) && candidate.s <= sharedPolygonScore * 1.1 && candidate.proj >= 24; - if (isLocalFollowUp) { - selectCandidate(candidate, "local-follow-up"); - recordComponentSpend(candidate, marginalCost); - remainingBudget -= marginalCost; - if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; - } - } - - return { selected, budgetLimit: budgetPlan.budgetLimit }; -} - -export function seamFacetSplitPlan( - polygons: Polygon[], - seamOptions: Overlap, - splitOptions: Split, - budget: number, - followUpContext?: FollowUp, -) { - const metas = buildPolygonMetas(polygons); - const records = buildEdgeRecords(polygons, metas, seamOptions.capacityScale); - const edgeOwners = new Map(); - for (const record of records) { - const owners = edgeOwners.get(record.key); - if (owners) owners.push(record); - else edgeOwners.set(record.key, [record]); - } - - const candidates = buildSeamFacetSplitCandidates(polygons, metas, edgeOwners, splitOptions) - .filter((candidate) => splitCandidateTouchesFollowUp(candidate, followUpContext)); - const selection = selectSeamFacetSplitCandidates(candidates, followUpContext ? "follow-up" : "primary", budget); - return { selected: selection.selected, candidates, budgetLimit: selection.budgetLimit }; -} - -export function applySeamFacetSplitSelection( - polygons: Polygon[], - selected: ReadonlyMap>, -) { - const out: Polygon[] = []; - for (let i = 0; i < polygons.length; i += 1) { - const polygon = polygons[i]; - const edges = selected.get(i); - if (edges && isRefinableSeamQuad(polygon)) out.push(...splitQuadIntoTriangles(polygon, edges)); - else out.push(polygon); - } - return out; -} - -export function seamFacetSplitPublicCandidate(candidate: Cand) { - const [a, b] = candidate.o; - const first = a ?? b; - const second = b ?? a; - return { - key: candidate.key, - aPolygon: first?.polygon ?? -1, - aEdge: first?.edge ?? -1, - bPolygon: second?.polygon ?? -1, - bEdge: second?.edge ?? -1, - color: first?.color ?? second?.color, - materialKey: first?.materialKey ?? second?.materialKey ?? "", - lengthPx: candidate.len, - projectedLengthPx: candidate.proj, - score: candidate.s, - normalRisk: candidate.nr, - shapeRisk: candidate.sr, - viewRisk: candidate.vr, - component: candidate.comp, - marginalCost: candidate.cost, - selected: candidate.sel, - reason: candidate.why, - }; -} diff --git a/packages/core/src/merge/seamRepair/geometry.ts b/packages/core/src/merge/seamRepair/geometry.ts index d04b593c4..a884606d4 100644 --- a/packages/core/src/merge/seamRepair/geometry.ts +++ b/packages/core/src/merge/seamRepair/geometry.ts @@ -1,10 +1,7 @@ import { signedArea2D as signedArea } from "../../atlas/solidTriangle"; import { crossVec as cross } from "../../math/vec3"; import type { Polygon, Vec3 } from "../../types"; -import type { - SeamFacetSplitOptions as SplitOptions, - SeamOverlapOptions as OverlapOptions, -} from "../seamRepairTypes"; +import type { SeamOverlapOptions as OverlapOptions } from "../seamRepairTypes"; export type Vec2 = [number, number]; @@ -38,17 +35,13 @@ export type Near = { gap: number; facingA: number; facingB: number; aStart: numb export type Repair = { start: number; end: number; amount: number }; -export type Split = { rotX: number; rotY: number; viewAware: boolean; passes: number; budget: number }; - export type Overlap = { overlapPx: number; maxGapPx: number; capacityScale: number }; export const DEFAULT_TILE = 50; export const MAX_NEAR_SEAM_GAP_PX = 14; -export const DEFAULT_SEAM_SPLIT_BUDGET = 40; export const TRUE_GAP_OVERLAP_AMOUNT_RATIO = 0.175; export const DEFAULT_TRUE_GAP_OVERLAP_PX = 1.25; export const EPS = 1e-6; -export const TOPOLOGY_EPS = 1e-4; function finiteOr(value: number | undefined, fallback: number) { return typeof value === "number" && Number.isFinite(value) ? value : fallback; @@ -79,24 +72,10 @@ export function seamOverlapEnabled( return !(typeof rawOptions === "number" && rawOptions <= 0) && options.maxGapPx > EPS && options.capacityScale > EPS; } -export function resolveSeamFacetSplitOptions(options?: SplitOptions) { - return { - rotX: finiteOr(options?.rotX, 65), - rotY: finiteOr(options?.rotY, 45), - viewAware: options?.viewAware !== false, - passes: Math.max(1, Math.min(3, Math.round(finiteOr(options?.passes, 2)))), - budget: Math.max(0, Math.min(256, Math.round(finiteOr(options?.budget, DEFAULT_SEAM_SPLIT_BUDGET)))), - }; -} - export function cssPoints(vertices: Vec3[]): Vec3[] { return vertices.map((v): Vec3 => [v[1] * DEFAULT_TILE, v[0] * DEFAULT_TILE, v[2] * DEFAULT_TILE]); } -export function fromCssPoint(point: Vec3): Vec3 { - return [point[1] / DEFAULT_TILE, point[0] / DEFAULT_TILE, point[2] / DEFAULT_TILE]; -} - export function pointKey(point: Vec3) { return `${point[0]},${point[1]},${point[2]}`; } @@ -320,14 +299,3 @@ export function buildEdgeRecords( export function compatibleRepairMaterials(a: Edge, b: Edge) { return a.materialKey === b.materialKey && a.color === b.color; } - -export function sameTopologyPoint(a: Vec3, b: Vec3) { - return length(sub(a, b)) <= TOPOLOGY_EPS; -} - -export function edgeRecordsTouch(a: Edge, b: Edge) { - return sameTopologyPoint(a.a, b.a) || - sameTopologyPoint(a.a, b.b) || - sameTopologyPoint(a.b, b.a) || - sameTopologyPoint(a.b, b.b); -} diff --git a/packages/core/src/merge/seamRepair/nearSeam.ts b/packages/core/src/merge/seamRepair/nearSeam.ts index a6c4defe4..506ff748e 100644 --- a/packages/core/src/merge/seamRepair/nearSeam.ts +++ b/packages/core/src/merge/seamRepair/nearSeam.ts @@ -1,28 +1,15 @@ -import { signedArea2D as signedArea } from "../../atlas/solidTriangle"; import { boundsOverlap3D as edgeBoundsCouldOverlap } from "../../math/vec3"; import type { Polygon, Vec3 } from "../../types"; -import type { - SeamOverlapCandidate as OverlapCandidate, - SeamOverlapCandidateKind as OverlapKind, - SeamOverlapDiagnostics as OverlapDiagnostics, -} from "../seamRepairTypes"; +import type { SeamOverlapDiagnostics as OverlapDiagnostics } from "../seamRepairTypes"; import { buildEdgeRecords, buildPolygonMetas, compatibleRepairMaterials, - cssPoints, dot, - edgeOutward2D, - edgeRecordsTouch, - edgeSafeCapacity, EPS, - fromCssPoint, - hasTexture, - isWeaklyConvex, - localBasis, MAX_NEAR_SEAM_GAP_PX, } from "./geometry"; -import type { Edge, Near, Overlap, Repair, Vec2 } from "./geometry"; +import type { Edge, Near, Overlap, Repair } from "./geometry"; const MIN_RESIDUAL_PATCH_GAP_PX = 0.25; const MIN_PARALLEL_DOT = 0.985; @@ -33,43 +20,6 @@ const NEAR_SEAM_EXTENDED_SWEEP_PAIR_LIMIT = 25_000_000; const NEAR_SEAM_GRID_AVG_CELLS_PER_RECORD_LIMIT = 256; const NEAR_SEAM_GRID_MAX_CELLS_PER_RECORD_LIMIT = 8192; -function classifyCandidate(a: Edge, b: Edge) { - return compatibleRepairMaterials(a, b) - ? edgeRecordsTouch(a, b) ? "connected-facet" : "true-gap" - : "material-boundary"; -} - -function seamOverlapCandidate( - kind: OverlapKind, - a: Edge, - b: Edge, - info: Near, - targetClosurePx: number, - appliedClosurePx: number, -) { - return { - kind, - aPolygon: a.polygon, - aEdge: a.edge, - bPolygon: b.polygon, - bEdge: b.edge, - aColor: a.color, - bColor: b.color, - aMaterialKey: a.materialKey, - bMaterialKey: b.materialKey, - gapPx: info.gap, - spanPx: info.aEnd - info.aStart, - aStartPx: info.aStart, - aEndPx: info.aEnd, - bStartPx: info.bStart, - bEndPx: info.bEnd, - targetClosurePx, - appliedClosurePx, - residualGapPx: Math.max(0, info.gap - appliedClosurePx), - residualTargetPx: Math.max(0, targetClosurePx - appliedClosurePx), - }; -} - function addEdgeRepair( repairs: Array>, record: Edge, @@ -126,16 +76,14 @@ function finishDiagnostics( export function buildSeamEdgeAmounts( polygons: Polygon[], options: Overlap, - collectCandidates = false, diagnosticsOnly = false, ) { const metas = buildPolygonMetas(polygons); const records = buildEdgeRecords(polygons, metas, options.capacityScale); const repairs = diagnosticsOnly ? [] : polygons.map(() => new Map()); const diagnostics = emptyDiagnostics(); - const candidates = collectCandidates ? [] as OverlapCandidate[] : undefined; if (records.length === 0) { - return { edgeRepairs: repairs, diagnostics, candidates }; + return { edgeRepairs: repairs, diagnostics }; } const edgeOwners = new Map(); @@ -150,11 +98,10 @@ export function buildSeamEdgeAmounts( diagnostics.exactPairs += owners.length === 2 ? 1 : owners.length; } - buildNearSeamEdgeAmounts(records, edgeOwners, repairs, diagnostics, options, candidates); + buildNearSeamEdgeAmounts(records, edgeOwners, repairs, diagnostics, options); return { edgeRepairs: repairs, diagnostics: diagnosticsOnly ? diagnostics : finishDiagnostics(repairs, diagnostics), - candidates, }; } @@ -164,7 +111,6 @@ function buildNearSeamEdgeAmounts( repairs: Array>, diagnostics: OverlapDiagnostics, options: Overlap, - candidates: OverlapCandidate[] | undefined, ) { const maxGap = options.maxGapPx; const exactSharedKeys = new Set(); @@ -177,24 +123,16 @@ function buildNearSeamEdgeAmounts( const candidate = first.index < second.index ? second : first; if (candidate.polygon === record.polygon) return; if (record.key === candidate.key && exactSharedKeys.has(record.key)) return; - if (!candidates && !compatibleRepairMaterials(record, candidate)) return; + if (!compatibleRepairMaterials(record, candidate)) return; if (!edgeBoundsCouldOverlap(record, candidate, maxGap)) return; if (Math.abs(dot(record.dir, candidate.dir)) < MIN_PARALLEL_DOT) return; const info = nearSeamInfo(record, candidate, maxGap); if (!info) return; - const kind = classifyCandidate(record, candidate); const targetClosure = info.gap + options.overlapPx; - if (kind === "material-boundary") { - candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, 0)); - return; - } let remainingClosure = targetClosure; - if (remainingClosure <= MIN_RESIDUAL_PATCH_GAP_PX) { - candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, 0)); - return; - } + if (remainingClosure <= MIN_RESIDUAL_PATCH_GAP_PX) return; const maxClosureA = record.capacity * info.facingA; const maxClosureB = candidate.capacity * info.facingB; @@ -212,7 +150,6 @@ function buildNearSeamEdgeAmounts( remainingClosure -= extraB; } - candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, closureA + closureB)); if (repairs.length > 0 && closureA > EPS) { addEdgeRepair(repairs, record, info.aStart, info.aEnd, closureA / info.facingA); } @@ -397,116 +334,3 @@ function nearSeamInfo(a: Edge, b: Edge, maxGap: number) { bEnd: Math.max(b0T, b1T), }; } - -function repairPoint(a: Vec2, b: Vec2, edgeLength: number, distance: number): Vec2 { - const t = edgeLength <= EPS ? 0 : Math.max(0, Math.min(1, distance / edgeLength)); - return [ - a[0] + (b[0] - a[0]) * t, - a[1] + (b[1] - a[1]) * t, - ]; -} - -function pushUniquePoint(points: Vec2[], point: Vec2) { - const last = points[points.length - 1]; - if (last && Math.hypot(last[0] - point[0], last[1] - point[1]) <= EPS) return; - points.push(point); -} - -function normalizeRepairSegments( - segments: Repair[] | undefined, - edgeLength: number, - capacity: number, -) { - if (!segments?.length || edgeLength <= EPS || capacity <= EPS) return []; - const stops = new Set([0, edgeLength]); - for (const segment of segments) { - const start = Math.max(0, Math.min(edgeLength, segment.start)); - const end = Math.max(0, Math.min(edgeLength, segment.end)); - if (end - start <= EPS || segment.amount <= EPS) continue; - stops.add(start); - stops.add(end); - } - - const sortedStops = Array.from(stops).sort((a, b) => a - b); - const normalized: Repair[] = []; - for (let i = 0; i + 1 < sortedStops.length; i += 1) { - const start = sortedStops[i]; - const end = sortedStops[i + 1]; - if (end - start <= EPS) continue; - const mid = (start + end) / 2; - let amount = 0; - for (const segment of segments) { - if (mid + EPS < segment.start || mid - EPS > segment.end) continue; - amount = Math.max(amount, segment.amount); - } - const safeAmount = Math.min(capacity, amount); - if (safeAmount > EPS) normalized.push({ start, end, amount: safeAmount }); - } - return normalized; -} - -function isValidRepairedPolygon(source: Vec2[], repaired: Vec2[]) { - if (repaired.length < 3 || !isWeaklyConvex(repaired)) return false; - const sourceArea = signedArea(source); - const repairedArea = signedArea(repaired); - return Math.sign(repairedArea) === Math.sign(sourceArea) && Math.abs(repairedArea) >= Math.abs(sourceArea) - EPS; -} - -export function patchPolygon( - polygon: Polygon, - edgeRepairs: ReadonlyMap, - capacityScale: number, -) { - if (edgeRepairs.size === 0 || polygon.vertices.length < 3 || hasTexture(polygon)) return polygon; - - const points = cssPoints(polygon.vertices); - const basis = localBasis(points); - if (!basis || !isWeaklyConvex(basis.local)) return polygon; - - const repaired: Vec2[] = []; - for (let edgeIndex = 0; edgeIndex < basis.local.length; edgeIndex += 1) { - const a = basis.local[edgeIndex]; - const b = basis.local[(edgeIndex + 1) % basis.local.length]; - const edgeLength = Math.hypot(b[0] - a[0], b[1] - a[1]); - const outward = edgeOutward2D(basis.local, basis.area, edgeIndex); - if (!outward || edgeLength <= EPS) return polygon; - const segments = normalizeRepairSegments( - edgeRepairs.get(edgeIndex), - edgeLength, - edgeSafeCapacity(basis.local, edgeIndex) * capacityScale, - ); - - pushUniquePoint(repaired, a); - let cursor = 0; - for (const segment of segments) { - if (segment.start > cursor + EPS) { - pushUniquePoint(repaired, repairPoint(a, b, edgeLength, segment.start)); - } - - const start = repairPoint(a, b, edgeLength, segment.start); - const end = repairPoint(a, b, edgeLength, segment.end); - pushUniquePoint(repaired, [ - start[0] + outward[0] * segment.amount, - start[1] + outward[1] * segment.amount, - ]); - pushUniquePoint(repaired, [ - end[0] + outward[0] * segment.amount, - end[1] + outward[1] * segment.amount, - ]); - if (segment.end < edgeLength - EPS) pushUniquePoint(repaired, end); - cursor = segment.end; - } - } - - const first = repaired[0]; - const last = repaired[repaired.length - 1]; - if (first && last && Math.hypot(first[0] - last[0], first[1] - last[1]) <= EPS) repaired.pop(); - if (!isValidRepairedPolygon(basis.local, repaired)) return polygon; - - const vertices = repaired.map(([x, y]) => fromCssPoint([ - basis.origin[0] + x * basis.xAxis[0] + y * basis.yAxis[0], - basis.origin[1] + x * basis.xAxis[1] + y * basis.yAxis[1], - basis.origin[2] + x * basis.xAxis[2] + y * basis.yAxis[2], - ])); - return { ...polygon, vertices }; -} diff --git a/packages/core/src/merge/seamRepair/quadSplit.ts b/packages/core/src/merge/seamRepair/quadSplit.ts deleted file mode 100644 index 0ab0c5db7..000000000 --- a/packages/core/src/merge/seamRepair/quadSplit.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { signedArea2D as signedArea } from "../../atlas/solidTriangle"; -import { crossVec as cross } from "../../math/vec3"; -import type { Polygon, Vec3 } from "../../types"; -import { - cssPoints, - EPS, - fromCssPoint, - hasTexture, - length, - localBasis, - sub, -} from "./geometry"; -import type { Basis, Meta, Vec2 } from "./geometry"; - -const SEAM_SPLIT_INTERNAL_OVERLAP_PX = 1.25; -const SEAM_SPLIT_EDGE_OVERLAP_PX = 0.75; - -export function isRefinableSeamQuad(polygon: Polygon) { - return polygon.vertices.length === 4 && !hasTexture(polygon); -} - -export function quadShapeRisk(meta: Meta) { - const local = meta.basis?.local; - if (!local || local.length !== 4) return 1; - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - for (const [x, y] of local) { - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - } - const bboxArea = Math.max(EPS, (maxX - minX) * (maxY - minY)); - const fillRatio = Math.max(0, Math.min(1, Math.abs(meta.basis!.area) / bboxArea)); - return 0.75 + (1 - fillRatio) * 2.5; -} - -function cssDistance(a: Vec3, b: Vec3) { - return length(sub(cssPoints([a])[0], cssPoints([b])[0])); -} - -function triangleQuality(a: Vec3, b: Vec3, c: Vec3) { - const ab = cssDistance(a, b); - const bc = cssDistance(b, c); - const ca = cssDistance(c, a); - const longest = Math.max(ab, bc, ca); - if (longest <= EPS) return 0; - const area = length(cross(sub(cssPoints([b])[0], cssPoints([a])[0]), sub(cssPoints([c])[0], cssPoints([a])[0]))) * 0.5; - return area / (longest * longest); -} - -function intersectLocalLines(a0: Vec2, a1: Vec2, b0: Vec2, b1: Vec2): Vec2 | null { - const rx = a1[0] - a0[0]; - const ry = a1[1] - a0[1]; - const sx = b1[0] - b0[0]; - const sy = b1[1] - b0[1]; - const det = rx * sy - ry * sx; - if (Math.abs(det) <= EPS) return null; - const qpx = b0[0] - a0[0]; - const qpy = b0[1] - a0[1]; - const t = (qpx * sy - qpy * sx) / det; - return [a0[0] + t * rx, a0[1] + t * ry]; -} - -function offsetLocalConvexPointsByEdgeAmounts(points: Vec2[], amounts: number[]) { - if (points.length < 3 || points.length !== amounts.length) return null; - const maxAmount = Math.max(0, ...amounts); - if (maxAmount <= EPS) return points; - const area = signedArea(points); - if (Math.abs(area) <= EPS) return null; - const outwardSign = area > 0 ? 1 : -1; - const offsetLines: Array<{ a: Vec2; b: Vec2 }> = []; - for (let i = 0; i < points.length; i += 1) { - const a = points[i]; - const b = points[(i + 1) % points.length]; - const dx = b[0] - a[0]; - const dy = b[1] - a[1]; - const edgeLength = Math.hypot(dx, dy); - if (edgeLength <= EPS) return null; - const amount = Math.max(0, amounts[i]); - const ox = outwardSign * (dy / edgeLength) * amount; - const oy = outwardSign * (-dx / edgeLength) * amount; - offsetLines.push({ - a: [a[0] + ox, a[1] + oy], - b: [b[0] + ox, b[1] + oy], - }); - } - - const expanded: Vec2[] = []; - const maxMiter = Math.max(2, maxAmount * 4); - for (let i = 0; i < points.length; i += 1) { - const prev = offsetLines[(i + points.length - 1) % points.length]; - const next = offsetLines[i]; - const intersection = intersectLocalLines(prev.a, prev.b, next.a, next.b); - if (!intersection) return null; - const original = points[i]; - const dx = intersection[0] - original[0]; - const dy = intersection[1] - original[1]; - const miter = Math.hypot(dx, dy); - expanded.push( - miter > maxMiter - ? [original[0] + (dx / miter) * maxMiter, original[1] + (dy / miter) * maxMiter] - : intersection, - ); - } - return expanded; -} - -function cssPointFromLocal(basis: Basis, point: Vec2): Vec3 { - return [ - basis.origin[0] + basis.xAxis[0] * point[0] + basis.yAxis[0] * point[1], - basis.origin[1] + basis.xAxis[1] * point[0] + basis.yAxis[1] * point[1], - basis.origin[2] + basis.xAxis[2] * point[0] + basis.yAxis[2] * point[1], - ]; -} - -function offsetTriangleVertices(vertices: Vec3[], amounts: [number, number, number]) { - const basis = localBasis(cssPoints(vertices)); - if (!basis) return vertices; - const expanded = offsetLocalConvexPointsByEdgeAmounts(basis.local, amounts); - return expanded - ? expanded.map((point) => fromCssPoint(cssPointFromLocal(basis, point))) - : vertices; -} - -export function splitQuadIntoTriangles(polygon: Polygon, edges: ReadonlySet) { - const solid: Polygon = { ...polygon, uvs: undefined, textureTriangles: undefined }; - const [a, b, c, d] = polygon.vertices; - const acQuality = Math.min(triangleQuality(a, b, c), triangleQuality(a, c, d)); - const bdQuality = Math.min(triangleQuality(a, b, d), triangleQuality(b, c, d)); - const seamAmount = (edge: number) => edges.has(edge) ? SEAM_SPLIT_EDGE_OVERLAP_PX : 0; - return acQuality >= bdQuality - ? [ - { ...solid, vertices: offsetTriangleVertices([a, b, c], [seamAmount(0), seamAmount(1), SEAM_SPLIT_INTERNAL_OVERLAP_PX]) }, - { ...solid, vertices: offsetTriangleVertices([a, c, d], [SEAM_SPLIT_INTERNAL_OVERLAP_PX, seamAmount(2), seamAmount(3)]) }, - ] - : [ - { ...solid, vertices: offsetTriangleVertices([a, b, d], [seamAmount(0), SEAM_SPLIT_INTERNAL_OVERLAP_PX, seamAmount(3)]) }, - { ...solid, vertices: offsetTriangleVertices([b, c, d], [seamAmount(1), seamAmount(2), SEAM_SPLIT_INTERNAL_OVERLAP_PX]) }, - ]; -} diff --git a/packages/core/src/merge/seamRepairTypes.ts b/packages/core/src/merge/seamRepairTypes.ts index 943c833dd..b256e20c4 100644 --- a/packages/core/src/merge/seamRepairTypes.ts +++ b/packages/core/src/merge/seamRepairTypes.ts @@ -1,15 +1,16 @@ -export type SeamOverlapCandidateKind = "true-gap" | "connected-facet" | "material-boundary"; +export interface SeamOverlapDiagnostics { + exactPairs: number; + nearPairs: number; + patchedPolygons: number; + patchedEdges: number; + maxMeasuredGapPx: number; + maxAppliedAmountPx: number; + unclosedPairs: number; + maxResidualGapPx: number; +} -export interface SeamOverlapCandidate { kind: SeamOverlapCandidateKind; aPolygon: number; aEdge: number; bPolygon: number; bEdge: number; aColor?: string; bColor?: string; aMaterialKey: string; bMaterialKey: string; gapPx: number; spanPx: number; aStartPx: number; aEndPx: number; bStartPx: number; bEndPx: number; targetClosurePx: number; appliedClosurePx: number; residualGapPx: number; residualTargetPx: number; } - -export interface SeamOverlapDiagnostics { exactPairs: number; nearPairs: number; patchedPolygons: number; patchedEdges: number; maxMeasuredGapPx: number; maxAppliedAmountPx: number; unclosedPairs: number; maxResidualGapPx: number; } - -export interface SeamOverlapOptions { overlapPx?: number; maxGapPx?: number; capacityScale?: number; } - -export interface SeamFacetSplitOptions { rotX?: number; rotY?: number; viewAware?: boolean; passes?: number; budget?: number; } - -export type SeamFacetSplitCandidateReason = "component-anchor" | "global-outlier" | "local-follow-up" | "shared-polygon" | "below-threshold"; - -export interface SeamFacetSplitCandidate { key: string; aPolygon: number; aEdge: number; bPolygon: number; bEdge: number; color?: string; materialKey: string; lengthPx: number; projectedLengthPx: number; score: number; normalRisk: number; shapeRisk: number; viewRisk: number; component: number; marginalCost: number; selected: boolean; reason: SeamFacetSplitCandidateReason; } - -export interface SeamFacetSplitReport { candidates: SeamFacetSplitCandidate[]; selectedPolygons: number; selectedEdges: number; addedPolygons: number; } +export interface SeamOverlapOptions { + overlapPx?: number; + maxGapPx?: number; + capacityScale?: number; +} diff --git a/packages/core/src/parser/solidTextureSamples.ts b/packages/core/src/parser/solidTextureSamples.ts index 8905b6232..7f2fdd9bf 100644 --- a/packages/core/src/parser/solidTextureSamples.ts +++ b/packages/core/src/parser/solidTextureSamples.ts @@ -610,15 +610,6 @@ async function createSolidTextureBaker( }; } -export async function bakeSolidTextureSampledPolygons( - polygons: Polygon[], - options: SolidTextureSampleOptions = {}, -): Promise { - const baker = await createSolidTextureBaker(polygons, options); - if (!baker) return polygons; - return baker.bake(polygons).polygons; -} - export async function bakeSolidTextureSamples( result: ParseResult, options: SolidTextureSampleOptions = {}, diff --git a/packages/core/src/scene/polygonGeometry.test.ts b/packages/core/src/scene/polygonGeometry.test.ts index 8243f8804..516bc625c 100644 --- a/packages/core/src/scene/polygonGeometry.test.ts +++ b/packages/core/src/scene/polygonGeometry.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { computeTexturePaintMetrics, polygonFaces } from "./polygonGeometry"; +import { polygonFaces } from "./polygonGeometry"; import type { Polygon } from "../types"; describe("polygonFaces", () => { @@ -26,7 +26,6 @@ describe("polygonFaces", () => { it("face.v is a deep copy (mutation doesn't affect original)", () => { const faces = polygonFaces(tri); faces[0].v[0][0] = 99; - // original polygon is unchanged expect(tri.vertices[0][0]).toBe(0); }); @@ -41,14 +40,13 @@ describe("polygonFaces", () => { }); it("returns empty array when vertices is undefined-like", () => { - // Defensive — some callers may pass a partially-built polygon const p = { vertices: null } as unknown as Polygon; expect(polygonFaces(p)).toHaveLength(0); }); it("works for a quad (4 vertices) — returns single face with 4 vertices", () => { const quad: Polygon = { - vertices: [[0,0,0],[1,0,0],[1,1,0],[0,1,0]], + vertices: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], color: "#0000ff", }; const faces = polygonFaces(quad); @@ -57,154 +55,8 @@ describe("polygonFaces", () => { }); it("color is undefined when polygon has no color", () => { - const p: Polygon = { vertices: [[0,0,0],[1,0,0],[0,1,0]] }; + const p: Polygon = { vertices: [[0, 0, 0], [1, 0, 0], [0, 1, 0]] }; const faces = polygonFaces(p); expect(faces[0].color).toBeUndefined(); }); }); - -describe("computeTexturePaintMetrics", () => { - const tex = "https://example.com/t.png"; - - it("returns zeros for empty input", () => { - const m = computeTexturePaintMetrics([]); - expect(m.totalPolygons).toBe(0); - expect(m.measuredPolygons).toBe(0); - expect(m.elementArea).toBe(0); - expect(m.polygonArea).toBe(0); - expect(m.transparentRatio).toBe(0); - expect(m.overdrawRatio).toBe(0); - }); - - it("an axis-aligned textured quad has no overdraw — element area == polygon area", () => { - // 1×1 quad at tileSize 100 → 100×100 element box, fully filled by the quad. - const quad: Polygon = { - vertices: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], - texture: tex, - }; - const m = computeTexturePaintMetrics([quad]); - expect(m.measuredPolygons).toBe(1); - expect(m.texturedPolygons).toBe(1); - expect(m.elementArea).toBe(m.polygonArea); - expect(m.transparentArea).toBe(0); - expect(m.transparentRatio).toBe(0); - expect(m.overdrawRatio).toBeCloseTo(1, 5); - }); - - it("a right triangle fills half its bounding box (~50% transparent)", () => { - const tri: Polygon = { - vertices: [[0, 0, 0], [1, 0, 0], [0, 1, 0]], - texture: tex, - }; - const m = computeTexturePaintMetrics([tri]); - expect(m.measuredPolygons).toBe(1); - // overdraw = element / polygon ≈ 2 (triangle is half its bbox). - expect(m.overdrawRatio).toBeGreaterThan(1.9); - expect(m.overdrawRatio).toBeLessThan(2.1); - expect(m.transparentRatio).toBeGreaterThan(0.49); - expect(m.transparentRatio).toBeLessThan(0.51); - expect(m.worstTransparentRatio).toBe(m.transparentRatio); - }); - - it("skips untextured polygons when texturedOnly is true (the default)", () => { - const quad: Polygon = { - vertices: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], - color: "#ff0000", - // no texture - }; - const m = computeTexturePaintMetrics([quad]); - expect(m.totalPolygons).toBe(1); - expect(m.measuredPolygons).toBe(0); - expect(m.elementArea).toBe(0); - }); - - it("includes untextured polygons when texturedOnly is false", () => { - const quad: Polygon = { - vertices: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], - color: "#ff0000", - }; - const m = computeTexturePaintMetrics([quad], { texturedOnly: false }); - expect(m.measuredPolygons).toBe(1); - expect(m.texturedPolygons).toBe(0); - expect(m.elementArea).toBeGreaterThan(0); - }); - - it("degenerate polygons (< 3 vertices) are skipped", () => { - const line: Polygon = { vertices: [[0, 0, 0], [1, 0, 0]], texture: tex }; - const empty: Polygon = { vertices: [], texture: tex }; - const m = computeTexturePaintMetrics([line, empty]); - expect(m.totalPolygons).toBe(2); - expect(m.measuredPolygons).toBe(0); - }); - - it("polygons collinear in 3D (zero normal) are skipped", () => { - // All three points on the X-axis → degenerate (no surface normal). - const collinear: Polygon = { - vertices: [[0, 0, 0], [1, 0, 0], [2, 0, 0]], - texture: tex, - }; - const m = computeTexturePaintMetrics([collinear]); - expect(m.measuredPolygons).toBe(0); - }); - - it("scales linearly with tileSize", () => { - const quad: Polygon = { - vertices: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], - texture: tex, - }; - const small = computeTexturePaintMetrics([quad], { tileSize: 50 }); - const large = computeTexturePaintMetrics([quad], { tileSize: 100 }); - // Doubling tileSize quadruples area for a 2D quad. - expect(large.elementArea / small.elementArea).toBeCloseTo(4, 1); - expect(large.polygonArea / small.polygonArea).toBeCloseTo(4, 1); - }); - - it("layerElevation only affects polygons with Z extent", () => { - const flatQuad: Polygon = { - vertices: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], - texture: tex, - }; - const m1 = computeTexturePaintMetrics([flatQuad], { tileSize: 100, layerElevation: 100 }); - const m2 = computeTexturePaintMetrics([flatQuad], { tileSize: 100, layerElevation: 1000 }); - // Z-flat polygon: layerElevation shouldn't change its 2D-projected area. - expect(m1.elementArea).toBe(m2.elementArea); - expect(m1.polygonArea).toBeCloseTo(m2.polygonArea, 5); - }); - - it("aggregates worstTransparentRatio across a mixed batch", () => { - const fullQuad: Polygon = { - vertices: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], - texture: tex, - }; - const rightTri: Polygon = { - // Right triangle is always ~50% of its tightest bbox. - vertices: [[0, 0, 0], [10, 0, 0], [10, 1, 0]], - texture: tex, - }; - const m = computeTexturePaintMetrics([fullQuad, rightTri]); - expect(m.measuredPolygons).toBe(2); - // The triangle drives worstTransparentRatio (the quad's is ~0). - expect(m.worstTransparentRatio).toBeGreaterThan(0.45); - expect(m.worstTransparentRatio).toBeLessThan(0.55); - // Aggregate transparent ratio is below the per-polygon worst (the full - // quad pulls it down). - expect(m.transparentRatio).toBeGreaterThan(0); - expect(m.transparentRatio).toBeLessThan(m.worstTransparentRatio); - }); - - it("non-axis-aligned quad in 3D still projects to its native plane", () => { - // 1×1 quad lying on the Z=X plane (45° tilted around Y). - // Its tightest 2D-projected element box should be ~ (sqrt2*tileSize) - // × tileSize regardless of orientation in world space. - const tilted: Polygon = { - vertices: [[0, 0, 0], [1, 0, 1], [1, 1, 1], [0, 1, 0]], - texture: tex, - }; - const m = computeTexturePaintMetrics([tilted], { tileSize: 100, layerElevation: 100 }); - expect(m.measuredPolygons).toBe(1); - // For a planar quad the polygon area equals the element-box area (no - // transparent slack in its own plane), even after a 3D tilt. - expect(m.transparentRatio).toBeLessThan(0.05); - expect(m.overdrawRatio).toBeLessThan(1.1); - }); -}); diff --git a/packages/core/src/scene/polygonGeometry.ts b/packages/core/src/scene/polygonGeometry.ts index 1dd47d2ab..76d30e422 100644 --- a/packages/core/src/scene/polygonGeometry.ts +++ b/packages/core/src/scene/polygonGeometry.ts @@ -1,49 +1,15 @@ /** * Polygon geometry helpers — pure math operating on Polygon vertices. - * These helpers feed lighting, diagnostics, and renderer metrics without - * depending on browser APIs. */ -import type { Polygon, Vec2, Vec3 } from "../types"; +import type { Polygon, Vec3 } from "../types"; export interface PolygonFace { /** Vertices in CCW-from-outside order. Same as Polygon.vertices. */ v: Vec3[]; - /** Original polygon's color, if any (for lighting helpers). */ + /** Original polygon's color, if any. */ color?: string; } -export interface TexturePaintMetricsOptions { - /** CSS pixels per world X/Y unit. Matches renderer default. */ - tileSize?: number; - /** CSS pixels per world Z unit. Defaults to tileSize. */ - layerElevation?: number; - /** When true, skip untextured polygons. Defaults to true. */ - texturedOnly?: boolean; -} - -export interface TexturePaintMetrics { - /** Input polygon count before filtering. */ - totalPolygons: number; - /** Polygons included in the metric after filtering and degeneracy checks. */ - measuredPolygons: number; - /** Included polygons with a texture URL. */ - texturedPolygons: number; - /** Sum of rectangular element areas in CSS px^2. */ - elementArea: number; - /** Sum of projected polygon areas in CSS px^2. */ - polygonArea: number; - /** elementArea - polygonArea, clamped at 0. */ - transparentArea: number; - /** transparentArea / elementArea. */ - transparentRatio: number; - /** elementArea / polygonArea. */ - overdrawRatio: number; - /** Highest per-polygon transparentRatio. */ - worstTransparentRatio: number; -} - -const METRIC_EPS = 1e-9; - /** * Surface a polygon as a single face. The returned array always has length 1; * the indirection lets face-oriented consumers keep a common loop shape. @@ -57,151 +23,3 @@ export function polygonFaces(p: Polygon): PolygonFace[] { color: p.color, }]; } - -function computeNormal(pts: Vec3[]): Vec3 | null { - const p0 = pts[0]; - const p1 = pts[1]; - const p2 = pts[2]; - const e1: Vec3 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]; - const e2: Vec3 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]]; - const nx = e1[1] * e2[2] - e1[2] * e2[1]; - const ny = e1[2] * e2[0] - e1[0] * e2[2]; - const nz = e1[0] * e2[1] - e1[1] * e2[0]; - const len = Math.hypot(nx, ny, nz); - if (len <= METRIC_EPS) return null; - return [nx / len, ny / len, nz / len]; -} - -function polygonArea2D(points: Vec2[]): number { - let sum = 0; - for (let i = 0; i < points.length; i++) { - const [x1, y1] = points[i]; - const [x2, y2] = points[(i + 1) % points.length]; - sum += x1 * y2 - x2 * y1; - } - return Math.abs(sum) / 2; -} - -function projectToTightestElementBox( - vertices: Vec3[], - tileSize: number, - layerElevation: number, -): { elementArea: number; polygonArea: number } | null { - if (!vertices || vertices.length < 3) return null; - const cssPts: Vec3[] = vertices.map((v) => [ - v[1] * tileSize, - v[0] * tileSize, - v[2] * layerElevation, - ]); - const normal = computeNormal(cssPts); - if (!normal) return null; - - let bestElementArea = Infinity; - let bestPolygonArea = 0; - - for (let i = 0; i < cssPts.length; i++) { - const origin = cssPts[i]; - const next = cssPts[(i + 1) % cssPts.length]; - const rawX: Vec3 = [ - next[0] - origin[0], - next[1] - origin[1], - next[2] - origin[2], - ]; - const dot = rawX[0] * normal[0] + rawX[1] * normal[1] + rawX[2] * normal[2]; - const planeX: Vec3 = [ - rawX[0] - dot * normal[0], - rawX[1] - dot * normal[1], - rawX[2] - dot * normal[2], - ]; - const xLen = Math.hypot(planeX[0], planeX[1], planeX[2]); - if (xLen <= METRIC_EPS) continue; - const xAxis: Vec3 = [planeX[0] / xLen, planeX[1] / xLen, planeX[2] / xLen]; - const rawY: Vec3 = [ - normal[1] * xAxis[2] - normal[2] * xAxis[1], - normal[2] * xAxis[0] - normal[0] * xAxis[2], - normal[0] * xAxis[1] - normal[1] * xAxis[0], - ]; - const yLen = Math.hypot(rawY[0], rawY[1], rawY[2]); - if (yLen <= METRIC_EPS) continue; - const yAxis: Vec3 = [rawY[0] / yLen, rawY[1] / yLen, rawY[2] / yLen]; - - const local = cssPts.map((p): Vec2 => { - const dx = p[0] - origin[0]; - const dy = p[1] - origin[1]; - const dz = p[2] - origin[2]; - return [ - dx * xAxis[0] + dy * xAxis[1] + dz * xAxis[2], - dx * yAxis[0] + dy * yAxis[1] + dz * yAxis[2], - ]; - }); - - let xMin = Infinity; - let yMin = Infinity; - let xMax = -Infinity; - let yMax = -Infinity; - for (const [x, y] of local) { - xMin = Math.min(xMin, x); - yMin = Math.min(yMin, y); - xMax = Math.max(xMax, x); - yMax = Math.max(yMax, y); - } - - const width = xMax - xMin; - const height = yMax - yMin; - const elementArea = Math.max(1, Math.ceil(width)) * Math.max(1, Math.ceil(height)); - const polygonArea = polygonArea2D(local); - if (polygonArea <= METRIC_EPS) continue; - if (elementArea < bestElementArea) { - bestElementArea = elementArea; - bestPolygonArea = polygonArea; - } - } - - if (!Number.isFinite(bestElementArea) || bestPolygonArea <= METRIC_EPS) return null; - return { elementArea: bestElementArea, polygonArea: bestPolygonArea }; -} - -export function computeTexturePaintMetrics( - polygons: Polygon[], - options: TexturePaintMetricsOptions = {}, -): TexturePaintMetrics { - const tileSize = options.tileSize ?? 100; - const layerElevation = options.layerElevation ?? tileSize; - const texturedOnly = options.texturedOnly ?? true; - - let measuredPolygons = 0; - let texturedPolygons = 0; - let elementArea = 0; - let polygonArea = 0; - let worstTransparentRatio = 0; - - for (const polygon of polygons) { - const isTextured = Boolean(polygon.texture); - if (texturedOnly && !isTextured) continue; - - const projected = projectToTightestElementBox(polygon.vertices, tileSize, layerElevation); - if (!projected) continue; - - measuredPolygons += 1; - if (isTextured) texturedPolygons += 1; - elementArea += projected.elementArea; - polygonArea += projected.polygonArea; - worstTransparentRatio = Math.max( - worstTransparentRatio, - Math.max(0, projected.elementArea - projected.polygonArea) / projected.elementArea, - ); - } - - const transparentArea = Math.max(0, elementArea - polygonArea); - return { - totalPolygons: polygons.length, - measuredPolygons, - texturedPolygons, - elementArea, - polygonArea, - transparentArea, - transparentRatio: elementArea > 0 ? transparentArea / elementArea : 0, - overdrawRatio: polygonArea > 0 ? elementArea / polygonArea : 0, - worstTransparentRatio, - }; -} diff --git a/packages/core/src/shadow/projection.test.ts b/packages/core/src/shadow/projection.test.ts index 579682db8..1957d3939 100644 --- a/packages/core/src/shadow/projection.test.ts +++ b/packages/core/src/shadow/projection.test.ts @@ -1,95 +1,11 @@ import { describe, it, expect } from "vitest"; import { BAKED_SHADOW_MIN_UP, - BAKED_SHADOW_Z_SQUASH, - buildBakedShadowProjectionMatrix, ensureCcw2D, - isBakedShadowCaster, - isPointShadowCaster, polygonSignedArea2D, projectCssVertexToGround, - projectCssVertexToGroundFromPoint, } from "./projection"; -describe("buildBakedShadowProjectionMatrix", () => { - it("produces the identity transform for axis-aligned top-down light at ground=0", () => { - const m = buildBakedShadowProjectionMatrix([0, 0, -1], 0); - // col1 = [1,0,0,0], col2 = [0,1,0,0] - expect(m.slice(0, 4)).toEqual([1, 0, 0, 0]); - expect(m.slice(4, 8)).toEqual([0, 1, 0, 0]); - // -lx/lz = 0/-1 = 0, -ly/lz = 0/-1 = 0 - expect(m[8]).toBeCloseTo(0, 6); - expect(m[9]).toBeCloseTo(0, 6); - expect(m[10]).toBeCloseTo(BAKED_SHADOW_Z_SQUASH, 6); - expect(m[11]).toBe(0); - // Ground = 0: col4 = [0, 0, 0, 1] - expect(m[12]).toBeCloseTo(0, 6); - expect(m[13]).toBeCloseTo(0, 6); - expect(m[14]).toBeCloseTo(0, 6); - expect(m[15]).toBe(1); - }); - - it("offsets translation by groundCssZ", () => { - const m = buildBakedShadowProjectionMatrix([0, 0, -1], 100); - // With lx=ly=0, the only G-dependent entry left is m[14] = G*(1-Z) - expect(m[14]).toBeCloseTo(100 * (1 - BAKED_SHADOW_Z_SQUASH), 6); - }); - - it("encodes the shear from an oblique light direction", () => { - const m = buildBakedShadowProjectionMatrix([1, 0, -1], 0); - // After normalize: lx ≈ 0.7071, ly = 0, lz ≈ -0.7071 - // -lx/lz = -(0.7071)/(-0.7071) = +1 - expect(m[8]).toBeCloseTo(1, 5); - expect(m[9]).toBeCloseTo(0, 5); - }); - - it("clamps near-horizontal light up-axis to BAKED_SHADOW_MIN_UP", () => { - // lz = -0.0001 should be clamped to -BAKED_SHADOW_MIN_UP - const m = buildBakedShadowProjectionMatrix([0, 0, -0.0001], 0); - // The unnormalized direction [0,0,-0.0001] normalizes to [0,0,-1] (len 0.0001 > 0) - // So lz_normalized = -1, no clamp needed in this case. - // Use a tilted near-horizontal vector instead to actually exercise the clamp: - const m2 = buildBakedShadowProjectionMatrix([1, 0, -0.001], 0); - // After normalize lz ≈ -0.001 / 1.0000005 ≈ -0.001 → clamped to -0.01 - // -lx/lz with lx≈1, lz=-0.01 → +100 - expect(Math.abs(m2[8])).toBeLessThanOrEqual(100 + 1e-3); - expect(Math.abs(m2[8])).toBeGreaterThan(10); - // Use the public min directly to make the expectation obvious. - expect(BAKED_SHADOW_MIN_UP).toBe(0.01); - // Also exercise the variable so the unused-import linter is happy in - // a separate assertion path. - expect(m[10]).toBeCloseTo(BAKED_SHADOW_Z_SQUASH, 6); - }); -}); - -describe("isBakedShadowCaster", () => { - it("returns true for polygons whose normal points along the light direction (far side)", () => { - // Top-down light, bottom face of a cube (normal pointing down) → silhouette - expect(isBakedShadowCaster([0, 0, -1], [0, 0, -1])).toBe(true); - }); - - it("returns false for polygons whose normal opposes the light direction (lit side)", () => { - // Top-down light, top face of a cube (normal pointing up) → lit, not a caster - expect(isBakedShadowCaster([0, 0, 1], [0, 0, -1])).toBe(false); - }); - - it("returns false for polygons whose normal is perpendicular to the light", () => { - // Vertical wall under a top-down light: doesn't add to the silhouette - expect(isBakedShadowCaster([1, 0, 0], [0, 0, -1])).toBe(false); - }); - - it("handles oblique lights", () => { - // Light going down-and-right; a face whose normal also points down-and-right is a caster - expect(isBakedShadowCaster([1, 0, -1], [1, 0, -1])).toBe(true); - // Opposite normal → not a caster - expect(isBakedShadowCaster([-1, 0, 1], [1, 0, -1])).toBe(false); - }); - - it("is robust to an un-normalized light direction", () => { - expect(isBakedShadowCaster([0, 0, -1], [0, 0, -10])).toBe(true); - }); -}); - describe("projectCssVertexToGround", () => { it("returns the vertex's own XY when it sits on the ground plane", () => { const [x, y] = projectCssVertexToGround([10, 20, 50], [0, 0, 1], 50); @@ -123,46 +39,6 @@ describe("projectCssVertexToGround", () => { }); }); -describe("projectCssVertexToGroundFromPoint", () => { - it("projects radially: a point halfway between light and ground doubles its offset", () => { - // Light directly above origin at z=100; vertex at (10,0,50) sits halfway - // down. The shadow ray from (0,0,100) through (10,0,50) hits z=0 at - // x=20 (similar triangles: 10 grows to 20 as height halves to zero). - const p = projectCssVertexToGroundFromPoint([10, 0, 50], [0, 0, 100], 0); - expect(p).not.toBeNull(); - expect(p![0]).toBeCloseTo(20, 6); - expect(p![1]).toBeCloseTo(0, 6); - }); - - it("returns the vertex XY when the vertex sits on the ground plane", () => { - const p = projectCssVertexToGroundFromPoint([10, 20, 0], [0, 0, 100], 0); - expect(p).not.toBeNull(); - expect(p![0]).toBeCloseTo(10, 6); - expect(p![1]).toBeCloseTo(20, 6); - }); - - it("returns null when the vertex is above the light (no forward intersection)", () => { - // Light at z=10, vertex at z=50 → ground (z=0) is on the light's side. - expect(projectCssVertexToGroundFromPoint([5, 5, 50], [0, 0, 10], 0)).toBeNull(); - }); - - it("returns null when the shadow ray runs parallel to the ground", () => { - expect(projectCssVertexToGroundFromPoint([5, 5, 50], [0, 0, 50], 0)).toBeNull(); - }); -}); - -describe("isPointShadowCaster", () => { - it("is true when the face normal points away from the light", () => { - // Light above at z=100; face centroid below it with normal pointing down - // (away from the light) → casts. - expect(isPointShadowCaster([0, 0, 0], [0, 0, -1], [0, 0, 100])).toBe(true); - }); - - it("is false when the face normal points toward the light", () => { - expect(isPointShadowCaster([0, 0, 0], [0, 0, 1], [0, 0, 100])).toBe(false); - }); -}); - describe("polygonSignedArea2D", () => { it("returns +1 for a unit square in CCW order", () => { expect(polygonSignedArea2D([[0, 0], [1, 0], [1, 1], [0, 1]])).toBeCloseTo(1, 9); diff --git a/packages/core/src/shadow/projection.ts b/packages/core/src/shadow/projection.ts index 90d4dbd7e..edb318d0b 100644 --- a/packages/core/src/shadow/projection.ts +++ b/packages/core/src/shadow/projection.ts @@ -1,134 +1,14 @@ // Pure-math helpers for CPU shadow projection. // -// Current renderers use these helpers to project caster outlines into SVG -// shadow paths. The same matrix shape is still exposed for callers that need -// a CSS `matrix3d(...)` projection rather than projected 2D vertices. +// Renderers use these helpers to project caster outlines into SVG shadow paths. import type { Vec3 } from "../types"; -/** Tiny non-zero scale collapsed into the projection's Z column to keep - * the matrix invertible. Chromium skips elements whose composed - * transform is singular (m22 = 0 would make this a true projection - * matrix, but Chromium would refuse to paint it), so we crush Z to 1% - * of its input instead of exactly zero. The result still looks flat - * to the eye — sub-pixel drift on any realistic scene size. */ -export const BAKED_SHADOW_Z_SQUASH = 0.01; - /** Minimum absolute value of the up-axis light component before the * projection blows up (we divide by it). Matches the --clz clamp in * the dynamic-mode applyDynamicLightVars helper so baked + dynamic * behave identically when the light is near-horizontal. */ export const BAKED_SHADOW_MIN_UP = 0.01; -/** - * Build the CSS-space shadow projection matrix for a fixed light + ground - * plane. The 16-element output mirrors the retained `--shadow-proj` CSS - * custom property, but with literal numbers — ready to be formatted into a - * single `matrix3d(...)`. - * - * `lightDir` is the direction the light TRAVELS (e.g. `[0, 0, -1]` is - * straight down). PolyCSS world Z is up, and the world→CSS axis swap - * leaves Z alone — see styles.ts for the full convention. - * - * `groundCssZ` is the receiver plane in CSS-Z (= world-Z) coordinates, - * already in unit-less form (matrix3d entries must be dimensionless). - */ -export function buildBakedShadowProjectionMatrix( - lightDir: Vec3, - groundCssZ: number, -): number[] { - const len = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; - const lx = lightDir[0] / len; - const ly = lightDir[1] / len; - const lzRaw = lightDir[2] / len; - const lz = - Math.sign(lzRaw || 1) * Math.max(Math.abs(lzRaw), BAKED_SHADOW_MIN_UP); - const G = groundCssZ; - const Z = BAKED_SHADOW_Z_SQUASH; - // Column-major 4×4, identical layout to CSS matrix3d. - return [ - 1, 0, 0, 0, - 0, 1, 0, 0, - -lx / lz, -ly / lz, Z, 0, - (G * lx) / lz, (G * ly) / lz, G * (1 - Z), 1, - ]; -} - -/** - * Radial variant of `projectCssVertexToGround` for a point light at a fixed - * CSS-frame position. The shadow ray travels FROM the light THROUGH the - * vertex and onto the ground plane `z = groundCssZ`, so each vertex projects - * along its own direction (a true perspective projection) rather than the - * single parallel direction a directional light uses. - * - * Returns `null` when no valid forward intersection exists — the vertex sits - * on the light's side of the ground plane, or the ray runs parallel to it. - * The caller drops that vertex (and any polygon that loses ≥1 vertex falls - * back to a degenerate projection it can skip). - * - * `lightPos` and `cssVertex` are both in the dimensionless CSS frame (after - * the world→CSS axis swap + tile scale), matching `projectCssVertexToGround`. - */ -export function projectCssVertexToGroundFromPoint( - cssVertex: Vec3, - lightPos: Vec3, - groundCssZ: number, -): [number, number] | null { - const dz = cssVertex[2] - lightPos[2]; - // Ray parallel to the ground plane → never lands on it. - if (Math.abs(dz) < 1e-9) return null; - // point = vertex + s · (vertex − light); solve for ground z. - const s = (groundCssZ - cssVertex[2]) / dz; - // s < 0 means the ground is between the light and the vertex (or behind - // the light) — no cast shadow from this vertex. s = 0 is the vertex - // already sitting on the ground plane (projects to itself). - if (s < 0) return null; - return [ - cssVertex[0] + s * (cssVertex[0] - lightPos[0]), - cssVertex[1] + s * (cssVertex[1] - lightPos[1]), - ]; -} - -/** - * Point-light variant of `isBakedShadowCaster`. A polygon casts shadow when - * its outward normal points away from the light — i.e. the ray from the - * light to the polygon centroid runs into the back of the face. `centroid` - * and `lightPos` are CSS-frame; `normal` is the CSS-frame outward normal. - */ -export function isPointShadowCaster( - centroid: Vec3, - normal: Vec3, - lightPos: Vec3, -): boolean { - const dx = centroid[0] - lightPos[0]; - const dy = centroid[1] - lightPos[1]; - const dz = centroid[2] - lightPos[2]; - const len = Math.hypot(dx, dy, dz) || 1; - return (normal[0] * dx + normal[1] * dy + normal[2] * dz) / len > 0; -} - -/** - * Decides whether a polygon should cast a shadow given its outward - * normal and the light's travel direction. - * - * True for polygons whose normals point in the same direction as the - * light travels — i.e., on the far/dark side of the mesh from the - * light's POV. Those define the silhouette of the cast shadow. - * - * False for front-facing polygons whose projection would land inside - * the silhouette and only add overdraw. Dynamic mode hides these with - * a Lambert opacity gate; baked mode skips the DOM emission entirely. - */ -export function isBakedShadowCaster( - normal: Vec3, - lightDir: Vec3, -): boolean { - const len = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; - const lx = lightDir[0] / len; - const ly = lightDir[1] / len; - const lz = lightDir[2] / len; - return normal[0] * lx + normal[1] * ly + normal[2] * lz > 0; -} - /** * 2D convex hull (Andrew's monotone chain, O(n log n)). Returns the * hull vertices in CCW order. Used to compute a receiver mesh's XY @@ -198,14 +78,13 @@ export function ensureCcw2D( /** * Projects a single CSS-3D vertex onto the shadow ground plane, returning - * the resulting 2D point in CSS coordinates. Mirrors the retained - * `--shadow-proj` matrix, but evaluated on the CPU for a fixed light + ground - * so many projected vertices can be merged into one SVG shadow path. + * the resulting 2D point in CSS coordinates. Evaluated on the CPU for a + * fixed light + ground so many projected vertices can be merged into one + * SVG shadow path. * * `cssVertex` is a 3D point that has already been through the world→CSS * axis swap and unit scale (so its components are dimensionless CSS-space - * coordinates). `lightDir` follows the same `--clx/--cly/--clz` convention - * as `buildBakedShadowProjectionMatrix`. + * coordinates). `lightDir` follows the scene `--clx/--cly/--clz` convention. */ export function projectCssVertexToGround( cssVertex: Vec3, diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 5f962793c..6d06881a1 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1,5 +1,4 @@ /* Core type and constant definitions shared across polycss runtime modules. */ -export const DEFAULT_PROJECTION = "cubic" as const; /** * How polygon lighting is applied by DOM renderers. diff --git a/packages/polycss/src/api/createPolyScene.test.ts b/packages/polycss/src/api/createPolyScene.test.ts index 3a737b1ed..93a37d880 100644 --- a/packages/polycss/src/api/createPolyScene.test.ts +++ b/packages/polycss/src/api/createPolyScene.test.ts @@ -1412,12 +1412,8 @@ describe("createPolyScene", () => { const triangleLeaf = host.querySelector("u") as HTMLElement; const initialColor = leaf.style.color; const initialTriangleBackgroundColor = triangleLeaf.style.backgroundColor; - const previewScene = scene as PolySceneHandle & { - previewBakedSolidLighting(next: Pick): boolean; - clearBakedSolidLightingPreview(): void; - }; - expect(previewScene.previewBakedSolidLighting({ + expect(scene.previewBakedSolidLighting({ directionalLight: { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, ambientLight: { color: "#ffffff", intensity: 0.4 }, })).toBe(true); @@ -1433,7 +1429,7 @@ describe("createPolyScene", () => { expect(leaf.style.color).toBe(""); expect(triangleLeaf.style.backgroundColor).toBe(initialTriangleBackgroundColor); - previewScene.clearBakedSolidLightingPreview(); + scene.clearBakedSolidLightingPreview(); expect(sceneEl.style.getPropertyValue("--plz")).toBe(""); expect(sceneEl.style.getPropertyValue("--polycss-light-preview-active")).toBe(""); @@ -1452,12 +1448,8 @@ describe("createPolyScene", () => { const initialLeaf = leaf; const initialColor = leaf.style.color; const initialTriangleBackgroundColor = triangleLeaf.style.backgroundColor; - const previewScene = scene as PolySceneHandle & { - previewBakedSolidLighting(next: Pick): boolean; - commitBakedSolidLighting(): boolean; - }; - previewScene.previewBakedSolidLighting({ + scene.previewBakedSolidLighting({ directionalLight: { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, ambientLight: { color: "#ffffff", intensity: 0.4 }, }); @@ -1465,7 +1457,7 @@ describe("createPolyScene", () => { directionalLight: { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, ambientLight: { color: "#ffffff", intensity: 0.4 }, }); - expect(previewScene.commitBakedSolidLighting()).toBe(true); + expect(scene.commitBakedSolidLighting()).toBe(true); expect(host.querySelector("b, i, u")).toBe(initialLeaf); expect(leaf.style.color).not.toBe(""); @@ -1476,19 +1468,73 @@ describe("createPolyScene", () => { expect(triangleLeaf.style.backgroundColor).toBe(initialTriangleBackgroundColor); }); + it("clears baked solid preview state cleanly across auto rebake, dynamic switch, and manual options", () => { + scene = makeScene(host, { textureLighting: "baked", bakedLightPolicy: "auto" }); + const mesh = scene.add(makeParseResult([triangle("#336699")]), { + merge: false, + rotation: [0, 45, 0], + }); + const sceneEl = host.querySelector(".polycss-scene") as HTMLElement; + const leaf = () => host.querySelector("b, i, u") as HTMLElement; + + expect(scene.previewBakedSolidLighting({ + directionalLight: { direction: [0, 0, 1], color: "#00ff00", intensity: 2.5 }, + ambientLight: { color: "#ffffff", intensity: 0.9 }, + })).toBe(true); + expect(sceneEl.style.getPropertyValue("--polycss-light-preview-active")).toBe("1"); + expect(leaf().style.getPropertyValue("--polycss-paint")).toContain("--polycss-preview-r"); + + // Auto rebake clears preview and resets prepared state so a second preview re-installs leaf vars. + scene.setOptions({ + directionalLight: { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, + }); + expect(sceneEl.style.getPropertyValue("--polycss-light-preview-active")).toBe(""); + + expect(scene.previewBakedSolidLighting({ + directionalLight: { direction: [1, 0, 1], color: "#00ff00", intensity: 2.5 }, + ambientLight: { color: "#ffffff", intensity: 0.9 }, + })).toBe(true); + expect(sceneEl.style.getPropertyValue("--polycss-light-preview-active")).toBe("1"); + expect(leaf().style.getPropertyValue("--polycss-paint")).toContain("--polycss-preview-r"); + expect(leaf().style.getPropertyValue("--polycss-preview-r")).not.toBe(""); + + // Switching to dynamic mode clears preview color/intensity vars on rotated wrappers. + scene.setOptions({ + textureLighting: "dynamic", + directionalLight: { direction: [1, 0, 1], color: "#ff0000", intensity: 1 }, + ambientLight: { color: "#ffffff", intensity: 0.2 }, + }); + expect(sceneEl.style.getPropertyValue("--polycss-light-preview-active")).toBe(""); + expect(mesh.element.style.getPropertyValue("--plr")).toBe(""); + expect(mesh.element.style.getPropertyValue("--pli")).toBe(""); + expect(mesh.element.style.getPropertyValue("--pai")).toBe(""); + expect(mesh.element.style.getPropertyValue("--plx")).not.toBe(""); + + // Manual policy: unrelated setOptions preserves active preview scene lighting vars. + scene.destroy(); + scene = makeScene(host, { textureLighting: "baked", bakedLightPolicy: "manual" }); + scene.add(makeParseResult([triangle("#336699")]), { merge: false }); + const manualSceneEl = host.querySelector(".polycss-scene") as HTMLElement; + expect(scene.previewBakedSolidLighting({ + directionalLight: { direction: [0, 0, 1], color: "#00ff00", intensity: 2 }, + ambientLight: { color: "#ffffff", intensity: 0.5 }, + })).toBe(true); + scene.setOptions({ autoCenter: true }); + expect(manualSceneEl.style.getPropertyValue("--polycss-light-preview-active")).toBe("1"); + expect(manualSceneEl.style.getPropertyValue("--plx")).not.toBe(""); + expect(manualSceneEl.style.getPropertyValue("--plr")).not.toBe(""); + }); + it("rebakes atlas leaves in place when committing baked lighting (no flash)", () => { scene = makeScene(host, { textureLighting: "baked" }); scene.add(makeParseResult([texturedTriangle()]), { merge: false }); const initialLeaf = host.querySelector("s") as HTMLElement; - const previewScene = scene as PolySceneHandle & { - commitBakedSolidLighting(): boolean; - }; scene.setOptions({ directionalLight: { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, }); - expect(previewScene.commitBakedSolidLighting()).toBe(true); + expect(scene.commitBakedSolidLighting()).toBe(true); // Post-fix: commit uses `rebakeRenderEntryInPlace` rather than the // destructive `renderEntry`, so the same `` DOM node stays // mounted and only its atlas bitmap URL gets swapped. That removes @@ -2617,12 +2663,8 @@ describe("createPolyScene", () => { const initialTransform = initialSvg.style.transform; const initialPathD = initialSvg.querySelector("path")?.getAttribute("d"); const initialDirection = scene.getOptions().directionalLight?.direction; - const previewScene = scene as PolySceneHandle & { - previewBakedSolidLighting(next: Pick): boolean; - clearBakedSolidLightingPreview(): void; - }; - previewScene.previewBakedSolidLighting({ + scene.previewBakedSolidLighting({ directionalLight: { direction: [1, 0, 1] }, }); @@ -2633,7 +2675,7 @@ describe("createPolyScene", () => { expect(nextTransform !== initialTransform || nextPathD !== initialPathD).toBe(true); expect(scene.getOptions().directionalLight?.direction).toBe(initialDirection); - previewScene.clearBakedSolidLightingPreview(); + scene.clearBakedSolidLightingPreview(); expect(initialSvg.style.transform).toBe(initialTransform); expect(initialSvg.querySelector("path")?.getAttribute("d")).toBe(initialPathD); @@ -2649,13 +2691,8 @@ describe("createPolyScene", () => { const initialSvg = host.querySelector(".polycss-shadow") as SVGSVGElement; const initialTransform = initialSvg.style.transform; const initialPathD = initialSvg.querySelector("path")?.getAttribute("d"); - const previewScene = scene as PolySceneHandle & { - previewBakedSolidLighting(next: Pick & { - skipShadows?: boolean; - }): boolean; - }; - expect(previewScene.previewBakedSolidLighting({ + expect(scene.previewBakedSolidLighting({ directionalLight: { direction: [1, 0, 1] }, skipShadows: true, })).toBe(true); @@ -2675,11 +2712,8 @@ describe("createPolyScene", () => { const initialSvg = host.querySelector(".polycss-shadow") as SVGSVGElement; const initialTransform = initialSvg.style.transform; const initialPathD = initialSvg.querySelector("path")?.getAttribute("d"); - const previewScene = scene as PolySceneHandle & { - previewBakedSolidLighting(next: Pick): boolean; - }; - previewScene.previewBakedSolidLighting({ + scene.previewBakedSolidLighting({ directionalLight: { direction: [1, 0, 1] }, }); const previewTransform = initialSvg.style.transform; @@ -2730,31 +2764,4 @@ describe("scene.add — meshResolution option", () => { expect(handle).toBeTruthy(); expect(host.querySelectorAll("i,b,s,u").length).toBeGreaterThan(0); }); - - it("superseded setPolygonsChunked does not wipe a newer synchronous setPolygons()", async () => { - scene = makeScene(host); - const handle = scene.add(makeParseResult([triangle()])); - const many: Polygon[] = Array.from({ length: 120 }, (_, i) => ({ - vertices: [ - [i, 0, 0], - [i + 1, 0, 0], - [i, 1, 0], - ], - color: "#ff0000", - })); - const chunked = (handle as unknown as { setPolygonsChunked(p: Polygon[]): Promise }).setPolygonsChunked(many); - handle.setPolygons([ - triangle("#ff0000"), - { - vertices: [ - [5, 0, 0], - [6, 0, 0], - [5, 1, 0], - ], - color: "#00ff00", - }, - ]); - await chunked; - expect(handle.element.querySelectorAll("i,b,s,u").length).toBe(2); - }); }); diff --git a/packages/polycss/src/api/createPolyScene.ts b/packages/polycss/src/api/createPolyScene.ts index ac4a2c041..6cd43f741 100644 --- a/packages/polycss/src/api/createPolyScene.ts +++ b/packages/polycss/src/api/createPolyScene.ts @@ -23,7 +23,11 @@ import { } from "./scene/bakedLighting"; import { shadowOptsEqual, strategiesEqual, vec3Equal } from "./scene/equality"; import type { MeshEntry } from "./scene/internalTypes"; -import { applyDynamicLightVars } from "./scene/lightingVars"; +import { + BAKED_SOLID_PREVIEW_ACTIVE_VAR, + applyDynamicLightVars, + clearLightingVars, +} from "./scene/lightingVars"; import { addSceneMeshEntry } from "./scene/meshEntry"; import { syncMountedRenderedForCameraChange } from "./scene/mountSync"; import { effectiveTextureLighting } from "./scene/rebake"; @@ -133,7 +137,15 @@ export function createPolyScene( function applySceneStyle(el: HTMLElement, opts: Omit): void { applyCssZoomCompensation(el, layoutScale); el.style.transform = buildSceneTransformFromCamera(camera, autoCenterOffset, layoutScale); - applyDynamicLightVars(el, opts); + // Keep active baked-solid preview lighting vars intact during manual-policy + // setOptions calls (e.g. light-drag shadow updates or autoCenter toggles) + // unless setOptions explicitly cleared the preview first. + if ( + (opts.textureLighting ?? "baked") === "dynamic" || + el.style.getPropertyValue(BAKED_SOLID_PREVIEW_ACTIVE_VAR) !== "1" + ) { + applyDynamicLightVars(el, opts); + } } function applySceneCameraTransform(el: HTMLElement): void { @@ -203,13 +215,8 @@ export function createPolyScene( const normalizedPartial = normalizeSceneOptions(partial); currentOptions = { ...currentOptions, ...normalizedPartial }; ctx.options.current = currentOptions; - applySceneStyle(sceneEl, currentOptions); const nextAutoCenter = !!currentOptions.autoCenter; - for (const entry of meshes) { - applyMeshLightVarOverride(ctx, entry, entry.handle.transform.rotation); - } - const strategiesChanged = hasOwn("strategies") && !strategiesEqual(currentOptions.strategies, prevStrategies); const seamBleedChanged = hasOwn("seamBleed") && @@ -238,13 +245,6 @@ export function createPolyScene( textureBackendChanged || textureProjectionChanged || pointLightsChanged; - if (fullRenderTriggered) { - for (const entry of meshes) renderEntry(entry); - } - if (prevAutoCenter !== nextAutoCenter || prevAutoCenterSource !== currentOptions.autoCenterSource) { - recomputeAutoCenter(); - } - const textureLightingChanged = hasOwn("textureLighting") && prevTextureLighting !== currentOptions.textureLighting; const nextDirLight = currentOptions.directionalLight; @@ -259,6 +259,40 @@ export function createPolyScene( (prevAmbIntensity ?? 0.4) !== (nextAmbLight?.intensity ?? 0.4) || (prevAmbColor ?? "#ffffff") !== (nextAmbLight?.color ?? "#ffffff") ); + const autoRebakeTriggered = + !textureLightingChanged && + currentOptions.bakedLightPolicy === "auto" && + (directionalChanged || ambientChanged) && + !fullRenderTriggered; + + // Tear down any active baked-solid preview BEFORE applySceneStyle and + // applyMeshLightVarOverride so stale preview --plr/--plg/--pli/--pai vars + // on rotated wrappers are wiped cleanly before dynamic overrides run. + if (fullRenderTriggered || textureLightingChanged || autoRebakeTriggered) { + sceneEl.style.removeProperty(BAKED_SOLID_PREVIEW_ACTIVE_VAR); + for (const entry of meshes) { + if (entry.solidLightingPreviewActive || entry.solidLightingPreviewPrepared) { + clearLightingVars(entry.wrapper); + entry.lightOverrideSignature = "clear"; + entry.solidLightingPreviewActive = false; + entry.solidLightingPreviewPrepared = false; + } + } + } + + applySceneStyle(sceneEl, currentOptions); + + for (const entry of meshes) { + applyMeshLightVarOverride(ctx, entry, entry.handle.transform.rotation); + } + + if (fullRenderTriggered) { + for (const entry of meshes) renderEntry(entry); + } + if (prevAutoCenter !== nextAutoCenter || prevAutoCenterSource !== currentOptions.autoCenterSource) { + recomputeAutoCenter(); + } + const nextShadow = currentOptions.shadow; if (prevShadow?.followAnimation && !nextShadow?.followAnimation && ctx.animationShadowTrailingTimer !== null) { clearTimeout(ctx.animationShadowTrailingTimer); @@ -272,12 +306,7 @@ export function createPolyScene( const shadowReemitNeeded = directionalChanged || shadowAppearanceChanged || pointLightsChanged || (ambientChanged && currentOptions.bakedLightPolicy === "auto"); - if ( - !textureLightingChanged && - currentOptions.bakedLightPolicy === "auto" && - (directionalChanged || ambientChanged) && - !fullRenderTriggered - ) { + if (autoRebakeTriggered) { for (const entry of meshes) { if (effectiveTextureLighting(ctx, entry) !== "dynamic") { entry.handle.rebakeAtlas(); diff --git a/packages/polycss/src/api/scene/bakedLighting.ts b/packages/polycss/src/api/scene/bakedLighting.ts index 49f49db3b..677d07b5f 100644 --- a/packages/polycss/src/api/scene/bakedLighting.ts +++ b/packages/polycss/src/api/scene/bakedLighting.ts @@ -87,7 +87,7 @@ export function restoreBakedSolidPaint(ctx: SceneContext, entry: MeshEntry): boo } export function prepareBakedSolidLightingPreview(ctx: SceneContext, entry: MeshEntry): boolean { - if ((ctx.options.current.textureLighting ?? "baked") !== "baked") return false; + if (effectiveTextureLighting(ctx, entry) !== "baked") return false; let prepared = false; for (const item of entry.rendered) { if (!item.plan || item.kind === "atlas" || item.plan.texture) continue; @@ -101,7 +101,7 @@ export function prepareBakedSolidLightingPreview(ctx: SceneContext, entry: MeshE } export function installBakedSolidLightingPreview(ctx: SceneContext, entry: MeshEntry): boolean { - if ((ctx.options.current.textureLighting ?? "baked") !== "baked") return false; + if (effectiveTextureLighting(ctx, entry) !== "baked") return false; if (!entry.solidLightingPreviewPrepared && !prepareBakedSolidLightingPreview(ctx, entry)) return false; entry.solidLightingPreviewActive = true; return true; @@ -141,6 +141,7 @@ export function commitBakedSolidLighting(ctx: SceneContext, renderEntry: RenderE sceneEl.style.removeProperty(BAKED_SOLID_PREVIEW_ACTIVE_VAR); for (const entry of meshes) { clearLightingVars(entry.wrapper); + entry.lightOverrideSignature = "clear"; entry.solidLightingPreviewActive = false; } clearLightingVars(sceneEl); @@ -153,6 +154,7 @@ export function clearBakedSolidLightingPreview(ctx: SceneContext): void { if (!entry.solidLightingPreviewActive) continue; restoreBakedSolidPaint(ctx, entry); clearLightingVars(entry.wrapper); + entry.lightOverrideSignature = "clear"; } if ((ctx.options.current.textureLighting ?? "baked") !== "dynamic") { clearLightingVars(ctx.sceneEl); @@ -169,6 +171,7 @@ export function applyPreviewMeshLightVars( entry: MeshEntry, next: Pick, "directionalLight" | "ambientLight">, ): void { + if (effectiveTextureLighting(ctx, entry) !== "baked") return; const currentOptions = ctx.options.current; const rotation = entry.handle.transform.rotation; const dir = next.directionalLight?.direction ?? currentOptions.directionalLight?.direction; diff --git a/packages/polycss/src/api/scene/equality.ts b/packages/polycss/src/api/scene/equality.ts index 4b5e73dea..8ad418958 100644 --- a/packages/polycss/src/api/scene/equality.ts +++ b/packages/polycss/src/api/scene/equality.ts @@ -26,6 +26,21 @@ export function vec3Equal(a: Vec3 | undefined, b: Vec3 | undefined): boolean { return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; } +export function shadowOptionKey(shadow: PolySceneOptions["shadow"] | undefined): string { + if (!shadow) return ""; + return [ + shadow.color ?? "#000000", + shadow.opacity ?? 0.25, + shadow.lift ?? POLY_DEFAULT_SHADOW_LIFT, + shadow.maxExtend ?? 2000, + shadow.parametric ?? false, + shadow.definition ?? 16, + shadow.dragDefinition ?? -1, + shadow.style ?? "vector", + shadow.followAnimation ?? false, + ].join("|"); +} + export function shadowOptsEqual( a: PolySceneOptions["shadow"] | undefined, b: PolySceneOptions["shadow"] | undefined, diff --git a/packages/polycss/src/api/scene/internalTypes.ts b/packages/polycss/src/api/scene/internalTypes.ts index ed1af8e63..53ad81d8b 100644 --- a/packages/polycss/src/api/scene/internalTypes.ts +++ b/packages/polycss/src/api/scene/internalTypes.ts @@ -99,21 +99,6 @@ export interface MeshEntry { rebakeInFlight: boolean; rebakeQueued: boolean; rebakeQueuedLightDir: Vec3 | undefined; - /** Cached light-visibility raytrace result. Keyed by the polygon array - * reference (changes on `setPolygons`) plus the quantized mesh-local - * light direction. Recomputed on cache miss only — not per frame. Forces - * directScale=0 for occluded polygons via `lightOccludedPolyIndices` on - * atlas options, so baked shading drops to ambient-only on faces a - * shadow-map would cull. */ - lightOcclusionCache?: { - polygons: Polygon[]; - lightDirKey: string; - occluded: ReadonlySet; - /** Cached `findOverlappingPolygonDuplicates` drop-set for this mesh. - * Invariant under light direction, so it's computed once per polygons - * identity and reused on every cache-miss recompute. */ - dedupDropped: ReadonlySet; - }; } // ReceiverFacePlane + CasterPolyItem now live in @layoutit/polycss-core. diff --git a/packages/polycss/src/api/scene/meshEntry.ts b/packages/polycss/src/api/scene/meshEntry.ts index d34277d46..b5682a0e0 100644 --- a/packages/polycss/src/api/scene/meshEntry.ts +++ b/packages/polycss/src/api/scene/meshEntry.ts @@ -26,7 +26,7 @@ import { syncMountedRenderedForCameraChange } from "./mountSync"; import { tryUpdatePolygonLeafOnly } from "./polygonPatch"; import { renderEntryAtomic, requestRebakeAtlas, resolveMeshRenderOptions } from "./rebake"; import { disposeReceiverShadowMounts } from "./receiverShadow"; -import { renderSceneEntry, renderSceneEntryChunked } from "./renderEntry"; +import { renderSceneEntry } from "./renderEntry"; import type { SceneContext } from "./sceneContext"; import { clearCasterItemsCache, clearReceiverShadowCache } from "./shadowCache"; import { @@ -482,31 +482,6 @@ export function addSceneMeshEntry( } renderEntry(entry); }, - async setPolygonsChunked(polygons: Polygon[], options?: { - merge?: boolean; - stableDom?: boolean; - recomputeAutoCenter?: boolean; - }) { - const version = ++polygonUpdateVersion; - mergeOnUpdate = options?.merge ?? mergeOnUpdate; - stableDomOnUpdate = options?.stableDom ?? stableDomOnUpdate; - entry.stableDom = stableDomOnUpdate; - entry.voxelSource = undefined; - entry.polygons = preparePolygons(polygons, mergeOnUpdate); - clearCurrentTriangleFrame(); - handle.polygons = entry.polygons; - applyTransformOrigin(entry.polygons); - const shouldRecomputeAutoCenter = options?.recomputeAutoCenter ?? true; - const shouldCancel = () => entry.disposed || version !== polygonUpdateVersion; - const completed = await renderSceneEntryChunked(ctx, entry, shouldCancel); - if (!completed) { - // Only wipe DOM if the mesh was disposed; if superseded by a newer - // setPolygons/setPolygonsChunked call, that call already owns the DOM. - if (entry.disposed) clearRendered(ctx, entry); - return; - } - if (shouldRecomputeAutoCenter) recomputeAutoCenter(); - }, setTransform(t: Partial) { const hasOwn = (key: string): boolean => Object.prototype.hasOwnProperty.call(t, key); const prevCastShadow = entry.castShadow; diff --git a/packages/polycss/src/api/scene/mountSync.ts b/packages/polycss/src/api/scene/mountSync.ts index 6881dc490..73ee25349 100644 --- a/packages/polycss/src/api/scene/mountSync.ts +++ b/packages/polycss/src/api/scene/mountSync.ts @@ -1,8 +1,7 @@ /** * Mount synchronization composites — (re)mounting a mesh entry's rendered * leaves against the current camera-cull set, with optional Lambert - * bucketing in dynamic lighting mode and a chunked async variant for large - * meshes. + * bucketing in dynamic lighting mode. * * Sits above cameraCull + mountLifecycle and below the render orchestration * in createPolyScene. Extracted verbatim; closure-captured scene state comes @@ -29,11 +28,6 @@ import { import type { SceneContext } from "./sceneContext"; import type { MeshEntry } from "./internalTypes"; -// Used only by the internal async mesh update path. Batching DOM insertion -// keeps large gallery meshes below Chrome's long-task warning threshold -// without changing the synchronous public setPolygons() contract. -const ASYNC_MOUNT_BATCH_SIZE = 750; - export function syncMountedRendered(ctx: SceneContext, entry: MeshEntry): void { const doc = ctx.doc; clearMountedRendered(entry); @@ -112,43 +106,6 @@ export function syncMountedRendered(ctx: SceneContext, entry: MeshEntry): void { syncCameraCullSignature(ctx, entry); } -function yieldToMainThread(): Promise { - return new Promise((resolve) => setTimeout(resolve, 0)); -} - -export async function syncMountedRenderedChunked( - ctx: SceneContext, - entry: MeshEntry, - shouldCancel: () => boolean, -): Promise { - const doc = ctx.doc; - const useBuckets = - (entry.renderOverrides.textureLighting ?? ctx.options.current.textureLighting) === "dynamic" && !entry.stableDom; - if (useBuckets) { - syncMountedRendered(ctx, entry); - return !shouldCancel(); - } - - clearMountedRendered(entry); - let fragment = doc.createDocumentFragment(); - const before = firstPreservedChild(entry); - let count = 0; - for (const item of renderedItemsForCamera(ctx, entry)) { - if (shouldCancel()) return false; - restoreInlineDynamicNormalVars(ctx, entry, item); - fragment.appendChild(item.element); - count++; - if (count % ASYNC_MOUNT_BATCH_SIZE === 0) { - mountRenderedFragment(entry, fragment, before); - fragment = doc.createDocumentFragment(); - await yieldToMainThread(); - } - } - if (fragment.childNodes.length > 0) mountRenderedFragment(entry, fragment, before); - syncCameraCullSignature(ctx, entry); - return !shouldCancel(); -} - export function syncMountedRenderedForCameraChange( ctx: SceneContext, entry: MeshEntry, diff --git a/packages/polycss/src/api/scene/rebake.ts b/packages/polycss/src/api/scene/rebake.ts index d1020708d..c99046a40 100644 --- a/packages/polycss/src/api/scene/rebake.ts +++ b/packages/polycss/src/api/scene/rebake.ts @@ -172,9 +172,12 @@ export function rebakeRenderEntryInPlace( for (const item of newAtlas.rendered) { const existing = entry.renderedByPolygonIndex[item.polygonIndex]; if (!existing) continue; + existing.plan = item.plan; const nextStyle = item.element.getAttribute("style"); if (nextStyle !== null) existing.element.setAttribute("style", nextStyle); } + entry.solidLightingPreviewPrepared = false; + entry.solidLightingPreviewActive = false; const spd = (newAtlas as { solidPaintDefaults?: SolidPaintDefaults }) .solidPaintDefaults; if (spd) applySolidPaintVars(entry.wrapper, spd); diff --git a/packages/polycss/src/api/scene/renderEntry.ts b/packages/polycss/src/api/scene/renderEntry.ts index 83eccf61b..f97b63bca 100644 --- a/packages/polycss/src/api/scene/renderEntry.ts +++ b/packages/polycss/src/api/scene/renderEntry.ts @@ -1,13 +1,12 @@ /** - * Per-mesh rendering entry points (synchronous and chunked-async) for - * `createPolyScene`. Operates purely on `SceneContext` + `MeshEntry`. + * Per-mesh rendering entry point for `createPolyScene`. + * Operates purely on `SceneContext` + `MeshEntry`. */ import type { Vec3 } from "@layoutit/polycss-core"; import { getSolidPaintDefaults, renderPolygonsWithStableTriangles, renderPolygonsWithTextureAtlas, - renderPolygonsWithTextureAtlasAsync, type SolidPaintDefaults, } from "../../render/textureAtlas"; import { createPolyVoxelRenderer } from "../../render/voxelRenderer"; @@ -15,7 +14,7 @@ import { cameraCullRotation, recomputeCameraCullGroups } from "./cameraCull"; import type { MeshEntry } from "./internalTypes"; import { applySolidPaintVars } from "./lightingVars"; import { TEXTURES_READY, clearRendered, setRendered } from "./mountLifecycle"; -import { syncMountedRendered, syncMountedRenderedChunked } from "./mountSync"; +import { syncMountedRendered } from "./mountSync"; import { canRenderVoxelDirect, collectAtlasUrlsFromRendered, @@ -56,12 +55,8 @@ export function renderSceneEntry( } } - const resolvedRenderOptions = resolveMeshRenderOptions(ctx, entry, lightDirectionOverride); - const entryLighting = resolvedRenderOptions.textureLighting; - const renderOptions = { - ...resolvedRenderOptions, - lightOccludedPolyIndices: undefined as ReadonlySet | undefined, - }; + const renderOptions = resolveMeshRenderOptions(ctx, entry, lightDirectionOverride); + const entryLighting = renderOptions.textureLighting; let stableAtlas: ReturnType = null; if (entry.stableDom) { const solidPaintDefaults = getSolidPaintDefaults(entry.polygons, renderOptions); @@ -116,49 +111,3 @@ export function renderSceneEntry( } } } - -export async function renderSceneEntryChunked( - ctx: SceneContext, - entry: MeshEntry, - shouldCancel: () => boolean, -): Promise { - clearRendered(ctx, entry); - const resolvedRenderOptions = resolveMeshRenderOptions(ctx, entry); - const entryLighting = resolvedRenderOptions.textureLighting; - const renderOptions = { - ...resolvedRenderOptions, - lightOccludedPolyIndices: undefined as ReadonlySet | undefined, - }; - const atlas = entry.stableDom - ? renderPolygonsWithStableTriangles(entry.polygons, renderOptions) - : null; - if (atlas) { - const solidPaintDefaults = getSolidPaintDefaults(entry.polygons, renderOptions); - applySolidPaintVars(entry.wrapper, solidPaintDefaults); - setRendered(entry, atlas.rendered, atlas.dispose, atlas.pagesReady); - recomputeCameraCullGroups(entry); - syncMountedRendered(ctx, entry); - emitShadowLeaves(ctx, entry); - return !shouldCancel(); - } - - const asyncAtlas = await renderPolygonsWithTextureAtlasAsync( - entry.polygons, - { - ...renderOptions, - skipDynamicNormalVars: entryLighting === "dynamic", - } as typeof renderOptions & { skipDynamicNormalVars: boolean }, - shouldCancel, - ); - if (shouldCancel()) { - asyncAtlas.dispose(); - return false; - } - applySolidPaintVars(entry.wrapper, asyncAtlas.solidPaintDefaults); - setRendered(entry, asyncAtlas.rendered, asyncAtlas.dispose, asyncAtlas.pagesReady); - entry.skipBucketNormalCleanupOnce = entryLighting === "dynamic" && !entry.stableDom; - recomputeCameraCullGroups(entry); - const mounted = await syncMountedRenderedChunked(ctx, entry, shouldCancel); - if (mounted) emitShadowLeaves(ctx, entry); - return mounted; -} diff --git a/packages/polycss/src/api/scene/types.ts b/packages/polycss/src/api/scene/types.ts index 0539ff572..81dfff940 100644 --- a/packages/polycss/src/api/scene/types.ts +++ b/packages/polycss/src/api/scene/types.ts @@ -427,6 +427,18 @@ export interface PolySceneHandle { setCenterPolygons(polygons: readonly Polygon[] | null): void; /** Current resolved auto-center bbox offset in world units. */ getAutoCenterOffset(): Vec3; + /** Preview directional/ambient light updates on baked solid leaves via CSS + * vars without re-rasterising atlases (for smooth slider drags). */ + previewBakedSolidLighting( + next: Pick, "directionalLight" | "ambientLight"> & { + skipShadows?: boolean; + }, + ): boolean; + /** Commit the current scene lighting onto baked solid and atlas leaves in + * place and tear down preview vars. */ + commitBakedSolidLighting(): boolean; + /** Cancel an active baked solid lighting preview and restore committed paint. */ + clearBakedSolidLightingPreview(): void; } /** Symbol-keyed extension point on `PolyMeshHandle` for the animation mixer. @@ -467,10 +479,4 @@ export interface PolyAnimationTriangleFrameTarget { export interface InternalPolyMeshHandle extends PolyMeshHandle, - PolyAnimationTriangleFrameTarget { - setPolygonsChunked(polygons: Polygon[], options?: { - merge?: boolean; - stableDom?: boolean; - recomputeAutoCenter?: boolean; - }): Promise; -} + PolyAnimationTriangleFrameTarget {} diff --git a/packages/polycss/src/elements/PolySceneElement.ts b/packages/polycss/src/elements/PolySceneElement.ts index 21412732d..3cbf63b84 100644 --- a/packages/polycss/src/elements/PolySceneElement.ts +++ b/packages/polycss/src/elements/PolySceneElement.ts @@ -50,6 +50,8 @@ const OBSERVED_ATTRS = [ "rot-x", "rot-y", "zoom", + "distance", + "target", // Scene-level attrs "directional-direction", "directional-color", diff --git a/packages/polycss/src/elements/PolyShapeElements.test.ts b/packages/polycss/src/elements/PolyShapeElements.test.ts index ce5a81371..fcc1f74b2 100644 --- a/packages/polycss/src/elements/PolyShapeElements.test.ts +++ b/packages/polycss/src/elements/PolyShapeElements.test.ts @@ -187,4 +187,34 @@ describe("leaf DOM production", () => { scene.removeChild(el); expect(scene.querySelectorAll(".polycss-mesh").length).toBe(0); }); + + it("observes shadow and auto-center attributes across all 11 shape elements", () => { + const classes = [ + PolyBoxElement, + PolyPlaneElement, + PolyRingElement, + PolyOctahedronElement, + PolySphereElement, + PolyTetrahedronElement, + PolyIcosahedronElement, + PolyDodecahedronElement, + PolyCylinderElement, + PolyConeElement, + PolyTorusElement, + ]; + for (const Cls of classes) { + expect(Cls.observedAttributes).toContain("cast-shadow"); + expect(Cls.observedAttributes).toContain("receive-shadow"); + expect(Cls.observedAttributes).toContain("exclude-from-auto-center"); + } + + const scene = mountInScene("poly-box", { size: "100" }); + const boxEl = scene.querySelector("poly-box")!; + const meshHandle = scene.getScene()!.meshes()[0]!; + expect(meshHandle.transform.castShadow).toBe(false); + boxEl.setAttribute("cast-shadow", ""); + expect(meshHandle.transform.castShadow).toBe(true); + boxEl.setAttribute("exclude-from-auto-center", ""); + expect(meshHandle.transform.excludeFromAutoCenter).toBe(true); + }); }); diff --git a/packages/polycss/src/elements/PolyShapeElements.ts b/packages/polycss/src/elements/PolyShapeElements.ts index 62bc7dcb1..b45ef0881 100644 --- a/packages/polycss/src/elements/PolyShapeElements.ts +++ b/packages/polycss/src/elements/PolyShapeElements.ts @@ -56,6 +56,25 @@ function parseVec3Attr(el: HTMLElement, name: string): Vec3 | undefined { return parseVec3(el.getAttribute(name)); } +const COMMON_SHAPE_ATTRS = [ + "color", + "auto-center", + "position", + "scale", + "rotation", + "cast-shadow", + "receive-shadow", + "exclude-from-auto-center", +] as const; + +function parseScaleAttr(el: HTMLElement): number | Vec3 | undefined { + const raw = el.getAttribute("scale"); + if (!raw) return undefined; + if (raw.includes(",")) return parseVec3Attr(el, "scale"); + const n = parseFloat(raw); + return Number.isFinite(n) ? n : undefined; +} + /** * Base class for all primitive shape elements. Subclasses implement * `buildPolygons()` which returns a Polygon[] from this element's attributes. @@ -87,20 +106,16 @@ abstract class PolyShapeElement extends ELEMENT_BASE { name === "scale" || name === "rotation" || name === "cast-shadow" || - name === "receive-shadow" + name === "receive-shadow" || + name === "exclude-from-auto-center" ) { this._handle.setTransform({ position: parseVec3Attr(this, "position"), - scale: (() => { - const raw = this.getAttribute("scale"); - if (!raw) return undefined; - if (raw.includes(",")) return parseVec3Attr(this, "scale"); - const n = parseFloat(raw); - return Number.isFinite(n) ? n : undefined; - })(), + scale: parseScaleAttr(this), rotation: parseVec3Attr(this, "rotation"), castShadow: this.hasAttribute("cast-shadow"), receiveShadow: this.hasAttribute("receive-shadow"), + excludeFromAutoCenter: this.hasAttribute("exclude-from-auto-center"), }); return; } @@ -139,13 +154,7 @@ abstract class PolyShapeElement extends ELEMENT_BASE { parseResult, { position: parseVec3Attr(this, "position"), - scale: (() => { - const raw = this.getAttribute("scale"); - if (!raw) return undefined; - if (raw.includes(",")) return parseVec3Attr(this, "scale"); - const n = parseFloat(raw); - return Number.isFinite(n) ? n : undefined; - })(), + scale: parseScaleAttr(this), rotation: parseVec3Attr(this, "rotation"), // Shadow flags mirror so primitive shapes can act as // ground planes for shadow receivers without needing a GLB. @@ -165,7 +174,7 @@ abstract class PolyShapeElement extends ELEMENT_BASE { export class PolyBoxElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["size", "color", "auto-center", "position", "scale", "rotation"]; + return ["size", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -180,18 +189,7 @@ export class PolyBoxElement extends PolyShapeElement { export class PolyPlaneElement extends PolyShapeElement { static get observedAttributes(): string[] { - return [ - "axis", - "size", - "offset", - "color", - "auto-center", - "position", - "scale", - "rotation", - "cast-shadow", - "receive-shadow", - ]; + return ["axis", "size", "offset", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -214,7 +212,7 @@ export class PolyPlaneElement extends PolyShapeElement { export class PolyRingElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["axis", "radius", "segments", "half-thickness", "color", "auto-center", "position", "scale", "rotation"]; + return ["axis", "radius", "segments", "half-thickness", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -233,7 +231,7 @@ export class PolyRingElement extends PolyShapeElement { export class PolyOctahedronElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["size", "color", "center", "auto-center", "position", "scale", "rotation"]; + return ["size", "center", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -247,7 +245,7 @@ export class PolyOctahedronElement extends PolyShapeElement { export class PolyTetrahedronElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["size", "color", "auto-center", "position", "scale", "rotation"]; + return ["size", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -260,7 +258,7 @@ export class PolyTetrahedronElement extends PolyShapeElement { export class PolyIcosahedronElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["size", "color", "auto-center", "position", "scale", "rotation"]; + return ["size", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -273,7 +271,7 @@ export class PolyIcosahedronElement extends PolyShapeElement { export class PolyDodecahedronElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["size", "color", "auto-center", "position", "scale", "rotation"]; + return ["size", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -286,7 +284,7 @@ export class PolyDodecahedronElement extends PolyShapeElement { export class PolySphereElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["radius", "subdivisions", "color", "auto-center", "position", "scale", "rotation"]; + return ["radius", "subdivisions", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -302,7 +300,7 @@ export class PolySphereElement extends PolyShapeElement { export class PolyCylinderElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["radius", "radius-top", "height", "radial-segments", "color", "auto-center", "position", "scale", "rotation"]; + return ["radius", "radius-top", "height", "radial-segments", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -319,7 +317,7 @@ export class PolyCylinderElement extends PolyShapeElement { export class PolyConeElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["radius", "height", "radial-segments", "color", "auto-center", "position", "scale", "rotation"]; + return ["radius", "height", "radial-segments", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { @@ -334,7 +332,7 @@ export class PolyConeElement extends PolyShapeElement { export class PolyTorusElement extends PolyShapeElement { static get observedAttributes(): string[] { - return ["radius", "tube", "radial-segments", "tubular-segments", "color", "auto-center", "position", "scale", "rotation"]; + return ["radius", "tube", "radial-segments", "tubular-segments", ...COMMON_SHAPE_ATTRS]; } buildPolygons(): Polygon[] { diff --git a/packages/polycss/src/index.ts b/packages/polycss/src/index.ts index 1425295fb..a964542b0 100644 --- a/packages/polycss/src/index.ts +++ b/packages/polycss/src/index.ts @@ -122,7 +122,6 @@ export type { RenderedPoly, RenderTextureAtlasOptions, RenderTextureAtlasResult, - RenderTextureAtlasAsyncResult, SolidTriangleFrame, } from "./render/textureAtlas"; export { @@ -144,10 +143,8 @@ export { packTextureAtlasPlansWithScale, buildAtlasPages, renderPolygonsWithTextureAtlas, - renderPolygonsWithTextureAtlasAsync, updateStableTriangleFrame, renderPolygonsWithStableTriangles, - updatePolygonsWithStableTriangles, updatePolygonsWithStableTopology, } from "./render/textureAtlas"; export type { diff --git a/packages/polycss/src/internal.ts b/packages/polycss/src/internal.ts index 0b69527ae..efb2c172a 100644 --- a/packages/polycss/src/internal.ts +++ b/packages/polycss/src/internal.ts @@ -46,6 +46,8 @@ export { restoreVoxelMeshClass, } from "./api/standaloneMesh"; +export { shadowOptionKey } from "./api/scene/equality"; + export { buildDirectMaterialLeafDescriptor, buildFallbackLeafDescriptor, diff --git a/packages/polycss/src/render/atlas/emit.ts b/packages/polycss/src/render/atlas/emit.ts index 1a673ef57..73caeb8f9 100644 --- a/packages/polycss/src/render/atlas/emit.ts +++ b/packages/polycss/src/render/atlas/emit.ts @@ -265,10 +265,7 @@ export function shadedSolidPlanForNormal( const ambientIntensity = Math.max(0, ambientCfg?.intensity ?? DEFAULT_AMBIENT_INTENSITY); const lLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; - const occluded = options.lightOccludedPolyIndices?.has(source.index) ?? false; - const directScale = occluded - ? 0 - : lightIntensity * Math.max(0, normal[0] * lx + normal[1] * ly + normal[2] * lz); + const directScale = lightIntensity * Math.max(0, normal[0] * lx + normal[1] * ly + normal[2] * lz); return { ...source, polygon, diff --git a/packages/polycss/src/render/atlas/index.ts b/packages/polycss/src/render/atlas/index.ts index 309dfc6a6..2c0a0d45c 100644 --- a/packages/polycss/src/render/atlas/index.ts +++ b/packages/polycss/src/render/atlas/index.ts @@ -16,7 +16,6 @@ export type { RenderTextureAtlasOptions, RenderedPoly, RenderTextureAtlasResult, - RenderTextureAtlasAsyncResult, } from "./types"; export { packTextureAtlasPlansWithScale } from "./packing"; export { buildTextureEdgeRepairSets, buildSeamBleedPolygonEdges, buildSeamBleedPolygonSet } from "@layoutit/polycss-core"; @@ -33,7 +32,6 @@ export { export { getSolidPaintDefaults, renderPolygonsWithTextureAtlas, - renderPolygonsWithTextureAtlasAsync, updateStableTriangleFrame, updatePolygonsWithStableTopology, } from "./renderPolygons"; @@ -46,5 +44,4 @@ export { export { formatBorderShapeEntryMatrix, cssBorderShapeForPlan } from "@layoutit/polycss-core"; export { renderPolygonsWithStableTriangles, - updatePolygonsWithStableTriangles, } from "./stableTriangle"; diff --git a/packages/polycss/src/render/atlas/render/asyncRender.ts b/packages/polycss/src/render/atlas/render/asyncRender.ts deleted file mode 100644 index a1d507b3f..000000000 --- a/packages/polycss/src/render/atlas/render/asyncRender.ts +++ /dev/null @@ -1,139 +0,0 @@ -import type { Polygon, TextureAtlasPlan } from "@layoutit/polycss-core"; -import { - ASYNC_RENDER_BUDGET_MS, - buildBasisHints, - computeTextureAtlasPlan, -} from "@layoutit/polycss-core"; -import type { - InternalRenderTextureAtlasOptions, - RenderedPoly, - RenderTextureAtlasAsyncResult, - RenderTextureAtlasOptions, -} from "../types"; -import { resolveProjectiveQuadGuards } from "../plan"; -import { getSolidPaintDefaultsForPlans } from "../strategy"; -import { packTextureAtlasPlansWithScale } from "../packing"; -import { - buildRenderSeamBleedEdges, - classifyPolygonRenderPlans, - projectiveQuadGuardDefaults, - resolveAtlasRenderCapabilities, - seamAtlasOptions, - type ClassifiedPolygonPlans, -} from "./planning"; -import { attachAtlasPageHydration, emitPolygonLeaf } from "./emitLeaves"; - -function yieldToMainThread(): Promise { - return new Promise((resolve) => setTimeout(resolve, 0)); -} - -async function yieldIfOverBudget(started: number): Promise { - if (performance.now() - started < ASYNC_RENDER_BUDGET_MS) return started; - await yieldToMainThread(); - return performance.now(); -} - -export async function renderPolygonsWithTextureAtlasAsync( - polygons: Polygon[], - options: RenderTextureAtlasOptions = {}, - shouldCancel: () => boolean = () => false, -): Promise { - const doc = options.doc ?? (typeof document !== "undefined" ? document : null); - if (!doc || shouldCancel()) { - return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; - } - - const textureLighting = options.textureLighting ?? "baked"; - const internalOptions = options as InternalRenderTextureAtlasOptions; - const skipDynamicNormalVars = - textureLighting === "dynamic" && internalOptions.skipDynamicNormalVars === true; - const capabilities = resolveAtlasRenderCapabilities(doc, options); - await yieldToMainThread(); - if (shouldCancel()) return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; - - const basisHints = buildBasisHints(polygons, options); - const projectiveQuadGuards = resolveProjectiveQuadGuards(doc, projectiveQuadGuardDefaults(options)); - const seamBleedEdges = buildRenderSeamBleedEdges(polygons, options); - let batchStarted = performance.now(); - const plans: Array = new Array(polygons.length); - for (let i = 0; i < polygons.length; i++) { - plans[i] = computeTextureAtlasPlan( - polygons[i], - i, - seamAtlasOptions(i, seamBleedEdges, options), - projectiveQuadGuards, - basisHints[i], - ); - batchStarted = await yieldIfOverBudget(batchStarted); - if (shouldCancel()) return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; - } - - const solidPaintDefaults = options.solidPaintDefaults ?? - getSolidPaintDefaultsForPlans(plans, textureLighting, doc, options.strategies); - const triangleOptions = { ...options, solidPaintDefaults }; - const classifiedPlans: ClassifiedPolygonPlans[] = new Array(plans.length); - const atlasPlans: Array = new Array(plans.length); - for (let i = 0; i < plans.length; i++) { - const classified = classifyPolygonRenderPlans( - plans[i], - capabilities, - options, - triangleOptions, - projectiveQuadGuards, - ); - classifiedPlans[i] = classified; - atlasPlans[i] = classified.atlasPlan; - batchStarted = await yieldIfOverBudget(batchStarted); - if (shouldCancel()) return { rendered: [], solidPaintDefaults, dispose: () => {} }; - } - - const { packed, atlasScale } = packTextureAtlasPlansWithScale( - atlasPlans, - options.textureQuality, - doc, - options.textureLeafSizing, - ); - const atlasElements = new Map(); - const rendered: RenderedPoly[] = []; - const emitContext = { - doc, - textureLighting, - skipDynamicNormalVars, - textureImageRendering: options.textureImageRendering, - solidPaintDefaults, - capabilities, - packed, - atlasElements, - rendered, - }; - - for (let i = 0; i < polygons.length; i++) { - const plan = plans[i]; - if (!plan) continue; - emitPolygonLeaf(i, plan, classifiedPlans[i], emitContext); - batchStarted = await yieldIfOverBudget(batchStarted); - if (shouldCancel()) { - for (const item of rendered) item.dispose(); - return { rendered: [], solidPaintDefaults, dispose: () => {} }; - } - } - - rendered.sort((a, b) => a.polygonIndex - b.polygonIndex); - - const { pagesReady, dispose } = attachAtlasPageHydration( - packed, - atlasScale, - atlasElements, - textureLighting, - doc, - options.textureImageRendering, - shouldCancel, - ); - - return { - rendered, - solidPaintDefaults, - pagesReady, - dispose, - }; -} diff --git a/packages/polycss/src/render/atlas/renderPolygons.ts b/packages/polycss/src/render/atlas/renderPolygons.ts index 4b772e0fd..07ef64ef1 100644 --- a/packages/polycss/src/render/atlas/renderPolygons.ts +++ b/packages/polycss/src/render/atlas/renderPolygons.ts @@ -18,7 +18,6 @@ import { } from "./render/planning"; import { attachAtlasPageHydration, emitPolygonLeaf } from "./render/emitLeaves"; -export { renderPolygonsWithTextureAtlasAsync } from "./render/asyncRender"; export { updateStableTriangleFrame } from "./render/stableTriangleFrame"; export { updatePolygonsWithStableTopology } from "./render/stableTopologyUpdate"; diff --git a/packages/polycss/src/render/atlas/stableTriangle.test.ts b/packages/polycss/src/render/atlas/stableTriangle.test.ts index 1238f9177..3131e0913 100644 --- a/packages/polycss/src/render/atlas/stableTriangle.test.ts +++ b/packages/polycss/src/render/atlas/stableTriangle.test.ts @@ -1,21 +1,16 @@ /** * Feature tests: stable triangle DOM operations * - * Covers renderPolygonsWithStableTriangles, updatePolygonsWithStableTriangles, - * and updateStableTriangleFrame. + * Covers renderPolygonsWithStableTriangles and updateStableTriangleFrame. * * The key contracts: * - renderPolygonsWithStableTriangles emits one per triangle. * - When "u" strategy is disabled, renderPolygonsWithStableTriangles returns null. - * - updatePolygonsWithStableTriangles updates transform in-place without re-mounting. * - updateStableTriangleFrame requires optimizeStableTriangleStyle=true to return true. */ import { describe, it, expect } from "vitest"; import type { Polygon } from "@layoutit/polycss-core"; -import { - renderPolygonsWithStableTriangles, - updatePolygonsWithStableTriangles, -} from "./stableTriangle"; +import { renderPolygonsWithStableTriangles } from "./stableTriangle"; import { updateStableTriangleFrame } from "./renderPolygons"; // --------------------------------------------------------------------------- @@ -59,11 +54,6 @@ const ADJACENT_TRIANGLE_A: Polygon = { color: "#ff0000", }; -const MOVED_TRIANGLE_A: Polygon = { - vertices: [[0.1, 0, 0], [1.1, 0, 0], [0.1, 1, 0]], - color: "#ff0000", -}; - // --------------------------------------------------------------------------- // Tests: renderPolygonsWithStableTriangles // --------------------------------------------------------------------------- @@ -161,68 +151,6 @@ describe("renderPolygonsWithStableTriangles — initial render", () => { }); }); -// --------------------------------------------------------------------------- -// Tests: updatePolygonsWithStableTriangles -// --------------------------------------------------------------------------- - -describe("updatePolygonsWithStableTriangles — in-place update", () => { - it("returns null when u strategy is disabled", () => { - const doc = makeDoc(); - const initial = renderPolygonsWithStableTriangles([TRIANGLE_A], { doc })!; - const updated = updatePolygonsWithStableTriangles(initial.rendered, [MOVED_TRIANGLE_A], { - doc, - strategies: { disable: ["u"] }, - }); - expect(updated).toBeNull(); - initial.dispose(); - }); - - it("returns null when rendered contains non-triangle kinds", () => { - const doc = makeDoc(); - const fakeRendered = [{ - polygonIndex: 0, - element: document.createElement("b"), - kind: "solid" as const, - dispose: () => {}, - }]; - const result = updatePolygonsWithStableTriangles(fakeRendered, [TRIANGLE_A], { doc }); - expect(result).toBeNull(); - }); - - it("returns null when polygon count mismatches rendered count", () => { - const doc = makeDoc(); - const initial = renderPolygonsWithStableTriangles([TRIANGLE_A, TRIANGLE_B], { doc })!; - const result = updatePolygonsWithStableTriangles(initial.rendered, [TRIANGLE_A], { doc }); - expect(result).toBeNull(); - initial.dispose(); - }); - - it("returns the same rendered array (no remount)", () => { - const doc = makeDoc(); - const initial = renderPolygonsWithStableTriangles([TRIANGLE_A], { doc })!; - const originalElement = initial.rendered[0].element; - const updated = updatePolygonsWithStableTriangles( - initial.rendered, - [MOVED_TRIANGLE_A], - { doc }, - ); - expect(updated).not.toBeNull(); - expect(updated!.rendered[0].element).toBe(originalElement); // same DOM node - initial.dispose(); - }); - - it("updates the transform on the leaf after update", () => { - const doc = makeDoc(); - const initial = renderPolygonsWithStableTriangles([TRIANGLE_A], { doc })!; - const beforeTransform = initial.rendered[0].element.style.transform; - updatePolygonsWithStableTriangles(initial.rendered, [MOVED_TRIANGLE_A], { doc }); - const afterTransform = initial.rendered[0].element.style.transform; - // Transform should change when polygon moves - expect(afterTransform).not.toBe(beforeTransform); - initial.dispose(); - }); -}); - // --------------------------------------------------------------------------- // Tests: updateStableTriangleFrame // --------------------------------------------------------------------------- diff --git a/packages/polycss/src/render/atlas/stableTriangle.ts b/packages/polycss/src/render/atlas/stableTriangle.ts index 99ba541d6..9cb83bd5b 100644 --- a/packages/polycss/src/render/atlas/stableTriangle.ts +++ b/packages/polycss/src/render/atlas/stableTriangle.ts @@ -444,130 +444,3 @@ export function renderPolygonsWithStableTriangles( dispose() {}, }; } - -export function updatePolygonsWithStableTriangles( - rendered: RenderedPoly[], - polygons: Polygon[], - options: RenderTextureAtlasOptions = {}, -): RenderTextureAtlasResult | null { - const doc = options.doc ?? (typeof document !== "undefined" ? document : null); - if (!doc) return { rendered, dispose: () => {} }; - const solidTrianglePrimitive = resolveSolidTrianglePrimitive(doc, options.strategies); - if (!solidTrianglePrimitive) return null; - if (rendered.some((item) => item.kind !== "triangle")) return null; - if (polygons.length !== rendered.length) return null; - for (let i = 0; i < rendered.length; i++) { - if (rendered[i].polygonIndex !== i) return null; - } - - const optimizeTriangleStyle = - (options as InternalRenderTextureAtlasOptions).optimizeStableTriangleStyle === true && - (options.textureLighting ?? "baked") === "baked"; - const internalOptions = options as InternalRenderTextureAtlasOptions; - const stableTriangleDebug = internalOptions.stableTriangleDebug; - const stableTriangleUpdateMode = internalOptions.stableTriangleUpdateMode ?? - (stableTriangleDebug === "plan-only" || stableTriangleDebug === "transform-only" - ? stableTriangleDebug - : "full"); - const colorOnly = optimizeTriangleStyle && stableTriangleUpdateMode === "color-only"; - const colorState = stableTriangleColorState(internalOptions); - const matrixDecimals = stableTriangleMatrixDecimals(internalOptions.stableTriangleMatrixDecimals); - if ( - updateStableTriangleElementsStreaming( - rendered, - polygons, - options, - optimizeTriangleStyle, - stableTriangleUpdateMode, - colorState, - ) - ) { - return { - rendered, - dispose() {}, - }; - } - const nextTrianglePlans: Array = new Array(rendered.length); - const nextTriangleColorPlans: Array = new Array(rendered.length); - const seamBleedEdges = buildStableTriangleSeamEdges(polygons, options); - for (let i = 0; i < rendered.length; i++) { - const element = rendered[i].element as SolidTriangleElement; - if (colorOnly) { - const shouldComputeColor = internalOptions.stableTriangleColorPolicy === "adaptive" || - shouldComputeStableTriangleColor( - element, - i, - optimizeTriangleStyle, - stableTriangleDebug, - internalOptions.stableTriangleColorPolicy, - colorState, - ); - nextTriangleColorPlans[i] = shouldComputeColor - ? computeSolidTriangleColorPlan(polygons[i], i, options) - : null; - continue; - } - nextTrianglePlans[i] = computeSolidTrianglePlan(polygons[i], i, stableTriangleSeamOptions(i, seamBleedEdges, options), { - basis: element.__polycssSolidTriangleBasis, - matrixDecimals, - primitive: solidTrianglePrimitive, - includeColor: stableTriangleUpdateMode !== "plan-only" && - stableTriangleUpdateMode !== "transform-only" && - shouldComputeStableTriangleColor( - element, - i, - optimizeTriangleStyle, - stableTriangleDebug, - internalOptions.stableTriangleColorPolicy, - colorState, - ), - }); - } - const adaptiveColorUpdates = optimizeTriangleStyle && stableTriangleUpdateMode !== "plan-only" && - stableTriangleUpdateMode !== "transform-only" - ? selectAdaptiveTriangleColorUpdates( - rendered, - colorOnly ? nextTriangleColorPlans : nextTrianglePlans, - internalOptions, - ) - : null; - - for (let i = 0; i < rendered.length; i++) { - if (colorOnly) { - const plan = nextTriangleColorPlans[i]; - if (plan) { - applySolidTriangleElementColorOnly( - rendered[i].element, - plan, - colorState, - adaptiveColorUpdates?.has(i), - ); - } - continue; - } - const plan = nextTrianglePlans[i]; - if (!plan) { - hideSolidTriangleElement(rendered[i].element); - continue; - } - if (optimizeTriangleStyle && stableTriangleUpdateMode === "plan-only") { - continue; - } else if (optimizeTriangleStyle && stableTriangleUpdateMode === "transform-only") { - applySolidTriangleElementTransformOnly(rendered[i].element, plan); - } else if (optimizeTriangleStyle) { - applySolidTriangleElementFast( - rendered[i].element, - plan, - colorState, - adaptiveColorUpdates?.has(i), - ); - } else { - applySolidTriangleElement(rendered[i].element, plan); - } - } - - return { - rendered, - dispose() {}, - }; -} diff --git a/packages/polycss/src/render/atlas/types.ts b/packages/polycss/src/render/atlas/types.ts index 07ff10234..0174ba1a1 100644 --- a/packages/polycss/src/render/atlas/types.ts +++ b/packages/polycss/src/render/atlas/types.ts @@ -28,21 +28,14 @@ export interface RenderTextureAtlasOptions { textureImageRendering?: PolyTextureImageRendering; textureBackend?: PolyTextureBackend; textureProjection?: PolyTextureProjection; + /** Raw public seam-bleed option; core resolves it via `resolveSeamBleedPx` + * (absolute px) and `seamBleedPrimitiveRatio` (primitive-bleed scale). */ + seamBleed?: import("@layoutit/polycss-core").PolySeamBleed; solidPaintDefaults?: import("@layoutit/polycss-core").SolidPaintDefaults; strategies?: import("@layoutit/polycss-core").PolyRenderStrategiesOption; - /** - * Indices of polygons that the directional light cannot reach (precomputed - * by createPolyScene via {@link computeLightVisibility}). Atlas + solid - * planning forces directScale to 0 for these polys so they render with - * ambient-only color, matching what a shadow-map pass would output. - */ - lightOccludedPolyIndices?: ReadonlySet; } export interface InternalRenderTextureAtlasOptions extends RenderTextureAtlasOptions { - /** Raw public seam-bleed option; core resolves it via `resolveSeamBleedPx` - * (absolute px) and `seamBleedPrimitiveRatio` (primitive-bleed scale). */ - seamBleed?: import("@layoutit/polycss-core").PolySeamBleed; seamEdges?: Set; computeSolidPaintDefaults?: boolean; skipDynamicNormalVars?: boolean; @@ -92,7 +85,3 @@ export interface RenderTextureAtlasResult { */ pagesReady?: Promise; } - -export interface RenderTextureAtlasAsyncResult extends RenderTextureAtlasResult { - solidPaintDefaults: import("@layoutit/polycss-core").SolidPaintDefaults; -} diff --git a/packages/polycss/src/render/polyDOM.test.ts b/packages/polycss/src/render/polyDOM.test.ts index e8966faf1..c539a730d 100644 --- a/packages/polycss/src/render/polyDOM.test.ts +++ b/packages/polycss/src/render/polyDOM.test.ts @@ -1,7 +1,6 @@ import { describe, it, expect, vi, afterEach } from "vitest"; import { renderPolygonsWithTextureAtlas, - renderPolygonsWithTextureAtlasAsync, updatePolygonsWithStableTopology, type RenderedPoly, type RenderTextureAtlasOptions, @@ -666,22 +665,6 @@ describe("renderPolygonsWithTextureAtlas", () => { result.dispose(); }); - it("async renderer returns the same solid triangle element shape", async () => { - const result = await renderPolygonsWithTextureAtlasAsync([FLAT_TRIANGLE, SECOND_FLAT_TRIANGLE]); - const element = result.rendered[0].element; - expect(result.rendered).toHaveLength(2); - expect(element.tagName.toLowerCase()).toBe("u"); - expect(element.style.transform).toContain("matrix3d("); - expect(result.solidPaintDefaults.paintColor).toMatch(/^#[0-9a-f]{6}$/); - result.dispose(); - }); - - it("async renderer returns empty output when cancelled before planning", async () => { - const result = await renderPolygonsWithTextureAtlasAsync([FLAT_TRIANGLE], {}, () => true); - expect(result.rendered).toEqual([]); - result.dispose(); - }); - it("uses the whole polygon normal when the first three vertices are nearly collinear", () => { const skinnyLeadingNgon: Polygon = { vertices: [ diff --git a/packages/polycss/src/render/textureAtlas.ts b/packages/polycss/src/render/textureAtlas.ts index 4fa004f98..9e665871b 100644 --- a/packages/polycss/src/render/textureAtlas.ts +++ b/packages/polycss/src/render/textureAtlas.ts @@ -13,7 +13,6 @@ export type { RenderTextureAtlasOptions, RenderedPoly, RenderTextureAtlasResult, - RenderTextureAtlasAsyncResult, ComputeTextureAtlasPlanOptions, } from "./atlas/index.ts"; export { @@ -31,7 +30,6 @@ export { filterAtlasPlans, getSolidPaintDefaults, renderPolygonsWithTextureAtlas, - renderPolygonsWithTextureAtlasAsync, updateStableTriangleFrame, updatePolygonsWithStableTopology, computeTextureAtlasPlanPublic, @@ -41,5 +39,4 @@ export { formatBorderShapeEntryMatrix, cssBorderShapeForPlan, renderPolygonsWithStableTriangles, - updatePolygonsWithStableTriangles, } from "./atlas/index"; diff --git a/packages/polycss/src/render/voxel/shading.test.ts b/packages/polycss/src/render/voxel/shading.test.ts new file mode 100644 index 000000000..654c1ab0b --- /dev/null +++ b/packages/polycss/src/render/voxel/shading.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vitest"; +import { canonicalBrushColor, shadeBrushColor } from "./shading"; + +describe("voxel shading", () => { + it("preserves translucent alpha without producing NaN channels", () => { + const shaded = shadeBrushColor( + [0, 0, 1], + "rgba(255, 128, 64, 0.5)", + { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, + { color: "#ffffff", intensity: 0.4 }, + ); + expect(shaded).toMatch(/^rgba\(\d+, \d+, \d+, 0\.5\)$/); + expect(shaded).not.toContain("NaN"); + }); + + it("shades opaque hex colors into valid hex output", () => { + const shaded = shadeBrushColor( + [0, 0, 1], + "#ff8040", + { direction: [0, 0, 1], color: "#ffffff", intensity: 1 }, + { color: "#ffffff", intensity: 0.4 }, + ); + expect(shaded).toMatch(/^#[0-9a-f]{6}$/i); + }); + + it("canonicalizes opaque and translucent brush colors", () => { + expect(canonicalBrushColor(undefined)).toBe("#cccccc"); + expect(canonicalBrushColor("rgb(255, 0, 128)")).toBe("#ff0080"); + expect(canonicalBrushColor("rgba(255, 0, 128, 0.5)")).toBe("rgba(255, 0, 128, 0.5)"); + }); +}); diff --git a/packages/polycss/src/render/voxel/shading.ts b/packages/polycss/src/render/voxel/shading.ts index d2e2da3bf..2700c170c 100644 --- a/packages/polycss/src/render/voxel/shading.ts +++ b/packages/polycss/src/render/voxel/shading.ts @@ -22,17 +22,6 @@ const DEFAULT_LIGHT_INTENSITY = 1; const DEFAULT_AMBIENT_COLOR = "#ffffff"; const DEFAULT_AMBIENT_INTENSITY = 0.4; -function parseColor(input: string): RGB { - const parsed = parsePureColor(input); - if (!parsed) return { r: 255, g: 255, b: 255, alpha: 1 }; - return { - r: parsed.rgb[0], - g: parsed.rgb[1], - b: parsed.rgb[2], - alpha: parsed.alpha, - }; -} - function clampChannel(value: number): number { return Math.round(Math.max(0, Math.min(255, value))); } @@ -76,14 +65,6 @@ export function shadeBrushColor( // came out ~π× brighter than the polygon-path shading for the same // light + base color (visible as blown-out voxel scenes vs polygon // scenes side by side). - const shaded = shadePolygon(baseColor, directScale, lightColor, ambientColor, ambientIntensity); - // Preserve alpha when the source had it (rare but supported for - // translucent voxels). shadePolygon returns a hex string; if the input - // had non-1 alpha, re-attach it via rgba(...). - const base = parseColor(baseColor); - if (base.alpha >= 1) return shaded; - const r = parseInt(shaded.slice(1, 3), 16); - const g = parseInt(shaded.slice(3, 5), 16); - const b = parseInt(shaded.slice(5, 7), 16); - return `rgba(${r}, ${g}, ${b}, ${base.alpha})`; + // shadePolygon already preserves non-1 alpha as `rgba(r, g, b, alpha)`. + return shadePolygon(baseColor, directScale, lightColor, ambientColor, ambientIntensity); } diff --git a/packages/polycss/src/runtime.ts b/packages/polycss/src/runtime.ts index e94ed3a16..6bbbbcb16 100644 --- a/packages/polycss/src/runtime.ts +++ b/packages/polycss/src/runtime.ts @@ -97,9 +97,7 @@ export { packTextureAtlasPlansWithScale, renderPolygonsWithStableTriangles, renderPolygonsWithTextureAtlas, - renderPolygonsWithTextureAtlasAsync, updatePolygonsWithStableTopology, - updatePolygonsWithStableTriangles, updateStableTriangleFrame, } from "./render/textureAtlas"; export type { @@ -109,7 +107,6 @@ export type { PackedTextureAtlasEntry, PolyRenderStrategiesOption, PolyRenderStrategy, - RenderTextureAtlasAsyncResult, RenderTextureAtlasOptions, RenderTextureAtlasResult, RenderedPoly, diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 3a6595d60..c8ef47c27 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -126,7 +126,11 @@ export type { Polygon, PolyMaterial, PolyDirectionalLight, + PolyPointLight, PolyAmbientLight, + PolySeamBleed, + PolySeamBleedEdgeValue, + PolySeamBleedEdges, PolyTextureLightingMode, PolyTextureLeafSizing, PolyTextureBackend, @@ -172,7 +176,9 @@ export type { BoxPolygonsOptions, ArrowPolygonsOptions, RingPolygonsOptions, + RingQuadPolygonsOptions, OctahedronPolygonsOptions, + SpherePolygonsOptions, TetrahedronPolygonsOptions, IcosahedronPolygonsOptions, DodecahedronPolygonsOptions, @@ -187,16 +193,8 @@ export type { ParseStlSolid, ParseStlTopology, SolidTextureSampleOptions, - TexturePaintMetrics, - TexturePaintMetricsOptions, CoverPlanarPolygonsOptions, CullInteriorOptions, - SeamFacetSplitCandidate, - SeamFacetSplitCandidateReason, - SeamFacetSplitOptions, - SeamFacetSplitReport, - SeamOverlapCandidate, - SeamOverlapCandidateKind, SeamOverlapDiagnostics, SeamOverlapOptions, CameraCullNormalGroup, @@ -216,12 +214,7 @@ export { optimizeMeshPolygons, optimizeMeshParseResult, simplifyTriangleMeshPolygons, - repairMeshSeams, - seamFacetSplitPolygons, - seamFacetSplitReport, seamOverlapDiagnostics, - seamOverlapPolygons, - seamOverlapReport, cullInteriorPolygons, cameraCullNormalGroups, cameraCullNormalGroupsFromPolygons, @@ -238,27 +231,25 @@ export { parseGltf, parseStl, bakeSolidTextureSamples, - bakeSolidTextureSampledPolygons, loadMesh, createIsometricCamera, parseVox, polygonFaces, - computeTexturePaintMetrics, - computeShapeLighting, parseColor, parsePureColor, parseHexColor, parseRgbColor, formatColor, clampChannel, - shadeColor, rotateVec3, inverseRotateVec3, axesHelperPolygons, boxPolygons, arrowPolygons, ringPolygons, + ringQuadPolygons, octahedronPolygons, + spherePolygons, tetrahedronPolygons, icosahedronPolygons, dodecahedronPolygons, @@ -284,16 +275,13 @@ export { worldPositionToPolyCss, BASE_TILE, DEFAULT_CAMERA_STATE, - DEFAULT_PROJECTION, POLY_DEFAULT_SHADOW_LIFT, - normalizeInvertMultiplier, buildPolyCameraSceneTransform, capturePolyCameraSnapshot, polyCameraTargetToCss, resolvePolyCameraAppliedPerspectiveStyle, createPolyAnimationMixer, optimizeAnimatedMeshPolygons, - DEFAULT_SEAM_FACET_SPLIT_OPTIONS, DEFAULT_SEAM_OVERLAP_OPTIONS, LoopOnce, LoopRepeat, diff --git a/packages/react/src/scene/PolyMesh.tsx b/packages/react/src/scene/PolyMesh.tsx index 1ac1feeb5..ce7d0cd53 100644 --- a/packages/react/src/scene/PolyMesh.tsx +++ b/packages/react/src/scene/PolyMesh.tsx @@ -51,6 +51,8 @@ import { import { recenterPolygons, useMeshGeometry } from "./mesh/useMeshGeometry"; import { useMeshEvents } from "./mesh/useMeshEvents"; +const useIsomorphicLayoutEffect = typeof document !== "undefined" ? useLayoutEffect : useEffect; + export interface PolyMeshProps extends TransformProps, InteractionProps { /** Stable identifier — exposed on the mesh handle and reflected as `data-poly-mesh-id`. */ id?: string; @@ -337,7 +339,7 @@ export const PolyMesh = forwardRef(function PolyM atomicAtlas: boolean; onFrameReady: PolyMeshProps["onFrameReady"]; } | null>(null); - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const el = wrapperRef.current; const teardown = () => { const existing = runtimeMeshRef.current; @@ -436,13 +438,13 @@ export const PolyMesh = forwardRef(function PolyM // Re-apply `.polycss-voxel-mesh` when React updates `className` on an adopted // direct-voxel wrapper (voxelRenderer attaches that class imperatively). - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { restoreVoxelMeshClass(wrapperRef.current); }, [className, isLoadingSlot, isErrorSlot]); // Sync polygon array updates without tearing down the mesh entry. const mountedPolygonsRef = useRef(null); - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const mesh = runtimeMeshRef.current; if (!mesh) { mountedPolygonsRef.current = null; @@ -461,7 +463,7 @@ export const PolyMesh = forwardRef(function PolyM }, [polygons, atomicAtlas, runtimeSceneSlot, activeVoxelSource, renderPolygon !== null, isLoadingSlot, isErrorSlot]); // Sync transform, shadow, and per-mesh render override prop updates. - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const mesh = runtimeMeshRef.current; if (!mesh) { appliedTransformRef.current = null; @@ -557,7 +559,7 @@ export const PolyMesh = forwardRef(function PolyM // Standalone fallback when `` is rendered outside `` // (e.g. isolated unit tests). - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const el = wrapperRef.current; if (sceneCtx || runtimeScene || !el || renderPolygon || isLoadingSlot || isErrorSlot) { clearOwnedDomNodes(standaloneOwnedRef.current); @@ -571,6 +573,7 @@ export const PolyMesh = forwardRef(function PolyM textureImageRendering, textureBackend, textureProjection, + seamBleed, }); standaloneReadyRef.current = mounted.ready; return () => mounted.dispose(); diff --git a/packages/react/src/scene/PolyScene.tsx b/packages/react/src/scene/PolyScene.tsx index e6027b3b4..6fd1b6a29 100644 --- a/packages/react/src/scene/PolyScene.tsx +++ b/packages/react/src/scene/PolyScene.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback, useLayoutEffect, useMemo, useRef } from "react"; +import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"; import type { CSSProperties, ReactNode } from "react"; import type { Polygon, @@ -14,7 +14,7 @@ import type { PolyTextureProjection, } from "@layoutit/polycss-core"; import { DEFAULT_SEAM_BLEED } from "@layoutit/polycss-core"; -import { adaptFallbackCamera } from "@layoutit/polycss/internal"; +import { adaptFallbackCamera, shadowOptionKey } from "@layoutit/polycss/internal"; import { createPolyScene, injectPolyBaseStyles, @@ -26,6 +26,8 @@ import { import { useCameraContext } from "../camera/context"; import { PolySceneContext } from "./sceneContext"; +const useIsomorphicLayoutEffect = typeof document !== "undefined" ? useLayoutEffect : useEffect; + export interface PolySceneProps { /** Polygons to render directly on the scene root. Composes additively with `children`. */ polygons?: Polygon[]; @@ -119,24 +121,15 @@ function PolySceneInner({ // Field-wise stable shadow identity so inline `shadow={{...}}` objects don't // trigger unnecessary shadow cache invalidations on parent re-renders. + const shadowKey = shadowOptionKey(shadow); const stableShadow = useMemo( () => shadow, // eslint-disable-next-line react-hooks/exhaustive-deps - [ - shadow?.color, - shadow?.opacity, - shadow?.lift, - shadow?.maxExtend, - shadow?.parametric, - shadow?.definition, - shadow?.dragDefinition, - shadow?.style, - shadow?.followAnimation, - ], + [shadowKey], ); // Mount and adopt the React-owned cameraEl + sceneEl into @layoutit/polycss/runtime. - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const sceneEl = localSceneElRef.current; if (!sceneEl) return; const doc = sceneEl.ownerDocument ?? (typeof document !== "undefined" ? document : undefined); @@ -189,7 +182,7 @@ function PolySceneInner({ }, [cameraElRef, cameraRef, runtimeCameraRef, runtimeSceneRef, runtimeSceneSlot, store]); // Sync scene-level options into the adopted runtime scene. - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const scene = runtimeSceneSlot.current; if (!scene) return; scene.setOptions({ @@ -227,7 +220,7 @@ function PolySceneInner({ ]); // Sync explicit autoCenter source polygons (centerPolygons ?? polygons). - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const scene = runtimeSceneSlot.current; if (!scene) return; const source = centerPolygonsProp ?? (polygonsProp && polygonsProp.length > 0 ? polygonsProp : null); @@ -238,7 +231,7 @@ function PolySceneInner({ // Sync direct `` geometry onto sceneEl without an // extra wrapper div (isSceneRootWrapper keeps sceneEl transform & classes intact). - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const scene = runtimeSceneSlot.current; const sceneEl = localSceneElRef.current; if (!scene || !sceneEl) return; @@ -269,7 +262,7 @@ function PolySceneInner({ }, [runtimeSceneSlot, polygonsProp]); // Keep camera transform synchronized after React commits (e.g. if style prop changed). - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { applyTransformDirect(); }); diff --git a/packages/react/src/store/sceneStore.ts b/packages/react/src/store/sceneStore.ts index 9f5706b76..3705ace67 100644 --- a/packages/react/src/store/sceneStore.ts +++ b/packages/react/src/store/sceneStore.ts @@ -91,5 +91,5 @@ export function useStoreSelector( const getSnapshot = useCallback(() => selectorRef.current(store.getState()), [store]); - return useSyncExternalStore(store.subscribe, getSnapshot); + return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot); } diff --git a/packages/react/src/three/PolyThreeOrthographicCamera.test.tsx b/packages/react/src/three/PolyThreeOrthographicCamera.test.tsx index 1b79f3f9f..d770fe42c 100644 --- a/packages/react/src/three/PolyThreeOrthographicCamera.test.tsx +++ b/packages/react/src/three/PolyThreeOrthographicCamera.test.tsx @@ -41,6 +41,7 @@ describe("PolyThreeOrthographicCamera", () => { expect(camEl?.getAttribute("data-polycss-camera-projection")).toBe("orthographic"); expect(camEl?.getAttribute("data-polycss-camera-perspective")).toBe("none"); expect(camEl?.getAttribute("data-polycss-camera-applied-perspective")).toBe("1000000px"); + expect(camEl?.style.perspective).toBe("1000000px"); expect(container.querySelector(".polycss-scene")).toBeTruthy(); expect(container.querySelector(".polycss-mesh")).toBeTruthy(); act(() => root.unmount()); diff --git a/packages/react/src/three/PolyThreeOrthographicCamera.tsx b/packages/react/src/three/PolyThreeOrthographicCamera.tsx index cff7d044d..9e07ddf6e 100644 --- a/packages/react/src/three/PolyThreeOrthographicCamera.tsx +++ b/packages/react/src/three/PolyThreeOrthographicCamera.tsx @@ -104,7 +104,7 @@ function PolyThreeOrthographicCameraInner({
` component exists. In a -React or Vue app import them from `@layoutit/polycss-core`. +`ringQuadPolygons`, `spherePolygons`, `cylinderPolygons`, `conePolygons`, +`torusPolygons`, `tetrahedronPolygons`, `octahedronPolygons`, +`icosahedronPolygons`, `dodecahedronPolygons`, `axesHelperPolygons`, +`arrowPolygons`. ## Optimizer and mesh ops (all packages) `optimizeMeshPolygons`, `optimizeMeshParseResult`, `optimizeAnimatedMeshPolygons`, `mergePolygons`, `cullInteriorPolygons`, -`simplifyTriangleMeshPolygons`, `coverPlanarPolygons`, `repairMeshSeams`, -`bakeSolidTextureSamples`, `bakeSolidTextureSampledPolygons`, -`seamOverlapDiagnostics`, `seamOverlapPolygons`, `seamFacetSplitPolygons`. +`simplifyTriangleMeshPolygons`, `coverPlanarPolygons`, +`bakeSolidTextureSamples`, `seamOverlapDiagnostics`. ## Camera and coordinate math (all packages) @@ -123,8 +118,8 @@ From `@layoutit/polycss-core`, `@layoutit/polycss`, `-react` and `-vue`: `collectPolyRenderStats`, `collectPolyTextureReadiness`, `queryPolyLeaves`. From the renderer packages only: `injectPolyBaseStyles`. -React and Vue only: `findPolyMeshHandle`, `pointInMeshElement`, -`findMeshUnderPoint`. Vanilla has no exported equivalent. +Hit-testing: `pointInMeshElement` (vanilla, React, and Vue); +`findPolyMeshHandle` and `findMeshUnderPoint` (React and Vue). Texture resolution (from `@layoutit/polycss-core` or `@layoutit/polycss`, **not** the React/Vue indexes): `resolvePolyTextureLeafGeometry`, @@ -141,12 +136,10 @@ constants `LoopOnce`, `LoopRepeat`, `LoopPingPong`. Geometry: `Vec2`, `Vec3`, `Polygon`, `PolyMaterial`, `ParseResult`, `MeshResolution`. -Lights: `PolyDirectionalLight`, `PolyAmbientLight` (all packages). -`PolyPointLight` is narrower: `@layoutit/polycss-core`, `@layoutit/polycss`, and -`@layoutit/polycss/three` only. It is **not** re-exported by +Lights: `PolyDirectionalLight`, `PolyPointLight`, `PolyAmbientLight` (all +packages). `PolyPointLight` is also on `@layoutit/polycss/three` (not on `@layoutit/polycss-core/three`, `@layoutit/polycss-react/three`, or -`@layoutit/polycss-vue/three`, and React and Vue accept the `pointLights` prop -without exporting the type — take it from `@layoutit/polycss-core`. +`@layoutit/polycss-vue/three`). Texture: `PolyTextureLightingMode`, `PolyTextureLeafSizing`, `PolyTextureBackend`, `PolyTextureImageRendering`, `PolyTextureImageLighting`, diff --git a/packages/skills/skill/docs/lighting.md b/packages/skills/skill/docs/lighting.md index 49b2ac8ec..8162d5040 100644 --- a/packages/skills/skill/docs/lighting.md +++ b/packages/skills/skill/docs/lighting.md @@ -93,8 +93,8 @@ Three-parity baseline. ## Per-mesh override -React/Vue expose `textureLighting` as a `` prop. Vanilla meshes -inherit the scene value. +`textureLighting` can be overridden per mesh on both `` and vanilla +`scene.add(result, { textureLighting })`. ## Example diff --git a/packages/skills/skill/docs/scenes-and-cameras.md b/packages/skills/skill/docs/scenes-and-cameras.md index ded2b32e4..3466b10b7 100644 --- a/packages/skills/skill/docs/scenes-and-cameras.md +++ b/packages/skills/skill/docs/scenes-and-cameras.md @@ -84,27 +84,27 @@ bleed and sub-`1.5` values shrink them proportionally. | `position` | `Vec3` | Offset in scene space. | | `scale` | `number \| Vec3` | | | `rotation` | `Vec3` | Euler **degrees** `[x, y, z]`. | -| `autoCenter` | `boolean` | **Not a vanilla `scene.add` option** — it is a `` prop and a `` attribute only. Shifts the mesh so its bbox center sits at the local origin before `position`. (The scene-level `autoCenter` above is a different, unrelated option.) | +| `autoCenter` | `boolean` | Supported in `scene.add`, ``, and ``. Shifts the mesh so its bbox center sits at the local origin before `position`. (The scene-level `autoCenter` above is a different, unrelated option.) | | `castShadow` / `receiveShadow` | `boolean` | See [shadows.md](shadows.md). | | `merge` | `boolean` | Default `true`. `false` renders the array entering the renderer exactly as given. | | `meshResolution` | `"lossy" \| "lossless"` | Default `"lossy"`. | | `stableDom` | `boolean` | Vanilla only; needed for skeletal animation. | | `shadowDefinition` | `number` | Per-mesh parametric shadow detail. | -| `excludeFromAutoCenter` | `boolean` | **Vanilla only, and a `scene.add(result, transform)` option** — there is no React/Vue prop. Keeps this mesh out of the scene's auto-center bbox, for helpers and debug overlays. | +| `excludeFromAutoCenter` | `boolean` | Supported in `scene.add`, ``, ``, and all primitive shape elements. Keeps this mesh out of the scene's auto-center bbox, for helpers and debug overlays. | -React/Vue additionally expose per-mesh `textureLighting`, `textureQuality`, -`textureLeafSizing`, `textureImageRendering`, `textureBackend`, -`textureProjection`, `seamBleed`, `atomicAtlas`, and `onFrameReady`. Vanilla -meshes inherit the scene values for those. +Per-mesh overrides `textureLighting`, `textureQuality`, `textureLeafSizing`, +`textureImageRendering`, `textureBackend`, `textureProjection`, `seamBleed`, +`atomicAtlas`, and `onFrameReady` are available on both `scene.add(result, +transform)` and ``. ## Custom element caveats `` supports `directional-*`, `ambient-*`, `texture-lighting`, `texture-quality`, `texture-leaf-sizing`, `texture-image-rendering`, `texture-backend`, `texture-projection`, `auto-center`, and the implicit-camera -attributes. Only `perspective`, `rot-x`, `rot-y`, and `zoom` are *observed* — -mutating `distance` or `target` alone does not update the implicit camera. -`perspective` only selects the camera type at connect time. Use the imperative +attributes (`perspective`, `rot-x`, `rot-y`, `zoom`, `distance`, `target`). +`rot-x`, `rot-y`, `zoom`, `distance`, and `target` update the implicit camera +live; `perspective` selects the camera type at connect time. Use the imperative API for `shadow`, `seamBleed`, and `strategies`. `` supports `src`, `mtl`, `mesh-resolution`, `position`, `scale`, diff --git a/packages/skills/skill/docs/shapes-and-primitives.md b/packages/skills/skill/docs/shapes-and-primitives.md index b955a6e8d..d73bf7d2a 100644 --- a/packages/skills/skill/docs/shapes-and-primitives.md +++ b/packages/skills/skill/docs/shapes-and-primitives.md @@ -9,9 +9,7 @@ Three layers, same geometry: | Components | `` / `` | Mounted mesh | Core generators are exported from every package (`@layoutit/polycss`, `-react`, -`-vue`, `-core`) with two exceptions: **`spherePolygons` and `ringQuadPolygons` -are not re-exported by React or Vue** — import those from -`@layoutit/polycss-core`, which both framework packages already depend on. Use +`-vue`, `-core`), including `spherePolygons` and `ringQuadPolygons`. Use generators when you want raw arrays to post-process. ## Options and defaults @@ -139,8 +137,7 @@ The cap at 3 is deliberate — DOM cost. ### Other generators -`axesHelperPolygons` and `arrowPolygons` (all packages), plus `ringQuadPolygons` -(core and `@layoutit/polycss` only — see the note at the top). +`axesHelperPolygons`, `arrowPolygons`, and `ringQuadPolygons` (all packages). ## Usage diff --git a/packages/skills/skill/docs/troubleshooting.md b/packages/skills/skill/docs/troubleshooting.md index cec96751a..9044c9f1b 100644 --- a/packages/skills/skill/docs/troubleshooting.md +++ b/packages/skills/skill/docs/troubleshooting.md @@ -31,7 +31,6 @@ is simply wrong or absent. Work the symptom table before adding instrumentation. | A direct image leaf ignores scene lighting | By design — direct image leaves are source-lit. Use the atlas backend for scene lighting. | | `PolyScene` throws | It must be nested inside a camera component. | | The scene is invisible / flat / wrong scale | Check camera nesting (camera outer, scene inner), then `zoom` (CSS px per world unit, default `0.65`) and `targetSize`. | -| `` or `target` changes do nothing | Only `perspective`, `rot-x`, `rot-y`, `zoom` are observed on the implicit camera. Change one of those, or use the imperative API. | | `` change does nothing | Read at load only. | | Per-polygon click handlers stopped firing after a change | Polygons got merged into one leaf. Use `merge: false`. | | Animation plays but the mesh flickers or re-mounts | Topology is not stable. Vanilla needs `{ merge: false, stableDom: true }`; React/Vue need `meshResolution="lossless"` / `merge={false}`. | diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index 62241404c..b49f0eec3 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -117,7 +117,11 @@ export type { Vec2, Vec3, PolyDirectionalLight, + PolyPointLight, PolyAmbientLight, + PolySeamBleed, + PolySeamBleedEdgeValue, + PolySeamBleedEdges, PolyTextureLightingMode, PolyTextureLeafSizing, PolyTextureBackend, @@ -163,7 +167,9 @@ export type { BoxPolygonsOptions, ArrowPolygonsOptions, RingPolygonsOptions, + RingQuadPolygonsOptions, OctahedronPolygonsOptions, + SpherePolygonsOptions, TetrahedronPolygonsOptions, IcosahedronPolygonsOptions, DodecahedronPolygonsOptions, @@ -178,16 +184,8 @@ export type { ParseStlSolid, ParseStlTopology, SolidTextureSampleOptions, - TexturePaintMetrics, - TexturePaintMetricsOptions, CoverPlanarPolygonsOptions, CullInteriorOptions, - SeamFacetSplitCandidate, - SeamFacetSplitCandidateReason, - SeamFacetSplitOptions, - SeamFacetSplitReport, - SeamOverlapCandidate, - SeamOverlapCandidateKind, SeamOverlapDiagnostics, SeamOverlapOptions, CameraCullNormalGroup, @@ -207,12 +205,7 @@ export { optimizeMeshPolygons, optimizeMeshParseResult, simplifyTriangleMeshPolygons, - repairMeshSeams, - seamFacetSplitPolygons, - seamFacetSplitReport, seamOverlapDiagnostics, - seamOverlapPolygons, - seamOverlapReport, cullInteriorPolygons, cameraCullNormalGroups, cameraCullNormalGroupsFromPolygons, @@ -229,27 +222,25 @@ export { parseGltf, parseStl, bakeSolidTextureSamples, - bakeSolidTextureSampledPolygons, loadMesh, createIsometricCamera, parseVox, polygonFaces, - computeTexturePaintMetrics, - computeShapeLighting, parseColor, parsePureColor, parseHexColor, parseRgbColor, formatColor, clampChannel, - shadeColor, rotateVec3, inverseRotateVec3, axesHelperPolygons, boxPolygons, arrowPolygons, ringPolygons, + ringQuadPolygons, octahedronPolygons, + spherePolygons, tetrahedronPolygons, icosahedronPolygons, dodecahedronPolygons, @@ -275,16 +266,13 @@ export { worldPositionToPolyCss, BASE_TILE, DEFAULT_CAMERA_STATE, - DEFAULT_PROJECTION, POLY_DEFAULT_SHADOW_LIFT, - normalizeInvertMultiplier, buildPolyCameraSceneTransform, capturePolyCameraSnapshot, polyCameraTargetToCss, resolvePolyCameraAppliedPerspectiveStyle, createPolyAnimationMixer, optimizeAnimatedMeshPolygons, - DEFAULT_SEAM_FACET_SPLIT_OPTIONS, DEFAULT_SEAM_OVERLAP_OPTIONS, LoopOnce, LoopRepeat, diff --git a/packages/vue/src/scene/PolyMesh.ts b/packages/vue/src/scene/PolyMesh.ts index a119b773a..65c237fe6 100644 --- a/packages/vue/src/scene/PolyMesh.ts +++ b/packages/vue/src/scene/PolyMesh.ts @@ -288,6 +288,7 @@ export const PolyMesh = defineComponent({ textureImageRendering: props.textureImageRendering, textureBackend: props.textureBackend, textureProjection: props.textureProjection, + seamBleed: props.seamBleed, }); standaloneDispose = mounted.dispose; standaloneReady = mounted.ready; diff --git a/packages/vue/src/scene/PolyScene.ts b/packages/vue/src/scene/PolyScene.ts index 6ed09ff6d..c4fffbdca 100644 --- a/packages/vue/src/scene/PolyScene.ts +++ b/packages/vue/src/scene/PolyScene.ts @@ -37,7 +37,7 @@ import { type PolyShadowOptions, type TextureQuality, } from "@layoutit/polycss/runtime"; -import { adaptFallbackCamera } from "@layoutit/polycss/internal"; +import { adaptFallbackCamera, shadowOptionKey } from "@layoutit/polycss/internal"; import { PolyCameraContextKey } from "../camera"; import { PolySceneContextKey } from "./sceneContext"; @@ -105,19 +105,7 @@ export const PolyScene = defineComponent({ let lastShadowKey: string | undefined; const stableShadow = computed(() => { const next = props.shadow; - const key = next - ? [ - next.color, - next.opacity, - next.lift, - next.maxExtend, - next.parametric, - next.definition, - next.dragDefinition, - next.style, - next.followAnimation, - ].join("|") - : ""; + const key = shadowOptionKey(next); if (key === lastShadowKey) return lastShadow; lastShadowKey = key; lastShadow = next; diff --git a/packages/vue/src/scene/useMesh.ts b/packages/vue/src/scene/useMesh.ts index c1c9530eb..f5a231cb4 100644 --- a/packages/vue/src/scene/useMesh.ts +++ b/packages/vue/src/scene/useMesh.ts @@ -72,6 +72,11 @@ export function usePolyMesh(src: Ref, options?: UseMeshOptions): UseMesh return; } + if (typeof window === "undefined") { + // Pure Node SSR: keep loading state without firing network requests. + return; + } + let cancelled = false; loading.value = true; diff --git a/packages/vue/src/shapes/PolyShapes.test.ts b/packages/vue/src/shapes/PolyShapes.test.ts index ad059d74e..3512be55d 100644 --- a/packages/vue/src/shapes/PolyShapes.test.ts +++ b/packages/vue/src/shapes/PolyShapes.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, afterEach, vi } from "vitest"; -import { createApp, h } from "vue"; +import { createApp, h, ref } from "vue"; +import type { PolyMeshHandle } from "../scene/events"; import { PolyCamera } from "../camera/PolyCamera"; import { PolyScene } from "../scene/PolyScene"; import { @@ -22,7 +23,10 @@ afterEach(() => { document.body.innerHTML = ""; }); -function renderShape(shapeVNode: ReturnType): HTMLElement { +function renderShape( + shapeVNode: ReturnType | (() => ReturnType), + sceneProps: Record = {}, +): HTMLElement { const container = document.createElement("div"); document.body.appendChild(container); const app = createApp({ @@ -30,8 +34,8 @@ function renderShape(shapeVNode: ReturnType): HTMLElement { return () => h(PolyCamera, {}, { default: () => - h(PolyScene, {}, { - default: () => shapeVNode, + h(PolyScene, sceneProps, { + default: () => (typeof shapeVNode === "function" ? shapeVNode() : shapeVNode), }), }); }, @@ -61,6 +65,47 @@ describe("PolyBox (Vue)", () => { expect(full.querySelectorAll("i,b,s,u")).toHaveLength(3); expect(withoutTop.querySelectorAll("i,b,s,u")).toHaveLength(2); }); + + it("forwards PolyMesh attrs, class, click handlers, ref handle, and default slot children", () => { + const onClick = vi.fn(); + const boxRef = ref(null); + // Compile-time type check: PolyBox $props must expose full ShapeMeshProps. + const typedCheck: Partial["$props"]> = { + size: 100, + castShadow: true, + receiveShadow: false, + seamBleed: 0, + merge: true, + textureLighting: "baked", + onClick, + }; + expect(typedCheck.castShadow).toBe(true); + const container = renderShape( + () => + h( + PolyBox, + { + ref: boxRef, + size: 100, + color: "#ff6644", + castShadow: true, + class: "custom-vue-box", + onClick, + }, + { default: () => h("span", { class: "slot-child" }, "label") }, + ), + { directionalLight: { direction: [0.4, -0.7, 0.59], intensity: 1 } }, + ); + const meshEl = container.querySelector(".polycss-mesh") as HTMLElement | null; + expect(meshEl?.classList.contains("custom-vue-box")).toBe(true); + expect(container.querySelector(".slot-child")?.textContent).toBe("label"); + expect(container.querySelector("svg.polycss-shadow")).not.toBeNull(); + expect(typeof boxRef.value?.rebakeAtlas).toBe("function"); + expect(boxRef.value?.element).toBe(meshEl); + const leaf = container.querySelector("i,b,s,u") as HTMLElement | null; + leaf?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(onClick).toHaveBeenCalledTimes(1); + }); }); describe("PolyPlane (Vue)", () => { diff --git a/packages/vue/src/shapes/PolyShapes.ts b/packages/vue/src/shapes/PolyShapes.ts index b20ef0157..5dcf8e4a2 100644 --- a/packages/vue/src/shapes/PolyShapes.ts +++ b/packages/vue/src/shapes/PolyShapes.ts @@ -1,13 +1,14 @@ /** * Primitive shape components — thin wrappers over the polygon generators in * @layoutit/polycss-core. Each component calls the matching `xPolygons()` - * generator and passes the result to ``. + * generator and forwards all remaining PolyMesh props, listeners, class/style, + * slots, and imperative handle methods to ``. * * Props are flat (shape geometry + common PolyMesh props). No geometry/material * split — a Polygon carries its own color/texture. */ -import { computed, defineComponent, h } from "vue"; -import type { PropType } from "vue"; +import { computed, defineComponent, h, ref } from "vue"; +import type { ComponentObjectPropsOptions, ExtractPropTypes, PropType, SlotsType } from "vue"; import { boxPolygons, planePolygons, @@ -33,27 +34,129 @@ import type { CylinderPolygonsOptions, ConePolygonsOptions, TorusPolygonsOptions, + MeshResolution, PolyMaterial, + PolySeamBleed, + PolyTextureBackend, + PolyTextureImageRendering, + PolyTextureLeafSizing, + PolyTextureLightingMode, + PolyTextureProjection, + Polygon, Vec2, Vec3, } from "@layoutit/polycss-core"; +import type { TextureQuality } from "@layoutit/polycss/runtime"; import { PolyMesh } from "../scene/PolyMesh"; import type { PolyMeshProps } from "../scene/PolyMesh"; +import type { PolyEventHandler, PolyMeshHandle } from "../scene/events"; +import type { UseMeshOptions } from "../scene/useMesh"; -// ── Shared mesh prop pass-through helpers ──────────────────────────────────── -// We spread the mesh-compatible props without src/mtl/polygons (those are -// controlled by the shape component). Vue doesn't allow direct key exclusion -// from interfaces, so we pick explicit passes through `attrs` where needed. +// Shared mesh props — strip polygon-source props controlled by the shape component. type ShapeMeshProps = Omit; +const SHAPE_MESH_PROPS = { + id: { type: String, default: undefined }, + autoCenter: { type: Boolean, default: false }, + excludeFromAutoCenter: { type: Boolean, default: false }, + textureLighting: { type: String as PropType, default: undefined }, + textureQuality: { type: [Number, String] as PropType, default: undefined }, + textureLeafSizing: { type: String as PropType, default: undefined }, + textureImageRendering: { type: String as PropType, default: undefined }, + textureBackend: { type: String as PropType, default: undefined }, + textureProjection: { type: String as PropType, default: undefined }, + seamBleed: { type: [Number, String] as PropType, default: undefined }, + atomicAtlas: { type: Boolean as PropType, default: false }, + onFrameReady: { type: Function as PropType<() => void>, default: undefined }, + castShadow: { type: Boolean as PropType, default: false }, + receiveShadow: { type: Boolean as PropType, default: false }, + shadowDefinition: { type: Number as PropType, default: undefined }, + merge: { type: Boolean as PropType, default: true }, + meshResolution: { type: String as PropType, default: undefined }, + parseOptions: { type: Object as PropType, default: undefined }, + class: { type: String, default: undefined }, + position: { type: Array as unknown as PropType, default: undefined }, + scale: { type: [Number, Array] as unknown as PropType, default: undefined }, + rotation: { type: Array as unknown as PropType, default: undefined }, + onClick: { type: Function as PropType>, default: undefined }, + onContextMenu: { type: Function as PropType>, default: undefined }, + onDoubleClick: { type: Function as PropType>, default: undefined }, + onWheel: { type: Function as PropType>, default: undefined }, + onPointerDown: { type: Function as PropType>, default: undefined }, + onPointerUp: { type: Function as PropType>, default: undefined }, + onPointerMove: { type: Function as PropType>, default: undefined }, + onPointerOver: { type: Function as PropType>, default: undefined }, + onPointerOut: { type: Function as PropType>, default: undefined }, + onPointerEnter: { type: Function as PropType>, default: undefined }, + onPointerLeave: { type: Function as PropType>, default: undefined }, + onPointerCancel: { type: Function as PropType>, default: undefined }, +} as const; + +const SHAPE_MESH_PROP_KEYS = Object.keys(SHAPE_MESH_PROPS) as Array; +const RESOLVED_PROMISE = Promise.resolve(); + +function definePolyShape( + name: string, + shapeProps: TShapeProps, + buildPolygons: (props: Readonly>) => Polygon[], +) { + return defineComponent({ + name, + inheritAttrs: false, + slots: Object as SlotsType<{ + default?: Record; + polygon?: { polygon: Polygon; index: number }; + }>, + props: { + ...SHAPE_MESH_PROPS, + ...shapeProps, + } as typeof SHAPE_MESH_PROPS & TShapeProps, + setup(props, { attrs, slots, expose }) { + const meshRef = ref(null); + const polygons = computed(() => + buildPolygons(props as unknown as Readonly>), + ); + const forwardedHandle: PolyMeshHandle = { + get element() { return meshRef.value?.element ?? null; }, + get id() { return meshRef.value?.id; }, + getPosition: () => meshRef.value?.getPosition(), + getRotation: () => meshRef.value?.getRotation(), + getScale: () => meshRef.value?.getScale(), + getPolygons: () => meshRef.value?.getPolygons() ?? polygons.value, + setPolygons: (next) => meshRef.value?.setPolygons(next), + rebakeAtlas: () => meshRef.value?.rebakeAtlas(), + whenTexturesReady: () => meshRef.value?.whenTexturesReady() ?? RESOLVED_PROMISE, + updatePolygon: (target, partial) => meshRef.value?.updatePolygon(target, partial), + }; + expose(forwardedHandle); + return () => { + const restAttrs: Record = {}; + for (const [key, value] of Object.entries(attrs)) { + if (key === "src" || key === "mtl" || key === "polygons") continue; + restAttrs[key] = value; + } + const meshProps: Record = { + ...restAttrs, + ref: meshRef, + polygons: polygons.value, + }; + const rawProps = props as Record; + for (const key of SHAPE_MESH_PROP_KEYS) { + if (rawProps[key] !== undefined) meshProps[key] = rawProps[key]; + } + return h(PolyMesh, meshProps, slots); + }; + }, + }); +} + // ── Fixed-geometry primitives ───────────────────────────────────────────────── export interface PolyBoxProps extends ShapeMeshProps, BoxPolygonsOptions {} -export const PolyBox = defineComponent({ - name: "PolyBox", - props: { - // BoxPolygonsOptions +export const PolyBox = definePolyShape( + "PolyBox", + { size: { type: [Number, Array] as PropType, default: undefined }, center: { type: Array as unknown as PropType, default: undefined }, min: { type: Array as unknown as PropType, default: undefined }, @@ -64,182 +167,93 @@ export const PolyBox = defineComponent({ uvs: { type: Array as PropType, default: undefined }, data: { type: Object as PropType, default: undefined }, faces: { type: Object as PropType, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, - }, - setup(props) { - const polygons = computed(() => - boxPolygons({ - size: props.size as number | Vec3 | undefined, - center: props.center, - min: props.min, - max: props.max, - color: props.color, - texture: props.texture, - material: props.material, - uvs: props.uvs, - data: props.data, - faces: props.faces, - }), - ); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); }, -}); + (props) => + boxPolygons({ + size: props.size as number | Vec3 | undefined, + center: props.center, + min: props.min, + max: props.max, + color: props.color, + texture: props.texture, + material: props.material, + uvs: props.uvs, + data: props.data, + faces: props.faces, + }), +); export interface PolyPlaneProps extends ShapeMeshProps, PlanePolygonsOptions {} -export const PolyPlane = defineComponent({ - name: "PolyPlane", - props: { - axis: { type: Number as PropType<0 | 1 | 2>, required: true }, +export const PolyPlane = definePolyShape( + "PolyPlane", + { + axis: { type: Number as PropType<0 | 1 | 2>, required: true as const }, size: { type: Number, default: undefined }, offset: { type: [Number, Array] as unknown as PropType, default: undefined }, along: { type: Number, default: undefined }, color: { type: String, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, }, - setup(props) { - const polygons = computed(() => - planePolygons({ - axis: props.axis, - size: props.size, - offset: props.offset, - along: props.along, - color: props.color, - }), - ); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); - }, -}); + (props) => + planePolygons({ + axis: props.axis, + size: props.size, + offset: props.offset, + along: props.along, + color: props.color, + }), +); export interface PolyRingProps extends ShapeMeshProps, RingPolygonsOptions {} -export const PolyRing = defineComponent({ - name: "PolyRing", - props: { - axis: { type: Number as PropType<0 | 1 | 2>, required: true }, - radius: { type: Number, required: true }, +export const PolyRing = definePolyShape( + "PolyRing", + { + axis: { type: Number as PropType<0 | 1 | 2>, required: true as const }, + radius: { type: Number, required: true as const }, halfThickness: { type: Number, default: undefined }, segments: { type: Number, default: undefined }, color: { type: String, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, - }, - setup(props) { - const polygons = computed(() => - ringPolygons({ - axis: props.axis, - radius: props.radius, - halfThickness: props.halfThickness, - segments: props.segments, - color: props.color, - }), - ); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); }, -}); + (props) => + ringPolygons({ + axis: props.axis, + radius: props.radius, + halfThickness: props.halfThickness, + segments: props.segments, + color: props.color, + }), +); export interface PolyOctahedronProps extends ShapeMeshProps, OctahedronPolygonsOptions {} -export const PolyOctahedron = defineComponent({ - name: "PolyOctahedron", - props: { - center: { type: Array as unknown as PropType, required: true }, - size: { type: Number, required: true }, +export const PolyOctahedron = definePolyShape( + "PolyOctahedron", + { + center: { type: Array as unknown as PropType, required: true as const }, + size: { type: Number, required: true as const }, color: { type: String, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, - }, - setup(props) { - const polygons = computed(() => - octahedronPolygons({ - center: props.center, - size: props.size, - color: props.color, - }), - ); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); }, -}); + (props) => + octahedronPolygons({ + center: props.center, + size: props.size, + color: props.color, + }), +); function defineSizeColorShape( name: string, - generator: (opts: { size?: number; color?: string }) => ReturnType, + generator: (opts: { size?: number; color?: string }) => Polygon[], ) { - return defineComponent({ + return definePolyShape( name, - props: { + { size: { type: Number, default: undefined }, color: { type: String, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, - }, - setup(props) { - const polygons = computed(() => generator({ size: props.size, color: props.color })); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); }, - }); + (props) => generator({ size: props.size, color: props.color }), + ); } export interface PolyTetrahedronProps extends ShapeMeshProps, TetrahedronPolygonsOptions {} @@ -256,148 +270,80 @@ export const PolyDodecahedron = defineSizeColorShape("PolyDodecahedron", dodecah export interface PolySphereProps extends ShapeMeshProps, SpherePolygonsOptions {} -export const PolySphere = defineComponent({ - name: "PolySphere", - props: { +export const PolySphere = definePolyShape( + "PolySphere", + { radius: { type: Number, default: undefined }, subdivisions: { type: Number, default: undefined }, color: { type: String, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, - }, - setup(props) { - const polygons = computed(() => - spherePolygons({ radius: props.radius, subdivisions: props.subdivisions, color: props.color }), - ); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); }, -}); + (props) => + spherePolygons({ + radius: props.radius, + subdivisions: props.subdivisions, + color: props.color, + }), +); // ── Parametric primitives ───────────────────────────────────────────────────── export interface PolyCylinderProps extends ShapeMeshProps, CylinderPolygonsOptions {} -export const PolyCylinder = defineComponent({ - name: "PolyCylinder", - props: { +export const PolyCylinder = definePolyShape( + "PolyCylinder", + { radius: { type: Number, default: undefined }, radiusTop: { type: Number, default: undefined }, height: { type: Number, default: undefined }, radialSegments: { type: Number, default: undefined }, color: { type: String, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, }, - setup(props) { - const polygons = computed(() => - cylinderPolygons({ - radius: props.radius, - radiusTop: props.radiusTop, - height: props.height, - radialSegments: props.radialSegments, - color: props.color, - }), - ); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); - }, -}); + (props) => + cylinderPolygons({ + radius: props.radius, + radiusTop: props.radiusTop, + height: props.height, + radialSegments: props.radialSegments, + color: props.color, + }), +); export interface PolyConeProps extends ShapeMeshProps, ConePolygonsOptions {} -export const PolyCone = defineComponent({ - name: "PolyCone", - props: { +export const PolyCone = definePolyShape( + "PolyCone", + { radius: { type: Number, default: undefined }, height: { type: Number, default: undefined }, radialSegments: { type: Number, default: undefined }, color: { type: String, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, - }, - setup(props) { - const polygons = computed(() => - conePolygons({ - radius: props.radius, - height: props.height, - radialSegments: props.radialSegments, - color: props.color, - }), - ); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); }, -}); + (props) => + conePolygons({ + radius: props.radius, + height: props.height, + radialSegments: props.radialSegments, + color: props.color, + }), +); export interface PolyTorusProps extends ShapeMeshProps, TorusPolygonsOptions {} -export const PolyTorus = defineComponent({ - name: "PolyTorus", - props: { +export const PolyTorus = definePolyShape( + "PolyTorus", + { radius: { type: Number, default: undefined }, tube: { type: Number, default: undefined }, radialSegments: { type: Number, default: undefined }, tubularSegments: { type: Number, default: undefined }, color: { type: String, default: undefined }, - // Common mesh props - position: { type: Array as unknown as PropType, default: undefined }, - scale: { type: [Number, Array] as unknown as PropType, default: undefined }, - rotation: { type: Array as unknown as PropType, default: undefined }, - autoCenter: { type: Boolean, default: false }, - id: { type: String, default: undefined }, - }, - setup(props) { - const polygons = computed(() => - torusPolygons({ - radius: props.radius, - tube: props.tube, - radialSegments: props.radialSegments, - tubularSegments: props.tubularSegments, - color: props.color, - }), - ); - return () => - h(PolyMesh, { - polygons: polygons.value, - position: props.position, - scale: props.scale, - rotation: props.rotation, - autoCenter: props.autoCenter, - id: props.id, - }); }, -}); + (props) => + torusPolygons({ + radius: props.radius, + tube: props.tube, + radialSegments: props.radialSegments, + tubularSegments: props.tubularSegments, + color: props.color, + }), +); diff --git a/packages/vue/src/three/PolyThreeOrthographicCamera.test.ts b/packages/vue/src/three/PolyThreeOrthographicCamera.test.ts index dff4e7e6d..3250ff543 100644 --- a/packages/vue/src/three/PolyThreeOrthographicCamera.test.ts +++ b/packages/vue/src/three/PolyThreeOrthographicCamera.test.ts @@ -48,6 +48,7 @@ describe("PolyThreeOrthographicCamera", () => { expect(camEl?.getAttribute("data-polycss-camera-projection")).toBe("orthographic"); expect(camEl?.getAttribute("data-polycss-camera-perspective")).toBe("none"); expect(camEl?.getAttribute("data-polycss-camera-applied-perspective")).toBe("1000000px"); + expect(camEl?.style.perspective).toBe("1000000px"); expect(container.querySelector(".polycss-scene")).toBeTruthy(); expect(container.querySelector(".polycss-mesh")).toBeTruthy(); app.unmount(); diff --git a/packages/vue/src/three/PolyThreeOrthographicCamera.ts b/packages/vue/src/three/PolyThreeOrthographicCamera.ts index 9eb15f484..69a97c2ba 100644 --- a/packages/vue/src/three/PolyThreeOrthographicCamera.ts +++ b/packages/vue/src/three/PolyThreeOrthographicCamera.ts @@ -85,7 +85,7 @@ export const PolyThreeOrthographicCamera = defineComponent({ { ref: cameraElRef, class: `polycss-camera${props.class ? ` ${props.class}` : ""}`, - style: { perspective: "none" }, + style: { perspective: "1000000px" }, "data-polycss-camera-projection": "orthographic", "data-polycss-camera-perspective": "none", "data-polycss-camera-applied-perspective": "1000000px", diff --git a/website/public/skill.md b/website/public/skill.md index 0b624a17c..ebe2af5c2 100644 --- a/website/public/skill.md +++ b/website/public/skill.md @@ -44,9 +44,10 @@ Read the file that matches the task before writing non-trivial code. | `@layoutit/polycss-fonts` | Text → extruded 3D `Polygon[]`. | | `@layoutit/polycss-morph` | Prepared models with retained DOM, morphs, skinning, playback. | -React and Vue depend on `core` only, so **do not import renderer or component -APIs from `@layoutit/polycss` in a React or Vue app** — use the framework -package, and take anything it does not re-export from `@layoutit/polycss-core`. +React and Vue share `@layoutit/polycss/runtime` and `@layoutit/polycss-core` +internally, so **do not import renderer or component APIs from +`@layoutit/polycss` in a React or Vue app** — use the framework package, and +take anything it does not re-export from `@layoutit/polycss-core`. The one documented exception is `exportPolySceneSnapshot`, which lives only in `@layoutit/polycss` because it is browser DOM serialization rather than diff --git a/website/public/skill/SKILL.md b/website/public/skill/SKILL.md index 2e3b98c2d..5efc71479 100644 --- a/website/public/skill/SKILL.md +++ b/website/public/skill/SKILL.md @@ -44,9 +44,10 @@ Read the file that matches the task before writing non-trivial code. | `@layoutit/polycss-fonts` | Text → extruded 3D `Polygon[]`. | | `@layoutit/polycss-morph` | Prepared models with retained DOM, morphs, skinning, playback. | -React and Vue depend on `core` only, so **do not import renderer or component -APIs from `@layoutit/polycss` in a React or Vue app** — use the framework -package, and take anything it does not re-export from `@layoutit/polycss-core`. +React and Vue share `@layoutit/polycss/runtime` and `@layoutit/polycss-core` +internally, so **do not import renderer or component APIs from +`@layoutit/polycss` in a React or Vue app** — use the framework package, and +take anything it does not re-export from `@layoutit/polycss-core`. The one documented exception is `exportPolySceneSnapshot`, which lives only in `@layoutit/polycss` because it is browser DOM serialization rather than diff --git a/website/public/skill/docs/api-index.md b/website/public/skill/docs/api-index.md index 96ad9b31b..d724c28df 100644 --- a/website/public/skill/docs/api-index.md +++ b/website/public/skill/docs/api-index.md @@ -10,8 +10,8 @@ here and not in your editor's completions, do not invent it. the renderer's atlas internals. - `@layoutit/polycss-react` and `@layoutit/polycss-vue` re-export a **curated list** of core — parsers, generators, math, and the common types — not all of - it. A core name missing from their index (for example `PolyPointLight`, or the - `resolvePolyTexture*` helpers, `spherePolygons`) is imported from + it. A core name missing from their index (for example the + `resolvePolyTexture*` helpers) is imported from `@layoutit/polycss-core` directly, which React and Vue already depend on. Do not take renderer or component APIs from `@layoutit/polycss` in a React or Vue app — the one exception is `exportPolySceneSnapshot`, which exists only @@ -80,22 +80,17 @@ classes. Importing `@layoutit/polycss` does **not** register them — import ## Geometry generators From every package: `boxPolygons`, `planePolygons`, `ringPolygons`, -`cylinderPolygons`, `conePolygons`, `torusPolygons`, `tetrahedronPolygons`, -`octahedronPolygons`, `icosahedronPolygons`, `dodecahedronPolygons`, -`axesHelperPolygons`, `arrowPolygons`. - -**`spherePolygons` and `ringQuadPolygons` are the exceptions:** they are -exported from `@layoutit/polycss-core` and `@layoutit/polycss` but **not** from -the React or Vue indexes, even though the `` component exists. In a -React or Vue app import them from `@layoutit/polycss-core`. +`ringQuadPolygons`, `spherePolygons`, `cylinderPolygons`, `conePolygons`, +`torusPolygons`, `tetrahedronPolygons`, `octahedronPolygons`, +`icosahedronPolygons`, `dodecahedronPolygons`, `axesHelperPolygons`, +`arrowPolygons`. ## Optimizer and mesh ops (all packages) `optimizeMeshPolygons`, `optimizeMeshParseResult`, `optimizeAnimatedMeshPolygons`, `mergePolygons`, `cullInteriorPolygons`, -`simplifyTriangleMeshPolygons`, `coverPlanarPolygons`, `repairMeshSeams`, -`bakeSolidTextureSamples`, `bakeSolidTextureSampledPolygons`, -`seamOverlapDiagnostics`, `seamOverlapPolygons`, `seamFacetSplitPolygons`. +`simplifyTriangleMeshPolygons`, `coverPlanarPolygons`, +`bakeSolidTextureSamples`, `seamOverlapDiagnostics`. ## Camera and coordinate math (all packages) @@ -123,8 +118,8 @@ From `@layoutit/polycss-core`, `@layoutit/polycss`, `-react` and `-vue`: `collectPolyRenderStats`, `collectPolyTextureReadiness`, `queryPolyLeaves`. From the renderer packages only: `injectPolyBaseStyles`. -React and Vue only: `findPolyMeshHandle`, `pointInMeshElement`, -`findMeshUnderPoint`. Vanilla has no exported equivalent. +Hit-testing: `pointInMeshElement` (vanilla, React, and Vue); +`findPolyMeshHandle` and `findMeshUnderPoint` (React and Vue). Texture resolution (from `@layoutit/polycss-core` or `@layoutit/polycss`, **not** the React/Vue indexes): `resolvePolyTextureLeafGeometry`, @@ -141,12 +136,10 @@ constants `LoopOnce`, `LoopRepeat`, `LoopPingPong`. Geometry: `Vec2`, `Vec3`, `Polygon`, `PolyMaterial`, `ParseResult`, `MeshResolution`. -Lights: `PolyDirectionalLight`, `PolyAmbientLight` (all packages). -`PolyPointLight` is narrower: `@layoutit/polycss-core`, `@layoutit/polycss`, and -`@layoutit/polycss/three` only. It is **not** re-exported by +Lights: `PolyDirectionalLight`, `PolyPointLight`, `PolyAmbientLight` (all +packages). `PolyPointLight` is also on `@layoutit/polycss/three` (not on `@layoutit/polycss-core/three`, `@layoutit/polycss-react/three`, or -`@layoutit/polycss-vue/three`, and React and Vue accept the `pointLights` prop -without exporting the type — take it from `@layoutit/polycss-core`. +`@layoutit/polycss-vue/three`). Texture: `PolyTextureLightingMode`, `PolyTextureLeafSizing`, `PolyTextureBackend`, `PolyTextureImageRendering`, `PolyTextureImageLighting`, diff --git a/website/public/skill/docs/lighting.md b/website/public/skill/docs/lighting.md index 49b2ac8ec..8162d5040 100644 --- a/website/public/skill/docs/lighting.md +++ b/website/public/skill/docs/lighting.md @@ -93,8 +93,8 @@ Three-parity baseline. ## Per-mesh override -React/Vue expose `textureLighting` as a `` prop. Vanilla meshes -inherit the scene value. +`textureLighting` can be overridden per mesh on both `` and vanilla +`scene.add(result, { textureLighting })`. ## Example diff --git a/website/public/skill/docs/scenes-and-cameras.md b/website/public/skill/docs/scenes-and-cameras.md index ded2b32e4..3466b10b7 100644 --- a/website/public/skill/docs/scenes-and-cameras.md +++ b/website/public/skill/docs/scenes-and-cameras.md @@ -84,27 +84,27 @@ bleed and sub-`1.5` values shrink them proportionally. | `position` | `Vec3` | Offset in scene space. | | `scale` | `number \| Vec3` | | | `rotation` | `Vec3` | Euler **degrees** `[x, y, z]`. | -| `autoCenter` | `boolean` | **Not a vanilla `scene.add` option** — it is a `` prop and a `` attribute only. Shifts the mesh so its bbox center sits at the local origin before `position`. (The scene-level `autoCenter` above is a different, unrelated option.) | +| `autoCenter` | `boolean` | Supported in `scene.add`, ``, and ``. Shifts the mesh so its bbox center sits at the local origin before `position`. (The scene-level `autoCenter` above is a different, unrelated option.) | | `castShadow` / `receiveShadow` | `boolean` | See [shadows.md](shadows.md). | | `merge` | `boolean` | Default `true`. `false` renders the array entering the renderer exactly as given. | | `meshResolution` | `"lossy" \| "lossless"` | Default `"lossy"`. | | `stableDom` | `boolean` | Vanilla only; needed for skeletal animation. | | `shadowDefinition` | `number` | Per-mesh parametric shadow detail. | -| `excludeFromAutoCenter` | `boolean` | **Vanilla only, and a `scene.add(result, transform)` option** — there is no React/Vue prop. Keeps this mesh out of the scene's auto-center bbox, for helpers and debug overlays. | +| `excludeFromAutoCenter` | `boolean` | Supported in `scene.add`, ``, ``, and all primitive shape elements. Keeps this mesh out of the scene's auto-center bbox, for helpers and debug overlays. | -React/Vue additionally expose per-mesh `textureLighting`, `textureQuality`, -`textureLeafSizing`, `textureImageRendering`, `textureBackend`, -`textureProjection`, `seamBleed`, `atomicAtlas`, and `onFrameReady`. Vanilla -meshes inherit the scene values for those. +Per-mesh overrides `textureLighting`, `textureQuality`, `textureLeafSizing`, +`textureImageRendering`, `textureBackend`, `textureProjection`, `seamBleed`, +`atomicAtlas`, and `onFrameReady` are available on both `scene.add(result, +transform)` and ``. ## Custom element caveats `` supports `directional-*`, `ambient-*`, `texture-lighting`, `texture-quality`, `texture-leaf-sizing`, `texture-image-rendering`, `texture-backend`, `texture-projection`, `auto-center`, and the implicit-camera -attributes. Only `perspective`, `rot-x`, `rot-y`, and `zoom` are *observed* — -mutating `distance` or `target` alone does not update the implicit camera. -`perspective` only selects the camera type at connect time. Use the imperative +attributes (`perspective`, `rot-x`, `rot-y`, `zoom`, `distance`, `target`). +`rot-x`, `rot-y`, `zoom`, `distance`, and `target` update the implicit camera +live; `perspective` selects the camera type at connect time. Use the imperative API for `shadow`, `seamBleed`, and `strategies`. `` supports `src`, `mtl`, `mesh-resolution`, `position`, `scale`, diff --git a/website/public/skill/docs/shapes-and-primitives.md b/website/public/skill/docs/shapes-and-primitives.md index b955a6e8d..d73bf7d2a 100644 --- a/website/public/skill/docs/shapes-and-primitives.md +++ b/website/public/skill/docs/shapes-and-primitives.md @@ -9,9 +9,7 @@ Three layers, same geometry: | Components | `` / `` | Mounted mesh | Core generators are exported from every package (`@layoutit/polycss`, `-react`, -`-vue`, `-core`) with two exceptions: **`spherePolygons` and `ringQuadPolygons` -are not re-exported by React or Vue** — import those from -`@layoutit/polycss-core`, which both framework packages already depend on. Use +`-vue`, `-core`), including `spherePolygons` and `ringQuadPolygons`. Use generators when you want raw arrays to post-process. ## Options and defaults @@ -139,8 +137,7 @@ The cap at 3 is deliberate — DOM cost. ### Other generators -`axesHelperPolygons` and `arrowPolygons` (all packages), plus `ringQuadPolygons` -(core and `@layoutit/polycss` only — see the note at the top). +`axesHelperPolygons`, `arrowPolygons`, and `ringQuadPolygons` (all packages). ## Usage diff --git a/website/public/skill/docs/troubleshooting.md b/website/public/skill/docs/troubleshooting.md index cec96751a..9044c9f1b 100644 --- a/website/public/skill/docs/troubleshooting.md +++ b/website/public/skill/docs/troubleshooting.md @@ -31,7 +31,6 @@ is simply wrong or absent. Work the symptom table before adding instrumentation. | A direct image leaf ignores scene lighting | By design — direct image leaves are source-lit. Use the atlas backend for scene lighting. | | `PolyScene` throws | It must be nested inside a camera component. | | The scene is invisible / flat / wrong scale | Check camera nesting (camera outer, scene inner), then `zoom` (CSS px per world unit, default `0.65`) and `targetSize`. | -| `` or `target` changes do nothing | Only `perspective`, `rot-x`, `rot-y`, `zoom` are observed on the implicit camera. Change one of those, or use the imperative API. | | `` change does nothing | Read at load only. | | Per-polygon click handlers stopped firing after a change | Polygons got merged into one leaf. Use `merge: false`. | | Animation plays but the mesh flickers or re-mounts | Topology is not stable. Vanilla needs `{ merge: false, stableDom: true }`; React/Vue need `meshResolution="lossless"` / `merge={false}`. | diff --git a/website/src/components/VanillaScene/VanillaScene.tsx b/website/src/components/VanillaScene/VanillaScene.tsx index d9072720f..79a805fb8 100644 --- a/website/src/components/VanillaScene/VanillaScene.tsx +++ b/website/src/components/VanillaScene/VanillaScene.tsx @@ -33,7 +33,6 @@ import { bakedLightingSignature, fpvOptionsFromSceneOptions, lightHelperPosition, - type BakedSolidLightingPreviewSceneHandle, type VanillaSceneProps, type VanillaSceneTransientHandle, } from "./sceneHelpers"; @@ -153,7 +152,7 @@ export function VanillaScene({ } else { scene.setOptions({ directionalLight: nextDirectionalLight }); } - (scene as BakedSolidLightingPreviewSceneHandle).previewBakedSolidLighting?.({ + scene.previewBakedSolidLighting({ directionalLight: nextDirectionalLight, ambientLight: ambientFromOptions(nextOptions), skipShadows: !previewShadow, @@ -503,7 +502,7 @@ export function VanillaScene({ options.textureLighting === "baked" && committedBakedLightingRef.current !== nextLightingSignature ) { - (scene as BakedSolidLightingPreviewSceneHandle).commitBakedSolidLighting?.(); + scene.commitBakedSolidLighting(); committedBakedLightingRef.current = nextLightingSignature; } else if (options.textureLighting !== "baked") { committedBakedLightingRef.current = nextLightingSignature; diff --git a/website/src/components/VanillaScene/sceneHelpers.ts b/website/src/components/VanillaScene/sceneHelpers.ts index 3ef39c0fa..72f184090 100644 --- a/website/src/components/VanillaScene/sceneHelpers.ts +++ b/website/src/components/VanillaScene/sceneHelpers.ts @@ -7,7 +7,6 @@ import type { import type { ParseResult, PolyMeshHandle as VanillaPolyMeshHandle, - PolySceneHandle, Vec3, } from "@layoutit/polycss"; import type { GizmoMode, SceneOptionsState } from "../types"; @@ -29,15 +28,6 @@ export interface VanillaSceneTransientHandle { applyLightOptions(options: SceneOptionsState, preview?: { shadow?: boolean }): void; } -export type BakedSolidLightingPreviewSceneHandle = PolySceneHandle & { - previewBakedSolidLighting?: (next: { - directionalLight?: PolyDirectionalLight; - ambientLight?: PolyAmbientLight; - skipShadows?: boolean; - }) => boolean; - commitBakedSolidLighting?: () => boolean; -}; - export interface VanillaSceneProps { polygons: Polygon[]; interiorShellPolygons: Polygon[]; diff --git a/website/src/content/docs/api/headless.mdx b/website/src/content/docs/api/headless.mdx index fee76ae8c..48682e5f0 100644 --- a/website/src/content/docs/api/headless.mdx +++ b/website/src/content/docs/api/headless.mdx @@ -488,7 +488,7 @@ The vanilla package also exposes renderer and atlas building blocks for diagnost
Advanced renderer exports -- Atlas planning/rendering: `computeTextureAtlasPlanPublic`, `buildAtlasPages`, `renderPolygonsWithTextureAtlas`, `renderPolygonsWithTextureAtlasAsync`, `filterAtlasPlans`, `packTextureAtlasPlansWithScale`, `buildTextureEdgeRepairSets`. +- Atlas planning/rendering: `computeTextureAtlasPlanPublic`, `buildAtlasPages`, `renderPolygonsWithTextureAtlas`, `filterAtlasPlans`, `packTextureAtlasPlansWithScale`, `buildTextureEdgeRepairSets`. - Stable DOM animation: `renderPolygonsWithStableTriangles`, `updatePolygonsWithStableTopology`, `updateStableTriangleFrame`. - Scene transform helpers: `worldPositionToPolyCss`, `worldDirectionToPolyCss`, `worldDirectionalLightToPolyCss`, `worldDistanceToPolyCss`, `polyCssDistanceToWorld`, `polyCssPositionToWorld`, `buildPolyMeshTransform`, `buildPolySceneTransform`. - Strategy and CSS helpers: `getSolidPaintDefaults`, `getSolidPaintDefaultsFromPlans`, `isBorderShapeSupported`, `isSolidTriangleSupported`, `isFullRectSolid`, `isSolidTrianglePlan`, `isProjectiveQuadPlan`, `cssBorderShapeForPlan`, `formatMatrix3d`, `formatCssLengthPx`, `formatSolidQuadEntryMatrix`, `formatBorderShapeEntryMatrix`.