<! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createMeleeArc(origin, direction, range, arcAngleDeg)

isInMeleeArc(arc, targetPos, targetRadius = 0)

isInMeleeArc3D(arc, targetPos, targetRadius = 0, verticalToleranceRad = Math.PI / 4)

checkMeleeHits(state, attackerPos, attackerDir, targets)

sweepMeleeArc(origin, startDir, endDir, range, targets, sweepSamples = 5)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create a melee attack arc (pie slice shaped hitbox) Parameters: (number[]) — [x, y, z] attack origin (number[]) — [x, y, z] facing direction (normalized) (number) — Attack range in meters (number) — Total arc angle in degrees (symmetric around direction) Returns: Melee attack arc Check if a point is within the melee arc (2D horizontal check) Uses cosine comparison for efficiency (avoids atan2) Parameters: (Object) — Melee arc from createMeleeArc (number[]) — [x, y, z] target position (number) — Target hitbox radius (default 0) Returns: True if target is hit Check if target is in 3D melee arc (includes vertical angle) Parameters: (Object) — Melee arc (number[]) — [x, y, z] (number) — Target radius (number) — Vertical angle tolerance (default ±45°) Returns: True if hit Create a melee attack state tracker Parameters: (Object) — Attack configuration (number) — Windup duration in ms (number) — Active (damaging) duration in ms (number) — Recovery duration in ms (number) — Attack range (number) — Attack arc in degrees (number) — Base damage Returns: Attack state Start a melee attack Parameters: (Object) — Attack state (number) — Current timestamp (ms) Returns: True if attack started Update melee attack state and check phase transitions Parameters: (Object) — Attack state (number) — Current timestamp (ms) Returns: {phase, justEntered, justExited} Try to interrupt a melee attack (e.g., from stagger) Parameters: (Object) — Attack state Returns: True if interrupted Check for hits during active phase Parameters: (Object) — Attack state (number[]) — [x, y, z] attacker position


— Attack state Returns: True if interrupted Check for hits during active phase Parameters: (Object) — Attack state (number[]) — [x, y, z] attacker position (number[]) — [x, y, z] facing direction Returns: } Hits this frame Chain to next combo attack Parameters: (Object) — Attack state (number) — Current timestamp (ms) Returns: True if combo continues Get combo multiplier for current step Parameters: (number) — Current combo step (0 indexed) Returns: Damage multiplier Perform a sweeping melee attack across multiple positions Useful for wide slash attacks Parameters: (number[]) — [x, y, z] (number[]) — [x, y, z] start of sweep (number[]) — [x, y, z] end of sweep (number) — Attack range (number) — Number of arc samples (default 5) Returns: } Targets hit by sweep Get remaining time in current phase Parameters: (Object) — Attack state (number) — Current timestamp (ms) Returns: Remaining time in ms, or 0 if idle Get phase progress (0 1) Parameters: (Object) — Attack state (number) — Current timestamp (ms) Returns: Progress 0 1 Constants — Attack phase types — Default phase durations in milliseconds <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter


cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


recallEpisodesWithEntity(memory, entityId, limit = 10)

recallEpisodesWithEmotion(memory, emotion, limit = 10)

storeFact(memory, key, value, meta = {})

storeRelationship(memory, subject, predicate, object, confidence = 1.0)

storeBelief(memory, topic, belief, confidence = 0.5)

challengeBelief(memory, topic, evidenceStrength = 0.1)

practiceSkill(memory, skill, success = true)

formHabit(memory, trigger, action, initialStrength = 0.3)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create working memory (limited capacity short term) Parameters: (number) — Max items (default 7, like humans) Returns: Working memory Add item to working memory (displaces oldest if full) Parameters: (Object) — Working memory (Object) — {type, data, priority} Set focus of attention Parameters: (Object) — Working memory (string) — Focus type ( ) — Focus data Get items from working memory by type Parameters: (Object) — Working memory (string) — Item type Returns: Matching items Clear working memory Parameters: (Object) — Working memory Create episodic memory (personal experiences) Parameters: (number) — Maximum stored episodes Returns: Episodic memory Create an episode (memory of an event) Parameters: (Object) — Episode data Returns: Episode Store an episode Parameters: (Object) — Episodic memory (Object) — Episode to store Recall episodes involving an entity Parameters: (Object) — Episodic memory (number) — Entity ID (number) — Max episodes to return Returns: Episodes Recall episodes by emotion Parameters: (Object) — Episodic memory (string) — Emotion type (number) — Max episodes Returns: Episodes Recall recent episodes Parameters: (Object) — Episodic memory (number) — Number to recall Returns: Recent episodes Search episodes by criteria Parameters: (Object) — Episodic memory (Object) — Search criteria Returns: Matching episodes Create semantic memory (facts and knowledge) Returns: Semantic memory Store a fact Parameters: (Object) — Semantic memory (string) — Fact key ( ) — Fact value (Object) — Metadata {confidence, source} Retrieve a fact Parameters: (Object) — Semantic


(Object) — Semantic memory (string) — Fact key ( ) — Fact value (Object) — Metadata {confidence, source} Retrieve a fact Parameters: (Object) — Semantic memory (string) — Fact key Returns: null} Fact or null Store a relationship between entities Parameters: (Object) — Semantic memory (number) — Subject entity ID (string) — Relationship type (number) — Object entity ID (number) — Confidence 0 1 Query relationships Parameters: (Object) — Semantic memory (Object) — {subject?, predicate?, object?} Returns: Matching relationships Store a belief Parameters: (Object) — Semantic memory (string) — Belief topic (string) — The belief (number) — How strongly held Challenge a belief (potentially weakens it) Parameters: (Object) — Semantic memory (string) — Belief topic (number) — Strength of contradicting evidence Create procedural memory (skills and habits) Returns: Procedural memory Record skill practice Parameters: (Object) — Procedural memory (string) — Skill name (boolean) — Was the attempt successful Get skill proficiency Parameters: (Object) — Procedural memory (string) — Skill name Returns: Proficiency 0 1 Form a habit Parameters: (Object) — Procedural memory (string) — What triggers the habit (string) — The habitual action (number) — Starting strength Get habitual response to trigger Parameters: (Object) — Procedural memory (string) — Trigger situation Returns: Habitual action or null Create complete NPC memory system Parameters: (Object) — Configuration Returns: Complete memory system Consolidate memories (transfer from working to long term) Parameters: (Object) — Memory system Get overall impression of an entity Parameters: (Object) — Memory system (number) — Entity ID Returns: Impression {sentiment, familiarity, memories} Constants — Memory types — Event importance


Parameters: (Object) — Memory system (number) — Entity ID Returns: Impression {sentiment, familiarity, memories} Constants — Memory types — Event importance levels <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter.


processDamageMorale(state, damage, fromBehind = false)

processAllyDeath(state, wasLeader = false)

processEnemyDeath(state, wasLeader = false)

updateMorale(state, deltaTimeSec, inCombat, inCover)

updateMoraleContext(state, alliesNearby, enemiesVisible, leaderNearby)

