Hylograph.ForceEngine
- Package
- purescript-hylograph-simulation
- Repository
- afcondon/purescript-hylograph-simulation
Pure Force Engine
A clean, debuggable force simulation engine. The forces are PureScript
(hylograph-forces: d3-force's, bit for bit, and more); the loop is
this library's own. There is no D3 in it.
What that buys over d3.forceSimulation:
- Full control over when forces run
- Predictable, debuggable behavior
- Clean PureScript types
- No hidden state or timers
Usage:
import Hylograph.ForceEngine as FE
main = do
sim <- FE.create FE.defaultConfig
FE.setNodes myNodes sim
FE.addForce (FE.ManyBody "charge" FE.defaultManyBody) sim
FE.onTick (renderNodes sim) sim
FE.start sim
Re-exports from Hylograph.ForceEngine.Core
#ForceRecipe Source
newtype ForceRecipe :: Row Type -> Typenewtype ForceRecipe row
What a force is, before it has met its nodes: given the simulation's
generator, nodes and links, the force itself, or why it cannot be made
(a link naming a node that is not there: node not found: <id>).
Constructors
ForceRecipe (RandomSource -> Array (Node row) -> Links -> Either String (Force (NodeRow row)))
#ForceHandle Source
newtype ForceHandle :: Row Type -> Typenewtype ForceHandle row
A force that has its nodes, and the recipe it was made from, so that it can be made again when they change.
#simulationTick Source
simulationTick :: forall row. { alpha :: Number, alphaDecay :: Number, alphaMin :: Number, alphaTarget :: Number, forces :: Array (ForceHandle row), nodes :: Array (Node row), velocityRetention :: Number } -> Effect NumberA complete tick: apply the forces at the current alpha, move the nodes, apply hard containment, and return the cooled alpha.
#reinitializeForce Source
reinitializeForce :: forall row. RandomSource -> Array (Node row) -> Links -> ForceHandle row -> Either String (ForceHandle row)Make a force again, from the recipe it was first made from, for nodes or links that have changed.
#initializeNodes Source
initializeNodes :: forall row. Array (Node row) -> Effect Unitd3's initializeNodes: give every node its index, put a pinned node on
its pin, stop a node with no velocity, and give a node with no position
a place on d3's phyllotaxis spiral. (Until 2026-11-18 a node with no
position was put somewhere at random.)
#initializeForce Source
initializeForce :: forall row. RandomSource -> Array (Node row) -> Links -> ForceRecipe row -> Either String (ForceHandle row)Make a force for these nodes and links.
#createRadial Source
createRadial :: forall row. RadialConfig -> ForceRecipe rowA force pulling every node toward one circle.
#createManyBody Source
createManyBody :: forall row. ManyBodyConfig -> ForceRecipe rowA many-body (charge) force with one strength for every node.
#createLink Source
createLink :: forall row. LinkConfig -> ForceRecipe rowA link force with one distance and one strength for every link.
#createForceY Source
createForceY :: forall row. ForceYConfig -> ForceRecipe rowA force pulling every node toward one y.
#createForceX Source
createForceX :: forall row. ForceXConfig -> ForceRecipe rowA force pulling every node toward one x.
#createCollide Source
createCollide :: forall row. CollideConfig -> ForceRecipe rowA collision force with one radius for every node.
#createCenter Source
createCenter :: forall row. CenterConfig -> ForceRecipe rowA centering force.
#applyForces Source
applyForces :: forall row. Array (ForceHandle row) -> Number -> Effect UnitApply forces in order, each seeing what the ones before it did.
#applyForce Source
applyForce :: forall row. ForceHandle row -> Number -> Effect UnitApply a single force: it changes the velocities (or, for centering, the positions) of the nodes it was initialized with.
Re-exports from Hylograph.ForceEngine.Events
#SimulationEvent Source
data SimulationEventEvents that can occur during simulation lifecycle.
These types are primarily for Halogen integration via subscriptions. Internally, callbacks are invoked directly without constructing these values.
Usage with Halogen:
handleAction (SimEvent event) = case event of
Tick -> liftEffect updateDOMPositions
Started -> H.modify_ _ { simRunning = true }
Stopped -> H.modify_ _ { simRunning = false }
AlphaDecayed alpha -> when (alpha < 0.1) $ liftEffect doSomething
Constructors
Instances
#SimulationCallbacks Source
type SimulationCallbacks = { onAlphaThreshold :: Ref (Number -> Effect Unit), onStart :: Ref (Effect Unit), onStop :: Ref (Effect Unit), onTick :: Ref (Effect Unit) }Callbacks for simulation events.
All callbacks are stored in Refs to allow dynamic updates and to keep the tick loop allocation-free (no closures created per-tick).
The callbacks are Effect Unit rather than taking event data because:
- Performance: No boxing/unboxing of event data in hot path
- Simplicity: Consumers can read simulation state directly if needed
- Flexibility: The consumer decides what data they need
#onSimulationTick Source
onSimulationTick :: Effect Unit -> SimulationCallbacks -> Effect UnitSet the tick callback.
WARNING: This callback runs 60x/second during simulation. Keep it fast! Avoid allocations, complex logic, or console.log.
Good:
onSimulationTick (updateGroupPositions nodes) callbacks
Bad:
onSimulationTick (do
nodes <- Ref.read nodesRef -- Extra ref read
log "tick" -- Console I/O
H.tell ... -- Halogen message (allocates)
) callbacks
#onSimulationStop Source
onSimulationStop :: Effect Unit -> SimulationCallbacks -> Effect UnitSet the stop callback.
Called when simulation stops (alpha < alphaMin). Safe to do heavier work here.
#onSimulationStart Source
onSimulationStart :: Effect Unit -> SimulationCallbacks -> Effect UnitSet the start callback.
Called when simulation starts running or is reheated from stopped state. Safe to do heavier work here (only called occasionally).
#onAlphaDecay Source
onAlphaDecay :: (Number -> Effect Unit) -> SimulationCallbacks -> Effect UnitSet the alpha threshold callback.
Called when alpha crosses common thresholds: 0.5, 0.1, 0.01. The callback receives the new alpha value.
Useful for:
- Progressive rendering (show more detail as simulation settles)
- UI updates (e.g., hide "Simulating..." spinner)
- Analytics (track how long simulations run)
#defaultCallbacks Source
defaultCallbacks :: Effect SimulationCallbacksCreate default callbacks (all no-ops).
Usage:
callbacks <- defaultCallbacks
Ref.write updateDOMPositions callbacks.onTick
sim <- createWithCallbacks config callbacks
Re-exports from Hylograph.ForceEngine.Links
#swizzleLinksByIndex Source
swizzleLinksByIndex :: forall node rawLink swizzled. (node -> Int) -> Array node -> Array { source :: Int, target :: Int | rawLink } -> (node -> node -> Int -> { source :: Int, target :: Int | rawLink } -> swizzled) -> Array swizzledSwizzle links by looking up nodes by their index field
USE THIS when working with a FILTERED node subset where array positions
don't match node.index values. Looks up nodes by their .index field
and silently drops links where either endpoint is not found.
PERFORMANCE: Uses FFI-backed IntMap for O(1) lookups instead of O(n) find.
This is essential for GUP patterns where you show only a subset of nodes.
Example:
let visibleNodes = filter isVisible allNodes
swizzled = swizzleLinksByIndex _.index visibleNodes links \src tgt i link ->
{ source: src, target: tgt, index: i, value: link.value }
#swizzleLinks Source
swizzleLinks :: forall node rawLink swizzled. Array node -> Array { source :: Int, target :: Int | rawLink } -> (node -> node -> Int -> { source :: Int, target :: Int | rawLink } -> swizzled) -> Array swizzledConvert raw links (integer indices) to swizzled links (node references)
Expects link.source and link.target to be valid array indices into the
nodes array. Links with out-of-bounds indices are silently dropped.
Note: If your link indices are semantic (node.index field values) rather than
array positions, use swizzleLinksByIndex instead, which looks up nodes by
their .index field.
The transform function allows you to build the output link record, copying extra fields from the raw link as needed.
Example:
let swizzled = swizzleLinks nodes rawLinks \src tgt i link ->
{ source: src, target: tgt, index: i, value: link.value }
#filterLinksToSubset Source
filterLinksToSubset :: forall node linkData. (node -> Int) -> Array node -> Array { source :: Int, target :: Int | linkData } -> Array { source :: Int, target :: Int | linkData }Filter links to only those where both endpoints are in the node subset
PERFORMANCE: Uses FFI-backed IntSet for O(1) membership instead of O(n) elem.
Use this before swizzling when you want to show links only between
visible/selected nodes. Pairs naturally with swizzleLinksByIndex.
Example:
let visibleNodes = filter isVisible allNodes
visibleLinks = filterLinksToSubset _.index visibleNodes allLinks
swizzled = swizzleLinksByIndex _.index visibleNodes visibleLinks transform
Re-exports from Hylograph.ForceEngine.Registry
#AnySimulation Source
data AnySimulationInternal registry storage. Uses existential encoding to store simulations with different row types. The trade-off is we can only perform operations that work on any simulation.
#unsafeFromAny Source
unsafeFromAny :: forall row linkRow. AnySimulation -> Simulation row linkRow#unregister Source
unregister :: String -> Effect UnitUnregister a simulation by name.
Does nothing if no simulation with this name exists. The simulation is NOT stopped automatically.
#register Source
register :: forall row linkRow. String -> Simulation row linkRow -> Effect UnitRegister a simulation with a name.
If a simulation with this name already exists, it will be replaced. The old simulation is NOT stopped automatically.
sim <- create defaultConfig
register "call-graph" sim
#lookup Source
lookup :: String -> Effect (Maybe AnySimulation)Look up a simulation by name.
WARNING: The returned simulation has an unknown row type. Only use operations that work on any simulation (stop, isRunning, getAlpha). Calling getNodes will require an unsafe cast.
#listSimulations Source
listSimulations :: Effect (Array String)List all registered simulation names.
#debugRegistry Source
debugRegistry :: Effect UnitPrint debug information about all registered simulations.
Designed for use from browser console:
// In browser console:
import('./output/Hylograph.ForceEngine.Registry/index.js').then(m => m.debugRegistry())
#clearRegistry Source
clearRegistry :: Effect UnitClear the registry without stopping simulations.
Use stopAll first if you want to stop them.
Re-exports from Hylograph.ForceEngine.Simulation
#Simulation Source
type Simulation :: Row Type -> Row Type -> Typetype Simulation row linkRow = { alpha :: Ref Number, callbacks :: Maybe SimulationCallbacks, cancelAnimation :: Ref (Effect Unit), config :: SimConfig, forces :: Ref (Map String (ForceHandle row)), links :: Ref (Array { source :: Int, target :: Int | linkRow }), nodes :: Ref (Array (SimulationNode row)), prevAlpha :: Ref Number, random :: RandomSource, running :: Ref Boolean, settings :: Ref SimConfig, tickCallback :: Ref (Effect Unit) }
A running simulation This is a mutable structure that holds the simulation state
#tick Source
tick :: forall row linkRow. Simulation row linkRow -> Effect NumberRun a single tick of the simulation Returns the new alpha value
#start Source
start :: forall row linkRow. Simulation row linkRow -> Effect UnitStart the simulation animation loop
#setNodes Source
setNodes :: forall row linkRow. Array (SimulationNode row) -> Simulation row linkRow -> Effect UnitSet the nodes for the simulation This initializes the nodes and makes every force again for them.
The simulation adopts these records: it writes into them (an index, a
place for a node without one, and then every tick's positions and
velocities), as d3 does, and getNodes returns these same records.
Drag, and a DOM bound to the nodes, rely on that. For nodes as values,
the same on both engines, use Hylograph.Simulation.Stepped.
#setCallbacks Source
setCallbacks :: forall row linkRow. SimulationCallbacks -> Simulation row linkRow -> Simulation row linkRowSet the callbacks for a simulation (new multi-callback API) Note: This replaces any callbacks passed to createWithCallbacks
#removeForce Source
removeForce :: forall row linkRow. String -> Simulation row linkRow -> Effect UnitRemove a force from the simulation
#reheat Source
reheat :: forall row linkRow. Simulation row linkRow -> Effect UnitReheat the simulation (set alpha to 1)
#isRunning Source
isRunning :: forall row linkRow. Simulation row linkRow -> Effect BooleanCheck if the simulation is running
#getNodes Source
getNodes :: forall row linkRow. Simulation row linkRow -> Effect (Array (SimulationNode row))Get the current nodes (with updated positions): the records given to
setNodes, moved in place, the same ones every time.
#getCallbacks Source
getCallbacks :: forall row linkRow. Simulation row linkRow -> Maybe SimulationCallbacksGet the current callbacks (if any)
#getAlpha Source
getAlpha :: forall row linkRow. Simulation row linkRow -> Effect NumberGet the current alpha value
#defaultConfig Source
defaultConfig :: SimConfigDefault simulation configuration
#createWithCallbacks Source
createWithCallbacks :: forall row linkRow. SimConfig -> SimulationCallbacks -> Effect (Simulation row linkRow)Create a new simulation with callback system
Example:
callbacks <- defaultCallbacks
onSimulationTick updateDOM callbacks
onSimulationStop (log "Simulation settled") callbacks
sim <- createWithCallbacks config callbacks
#create Source
create :: forall row linkRow. SimConfig -> Effect (Simulation row linkRow)Create a new simulation (without callbacks)
For the new callback-based API, use createWithCallbacks instead.
#attachGroupDrag Source
attachGroupDrag :: forall row linkRow. Array Element -> String -> Simulation row linkRow -> Effect UnitAttach drag to transformed group elements (like bubble packs)
Unlike attachDrag, this version takes a container selector to
get pointer coordinates in the correct coordinate space. Use this when
dragging <g> elements that have transform attributes.
Example:
-- For bubble packs inside a zoom group
packElements <- select ".module-pack" >>= selectAll
attachGroupDrag packElements "#zoom-group" sim
#attachDrag Source
attachDrag :: forall row linkRow. Array Element -> Simulation row linkRow -> Effect UnitAttach simulation-aware drag behavior to node elements
This sets up pointer handlers (native Pointer Events, no D3) that:
- Reheat the simulation on drag start
- Update fx/fy (fixed position) during drag
- Clear fx/fy on drag end (release node)
Example:
elements <- select ".node" >>= selectAll
attachDrag elements sim
#addForce Source
addForce :: forall row linkRow. ForceSpec -> Simulation row linkRow -> Effect UnitAdd a force to the simulation
Re-exports from Hylograph.ForceEngine.Types
#RadialConfig Source
type RadialConfig = { radius :: Number, strength :: Number, x :: Number, y :: Number }Configuration for radial force
#ManyBodyConfig Source
type ManyBodyConfig = { distanceMax :: Number, distanceMin :: Number, strength :: Number, theta :: Number }Configuration for a many-body (charge) force
#LinkConfig Source
type LinkConfig = { distance :: Number, iterations :: Int, strength :: Number }Configuration for a link force
#ForceYConfig Source
type ForceYConfig = { strength :: Number, y :: Number }Configuration for Y positioning force
#ForceXConfig Source
type ForceXConfig = { strength :: Number, x :: Number }Configuration for X positioning force
#CollideConfig Source
type CollideConfig = { iterations :: Int, radius :: Number, strength :: Number }Configuration for a collision force
#CenterConfig Source
type CenterConfig = { strength :: Number, x :: Number, y :: Number }Configuration for centering force
- Modules
- Hylograph.
Config. Force - Hylograph.
Config. Scene - Hylograph.
ForceEngine - Hylograph.
ForceEngine. Core - Hylograph.
ForceEngine. Demo - Hylograph.
ForceEngine. Events - Hylograph.
ForceEngine. Links - Hylograph.
ForceEngine. Registry - Hylograph.
ForceEngine. Render - Hylograph.
ForceEngine. Setup - Hylograph.
ForceEngine. Setup. WASM - Hylograph.
ForceEngine. Simulation - Hylograph.
ForceEngine. Types - Hylograph.
ForceEngine. WASM - Hylograph.
ForceEngine. WASMEngine - Hylograph.
Scene. Engine - Hylograph.
Scene. Handle - Hylograph.
Scene. Rules - Hylograph.
Scene. Types - Hylograph.
Simulation - Hylograph.
Simulation. Emitter - Hylograph.
Simulation. HATS - Hylograph.
Simulation. Scene - Hylograph.
Simulation. Stepped - Hylograph.
Transition. Consumers - Hylograph.
Transition. Example