Plan — Clinical anatomy viewer (react-three-fiber)
Version: 1.2.0
Last Updated: 2026-05-31 16:18:42
Status: Decoupled (2026-05-31). Code lives in packages/clinical-anatomy/; production Pain is 2D-only. Plug-in via host adapter when clinical_anatomy is entitled. Engineering phases below run inside the isolated module only.
Product module (proposed slug): clinical_anatomy — sellable separately; not bundled with pain_tracking.
Owner docs: This plan + future docs/01 - BUSINESS REQUIRMENTS/XX-CLINICAL-ANATOMY-MODULE.md (not yet written).
Technical debt: The experimental @google/model-viewer turntable embedded in PainBodyMapTab predates this principle — see Decoupling from core.
Governing principle — pluggable module (non-negotiable)
Section titled “Governing principle — pluggable module (non-negotiable)”The 3D clinical anatomy viewer is not a feature inside Pain & Stats. It is a separate product module that:
- Does not ship with core LynCareOS until deliberately enabled — no dependency from core routes, Pain, billing tiers, or the main frontend bundle on anatomy code.
- Plugs in only via a narrow adapter contract — hosts (Pain, education, care plans) call a stable API surface; the module never imports Pain internals.
- Can be sold à la carte — own entitlement slug (
clinical_anatomy), tier matrix row, marketing page, and optional backend router when overlays need persistence. - Matures on its own schedule — r3f, layers, owned GLB pipeline, knowledge base, and Phase 3 overlays are developed in the module workspace without changing the 2D pain map, pain APIs, or reconciliation register for core pain.
Pain & Stats remains authoritative for pain recording today: custom 2D body map, 62 region slugs, api.pain.create, trends, alerts. The anatomy module may optionally emit compatible region events through the adapter when plugged into Pain — that is an integration choice at plug-in time, not a coupling requirement now.
Do not implement r3f swap, layer toggles, or further 3D work in frontend/src/components/pain/ until this module is extracted and the host adapter is defined.
Target module boundary
Section titled “Target module boundary”| Layer | Location (target) | Rule |
|---|---|---|
| Module package | packages/clinical-anatomy/ (or separate repo) | All Three.js/r3f, GLBs, anatomy KB, UI panels |
| Public API | packages/clinical-anatomy/src/index.ts | Only exports: viewer component, types, createAnatomyHostAdapter() |
| Host integration | Thin file in app, e.g. frontend/src/integrations/clinicalAnatomy.ts | Lazy import() gated by clinical_anatomy entitlement; one call site per host screen |
| Assets | packages/clinical-anatomy/assets/models/ | Not in frontend/public/models/ once decoupled |
| Dependencies | packages/clinical-anatomy/package.json | three, @react-three/fiber, @react-three/drei — not in root frontend/package.json until plug-in |
| Billing | tiers.json + module_delivery.json | clinical_anatomy in planned until launch; never required for pain_tracking |
Adapter contract (sketch — refine at plug-in):
/** Event the host may map to pain slugs or ignore. */export type AnatomyRegionTapEvent = { regionSlug: string label: string side: 'front' | 'back' | 'left' | 'right' xPct: number yPct: number /** Finer mesh id when segmented atlas exists. */ partId?: string}
export type ClinicalAnatomyViewerProps = { gender: 'male' | 'female' mode: 'education' | 'pain-input' onRegionTap?: (e: AnatomyRegionTapEvent) => void className?: string}Hosts pass props; the module never imports PainBodyMapTab, BodyMap, or lib/api.ts unless the host supplies callbacks.
Decoupling from core (done 2026-05-31)
Section titled “Decoupling from core (done 2026-05-31)”| Item | Was | Now |
|---|---|---|
| Viewer + resolver | frontend/.../pain/body3d/ | packages/clinical-anatomy/src/ |
| Pain Record UI | 2D/3D toggle in PainBodyMapTab | 2D only — no 3D imports |
@google/model-viewer | frontend/package.json | packages/clinical-anatomy/package.json only |
| GLB assets | frontend/public/models/ | packages/clinical-anatomy/public/models/ |
| Preview | In-app toggle | npm run dev in package (port 5175) |
| Billing slug | — | clinical_anatomy in module_delivery.json planned |
| Host wiring | — | frontend/src/integrations/README.md (stub; no code import yet) |
REQ-PAIN-13 remains a partial preview note; product track is REQ-ANAT-* when the module spec is written.
Why (module vision)
Section titled “Why (module vision)”The shipped 3D surface is a single-mesh turntable on <model-viewer>. It satisfies
the Phase 1 “rotate + tap a region” need, but it cannot grow into the clinical
anatomy component the product wants: independently toggleable layers (skeleton,
muscles, organs, nerves, circulatory, lymphatic, skin), per-part click-to-select
with an information panel, search-to-highlight, and pathology / care overlays.
<model-viewer> is Three.js wrapped as a web component optimised for “one tidy
model”. The layered vision needs direct scene-graph control — separate named
meshes, per-mesh materials, picking, outlining, and overlay shaders. The
React-idiomatic way to get that control is react-three-fiber (r3f) +
drei helpers, which is the agreed engine going forward.
Decisions locked
Section titled “Decisions locked”- Product shape: pluggable
clinical_anatomymodule — see Governing principle. - Engine:
@react-three/fiber+@react-three/drei(declarative Three.js) — inside the module package only. - Format: GLB (glTF Binary), one file per layer, each layer a group of named meshes.
- Host boundary:
AnatomyRegionTapEventadapter (above). When integrated with Pain, the host maps events to existing slugs and callsapi.pain.create— the module does not. - Assets / licensing (advised):
- Production ships clean licences only. CC-BY (attribution) now; a paid royalty-free segmented atlas (TurboSquid / CGTrader) when layers land.
- Keep the current HuBMAP CC-BY-4.0 body skins.
- CC-BY-SA (BodyParts3D / Z-Anatomy) is prototyping-only — never shipped. Share-alike is viral on the model files and conflicts with the repo’s no-viral-licence rule and the commercial posture. Confined to internal spikes to validate picking + layer UX.
- Data-model reuse: no backend, schema, or
PainEntryCreatechanges. The finer anatomy taxonomy (per-bone / per-organ) is an additive metadata layer that resolves down to the existing 62 region slugs for recording.
Guardrails (from .cursor/rules/rules.mdc)
Section titled “Guardrails (from .cursor/rules/rules.mdc)”- All API calls via
lib/api.ts; DB stays the source of truth; no client-side compliance figures. - No
any; JSDoc on public components/functions; component ≤ 300 lines, function ≤ 150 lines — split the scene graph into sub-components. - Lazy-load r3f, drei, and every GLB (3D must never enter the main bundle).
- Mobile + desktop + dark mode each verified; respect
prefers-reduced-motion. - WebGL-absent fallback to the 2D
BodyMapis mandatory (already wired). - No Cursor Canvas artefacts.
- Run
npm run build+npm run lint:strictbefore marking a phase done.
Phase 0 — r3f spike (throwaway, inside module package)
Section titled “Phase 0 — r3f spike (throwaway, inside module package)”Prove the engine before committing. Work only under packages/clinical-anatomy/ (or a
scratch repo). Do not import from frontend/src/components/pain/. Behind a dev-only flag, render one GLB in r3f
with OrbitControls and raycast picking; validate per-mesh name access, hover
outline, and tap → resolveRegion parity with the model-viewer path. Z-Anatomy
may be used here as a reference asset (not committed).
Exit: picking returns the same slugs the model-viewer path does for the same hits; no regression in the 2D fallback.
Phase 1 — Module viewer (r3f parity with legacy experiment)
Section titled “Phase 1 — Module viewer (r3f parity with legacy experiment)”Build ClinicalAnatomyViewer in the isolated package (not in pain/body3d/). Match legacy turntable behaviour for reference only; do not wire into PainBodyMapTab until plug-in milestone.
- New deps:
@react-three/fiber,@react-three/drei,three(lazy entry point). Body3DScene.tsx— Canvas + lights + camera; turntable-locked OrbitControls (azimuth free, polar locked, zoom/pan tuned to the existing turntable feel).useGLBloader (dreiuseGLTF) with Suspense + loading state + error boundary.- Port
handleTap→ r3fonPointerDownraycast; reuseregion3dMap.resolveRegionwith the same normalised-coordinate maths (lift it out so both engines share it). - Keep
painBody3DConfig(URLs, gender) and the WebGL guard. - Retire
modelViewer.d.tsand the@google/model-viewerdependency once parity is verified.
Exit: rotate + tap-to-record behaves identically to today on body + skeleton
(skeleton still bone-fallback if no segmented asset yet); bundle unchanged at
first paint (everything lazy); D26 updated.
Phase 2 — Layers, selection, knowledge base
Section titled “Phase 2 — Layers, selection, knowledge base”- Layer model:
AnatomyLayertype (skeleton | muscles | organs | circulatory | nervous | lymphatic | skin) → GLB url + toggle state + opacity. Layer toggle UI reusesPainSegmentedToggle/ a checklist; multiple layers visible at once. - Per-mesh selection: raycast returns the hit mesh
name; a thin highlight (dreiOutlinesor emissive swap) marks the selection. - Anatomy knowledge base: new structured content (JSON, keyed by mesh name) —
name,function,pathologies[],attachedMuscles[], and theregionSlugit maps to. Lives under a documented location (e.g.frontend/src/components/pain/body3d/anatomy/), versioned, clinically reviewed. - Info panel:
AnatomyInfoPanelshows the KB entry on select; “record pain here” CTA resolves the part → region slug → existingonRegionTap. - Search-to-highlight: type a part name → focus camera + highlight mesh.
- Assets: purchase / source the segmented, named atlas here (clean licence).
Exit: at least skeleton + one soft-tissue layer toggle independently; clicking a named part opens the info panel; recording still flows through the unchanged API.
Phase 3 — Clinical overlays (later)
Section titled “Phase 3 — Clinical overlays (later)”Pathology / medication / pain-map overlays as additive material/tint passes on the relevant meshes; care-plan + FHIR integration. Scoped separately once Phase 2 is proven — explicitly out of near-term scope. Tie to roadmap, not this plan’s MVP.
Files (anticipated)
Section titled “Files (anticipated)”frontend/src/components/pain/body3d/Body3DViewer.tsx— unchanged contract, r3f internals.frontend/src/components/pain/body3d/Body3DScene.tsx— new Canvas/scene graph.frontend/src/components/pain/body3d/useAnatomyModel.ts— GLB loader + cache.frontend/src/components/pain/body3d/region3dMap.ts— keep; shared by both engines.frontend/src/components/pain/body3d/anatomy/— knowledge base (Phase 2).frontend/src/components/pain/body3d/AnatomyInfoPanel.tsx— Phase 2.frontend/public/models/— GLB assets;licenses.jsonupdated per asset.
Onboarding — what a new model/session must read
Section titled “Onboarding — what a new model/session must read”A fresh session does not inherit chat. Read in this order before touching 3D code.
Project context (rules-mandated):
docs/00-INDEX.md,docs/19-CURRENT-STATE-AND-LAUNCH-PLAN.mddocs/02 - ARCHITECTURE_DESIGN/01-ARCHITECTURE.md,05-DEVELOPER-GUIDE.md.cursor/rules/rules.mdc— layer boundaries, tenant isolation, no-viral-licence rule
Anatomy viewer work:
- This plan (the spine).
docs/01 - BUSINESS REQUIRMENTS/26-PAIN-STATS-MODULE.md— “3D Body Turntable” subsection (current shipped behaviour).docs/01 - BUSINESS REQUIRMENTS/32-KNOWN-DEBTS-REGISTER.md— D26 (skeleton asset + verification debt).docs/01 - BUSINESS REQUIRMENTS/31-REQUIREMENTS-CODE-MARKETING-RECONCILIATION.md— REQ-PAIN-13.
Shipped 3D code (build on / swap):
frontend/src/components/pain/body3d/Body3DViewer.tsx— contract to preserve (onRegionTap).frontend/src/components/pain/body3d/region3dMap.ts— 3D-hit → region-slug resolver (keep, shared by both engines).frontend/src/components/pain/body3d/painBody3DConfig.ts— asset URLs + turntable camera.frontend/src/components/pain/body3d/webgl.ts,modelViewer.d.ts.frontend/src/test/components/region3dMap.test.ts— resolver tests.frontend/src/components/pain/PainBodyMapTab.tsx— where the viewer is wired (2D/3D toggle).frontend/public/models/licenses.json— asset attribution.
What is true today (one paragraph): A legacy <model-viewer> experiment is still
embedded in PainBodyMapTab (predates the pluggable-module rule). Do not extend it.
Pain & Stats core is the 2D body map. The anatomy product will live in
clinical_anatomy, developed in isolation, and plug in later via the host adapter.
Legacy 3D code should be decoupled when ready (see Decoupling from core).
Build our own assets (in-house pipeline)
Section titled “Build our own assets (in-house pipeline)”The viewer (Three.js / r3f) is code we own outright — no licence, no cost. The assets are the real work, and it is a 3D-art / medical-imaging job, not a coding job. The current 2D images are a design reference (proportions, style, region taxonomy) — not source material: a 2D PNG cannot be extruded into anatomically correct 3D.
Key advantage: tool licences never infect the output. Blender (GPL) and 3D Slicer (BSD) produce meshes that are ours — shippable closed and white-labelled. Building our own sidesteps the entire CC-BY-SA tension and yields an owned, tailored library (a product moat).
Pipeline A — segment open medical imaging (most credible; how BodyParts3D/HuBMAP were made):
- Source CC0 / public-domain volumetric scans — NIH 3D, Visible Human Project, TCIA.
- Auto-segment with TotalSegmentator (Apache-2.0) — 100+ structures from CT.
- Refine in 3D Slicer (BSD) / ITK-SNAP.
- Retopo / decimate / material / Draco-compress in Blender.
- Export GLB per layer with named meshes → feeds r3f layers + Phase 2 per-part selection.
Pipeline B — parametric/sculpt (faster for outer body): MakeHuman (CC0 output) for the body skin + base rig, then Blender detail. Strong for skin/body layers, weak for fine organs.
Recommendation — build and buy, staged (do not let asset creation block engineering):
- Now (Phase 1–early 2): keep CC-BY HuBMAP skins; a cheap royalty-free segmented atlas (~$50–300) unblocks layer + per-part work immediately.
- Long-term track: stand up Pipeline A to produce an owned, style-matched, white-labelled library. Cost is artist/imaging time (or a one-off contractor), not engineering. This becomes the canonical asset source and retires all asset-licence risk.
Docs to update as phases land
Section titled “Docs to update as phases land”26-PAIN-STATS-MODULE.md— replace the model-viewer subsection with the r3f viewer.32-KNOWN-DEBTS-REGISTER.md— evolveD26(segmented atlas + KB clinical review).05-DEVELOPER-GUIDE.md— new deps (r3f/drei/three) + 3D code map.31-REQUIREMENTS-CODE-MARKETING-RECONCILIATION.md—REQ-PAIN-13status by phase.public/models/licenses.json— attribution per shipped asset.