shouldSurrender(state, canEscape = true)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create morale state for an NPC Parameters: (Object) — Morale parameters Returns: Morale state Apply morale change Parameters: (Object) — Morale state (number) — Change amount (positive = boost, negative = damage) Apply suppression Parameters: (Object) — Morale state (number) — Suppression amount Process taking damage Parameters: (Object) — Morale state (number) — Damage amount (boolean) — Was flanked/surprised Process ally death Parameters: (Object) — Morale state (boolean) — Was the ally a leader Process enemy death Parameters: (Object) — Morale state (boolean) — Was the enemy a leader Rally (leader ability) Parameters: (Object) — Morale state Update morale over time (recovery, suppression decay) Parameters: (Object) — Morale state (number) — Delta time in seconds (boolean) — Currently in combat (boolean) — Currently in cover Update context (allies, enemies, leader) Parameters: (Object) — Morale state (number) — Number of allies nearby (number) — Number of enemies visible (boolean) — Is a leader nearby Get accuracy modifier based on morale Parameters: (Object) — Morale state Returns: Accuracy multiplier (0 1.2) Get movement speed modifier based on morale Parameters: (Object) — Morale state Returns: Speed multiplier Get reaction time modifier based on morale Parameters: (Object) — Morale state Returns: Reaction time multiplier (higher = slower) Check if NPC should flee Parameters: (Object) — Morale state Returns: Should flee Check if NPC should surrender Parameters: (Object) — Morale state (boolean) — Is escape possible Returns: Should surrender Check if NPC should take


Should flee Check if NPC should surrender Parameters: (Object) — Morale state (boolean) — Is escape possible Returns: Should surrender Check if NPC should take cover Parameters: (Object) — Morale state (boolean) — Already in cover Returns: Should seek cover Check if NPC should be aggressive (charge, flank) Parameters: (Object) — Morale state Returns: Should be aggressive Roll morale check for risky action Parameters: (Object) — Morale state (number) — Difficulty 0 100 (higher = harder) Returns: Passed check Calculate group morale average Parameters: (Array<Object ) — Array of morale states Returns: Average morale Check if group is routing (majority broken) Parameters: (Array<Object ) — Array of morale states Returns: Group is routing Apply group rally (leader ability affecting all nearby) Parameters: (Array<Object ) — Array of morale states Constants — Morale states — Default morale parameters <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


checkVision(perception, npcPos, npcFacing, targetPos, obstacles)

calculateDetectionRate(visionResult, perception, options = {})

createNoiseEvent(position, loudness, type, sourceId = null)

processVisualDetection(perception, npcPos, npcFacing, target, obstacles, deltaTimeSec, options = {})

processDamage(perception, damageDirection = null, attackerId = null)

checkInvestigationComplete(perception, npcPos, arrivalRadius = 2)

updatePerception(perception, npcPos, npcFacing, targets, noiseEvents, obstacles, deltaTimeSec)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create perception state for an NPC Parameters: (Object) — Perception parameters Returns: Perception state Check if target is in vision cone Parameters: (Object) — Perception state (number[]) — NPC position (number[]) — NPC facing direction (number[]) — Target position (Array) — Obstacles for LOS check Returns: } Calculate detection rate based on visibility conditions Parameters: (Object) — Result from checkVision (Object) — Perception state (Object) — Additional factors Returns: Detection rate multiplier Create a noise event Parameters: (number[]) — Noise position (number) — Noise loudness (0 1) (string) — Noise type (footstep, gunshot, explosion, voice) (number) — Source entity ID Returns: Noise event Check if NPC can hear a noise event Parameters: (Object) — Perception state (number[]) — NPC position (Object) — Noise event Returns: } Process visual detection of a target Parameters: (Object) — Perception state (number[]) — NPC position (number[]) — NPC facing (Object) — Target {id, position} (Array) — Obstacles (number) — Delta time in seconds (Object) — Detection options Returns: } Process a noise event Parameters: (Object) — Perception state (number[]) — NPC position (Object) — Noise event Returns: } Process taking damage Parameters: (Object) — Perception state (number[]) — Direction damage came from (optional) (number) — Attacker ID (optional) Share threat info from teammate Parameters: (Object) — Perception state (number) — Threat ID (number[]) — Threat position Get last known position of an entity Parameters: (Object) — Perception state (number) — Entity ID


state (number) — Threat ID (number[]) — Threat position Get last known position of an entity Parameters: (Object) — Perception state (number) — Entity ID Returns: Last known position or null Get the most threatening known entity Parameters: (Object) — Perception state Returns: {id, position, awarenessOf, lastSeen} Decay awareness over time Parameters: (Object) — Perception state (number) — Delta time in seconds (boolean) — Whether any threats are visible Check if investigation is complete Parameters: (Object) — Perception state (number[]) — NPC position (number) — Radius to consider "arrived" Returns: True if investigation complete Full perception update tick Parameters: (Object) — Perception state (number[]) — NPC position (number[]) — NPC facing (Array<Object ) — Potential targets (Array<Object ) — Recent noise events (Array) — Obstacles (number) — Delta time in seconds Returns: } Constants — Awareness states — Sense types — Default perception parameters from AISchema <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying


: Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


applyEmotionalStimulus(state, emotion, intensity, personality = null)

decayEmotions(state, deltaTimeSec, decayRate = 0.1)

hasComplexEmotion(state, complexEmotion, threshold = 0.3)

recordInteraction(tracker, entityId, interactionType, valence, intensity = 0.5)

willHelp(tracker, entityId, personality = null)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create personality profile Parameters: (Object) — Initial trait values ( 1 to 1) Returns: Personality profile Create personality from archetype Parameters: (string) — Archetype name Returns: Personality profile Get personality based behavior modifier Parameters: (Object) — Personality profile (string) — Behavior type Returns: Modifier ( 1 to 1) Create emotional state Returns: Emotional state Apply emotional stimulus Parameters: (Object) — Emotional state (string) — Emotion type (number) — Stimulus intensity (0 1) (Object) — Personality (affects response) Decay emotions over time Parameters: (Object) — Emotional state (number) — Delta time in seconds (number) — Base decay rate Check for complex emotion Parameters: (Object) — Emotional state (string) — Complex emotion name (number) — Detection threshold Returns: Is emotion present Create relationship tracker Returns: Relationship tracker Create or get relationship with entity Parameters: (Object) — Relationship tracker (number) — Other entity ID Returns: Relationship data Record interaction with entity Parameters: (Object) — Relationship tracker (number) — Other entity ID (string) — Type of interaction (number) — Positive/negative ( 1 to 1) (number) — Interaction intensity (0 1) Get disposition toward entity Parameters: (Object) — Relationship tracker (number) — Other entity ID Returns: Disposition ( 1 to 1) Will entity help another Parameters: (Object) — Relationship tracker (number) — Other entity ID (Object) — Helper's personality Returns: Will help Create complete character psychological state Parameters: (Object) —


tracker (number) — Other entity ID (Object) — Helper's personality Returns: Will help Create complete character psychological state Parameters: (Object) — Configuration Returns: Character state Update character state Parameters: (Object) — Character state (number) — Delta time Constants — Personality trait ranges: 1 to 1 — Primary emotions — Emotion combinations — Relationship types <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


updateObjectiveProgress(objective, amount = 1)

generateQuest(templateId, params, context = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create quest objective Parameters: (Object) — Objective config Returns: Objective Update objective progress Parameters: (Object) — Objective (number) — Progress to add Returns: Whether objective completed Create quest Parameters: (Object) — Quest config Returns: Quest Check if quest can be accepted Parameters: (Object) — Quest (Object) — Player state {level, completedQuests, reputation, inventory, flags} Returns: } Accept quest Parameters: (Object) — Quest Returns: Success Check quest completion Parameters: (Object) — Quest Returns: Is complete Turn in quest and get rewards Parameters: (Object) — Quest Returns: Rewards or null if can't turn in Fail quest Parameters: (Object) — Quest (string) — Failure reason Create quest manager Returns: Quest manager Register quest Parameters: (Object) — Quest manager (Object) — Quest to register Update available quests based on player state Parameters: (Object) — Quest manager (Object) — Player state Report event for quest objectives Parameters: (Object) — Quest manager (string) — kill, collect, talk, etc. (Object) — {targetType, targetId, location, amount} Returns: Updated quests Generate procedural quest Parameters: (string) — Template to use (Object) — Generation parameters (Object) — World context for content selection Returns: Generated quest Generate daily quests Parameters: (Object) — World context (number) — Number of quests Returns: Generated quests Constants — Quest types — Quest status — Quest priority <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision


types — Quest status — Quest priority <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Set the global AI RNG context. Call this at the start of each game tick. Parameters: (number) — World seed (shared by server) (number) — Current game tick Get RNG state for a specific entity (deterministic per entity+tick) Parameters: (number) — Entity ID Returns: RNG state for this entity Get RNG state for a position (terrain, spawns, etc.) Parameters: (number) — X coordinate (number) — Y coordinate (number) — Z coordinate Returns: RNG state for this position Get RNG state for interaction between two entities Parameters: (number) — First entity (number) — Second entity Returns: RNG state (order independent) Create RNG stream for a specific entity Use when you need multiple random values for one entity in the same tick Parameters: (number) — No description in source JSDoc. Returns: RNG with same API as aiRng Create RNG stream for a world position Parameters: (number) — No description in source JSDoc. (number) — No description in source JSDoc. (number) — No description in source JSDoc. Returns: RNG with same API as aiRng Constants Re exports <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is


Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createGPURaycastSystem(device, options = {})

async batchRaycast(system, rays, targets, targetType = "sphere")

shouldUseGPURaycast(rayCount, threshold = 500)

async benchmarkRaycast(system, rayCount = 1000, targetCount = 100)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create a GPU raycast system Parameters: (GPUDevice) — WebGPU device (Object) — Options Returns: GPU raycast system Upload ray data to GPU Parameters: (Object) — GPU raycast system Upload AABB targets to GPU Parameters: (Object) — GPU raycast system Upload sphere targets to GPU Parameters: (Object) — GPU raycast system Dispatch GPU raycast against AABBs Parameters: (Object) — GPU raycast system (GPUCommandEncoder) — Command encoder Dispatch GPU raycast against spheres Parameters: (Object) — GPU raycast system (GPUCommandEncoder) — Command encoder Copy results to readback buffer Parameters: (Object) — GPU raycast system (GPUCommandEncoder) — Command encoder Read back results from GPU (async) Parameters: (Object) — GPU raycast system Returns: } Results Full batch raycast operation Parameters: (Object) — GPU raycast system (Array) — Ray data (Array) — Target data (AABB or sphere) (string) — "aabb" or "sphere" Returns: Raycast results Destroy GPU raycast system and free resources Parameters: (Object) — GPU raycast system Determine if GPU raycast should be used based on ray count Parameters: (number) — Number of rays to cast (number) — Threshold for GPU usage (default 500) Returns: True if GPU should be used Benchmark CPU vs GPU raycast for calibration Parameters: (Object) — GPU raycast system (number) — Number of rays to test (number) — Number of targets Returns: } <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and


Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


scoreActivity(activity, needs, gameHour = 12)

selectActivity(activities, needs, gameHour = 12)

addScheduleEntry(schedule, hour, activityId, priority = 1, days = null)

getScheduledActivity(schedule, gameHour, dayOfWeek = 0)

updateScheduler(scheduler, gameHour, dayOfWeek, deltaGameHours)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create needs state Parameters: (Object) — Initial values (0 1) Returns: Needs state Update needs over time Parameters: (Object) — Needs state (number) — Game hours elapsed Satisfy a need Parameters: (Object) — Needs state (string) — Need type (number) — Satisfaction amount (0 1) Get most urgent need Parameters: (Object) — Needs state Returns: } Most urgent need Get all critical needs Parameters: (Object) — Needs state Returns: Critical needs Calculate overall wellbeing Parameters: (Object) — Needs state Returns: Wellbeing 0 1 Create an activity definition Parameters: (Object) — Activity config Returns: Activity Score an activity based on needs Parameters: (Object) — Activity definition (Object) — Current needs (number) — Current game hour (0 24) Returns: Activity score Select best activity from options Parameters: (Array<Object ) — Available activities (Object) — Current needs (number) — Current game hour Returns: Best activity Create a daily schedule Returns: Schedule Add scheduled entry Parameters: (Object) — Schedule (number) — Hour to start (0 24) (string) — Activity ID (number) — Override priority (Array<number ) — Days active (0=Sun, 1=Mon, etc.), null=all Get scheduled activity for time Parameters: (Object) — Schedule (number) — Current hour (number) — Day (0 6) Returns: Schedule entry Create job definition Parameters: (Object) — Job config Returns: Job definition Check if currently work hours Parameters: (Object) — Job definition (number) — Current hour (number) — Day (0 6) Returns: Is work time Create NPC scheduler Parameters: (Object) — Configuration Returns:


(Object) — Job definition (number) — Current hour (number) — Day (0 6) Returns: Is work time Create NPC scheduler Parameters: (Object) — Configuration Returns: NPC scheduler Update NPC scheduler Parameters: (Object) — NPC scheduler (number) — Current game hour (number) — Day of week (number) — Time elapsed Returns: } Constants — Basic need types — Need urgency thresholds — Job types <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/ai/AISchema.js
Functions
getNodeTypeId(typeName)
getAwarenessStateId(stateName)
getAwarenessStateName(stateId)
getReputationLevel(value)
validatePerception(config)
validateSteeringAgent(config)
validatePersonality(config)
createDefaultPerception()
createDefaultSteeringAgent()
createDefaultPersonality()
createDefaultFaction(id, name)
Constants
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Get node type ID from name Get awareness state ID from name Get awareness state name from ID Get reputation level from value Validate perception parameters Validate steering agent config Validate personality Create default perception config Create default steering agent Create default personality Create default faction Constants — Behavior tree node status — Behavior tree node types — NPC awareness states — Sense types for perception — Perception parameters schema — Steering behavior types — Steering agent schema — Diplomatic stances — Reputation levels — Faction schema — Personality traits (Big Five + custom) — Personality schema — Complete NPC AI schema — Create preset personality <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


addTrailParticle(trail, position, intensity = 1.0)

smellAt(system, position, range, sensitivity = 1.0)

followScentTrail(system, position, targetSourceId, range)

senseVibrations(system, position, sensitivity = 1.0)

registerThreat(system, threatId, position, dangerLevel, type = "unknown")

senseDanger(system, position, range, sensitivity = 1.0)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create scent particle Parameters: (Object) — Scent config Returns: Scent particle Create scent trail (series of particles) Parameters: (string) — Source entity ID (string) — Scent type Returns: Scent trail Add particle to trail Parameters: (Object) — Scent trail (number[]) — Position (number) — Intensity Create scent system Returns: Scent system Update scent system Parameters: (Object) — Scent system (number) — Seconds Smell at position Parameters: (Object) — Scent system (number[]) — Sniffer position (number) — Smell range (number) — Smell sensitivity 0 1 Returns: } Follow scent trail Parameters: (Object) — Scent system (number[]) — Current position (string) — Source ID to track (number) — Search range Returns: } Create vibration event Parameters: (Object) — Config Returns: Vibration Create tremor sense system Returns: Tremor sense Emit vibration Parameters: (Object) — Tremor system (Object) — Vibration to emit Sense vibrations at position Parameters: (Object) — Tremor system (number[]) — Listener position (number) — Sensitivity 0 1 Returns: } Create danger sense system Returns: Danger sense Register threat Parameters: (Object) — Danger sense (string) — Threat ID (number[]) — Threat position (number) — Danger 0 1 (string) — Threat type Remove threat Parameters: (Object) — Danger sense (string) — Threat ID Sense danger level at position Parameters: (Object) — Danger sense (number[]) — Position to check (number) — Sense range (number) — Sensitivity 0 1 Returns: } Create environmental sensor Returns: Environment sensor Update environment readings Parameters: (Object) —


