Skip to content

Two-mouse Three.js simulation

Open Three.js Examples → Two Mice in the GUI, or ask Annolid Bot:

open threejs example two mice

The scene starts with a black C57BL/6 mouse and a snow-ivory BALB/c mouse on a matte anti-glare arena floor with curled aspen wood shavings. Models include multi-layer clumped fur with anisotropic guard-hair sheen, a sleek tapered skull with split upper-lip cushions, recessed oral cleft, curved ivory incisors, and tucked lower lip/chin, strain-calibrated rhinarium and almond palpebral rims, unified cupped vascularized ear pinnae, a monotonically tapered cervical bridge, crouched furred limbs with grounded articulated paws, mystacial and supraorbital vibrissae, and a countershaded annular-ringed tail. Exploration includes wall following, active rhythmic whisking, pauses to sniff, social investigation, rearing, and grooming. This is a procedural visualization, not a validated animal biomechanics model. Heart rate and respiration in the HUD are illustrative estimates.

Two-Mouse Three.js 3D simulation showing procedural C57BL/6 and BALB/c mice on an aspen-bedded open-field floor

Neuroscience behavioral arenas

Switch arenas live from Simulation Controls → Arena, launch directly via URL query parameter (two_mice.html?arena=<id>), or control them programmatically via window.annolidTwoMice.setArena(idOrLabel). Each arena configures its own 3D apparatus, exact wall/cliff/obstacle containment, tail collision wrapping, wall-supported rearing eligibility (disabled on exposed cliffs such as Elevated Plus Maze open arms and Barnes Maze edges), corridor- and doorway-aware routing for both autonomous exploration and Fly-Brain olfactory plume chemotaxis, arena-specific Fly-Brain sensory zone locations, camera framing, and live HUD ZONE readout.

Arena (?arena=) GUI Label Behavioral Domain Key Apparatus Features
open_field Open Field Locomotion & anxiety Rectangular acrylic open field with matte anti-glare floor and aspen shavings (default)
home_cage Home Cage (Bedding) Social & ethology Molded polycarbonate shoebox cage with corncob bedding, shredded nestlet, and stainless water port
circular_open_field Circular Open Field Locomotion & anxiety Cylindrical drum eliminating corner bias, with concentric center/middle/periphery scoring rings
elevated_plus_maze Elevated Plus Maze Unconditioned anxiety Elevated + apparatus on steel pedestal legs with two tall-walled closed arms (±X) and two open cliff arms (±Z)
y_maze Y-Maze Spatial working memory Symmetrical 120° three-arm spontaneous alternation maze with intra-maze visual cue cards and floor labels (A/B/C)
t_maze T-Maze Working memory & choice Start stem with raised guillotine start-box gate frame, central choice point, and left/right goal-arm reward wells
three_chamber Three-Chamber Social Social preference Crawley three-chamber polycarbonate box with framed central doorways and two cylindrical wire holding cups
light_dark_box Light-Dark Box Anxiety & photophobia Bright white light compartment (2/3) and charcoal dark compartment (1/3) with smoked canopy and transition doorway
barnes_maze Barnes Maze Spatial reference memory Elevated circular white table with 18 perimeter escape holes, under-table target escape box, and 4 distal cue stands
novel_object Novel Object (NOR) Recognition memory Square chamber with a familiar cylindrical lab bottle and a contrasting novel stepped geometric block tower

Viewing and playback

Drag to orbit, scroll to zoom, and use Simulation Controls → Camera for an overview, a view from above, or a camera that follows either strain. The follow camera preserves your orbit angle while moving with the subject.

  • Pause Simulation freezes motion and contact solving. The camera and pose-skeleton overlay remain usable while paused.
  • Playback Speed supports slow motion down to 0.25×, up to 1.5×.
  • Lighting Preset (Lighting → Lighting Preset) switches between calibrated studio looks (Studio Daylight, Warm Lab, High Contrast, IR Night, and CaLMS Monochrome) while synchronizing key/rim shader light directions for anisotropic fur and subsurface ear scattering.
  • Quality Mode changes pixel resolution and shadow resolution without changing exposure. Post-Processing applies ACES tone mapping and sRGB output encoding around the active orbit target so optional vignette, subtle macro depth-of-field, and film grain preserve scene brightness.
  • Fur Detail controls coat density for newly spawned subjects. Reduce it before spawning more mice on machines with limited graphics memory.
  • Clear All releases subject-specific GPU resources. Spawn Subject uses the selected strain and biological traits.

