Module

Hylograph.ForceEngine.WASM

Package
purescript-hylograph-simulation
Repository
afcondon/purescript-hylograph-simulation

WASM Force Engine

High-performance force simulation using Rust/WebAssembly. Faster than the default (PureScript) kernel; the README has the measurement.

Usage:

import Hylograph.ForceEngine.WASM as WASM

main = do
  -- Initialize WASM module (once at app startup)
  WASM.initWasm "./pkg/force_kernel.js"

  -- Create simulation
  sim <- WASM.create 1000

  -- Configure forces
  WASM.configureManyBody sim { strength: -30.0, theta: 0.9, distanceMin: 1.0, distanceMax: 10000.0 }
  WASM.configureLinks sim { distance: 30.0, strength: 1.0, iterations: 1 }
  WASM.configureCenter sim { x: 0.0, y: 0.0, strength: 1.0 }

  -- Set links
  WASM.setLinks sim [0, 1, 1, 2, 2, 3]  -- [source, target, source, target, ...]

  -- Run simulation
  WASM.tick sim

  -- Get results
  positions <- WASM.getPositions sim  -- [x0, y0, x1, y1, ...]

#WASMSimulation Source

data WASMSimulation

Opaque type for WASM simulation handle

#ManyBodyConfig Source

type ManyBodyConfig = { distanceMax :: Number, distanceMin :: Number, strength :: Number, theta :: Number }

Many-body force configuration

#LinkConfig Source

type LinkConfig = { distance :: Number, iterations :: Int, strength :: Number }

Link force configuration

#CenterConfig Source

type CenterConfig = { strength :: Number, x :: Number, y :: Number }

Center force configuration

#CollideConfig Source

type CollideConfig = { iterations :: Int, radius :: Number, strength :: Number }

Collide force configuration

#PositionConfig Source

type PositionConfig = { strength :: Number, target :: Number }

Configuration of a force pulling toward one coordinate (forceX, forceY)

#RadialConfig Source

type RadialConfig = { radius :: Number, strength :: Number, x :: Number, y :: Number }

Radial force configuration

#ForceId Source

newtype ForceId

One force in the kernel's force list, as returned by the add* functions. Valid until the next clearForces.

Instances

#initWasm Source

initWasm :: String -> Aff Unit

Initialize the WASM module. Call once at application startup.

The URL should point to the generated JavaScript module from wasm-pack. Example: initWasm "./pkg/force_kernel.js"

#isWasmReady Source

isWasmReady :: Effect Boolean

Check if WASM is initialized and ready

#create Source

create :: Int -> Effect WASMSimulation

Create a new WASM simulation with the given number of nodes. Nodes are initialized in a phyllotaxis (sunflower) pattern.

#free Source

free :: WASMSimulation -> Effect Unit

Free WASM simulation memory. Call when done with simulation.

#setNodeCount Source

setNodeCount :: WASMSimulation -> Int -> Effect Unit

Resize simulation to new node count

#setPosition Source

setPosition :: WASMSimulation -> Int -> Number -> Number -> Effect Unit

Set a single node's position

#setAllPositions Source

setAllPositions :: WASMSimulation -> Array Number -> Effect Unit

Set all positions from flat array [x0, y0, x1, y1, ...]

#getPositions Source

getPositions :: WASMSimulation -> Effect (Array Number)

Get all positions as flat array [x0, y0, x1, y1, ...]

#getPositionsAsObjects Source

getPositionsAsObjects :: WASMSimulation -> Effect (Array { x :: Number, y :: Number })

Get positions as array of {x, y} objects

#fixNode Source

fixNode :: WASMSimulation -> Int -> Number -> Number -> Effect Unit