— Sense range (number) — Sensitivity 0 1 Returns: } Create environmental sensor Returns: Environment sensor Update environment readings Parameters: (Object) — Environment sensor (Object) — {temperature, humidity, etc.} Get environmental comfort level Parameters: (Object) — Environment sensor Returns: } Detect environmental trend Parameters: (Object) — Environment sensor (string) — Property to check Returns: } rising, falling, stable Constants — Scent types <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


getSlotWorldPosition(smartObject, slotIndex = 0)

updateInteraction(interaction, npcPos, npcFacing, now)

findNearestUsable(registry, position, npcState, filters = {})

createHealthStation(id, position, healAmount = 50)

createAmmoCrate(id, position, ammoAmount = 30)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create a smart object Parameters: (Object) — Object configuration Returns: Smart object Get world position of an interaction slot Parameters: (Object) — Smart object (number) — Slot index Returns: } World position and facing Find available slot for interaction Parameters: (Object) — Smart object Returns: Slot index or 1 if none available Reserve a slot for an NPC Parameters: (Object) — Smart object (number) — Slot index (number) — NPC ID Returns: True if reserved Release a slot Parameters: (Object) — Smart object (number) — Slot index Check if NPC meets prerequisites for interaction Parameters: (Object) — Smart object (Object) — NPC state data Returns: } Can use and missing prereqs Create an interaction session Parameters: (Object) — Smart object (number) — NPC ID (number) — Reserved slot index Returns: Interaction session Update interaction state Parameters: (Object) — Interaction session (number[]) — NPC position (number[]) — NPC facing (number) — Current time Returns: } Complete interaction and apply effects Parameters: (Object) — Smart object (Object) — Interaction session (Object) — NPC state to modify Returns: Applied effects Create a smart object registry Returns: Registry Register a smart object Parameters: (Object) — Registry (Object) — Smart object Find smart objects by category Parameters: (Object) — Registry (string) — Category Returns: Matching objects Find smart objects by tag Parameters: (Object) — Registry (string) — Tag Returns: Matching objects Find nearest usable smart object Parameters: (Object) — Registry (number[]) — NPC position (Object) — NPC


— Registry (string) — Tag Returns: Matching objects Find nearest usable smart object Parameters: (Object) — Registry (number[]) — NPC position (Object) — NPC state (Object) — Filters {category, tag, maxDistance} Returns: Nearest usable object Create a health station smart object Parameters: (number) — Object ID (number[]) — World position (number) — Amount to heal Returns: Smart object Create an ammo crate smart object Parameters: (number) — Object ID (number[]) — World position (number) — Amount of ammo Returns: Smart object Create a door smart object Parameters: (number) — Object ID (number[]) — World position (number) — Y rotation Returns: Smart object Constants — Smart object categories — Interaction states <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


registerListener(system, entityId, config = {})

getRecentDetections(system, entityId, maxAge = 5000)

emitFootstep(system, position, surface = SURFACETYPE.CONCRETE, running = false)

emitGunshot(system, position, weaponType = "pistol")

emitExplosion(system, position, size = 1.0)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create a sound event Parameters: (Object) — Sound config Returns: Sound event Create sound propagation system Parameters: (Object) — Config Returns: Sound system Register listener (AI agent that can hear) Parameters: (Object) — Sound system (string) — Entity ID (Object) — Hearing config Update listener position Parameters: (Object) — Sound system (string) — Entity ID (number[]) — New position Add wall/occluder Parameters: (Object) — Sound system (Object) — {start, end, height, surface} Emit sound Parameters: (Object) — Sound system (Object) — Sound configuration Returns: Created sound event Calculate sound intensity at position Parameters: (Object) — Sound event (number[]) — Listener position (Array) — Wall occluders Returns: } Update sound propagation and detection Parameters: (Object) — Sound system (number) — Seconds Returns: New detections [{listenerId, sound, intensity}] Get recent detections for entity Parameters: (Object) — Sound system (string) — Entity ID (number) — Max age in ms Returns: Recent detections Get highest priority unhandled detection Parameters: (Object) — Sound system (string) — Entity ID Returns: Detection or null Emit footstep sound Parameters: (Object) — Sound system (number[]) — Position (string) — Surface type (boolean) — Is running Emit gunshot sound Parameters: (Object) — Sound system (number[]) — Position (string) — Weapon type (pistol, rifle, shotgun) Emit explosion sound Parameters: (Object) — Sound system (number[]) — Position (number) — Explosion size 0 1 Constants — Sound categories — Surface types for acoustic properties — Sound


(Object) — Sound system (number[]) — Position (number) — Explosion size 0 1 Constants — Sound categories — Surface types for acoustic properties — Sound priority for AI attention <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


addToSquad(manager, squad, npc, role = SQUADROLE.NONE)

queueBark(squad, npcId, barkType, data = {})