Appearance toggles that recompile material shaders or rebuild fur coats and limb chains retain the respawn notice, while continuous shader parameters, ear magnitude, pose skeleton overlays, and body/tail proportions update live (including while paused). Detailed Proportions controls rebuild shared trunk, head, and cervical meshes in place and synchronize coat/limb alignment on newly spawned subjects; Fur controls (Fur Detail, Guard Hair Ratio, Fur Length, and Clumpiness) configure multi-layer coat generation on newly spawned subjects. Physics uses fixed 30 Hz steps independently of rendering. Long stalls have bounded catch-up, hidden tabs do not advance the simulation, and unloading the view releases active and shared WebGL resources.

The viewer requires WebGL and loads pinned three@0.182.0 (OrbitControls, RoomEnvironment) and lil-gui@0.18.2 ES modules directly from Annolid's bundled local assets (annolid/gui/assets/threejs/), so it works offline without external CDN access. A loading error is displayed if WebGL initialization fails.

Reproducible pose capture

Top-down view of the Two-Mouse Three.js simulation with the 13-keypoint pose skeleton overlay enabled

The existing dataset=1, seed, frame, and fps query parameters and window.annolidPoseDataset.getFrame() / setFrame(index) API remain available. Frames advance monotonically. Track IDs, 13-keypoint ordering, COCO-style records, and contact-quality metadata are preserved.

Seeds reproduce captures within this scene version. The corrected motion and new model change images and trajectories relative to older versions; existing saved fixtures are not rewritten. Randomness is scene-local and does not replace the browser's Math.random function.

Generate a new dataset in a separate directory for inspection:

source .venv/bin/activate
python scripts/generate_two_mice_pose_dataset.py --output /tmp/two_mice_preview

Motor control

Locomotion follows the same layered design as Annolid's FlyBody controller (annolid/simulation/fly_brain.py), implemented in two_mice_control.js:

flowchart LR
  A["Behavior state<br/>explore, social, rear, groom<br/>or external command"] --> B["Descending drive<br/>speed, turn, arrest, gait"]
  B --> C["Limb CPG<br/>4 coupled phase oscillators"]
  C --> D["Motor decoder<br/>22 named joint targets"]
  D --> E["Rig + foot-plant IK"]
  E -- "paw reach / slip" --> C
  • Gaits: lateral-sequence walk (duty ≈ 0.70), diagonal trot (≈ 0.56), and half-bound gallop (≈ 0.42), selected from speed with hysteresis so the gait does not flicker. Behavior Controls → Gait forces one gait; the HUD shows the active gait and step frequency.
  • Stance and swing come from the oscillator phase. Paws retract monotonically while planted, swing with knee/wrist flexion, and a lift-off reflex starts the swing early when a planted paw reaches its reach or slip limit. When the drive stops, swings finish and all four paws plant. Turning in place steps rather than skating.
  • Rearing and grooming arrest stepping (like the fly's arrest neurons) and blend their postures on top of the locomotor targets.

Control and observation API

window.annolidTwoMice exposes a FlyBody-style task interface in the viewer:

const api = window.annolidTwoMice;
api.getArenas();                // list all 10 neuroscience arena specs and semantic zones
api.getArena();                 // active arena metadata
api.setArena('elevated_plus_maze'); // switch arena by id, alias, or GUI label (throws RangeError if invalid)
api.getLightingPresets();       // list available studio lighting preset names
api.setLightingPreset('High Contrast'); // switch lighting preset live (throws RangeError if invalid)
api.getActionSpec();            // joint names, ranges, neutral pose, gaits, command spec
api.getObservation(1);          // arena, semantic zone, egocentric velocity, yaw rate, joint positions/targets,
                                // foot contacts and slip, CPG phases, behavior state
api.getObservations();          // all subjects
api.setCommand(1, { forwardSpeed: 4, turnRate: 0.8, gait: 'auto', durationSec: 3 });
api.clearCommand(1);            // return to autonomous behavior
  • forwardSpeed is in scene units/s (negative walks backward), clipped to -0.25..1.24 × maxSpeed; turnRate is in rad/s, clipped to ±3. durationSec is optional; without it the command holds until cleared.
  • Invalid commands throw (TypeError/RangeError) instead of being ignored.
  • While a command is active, spontaneous pauses, social steering, rearing, and grooming are suppressed; wall and body contacts are still resolved. A posture already in progress finishes first.
  • Seeded dataset captures remain reproducible as long as no command is issued.

Fly-brain connectome mode (?fly_brain=1)

Open 3D Examples → Fly-Brain Mouse, open two_mice.html?fly_brain=1, toggle Fly Brain Control → Enable Fly Brain in the controls panel, or ask Annolid Bot:

open threejs example fly brain mouse

This mode runs a live biophysical Drosophila LIF spiking connectome (two_mice_fly_brain.js, using Shiu et al. 2024 / FlyWire / MaleCNS LIF parameters and canonical pathways from annolid/simulation/fly_brain.py) in a closed sensorimotor loop driving the 3D mouse rig through two_mice_control.js:

Fly-Brain connectome mode in the Two-Mouse Three.js simulation showing the live 264-neuron LIF spike raster, descending neuron activity bars, KC-to-MBON plasticity, Chrimson optogenetics panel, and reward zone

  • Sensory → Descending circuits:
  • Golden Sucrose Reward Zone radiates an olfactory gradient into ORN_L/R → PFL3_L/R → LAL_Inh → DNa02_L/R (left/right chemotaxis steering) and CX_Forward_Goal → DNp09 (forward walking/trotting).
  • Partner mouse bearing projects onto Visual_Target_L/R (LC10a) and rapid approach excites LC4_Looming → DNp01 (Giant Fiber escape gallop).
  • Anterior wall proximity excites Tactile_Ant → MDN → VNC_MDN_Inh (inhibits DNp09 and drives backward moonwalking).
  • Pair1 GABAergic arrest freezes locomotion; aDN1 triggers 3D face-wash grooming; DNg02 triggers vertical rearing.
  • Online dopamine plasticity (KC → MBON): inspired by nftechie/stonkfly, entering the Reward Zone fires PAM dopamine (strengthening KC_Reward_Zone → MBON_Approach and depressing MBON_Avoid), while entering the red Hazard Zone fires PPL1 aversive dopamine (strengthening KC_Hazard_Zone → MBON_Avoid to promote retreat).
  • Live Connectome Monitor & Optogenetics: displays a real-time scrolling LIF spike raster, descending-neuron activity bars, live KC → MBON synaptic weight multipliers, and one-click Chrimson stimulation buttons (Walk, Turn L/R, Moonwalk, Freeze, Groom, Rear, Escape, PAM DA, PPL1 DA).
  • JavaScript API (window.annolidTwoMice):
  • getFlyBrainMetadata()
  • enableFlyBrain(trackId, { dynamics, plasticityEnabled }) / disableFlyBrain(trackId)
  • getFlyBrainState(trackId)
  • stimulateFlyNeuron(trackId, cellType, current, durationSec)
  • applyFlyOptoPreset(trackId, presetId)
  • resetFlyBrainPlasticity(trackId)

Fly Brain mode is off by default in two_mice.html so seeded trajectories and pose dataset captures remain unchanged. This cross-species controller is an illustrative NeuroAI visualization, not a validated mouse brain model.

Validation and maintenance

The HTML is the presentation shell. two_mice_scene.js owns scene assembly, articulation, behavior, and pose export; two_mice_model.js owns procedural model construction and GPU resource ownership; two_mice_arenas.js owns the neuroscience arena catalog, 2D wall/obstacle/tail containment physics, zone classification, and lazy 3D apparatus builders; two_mice_control.js owns the joint/action spec, gait library, limb CPG, and motor decoder; two_mice_fly_brain.js owns the dependency-free Drosophila LIF connectome and dopamine plasticity controller; two_mice_simulation.js supplies the independent timing, random-stream, and wall-force helpers. All modules are served by Annolid's desktop asset server and included by the package's JS rules.

Run deterministic checks without a browser (uses node on PATH or Playwright's bundled Node runtime when installed in .venv):

source .venv/bin/activate
pytest tests/test_two_mice_arenas.py tests/test_two_mice_fly_brain.py tests/test_two_mice_control.py tests/test_two_mice_simulation.py tests/test_threejs_examples.py

Run the optional offline browser checks with Playwright Chromium installed:

ANNOLID_RUN_THREEJS_BROWSER_TESTS=1 \
ANNOLID_THREEJS_SCREENSHOT_DIR=output/playwright \
.venv/bin/python -m pytest tests/test_two_mice_browser.py

These check capture repeatability, contact bounds, deformed fur normals, pause, camera controls, resource cleanup, selected anatomy/rearing/grooming poses (including anatomy_qa views such as torso-side, ears-front, head-side, head-three-quarter, head-top, and mouth-front), and the motor-control API (in-place turning, commanded walking, foot slip). window.annolidTwoMice.getDiagnostics() exposes a read-only snapshot of simulation time, subject positions, and renderer resource counts for diagnostics.