Fix a node at a position (like D3's fx/fy)

#unfixNode Source

unfixNode :: WASMSimulation -> Int -> Effect Unit

Unfix a node

#setLinksFromRecords Source

setLinksFromRecords :: forall r. WASMSimulation -> Array { source :: Int, target :: Int | r } -> Effect Unit

Set links from array of records with source/target fields

#configureManyBody Source

configureManyBody :: WASMSimulation -> ManyBodyConfig -> Effect Unit

Configure many-body (charge) force

#configureCenter Source

configureCenter :: WASMSimulation -> CenterConfig -> Effect Unit

Configure center force

#enableForces Source

enableForces :: WASMSimulation -> { center :: Boolean, links :: Boolean, manyBody :: Boolean } -> Effect Unit

Enable/disable forces individually

#configureCollide Source

configureCollide :: WASMSimulation -> CollideConfig -> Effect Unit

Configure the built-in collide force

#configureForceX Source

configureForceX :: WASMSimulation -> PositionConfig -> Effect Unit

Configure the built-in forceX

#configureForceY Source

configureForceY :: WASMSimulation -> PositionConfig -> Effect Unit

Configure the built-in forceY

#enableForcesAll Source

enableForcesAll :: WASMSimulation -> { center :: Boolean, collide :: Boolean, forceX :: Boolean, forceY :: Boolean, links :: Boolean, manyBody :: Boolean } -> Effect Unit

Enable/disable all six built-in forces. (enableForces reaches only three of them and leaves the other three as they were.)

#clearForces Source

clearForces :: WASMSimulation -> Effect Unit

Remove every force from the force list. Built-in forces are unaffected; turn those off with enableForcesAll.

#forceCount Source

forceCount :: WASMSimulation -> Effect Int

Number of forces in the force list

#addManyBody Source

addManyBody :: WASMSimulation -> ManyBodyConfig -> Effect ForceId

Add a many-body (charge) force

#addCenter Source

addCenter :: WASMSimulation -> CenterConfig -> Effect ForceId

Add a centering force

#addForceX Source

addForceX :: WASMSimulation -> PositionConfig -> Effect ForceId

Add a force pulling nodes toward an x coordinate

#addForceY Source

addForceY :: WASMSimulation -> PositionConfig -> Effect ForceId

Add a force pulling nodes toward a y coordinate

#addCollide Source

addCollide :: WASMSimulation -> CollideConfig -> Effect ForceId

Add a collision force

#addRadial Source

addRadial :: WASMSimulation -> RadialConfig -> Effect ForceId

Add a radial force

#setForceStrengths Source

setForceStrengths :: WASMSimulation -> ForceId -> Array Number -> Effect Boolean

Give a force one strength per node (many-body, forceX, forceY, radial) or one per link (link), in node or link order. Returns false, changing nothing, for a force whose strength is a single number (center, collide).

#setForceRadii Source

setForceRadii :: WASMSimulation -> ForceId -> Array Number -> Effect Boolean

Give a force one radius per node (collide, radial). False for others.

#setForceTargets Source

setForceTargets :: WASMSimulation -> ForceId -> Array Number -> Effect Boolean

Give a force one target coordinate per node (forceX, forceY). A NaN target leaves that node alone. False for other forces.

#setForceDistances Source

setForceDistances :: WASMSimulation -> ForceId -> Array Number -> Effect Boolean

Give a link force one rest length per link. False for other forces.

#setForceMask Source

setForceMask :: WASMSimulation -> ForceId -> Array Boolean -> Effect Boolean

Filter a force: one Boolean per node, false meaning the node has strength 0 under this force. For forceX, forceY and radial that leaves the node alone. For many-body it means the node exerts no charge but is still pushed by the others, which is what the D3 kernel's filtered many-body does. False for forces with no per-node strength (link, center, collide).

#ManyBodyScope Source

data ManyBodyScope

Which pairs of nodes a many-body force acts between.

Constructors

Instances

#addTowards Source

addTowards :: WASMSimulation -> Number -> Effect ForceId

Add a force pulling each node toward its own target point: v += (target - position) * strength * alpha. It does nothing until setForceTargetsXY gives it targets.

#setForceTargetsXY Source

setForceTargetsXY :: WASMSimulation -> ForceId -> Array Number -> Effect Boolean

Give a towards force its targets, flat: [x0, y0, x1, y1, ...] in node order. A NaN leaves that node alone. Cheap to call every tick: an array of the same length overwrites the kernel's copy in place. False for any other force.

#addRectCollide Source

addRectCollide :: WASMSimulation -> { halfHeight :: Number, halfWidth :: Number, iterations :: Int, strength :: Number } -> Effect ForceId

Add a rectangle collision force: nodes are axis-aligned rectangles, pushed apart along the axis on which a pair overlaps least.

#setForceHalfWidths Source

setForceHalfWidths :: WASMSimulation -> ForceId -> Array Number -> Effect Boolean

Give a rectangle collision force one half-width per node.

#setForceHalfHeights Source

setForceHalfHeights :: WASMSimulation -> ForceId -> Array Number -> Effect Boolean

Give a rectangle collision force one half-height per node.

#addContainment Source

addContainment :: WASMSimulation -> { hard :: Boolean, strength :: Number } -> Effect ForceId

Add a containment force, with no regions yet. strength steers nodes back in before they move; hard also clamps positions after each tick. Every node is in region 0 unless setForceRegions says otherwise; node radii come from setForceRadii.

#containmentAddRect Source

containmentAddRect :: WASMSimulation -> ForceId -> { x0 :: Number, x1 :: Number, y0 :: Number, y1 :: Number } -> Effect Int

Add a rectangular region to a containment force. Returns its index among that force's regions, or -1 if the force is not a containment.

#containmentAddCircle Source

containmentAddCircle :: WASMSimulation -> ForceId -> { radius :: Number, x :: Number, y :: Number } -> Effect Int

Add a circular region to a containment force. Returns its index, or -1.

#containmentAddPolygon Source

containmentAddPolygon :: WASMSimulation -> ForceId -> Array { x :: Number, y :: Number } -> Effect Int

Add a convex polygon region (either winding) to a containment force. Returns its index, or -1.

#setForceRegions Source

setForceRegions :: WASMSimulation -> ForceId -> Array (Maybe Int) -> Effect Boolean

Assign each node a region of a containment force, by index; Nothing leaves the node free.

#addCohesion Source

addCohesion :: WASMSimulation -> Number -> Effect ForceId

Add a group cohesion force: each node is pulled toward the centroid of its group. Groups come from setForceGroups.

#setForceGroups Source

setForceGroups :: WASMSimulation -> ForceId -> Array (Maybe Int) -> Effect Boolean

Give a cohesion or many-body force one group per node, as non-negative numbers; Nothing is "in no group".

#setManyBodyScope Source

setManyBodyScope :: WASMSimulation -> ForceId -> ManyBodyScope -> Effect Boolean

Restrict a many-body force to pairs within a group, or between groups.

#setRectCollidePairs Source

setRectCollidePairs :: WASMSimulation -> ForceId -> ManyBodyScope -> Effect Boolean

Restrict a rectangle collision to pairs within a group, or between groups (the groups from setForceGroups; a filter from setCollideFilter).

#setRectCollideThrough Source

setRectCollideThrough :: WASMSimulation -> ForceId -> Boolean -> Effect Boolean

Let a rectangle pushed from both sides go through one of them.

#setDirectionalHard Source

setDirectionalHard :: WASMSimulation -> ForceId -> Boolean -> Effect Boolean

Make a directional constraint project its links after each tick, so that the gap asked for is the gap kept.

#addDirectional Source

addDirectional :: WASMSimulation -> { axis :: { x :: Number, y :: Number }, gap :: Number, iterations :: Int, strength :: Number } -> Effect ForceId

Add a directional link constraint: each link's target is pushed to be at least gap beyond its source along axis (which need not be a unit vector). Per-link gaps with setForceGaps, per-link strengths with setForceStrengths.

#setForceGaps Source

setForceGaps :: WASMSimulation -> ForceId -> Array Number -> Effect Boolean

Give a directional constraint one gap per link.

#Snapshot Source

data Snapshot

Everything that changes as a simulation runs (positions, velocities, pins, alpha and the other parameters, the state of the stream that nudges coincident nodes apart), as recorded by snapshot.

#snapshot Source

snapshot :: WASMSimulation -> Effect Snapshot

Record everything that changes as the simulation runs. Forces and links are configuration, not state, and are not recorded.

#restore Source

restore :: WASMSimulation -> Snapshot -> Effect Boolean

Put a simulation back in a recorded state. On a simulation with the same forces and links, restore followed by N ticks gives exactly the positions N more ticks gave (or would have given) the original. False, changing nothing, if the snapshot is malformed.

#kineticEnergy Source

kineticEnergy :: WASMSimulation -> Effect Number

Kinetic energy after the last tick, each node having unit mass: the sum of (vx^2 + vy^2) / 2. Falls toward 0 as the layout settles.

#maxDisplacement Source

maxDisplacement :: WASMSimulation -> Effect Number

The furthest any node moved during the last tick.

#maxAcceleration Source

maxAcceleration :: WASMSimulation -> Effect Number

The largest change in any node's step between the last two ticks: the acceleration it actually underwent. Unlike kineticEnergy and maxDisplacement it does not vanish at the far end of a swing, where a node is momentarily still. 0 until two ticks have been made.

#settled Source

settled :: WASMSimulation -> Number -> Number -> Effect Boolean

Is the simulation at rest: over the last two ticks, did no node move further than the first number in a tick, and no node's step change by more than the second? False until two ticks have been made.

#setCollideAlphaScaled Source

setCollideAlphaScaled :: WASMSimulation -> ForceId -> Boolean -> Effect Boolean

Make a collide force's strength follow alpha (true) or be d3's (false, the default). False for any other force.

#setCollideFilter Source

setCollideFilter :: WASMSimulation -> ForceId -> Array Boolean -> Effect Boolean

Filter a collide force by node: a node given false collides with nothing under this force. False for any other force.

#setAlpha Source

setAlpha :: WASMSimulation -> Number -> Effect Unit

Set alpha (temperature). Higher = more movement.

#getAlpha Source

getAlpha :: WASMSimulation -> Effect Number

Get current alpha

#setAlphaDecay Source

setAlphaDecay :: WASMSimulation -> Number -> Effect Unit

Set alpha decay rate

#setAlphaMin Source

setAlphaMin :: WASMSimulation -> Number -> Effect Unit

Set the alpha below which the simulation counts as finished

#setAlphaTarget Source

setAlphaTarget :: WASMSimulation -> Number -> Effect Unit

Set the alpha the simulation cools toward

#setVelocityRetention Source

setVelocityRetention :: WASMSimulation -> Number -> Effect Unit

Set the share of its velocity a node keeps from one tick to the next: 0.6 keeps 60% and loses 40% (d3's default, which d3 writes as a velocityDecay of 0.4).

#setVelocityDecay Source

setVelocityDecay :: WASMSimulation -> Number -> Effect Unit

Deprecated: the old name of setVelocityRetention, kept so that existing code compiles. It does exactly what it always did: the number is the share of velocity KEPT each tick, not the share lost.

#resetRandom Source

resetRandom :: WASMSimulation -> Effect Unit

Rewind the stream of nudges the kernel uses to separate coincident nodes. The kernel is deterministic: the stream is d3's own seeded generator, one per simulation, so a simulation rebuilt the same way repeats exactly. This puts an existing simulation back at the start.

#reheat Source

reheat :: WASMSimulation -> Effect Unit

Reheat simulation (reset alpha to 1.0)

#tick Source

tick :: WASMSimulation -> Effect Number

Run a single simulation tick. Returns new alpha value.

#tickN Source

tickN :: WASMSimulation -> Int -> Effect Number

Run multiple ticks. Stops early if alpha < alphaMin.

#isRunning Source

isRunning :: WASMSimulation -> Effect Boolean

Check if simulation is still running (alpha >= alphaMin)

#nodeCount Source

nodeCount :: WASMSimulation -> Effect Int

Get number of nodes

#linkCount Source

linkCount :: WASMSimulation -> Effect Int

Get number of links

#syncPositionsToWasm Source

syncPositionsToWasm :: forall r. WASMSimulation -> Array { x :: Number, y :: Number | r } -> Effect Unit

Copy positions from PureScript node array to WASM

#syncPositionsFromWasm Source

syncPositionsFromWasm :: forall r. WASMSimulation -> Array { vx :: Number, vy :: Number, x :: Number, y :: Number | r } -> Effect (Array { vx :: Number, vy :: Number, x :: Number, y :: Number | r })

Copy positions from WASM back to PureScript node array. Warning: This mutates the input array!

#syncNodesToWasm Source

syncNodesToWasm :: forall r. WASMSimulation -> Array { fx :: Nullable Number, fy :: Nullable Number, vx :: Number, vy :: Number, x :: Number, y :: Number | r } -> Effect Unit

Copy position, velocity and pinning (fx/fy, per axis) from PureScript nodes to WASM. A node whose position is NaN is placed on d3's phyllotaxis spiral.

#syncPinsToWasm Source

syncPinsToWasm :: forall r. WASMSimulation -> Array { fx :: Nullable Number, fy :: Nullable Number | r } -> Effect Unit

Copy the pins alone (fx/fy, null = free) from PureScript nodes to WASM.

#withPinsFromSnapshot Source

withPinsFromSnapshot :: forall r. Snapshot -> Array { fx :: Nullable Number, fy :: Nullable Number | r } -> Array { fx :: Nullable Number, fy :: Nullable Number | r }

The nodes with the pins a snapshot recorded, as new records. The snapshot must be of as many nodes.

#syncNodesFromWasm Source

syncNodesFromWasm :: forall r. WASMSimulation -> Array { vx :: Number, vy :: Number, x :: Number, y :: Number | r } -> Effect (Array { vx :: Number, vy :: Number, x :: Number, y :: Number | r })

Copy position and velocity from WASM back to PureScript nodes. Warning: This mutates the input array!