updateSquadTactics(manager, squad, threatPos, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create a squad manager Returns: Squad manager Create a new squad Parameters: (Object) — Squad manager (Object) — Leader NPC Returns: New squad Add NPC to squad Parameters: (Object) — Squad manager (Object) — Squad (Object) — NPC to add (number) — Squad role Remove NPC from their squad Parameters: (Object) — Squad manager (number) — NPC ID Disband a squad Parameters: (Object) — Squad manager (Object) — Squad to disband Update squad formations based on proximity NPCs within range form impromptu squads Parameters: (Object) — Squad manager (Array<Object ) — All NPCs Assign tactical roles to squad members Parameters: (Object) — Squad (number[]) — Threat position Calculate attack positions for coordinated assault Parameters: (Object) — Squad (number[]) — Target position (Array<Object ) — Available cover Returns: NPC ID → attack position Check if squad should coordinate suppression fire Parameters: (Object) — Squad (number[]) — Target position Returns: {suppressor, movers} or null Queue a bark for the squad Parameters: (Object) — Squad (number) — Speaking NPC ID (string) — BARK TYPE (Object) — Additional bark data Process pending barks Parameters: (Object) — Squad Returns: Barks to display/play Get bark text for a bark type Parameters: (string) — BARK TYPE Returns: Bark text Update squad tactical state Parameters: (Object) — Squad manager (Object) — Squad (number[]) — Threat position (if known) (Object) — Update options Get squad for an NPC Parameters: (Object) — Squad manager (number) — NPC ID Returns: Squad or null Get teammates for an NPC (excluding self) Parameters:


Get squad for an NPC Parameters: (Object) — Squad manager (number) — NPC ID Returns: Squad or null Get teammates for an NPC (excluding self) Parameters: (Object) — Squad manager (number) — NPC ID Returns: Teammate NPCs Constants — Squad roles — Communication bark types <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


arrive(agent, target, slowingRadius = 5)

separation(agent, neighbors, separationRadius = 3)

alignment(agent, neighbors, alignmentRadius = 5)

cohesion(agent, neighbors, cohesionRadius = 8)

setFlowDirection(field, x, y, dirX, dirZ)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create a steering agent Uses AISchema defaults for consistent configuration Parameters: (Object) — Agent configuration Returns: Steering agent Apply steering force to agent Parameters: (Object) — Steering agent (number[]) — Force vector Update agent physics Parameters: (Object) — Steering agent (number) — Delta time in seconds Seek: steer toward target Parameters: (Object) — Steering agent (number[]) — Target position Returns: Steering force Flee: steer away from target Parameters: (Object) — Steering agent (number[]) — Target position to flee from Returns: Steering force Arrive: seek with slowing near target Parameters: (Object) — Steering agent (number[]) — Target position (number) — Distance to start slowing Returns: Steering force Pursue: seek predicted future position of moving target Parameters: (Object) — Steering agent (number[]) — Target current position (number[]) — Target velocity Returns: Steering force Evade: flee from predicted future position Parameters: (Object) — Steering agent (number[]) — Pursuer position (number[]) — Pursuer velocity Returns: Steering force Wander: random steering Parameters: (Object) — Steering agent Returns: Steering force Avoid obstacles using ray casting Parameters: (Object) — Steering agent Returns: Steering force Avoid walls using feeler rays Parameters: (Object) — Steering agent Returns: Steering force Separation: steer away from nearby agents Parameters: (Object) — Steering agent (Array<Object ) — Nearby agents (number) — Distance to separate from Returns: Steering force Alignment: steer toward average heading of neighbors


agent (Array<Object ) — Nearby agents (number) — Distance to separate from Returns: Steering force Alignment: steer toward average heading of neighbors Parameters: (Object) — Steering agent (Array<Object ) — Nearby agents (number) — Neighborhood radius Returns: Steering force Cohesion: steer toward center of neighbors Parameters: (Object) — Steering agent (Array<Object ) — Nearby agents (number) — Neighborhood radius Returns: Steering force Combined flocking behavior Parameters: (Object) — Steering agent (Array<Object ) — Nearby agents (Object) — Behavior weights Returns: Combined steering force Follow a path Parameters: (Object) — Steering agent (Array<number[] ) — Array of waypoints (number) — Radius to consider "on path" Returns: } Create a flow field Parameters: (number) — Grid width (number) — Grid height (number) — Cell size in world units Returns: Flow field Set flow field cell direction Parameters: (Object) — Flow field (number) — Cell X (number) — Cell Y (number) — Direction X (number) — Direction Z Get flow direction at world position Parameters: (Object) — Flow field (number) — World X (number) — World Z Returns: Direction [x, 0, z] Follow flow field Parameters: (Object) — Steering agent (Object) — Flow field Returns: Steering force Generate flow field toward target Parameters: (Object) — Flow field (number) — Target world X (number) — Target world Z Re exports <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced:


accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


calculateMovementCost(grid, fromX, fromZ, toX, toZ)

calculateHeightAdvantage(grid, attackerX, attackerZ, defenderX, defenderZ)

findHighGround(grid, centerX, centerZ, radius, count = 5)

findConcealment(grid, centerX, centerZ, radius, count = 5)

detectChokepoints(grid, minX, minZ, maxX, maxZ)

evaluateTacticalPosition(grid, worldX, worldZ, threatDirection = null)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create terrain grid Parameters: (number) — Grid width (number) — Grid height (number) — World units per cell Returns: Terrain grid Set terrain type at cell Parameters: (Object) — Terrain grid (number) — Cell X (number) — Cell Y (string) — Terrain type Get terrain type at cell Parameters: (Object) — Terrain grid (number) — Cell X (number) — Cell Y Returns: Terrain type Set height at cell Parameters: (Object) — Terrain grid (number) — Cell X (number) — Cell Y (number) — Height value Get height at cell Parameters: (Object) — Terrain grid (number) — Cell X (number) — Cell Y Returns: Height World to grid coordinates Parameters: (Object) — Terrain grid (number) — World X (number) — World Z Returns: } Grid to world coordinates (cell center) Parameters: (Object) — Terrain grid (number) — Cell X (number) — Cell Y Returns: } Get terrain properties at world position Parameters: (Object) — Terrain grid (number) — World X (number) — World Z Returns: Terrain properties Calculate movement cost between two points Parameters: (Object) — Terrain grid (number) — Start world X (number) — Start world Z (number) — End world X (number) — End world Z Returns: Movement cost Get stealth modifier at position Parameters: (Object) — Terrain grid (number) — World X (number) — World Z Returns: Stealth multiplier (higher = better stealth) Get noise modifier at position Parameters: (Object) — Terrain grid (number) — World X (number) — World Z Returns: Noise multiplier (higher = louder) Calculate height advantage Parameters: (Object) — Terrain grid (number) — Attacker world X (number) — Attacker world Z


Noise multiplier (higher = louder) Calculate height advantage Parameters: (Object) — Terrain grid (number) — Attacker world X (number) — Attacker world Z (number) — Defender world X (number) — Defender world Z Returns: Height advantage ( 1 to 1, positive = attacker has advantage) Find high ground positions in area Parameters: (Object) — Terrain grid (number) — Center world X (number) — Center world Z (number) — Search radius (number) — Max positions to return Returns: } High ground positions Find concealment positions Parameters: (Object) — Terrain grid (number) — Center world X (number) — Center world Z (number) — Search radius (number) — Max positions Returns: } Detect chokepoints in area Parameters: (Object) — Terrain grid (number) — Min world X (number) — Min world Z (number) — Max world X (number) — Max world Z Returns: } Evaluate tactical position value Parameters: (Object) — Terrain grid (number) — World X (number) — World Z (number[]) — Direction threat is coming from Returns: Tactical evaluation Constants — Terrain types <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At


simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createConsideration(name, inputFn, curve, weight = 1)

createUtilityAction(name, considerations, execute, options = {})

selectActionWeighted(actions, context, randomFactor = 0.2)

selectActionBucketed(actions, context, bucketSize = 3)

createUtilityBrain(actions, options = {})

updateUtilityBrain(brain, context, now = performance.now()

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Linear curve: y = mx + b Parameters: (number) — Slope (m) (number) — Y intercept (b) Returns: Curve function Inverse linear curve: y = 1 x Returns: Curve function Quadratic curve: y = (x offset)^2 scale Parameters: (number) — Scale factor (number) — X offset Returns: Curve function Exponential curve: y = e^(kx) normalized Parameters: (number) — Exponent factor Returns: Curve function Logistic (S curve): y = 1 / (1 + e^( k(x midpoint))) Parameters: (number) — Steepness (number) — X value at y=0.5 Returns: Curve function Smoothstep curve: 3x^2 2x^3 Returns: Curve function Step curve: returns 0 below threshold, 1 above Parameters: (number) — Step threshold Returns: Curve function Bell curve (Gaussian like): peaks at center Parameters: (number) — Peak position (number) — Width of bell Returns: Curve function Custom curve from control points (piecewise linear) Returns: Curve function Create a consideration (single scoring factor) Parameters: (string) — Consideration name (Function) — Function to get normalized input (context) = 0 1 (Function) — Response curve function (number) — Weight multiplier (default 1) Returns: Consideration Evaluate a consideration Parameters: (Object) — Consideration object (Object) — Context data Returns: Score 0 1 Create a utility action Parameters: (string) — Action name (Array<Object ) — Array of considerations (Function) — Execution function (context) = void (Object) — Additional options Returns: Utility action Score an action Parameters: (Object) — Utility action (Object) — Context data Returns: Final score Select best action from candidates


Returns: Utility action Score an action Parameters: (Object) — Utility action (Object) — Context data Returns: Final score Select best action from candidates Parameters: (Array<Object ) — Available actions (Object) — Context data Returns: null} Best action or null Select action with weighted randomization Higher scores = higher chance, but not guaranteed Parameters: (Array<Object ) — Available actions (Object) — Context data (number) — Randomization factor (0 = deterministic, 1 = fully random) Returns: null} Selected action Select from top N actions (bucketing) Parameters: (Array<Object ) — Available actions (Object) — Context data (number) — Number of top actions to consider Returns: null} Selected action Create a utility AI brain Parameters: (Array<Object ) — Available actions (Object) — Brain options Returns: Utility brain Update utility brain and select action Parameters: (Object) — Utility brain (Object) — Context data (number) — Current time Returns: null} Selected action or null if no change Execute the current action Parameters: (Object) — Utility brain (Object) — Context data Create health consideration Parameters: (number) — Health % considered critical Returns: Consideration Create distance consideration Parameters: (number) — Ideal distance (number) — Maximum relevant distance Returns: Consideration Create ammo consideration Returns: Consideration Create threat consideration Returns: Consideration Create cover consideration Returns: Consideration Create line of sight consideration Returns: Consideration Create basic combat action set Parameters: (Object) — Action handler functions Returns: Actions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes


NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bu


wouldDoAction(system, action, threshold = 0)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create NPC values system Parameters: (Object) — Configuration Returns: Values system Create a life goal Parameters: (Object) — Goal config Returns: Life goal Get value strength Parameters: (Object) — Value system (string) — Value type Returns: Strength ( 3 to 3) Set value strength Parameters: (Object) — Value system (string) — Value type (number) — New level Modify value (shift toward a direction) Parameters: (Object) — Value system (string) — Value type (number) — Change amount Check if NPC values something Parameters: (Object) — Value system (string) — Value type Returns: Values it positively Get top values (what they care about most) Parameters: (Object) — Value system (number) — How many to return Returns: } Update psychological need Parameters: (Object) — Value system (string) — Need type (number) — Change in satisfaction Decay psychological needs over time Parameters: (Object) — Value system (number) — Time elapsed in seconds Get most deprived psychological need Parameters: (Object) — Value system Returns: } Calculate overall psychological wellbeing Parameters: (Object) — Value system Returns: Wellbeing 0 1 Add life goal Parameters: (Object) — Value system (Object) — Goal to add Update goal progress Parameters: (Object) — Value system (string) — Goal ID (number) — New progress (0 1) Start pursuing a goal Parameters: (Object) — Value system (string) — Goal ID Get active goals being pursued Parameters: (Object) — Value system Returns: Active goals Get unfulfilled dreams Parameters: (Object) — Value system Returns: Dreams Score an action based on values Parameters:


— Value system Returns: Active goals Get unfulfilled dreams Parameters: (Object) — Value system Returns: Dreams Score an action based on values Parameters: (Object) — Value system (Object) — {affects: {value: impact}} Returns: Score (higher = more aligned with values) Would NPC do this action based on values? Parameters: (Object) — Value system (Object) — Action with value impacts (number) — Minimum score to accept Returns: } Create value system from preset Parameters: (string) — Preset name Returns: Value system Constants — Value types things an NPC can care about — Value strength levels — Types of life goals — Goal status — Higher order psychological needs — Preference categories — Value presets for quick character creation <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createVehicle(vehicleType, position, heading = 0)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: AIVehicle.js ⚠ MULTIPLAYER: Uses deterministic RNG from AIRandom.js Functions Create vehicle definition Parameters: (Object) — Vehicle config Returns: Vehicle definition Create vehicle instance Parameters: (Object) — Vehicle type definition (number[]) — Starting position (number) — Starting heading (radians) Returns: Vehicle instance Update vehicle physics Parameters: (Object) — Vehicle instance (number) — Seconds elapsed Update vehicle AI Parameters: (Object) — Vehicle instance (Object) — World data (roads, traffic, etc.) (number) — Seconds elapsed Set vehicle path Parameters: (Object) — Vehicle (Array<number[] ) — Path waypoints Create traffic system Parameters: (Object) — Config Returns: Traffic system Update traffic system Parameters: (Object) — Traffic system (number) — Seconds elapsed Constants — Vehicle behavior modes — Traffic light states <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU


what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


fireHitscan(origin, direction, weapon, targets, obstacles = [])

fireShotgun(origin, direction, weapon, targets, obstacles = [])

calculateDamageFalloff(baseDamage, distance, rangeModifier = 0.98)

createProjectile(position, velocity, config = {})

checkProjectileCollision(projectile, targets, projectileRadius = 0.5)

resolveCircularAoE(center, radius, baseDamage, targets)

isInConeAoE(targetPos, origin, direction, halfAngleRad, range)

resolveConeAoE(origin, direction, coneAngleDeg, range, baseDamage, targets)

updateBeamTracking(beam, origin, targetPos, deltaTimeSec)

fireBeam(beam, origin, targets, obstacles, deltaTimeSec)

createGrenade(position, velocity, config = {})

updateGrenade(grenade, deltaTimeSec, surfaces = [])

calculateGrenadeLaunchVelocity(start, target, gravity, launchAngleDeg)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Fire a hitscan weapon (instant ray hit) Parameters: (number[]) — [x, y, z] muzzle position (number[]) — [x, y, z] aim direction (Object) — Weapon config Returns: {hit: boolean, targetId, damage, point, distance} Fire a shotgun (multiple pellets in ring pattern) Parameters: (number[]) — [x, y, z] (number[]) — [x, y, z] (Object) — Weapon config (Array) — Targets (Array) — Obstacles Returns: Array of hit results per pellet Calculate damage falloff (CS:GO style exponential) Parameters: (number) — Base weapon damage (number) — Distance to target (number) — Falloff rate (0.98 = 2% per 500 units) Returns: Final damage Create a projectile entity Parameters: (number[]) — [x, y, z] spawn position (number[]) — [x, y, z] initial velocity (Object) — Projectile config Returns: Projectile state Update projectile position (kinematic motion) Parameters: (Object) — Projectile state (number) — Delta time in seconds Get projectile position at future time (prediction) P(t) = P₀ + V₀×t + ½×g×t² Parameters: (Object) — Projectile state (number) — Time in seconds Returns: [x, y, z] predicted position Check projectile collision with targets Parameters: (Object) — Projectile state (number) — Projectile hitbox radius Returns: {targetId, point} or null Check if target is in circular AoE Parameters: (number[]) — [x, y, z] (number[]) — [x, y, z] AoE center (number) — AoE radius Returns: True if in AoE Calculate AoE damage with quadratic falloff Parameters: (number) — Base damage at center (number) — Distance from center (number) — AoE radius Returns: Damage amount Get all targets in circular AoE with


Parameters: (number) — Base damage at center (number) — Distance from center (number) — AoE radius Returns: Damage amount Get all targets in circular AoE with damage Parameters: (number[]) — [x, y, z] AoE center (number) — AoE radius (number) — Base damage Returns: } Affected targets Check if target is in cone AoE Parameters: (number[]) — [x, y, z] (number[]) — [x, y, z] cone origin (number[]) — [x, y, z] cone direction (number) — Half cone angle in radians (number) — Cone range Returns: True if in cone Get all targets in cone AoE Parameters: (number[]) — [x, y, z] (number[]) — [x, y, z] (number) — Full cone angle in degrees (number) — Cone range (number) — Base damage Returns: } Affected targets Create a beam weapon state Parameters: (Object) — Beam config Returns: Beam weapon state Update beam weapon direction toward target Parameters: (Object) — Beam weapon state (number[]) — [x, y, z] beam origin (number[]) — [x, y, z] target position (number) — Delta time in seconds Fire beam weapon (continuous damage) Parameters: (Object) — Beam weapon state (number[]) — [x, y, z] (Array) — Targets (Array) — Obstacles (number) — Delta time Returns: {hit, targetId, damage, endPoint} Create a grenade projectile Parameters: (number[]) — [x, y, z] spawn position (number[]) — [x, y, z] initial velocity (Object) — Grenade config Returns: Grenade state Update grenade physics Parameters: (Object) — Grenade state (number) — Delta time in seconds Returns: True if exploded Calculate grenade launch velocity to hit target Parameters: (number[]) — [x, y, z] throw position (number[]) — [x, y, z] target position (number) — Gravity value (number) — Launch angle in degrees Returns: [x, y, z] launch velocity or null if impossible Create an NPC weapon controller for multi weapon management Returns:


— Launch angle in degrees Returns: [x, y, z] launch velocity or null if impossible Create an NPC weapon controller for multi weapon management Returns: Weapon controller Add weapon to controller Parameters: (Object) — Weapon controller (string) — Weapon name (Object) — Weapon config Select best weapon for situation Parameters: (Object) — Weapon controller (Object) — Selection parameters (number) — Distance to target (boolean) — Whether LOS is clear (boolean) — Whether multiple targets are present Returns: Best weapon name Check if weapon can fire (fire rate cooldown) Parameters: (Object) — Weapon controller (string) — Weapon to check (number) — Current timestamp (ms) Returns: True if can fire Record wea


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create world time system Parameters: (Object) — Time config Returns: World time Advance world time Parameters: (Object) — World time (number) — Real seconds elapsed Returns: } Get current season Parameters: (Object) — World time Returns: Season Get day/night phase Parameters: (Object) — World time Returns: } Get formatted time string Parameters: (Object) — World time Returns: Formatted time Get formatted date string Parameters: (Object) — World time Returns: Formatted date Create weather system Parameters: (Object) — Weather config Returns: Weather system Update weather Parameters: (Object) — Weather system (Object) — World time (number) — Hours elapsed Get weather effects on gameplay Parameters: (Object) — Weather system Returns: Gameplay modifiers Create world event Parameters: (Object) — Event config Returns: World event Create world event manager Returns: Event manager Schedule world event Parameters: (Object) — Event manager (Object) — Event to schedule Update world events Parameters: (Object) — Event manager (number) — Current game time (total hours) (number) — Hours elapsed Returns: } Create complete world state Parameters: (Object) — Configuration Returns: World state Update world state Parameters: (Object) — World state (number) — Real seconds elapsed Returns: Changes that occurred Constants — Seasons — Days of week — Months — Weather types — Event types <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and


Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


bakeNavGridFromWorldSim(grid, worldSim, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Convert axial (q, r) to cube (q, r, s) coordinates Convert cube to axial coordinates Convert cube coordinates to world position (pointy top hexes) Parameters: (number) — Cube Q coordinate (number) — Cube R coordinate (number) — Hex size (center to corner) Returns: } World position Convert world position to cube hex coordinates Parameters: (number) — World X (number) — World Z (number) — Hex size Returns: } Cube coordinates (rounded) Round fractional cube coordinates to nearest hex Get 6 hex neighbors in cube coordinates Calculate hex distance in cube coordinates Get all hexes within range of center Parameters: (number) — Center Q (number) — Center R (number) — Range in hex steps Returns: Array of {q, r, s} coordinates Get hex ring at exact distance from center Parameters: (number) — Center Q (number) — Center R (number) — Ring radius Returns: Array of {q, r, s} coordinates Linear interpolation between two hexes (for line drawing) Parameters: (number) — Start Q (number) — Start R (number) — End Q (number) — End R Returns: Array of {q, r, s} coordinates along line Create hex grid for strategy layer Parameters: (number) — Grid radius in hexes (number) — Hex size in world units Returns: Hex grid data structure <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection


The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/ai/NavWorld.js
Functions
createNavWorld(options = {})
destroyNavWorld(navWorld)
addGridLayer(navWorld, name, grid)
getGridLayer(navWorld, name)
removeGridLayer(navWorld, name)
Notes & Examples
Physics Engine Integration


findPathOnGrid(grid, start, goal, options = {})

findPathInNavWorld(navWorld, layerName, start, goal, options = {})


spatialHashQueryRadius(hash, x, y, z, radius)

spatialHashQueryRadius2D(hash, x, z, radius)

spatialHashKNearest(hash, x, y, z, k, maxRadius = 100)

createObjectPool(factory, reset = null, initialSize = 100)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create a 3D spatial hash grid Parameters: (number) — Size of each cell (should match typical query radius) Returns: Spatial hash instance Insert an entity into the spatial hash Parameters: (Object) — Spatial hash (Object) — Entity with {id, position: [x, y, z], ...} Remove an entity from the spatial hash Parameters: (Object) — Spatial hash (number string) — Entity ID Update an entity's position in the spatial hash Parameters: (Object) — Spatial hash (Object) — Entity with updated position Query all entities within radius of a point Parameters: (Object) — Spatial hash (number) — Query X (number) — Query Y (number) — Query Z (number) — Query radius Returns: Entities within radius Query all entities within radius (2D, ignores Y) Parameters: (Object) — Spatial hash (number) — Query X (number) — Query Z (number) — Query radius Returns: Entities within radius Query entities in an AABB Parameters: (Object) — Spatial hash (number[]) — [x, y, z] minimum corner (number[]) — [x, y, z] maximum corner Returns: Entities in AABB Get K nearest neighbors to a point Parameters: (Object) — Spatial hash (number) — Query X (number) — Query Y (number) — Query Z (number) — Number of neighbors (number) — Maximum search radius Returns: } K nearest entities with distances Clear all entities from the spatial hash Parameters: (Object) — Spatial hash Get total entity count Parameters: (Object) — Spatial hash Returns: Total entities Rebuild the spatial hash from an entity array Parameters: (Object) — Spatial hash (Array<Object ) — Array of entities with {id, position} Create an object pool for


the spatial hash from an entity array Parameters: (Object) — Spatial hash (Array<Object ) — Array of entities with {id, position} Create an object pool for reducing GC pressure Parameters: (Function) — Factory function to create new objects (Function) — Function to reset an object before reuse (number) — Initial pool size Returns: Object pool Acquire an object from the pool Parameters: (Object) — Object pool Returns: Object from pool (or newly created) Release an object back to the pool Parameters: (Object) — Object pool (Object) — Object to release Release all active objects back to pool Parameters: (Object) — Object pool Get pool statistics Parameters: (Object) — Object pool Returns: } <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/ai/index.js
Re-exports
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Re exports , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere,


& Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


stepClothSimWorld(world, deltaSeconds, options = {})


sim/fluids/FDTDSolver.js
Classes
class YeeCell
class TimeVaryingMaterial
class FDTDSource
class FDTDSolver
Constants
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Yee cell field components Staggered grid: E at integers, H at half integers Method Signature Summary Time varying material properties Method Signature Summary Get permittivity at given time Get permeability at given time Check if point is within material region Method Signature Summary Get source value at time t Method Signature Summary Compute stable time step via CFL condition Initialize GPU resources Add time varying material Add source Schedule time reflection event Create photonic time crystal Update uniforms before step Update time varying materials Inject sources Perform one FDTD time step Run multiple steps Get field data for visualization Reset simulation Get simulation info Enforce CFL condition for numerical stability CFL: c dt <= dx / sqrt(dims) for FDTD Get minimum stable epsilon for given mu Compute number of sub steps needed for stability with fast media Run with adaptive sub stepping for stability Saturate field value to prevent NaN/Inf explosion Uses soft clipping: E sat tanh(E / E sat) Saturate 3D vector field Check for NaN/Inf in field data and recover Get stability diagnostics Auto configure dt for stability Constants — Physical constants — Material types — Boundary conditions — Source types <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision


and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createBoundaryPipeline(device, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Generate WGSL shader for applying solid boundaries to velocity This should run after the pressure projection step Generate WGSL shader for pressure solve with solid boundaries Modifies the Jacobi iteration to handle solid cells Create boundary enforcement pipeline Apply solid boundaries to velocity field <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/fluids/FluidConfig.js
Functions
normalizeFluidGridSize(input)
Constants
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


applyFluidSourcesCpu(world, options = {})


createMPMPipelines(device, options = {})

stepMPMWorld(world, particles, dt, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create MPM specific buffers for the fluid simulation Destroy MPM buffers Generate the P2G (Particle to Grid) compute shader Uses linear kernel (tent function) for simplicity Generate the Grid Update compute shader Converts accumulated momentum to velocity, applies forces and boundaries Generate the G2P (Grid to Particle) compute shader Create MPM compute pipelines Create a complete MPM simulation world Destroy MPM world Step the MPM simulation Parameters: (Object) — MPM world from createMPMWorld (Object) — Particle system with positionBuffer, velocityBuffer (number) — Time step (Object) — Additional options Update MPM world bounds <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createSpellForce(position, direction, power, element)

createSolidCollisionPipeline(device, workgroupSize = 256)

createCrystalBondPipeline(device, workgroupSize = 256)

createBondConstraintPipeline(device, workgroupSize = 256)

stepSolidCollision(device, collisionPipeline, phaseBuffers, particleWorld, colliderData, roomBounds, dt, options = {})

stepCrystalBonds(device, bondPipeline, phaseBuffers, particleWorld, options = {})

stepBondConstraints(device, constraintPipeline, phaseBuffers, particleWorld, bondCount, options = {})

stepCrystalSystem(device, systems, phaseBuffers, particleWorld, colliderData, roomBounds, dt, options = {})

createCrystalSystemPipelines(device, workgroupSize = 256)

async extractCrystalClusters(device, phaseBuffers, particleWorld, minClusterSize = 5)

createSeedInjectionParams(position, radius, seedStrength, temperature, magicSaturation)

createCrystallizationPipeline(device, workgroupSize = 256)

stepCrystallization(device, crystallization, phaseBuffers, particleWorld, dt, options = {})

injectFreezeSeeds(device, phaseBuffers, particleWorld, seedParams)

injectHeatSeeds(device, phaseBuffers, particleWorld, seedParams)

applyPhaseVisuals(device, phaseBuffers, particleWorld, options = {})

async extractFrozenShape(device, phaseChangeBuffers, gridSize, worldMin, cellSize)

injectMeltedFluid(device, fluidWorld, position, velocity, mass, radius)

async extractFrozenParticles(device, phaseBuffer, positionBuffer, particleCount, minClusterSize = 5)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Create phase change data structures Spell force injection point Generate shader for applying spell forces to fluid Generate shader for freeze effect (temperature based phase transition) Generate shader for particle based crystallization chain reaction Physics based with latent heat buffer, hysteresis, and asymmetric rates Key concepts from real physics: Latent heat: Energy absorbed/released during phase change while temp stays constant Hysteresis: Different thresholds for freezing vs melting (prevents flickering) Supercooling: Fluid can stay liquid below freezing until nucleation occurs Generate shader for solid particle collision Frozen particles get rigid collision with world, entities, AND other particles Also handles temperature transfer on contact Generate shader for crystal bond formation Finds nearby frozen particles and creates rigid bonds between them Generate shader for bond constraint solving (Position Based Dynamics) Maintains rigid crystal structure by keeping bonded particles at fixed distances Create compute pipeline for solid particle collision Create compute pipeline for crystal bond formation Create compute pipeline for bond constraint solving Step the solid collision system Parameters: (GPUDevice) — No description in source JSDoc. (Object) — from createSolidCollisionPipeline (Object) — from createPhaseChangeBuffers (Object) — particle sim world (Object) — { buffer, count } entity colliders (Object) — { min: [x,y,z], max: [x,y,z] } (number) — delta time (Object) — collision params overrides Step the crystal bond formation system Step the bond constraint


createSpellForce(position, direction, power, element)

createSolidCollisionPipeline(device, workgroupSize = 256)

createCrystalBondPipeline(device, workgroupSize = 256)

createBondConstraintPipeline(device, workgroupSize = 256)

stepSolidCollision(device, collisionPipeline, phaseBuffers, particleWorld, colliderData, roomBounds, dt, options = {})

stepCrystalBonds(device, bondPipeline, phaseBuffers, particleWorld, options = {})

stepBondConstraints(device, constraintPipeline, phaseBuffers, particleWorld, bondCount, options = {})

stepCrystalSystem(device, systems, phaseBuffers, particleWorld, colliderData, roomBounds, dt, options = {})

createCrystalSystemPipelines(device, workgroupSize = 256)

async extractCrystalClusters(device, phaseBuffers, particleWorld, minClusterSize = 5)

createSeedInjectionParams(position, radius, seedStrength, temperature, magicSaturation)

createCrystallizationPipeline(device, workgroupSize = 256)

stepCrystallization(device, crystallization, phaseBuffers, particleWorld, dt, options = {})

injectFreezeSeeds(device, phaseBuffers, particleWorld, seedParams)

injectHeatSeeds(device, phaseBuffers, particleWorld, seedParams)

applyPhaseVisuals(device, phaseBuffers, particleWorld, options = {})

async extractFrozenShape(device, phaseChangeBuffers, gridSize, worldMin, cellSize)

injectMeltedFluid(device, fluidWorld, position, velocity, mass, radius)

async extractFrozenParticles(device, phaseBuffer, positionBuffer, particleCount, minClusterSize = 5)

— { min: [x,y,z], max: [x,y,z] } (number) — delta time (Object) — collision params overrides Step the crystal bond formation system Step the bond constraint solver (PBD) Run multiple iterations for stability Read bond count from GPU (async) Clear all bonds (for reset or when spawning rigid body) Full crystal system combines all steps Call this each frame to handle solidification, collision, bonding, and constraints Create all crystal system pipelines at once Extract connected crystal clusters from bonds for rigid body spawning Uses Union Find algorithm to identify connected components Inject seed particles at a position (ice spell impact, magic anchor, etc.) Create compute pipeline for crystallization chain reaction Step the crystallization system run compute pass to propagate freezing Inject freeze seeds at a world position (for ice spell impact) Affects particles within radius sets their temp/magic/seed values Apply visual effects based on phase state (color frozen particles blue/white) Call this after stepCrystallization to update particle rendering Extract frozen region as convex hull for rigid body creation This runs on CPU after GPU freeze pass Clear freeze region after rigid body is spawned Inject mass/momentum when melting a rigid body Destroy phase change buffers Destroy crystal system pipelines Extract frozen particle cluster for rigid body spawning Returns particles that are FROZEN phase and form a connected cluster Constants — Phase states for fluid cells/particles — Particle solidification attributes (per particle) temperature: Current temp (ambient 20, freezing < 0) magicSaturation: 0 1, how much "freeze magic" has accumulated solidPhase: 0=fluid, 1=freezing, 2=frozen seedStrength: If 0, this particle spreads solidification — Crystal bond attributes (per