shAccumulate

Summary: Accumulate: out += sh * weight (in-place)


shConvolve

Summary: Convolve SH with per-band kernel (e.g., cosine lobe for diffuse)


shWindow

Summary: Apply Hanning window to reduce ringing


shRotate

Summary: Rotate SH coefficients by a 3x3 rotation matrix L0 is invariant. L1 rotates directly. L2 uses the explicit 5x5 rotation. Reference: Ivanic & Ruedenberg (1996), Green "SH Lighting: The Gritty Details" (2003)


shFromCubemap

Summary: Project 6-face cubemap to SH


shToGPUBuffer

Summary: Convert SH to Float32Array suitable for GPU uniform upload (already is Float32Array)


core/math/MathStatistics

Summary: MathStatistics.js - Running statistics, array stats, exponential moving average Consolidates: PerformanceAnalyzer inline variance/stdDev, FramePacingController running average Welford's online algorithm for numerically stable running stats


core/math/MathValidation

Summary: MathValidation.js - reusable finite, range, alignment, histogram, and probability reports.


rangeValidationReport

rangeValidationReport(value, min, max, options = {})


alignmentReport

alignmentReport(offset, alignment, options = {})


histogramValidationReport

histogramValidationReport(histogram, options = {})


probabilityDistributionReport

probabilityDistributionReport(probabilities, options = {})


typedArrayLayoutReport

typedArrayLayoutReport(view, options = {})


vectorValidationReport

vectorValidationReport(values, options = {})


colorValidationReport

colorValidationReport(color, options = {})


schemaValidationReport

schemaValidationReport(value, schema, options = {})


assertValidationReport

assertValidationReport(report, message = 'validation failed')


assertSchema

assertSchema(value, schema, options = {})


core/math/MathVec2


vec2SmoothDamp(current, target, currentVelocity, smoothTime, dt, maxSpeed = Infinity)


core/math/MathVec3

Summary: MathVec3.js - 3D Vector operations Depends on: MathConstants.js, MathScalar.js, MathRandom.js


vec3RotateTowards(current, target, maxRadiansDelta, maxMagnitudeDelta)


vec3SmoothDamp(current, target, currentVelocity, smoothTime, dt, maxSpeed = Infinity)


vec3SafeNormalize(v, fallback = [0, 1, 0])


core/math/MathVec4


vec4SafeNormalize(v, fallback = [0,0,0,1])


core/math/MediaTimingMath

Summary: MediaTimingMath.js - pure WebCodecs-shaped timestamp, cadence, sync, and metadata reports.


mediaTimestampReport

mediaTimestampReport(sample = {}, options = {})


mediaFrameIndexAtTimestamp

mediaFrameIndexAtTimestamp(timestamp, options = {})


mediaTimestampForFrameIndex

mediaTimestampForFrameIndex(frameIndex, options = {})


mediaTimelineReport

mediaTimelineReport(samples = [], options = {})


mediaDroppedFrameReport

mediaDroppedFrameReport(samples = [], options = {})


mediaDriftReport

mediaDriftReport(reference, candidate, options = {})


mediaAvSyncReport

mediaAvSyncReport(audioSamples = [], videoSamples = [], options = {})


mediaAudioDataTimingReport

mediaAudioDataTimingReport(audioData = {}, options = {})


mediaColorSpaceReport

mediaColorSpaceReport(videoFrameOrColorSpace = {}, options = {})


mediaQueuePressureReport

mediaQueuePressureReport(queue = {}, options = {})


core/math/MemoryLayoutMath

Summary: MemoryLayoutMath.js - byte alignment, struct, interleaved, planar, WGSL, and std140 layout reports.


memoryLayoutAlignmentForKind

memoryLayoutAlignmentForKind(kind, fallback = 1)


interleavedVertexLayoutReport

interleavedVertexLayoutReport(attributes, options = {})


planarBufferLayoutReport

planarBufferLayoutReport(attributes, elementCount, options = {})


aosElementByteOffset

aosElementByteOffset(index, stride, fieldOffset = 0, baseOffset = 0)


soaElementByteOffset

soaElementByteOffset(index, elementByteSize, baseOffset = 0)


core/math/MeshAttributeMath

Summary: MeshAttributeMath.js - glTF-style accessor component, stride, tangent-frame, and decode helpers.


morphWeightStateReport

morphWeightStateReport(value, options = {})

Summary: Validate serializable per-model morph control state keyed by stable part index.


positionBoundsReport

positionBoundsReport(positions, options = {})


morphAttributeDeltasReport

morphAttributeDeltasReport(baseValues, morphTargets, morphWeights, options = {})


morphedPositionBoundsReport

morphedPositionBoundsReport(basePositions, morphTargets, morphWeights, options = {})


skinnedPositionBoundsReport

skinnedPositionBoundsReport(bindPositions, jointIndices, jointWeights, skinMatrices, options = {},)


readAccessorComponent

readAccessorComponent(view, byteOffset, componentType, normalized = false)


accessorByteLayout

accessorByteLayout(accessor, bufferView = {})


readAccessorArray

readAccessorArray(source, accessor, bufferView = {}, options = {})


accessorDecodeMetadata

accessorDecodeMetadata(accessor, bufferView = {})


attributeBounds

attributeBounds(values, componentCount = 3)


meshoptDecodeMetadata

meshoptDecodeMetadata(extension = {}, bufferView = {})


tangentHandedness

tangentHandedness(tangent, fallback = 1)


tangentFrameFromNormalTangent

tangentFrameFromNormalTangent(normal, tangent, options = {})


gltfBitangentFromTangent

gltfBitangentFromTangent(normal, tangent, options = {})


decodeNormalTextureSample

decodeNormalTextureSample(sample, normalScale = 1, options = {})


normalTextureSampleToWorld

normalTextureSampleToWorld(sample, normal, tangent, normalScale = 1, options = {})


mikkTSpaceReferenceFingerprint

mikkTSpaceReferenceFingerprint(preparedInput, faceTangents = null)


mikkTSpaceReferenceProofReport

mikkTSpaceReferenceProofReport(preparedInput, faceTangents, proof = null, registry = MIKK_REFERENCE_CORPUS_REGISTRY)


mikkTSpaceFaceTangentOutputReport

mikkTSpaceFaceTangentOutputReport(faceTangents, expectedVertexCount, options = {})


applyMikkTSpaceFaceTangents

applyMikkTSpaceFaceTangents(preparedInput, faceTangents, options = {})


splitGeometryForTangentSpace

splitGeometryForTangentSpace(geometry, options = {})


tangentSpaceCompatibilityReport

tangentSpaceCompatibilityReport(geometry, referenceTangents = null, options = {})


generateTangentsFromGeometry

generateTangentsFromGeometry(positions, normals, uvs, indices = null, options = {})


core/math/MeshMath

Summary: MeshMath.js - reusable peer-graph, neighbor, relay, gossip, and mesh-health helpers.


peerNeighborScoreReport

peerNeighborScoreReport(peer = {}, options = {})


core/math/NavigationMath

Summary: NavigationMath.js - pure navigation corridor, path, area-cost, and steering reports.


navPathLength

navPathLength(waypoints = [], options = {})


navStringPull

navStringPull(portals = [], options = {})


navPathCorridorReport

navPathCorridorReport(portals = [], options = {})


navAreaTraversalCost

navAreaTraversalCost(distance, area = 0, options = {})


navNearestPolyScore

navNearestPolyScore(point, polygon, options = {})


navSmoothPath

navSmoothPath(waypoints = [], smoothing = 0.5, options = {})


navSteeringTargetReport

navSteeringTargetReport(currentPosition, waypoints = [], options = {})


core/math/NetworkMetricMath

Summary: NetworkMetricMath.js - reusable RTT, jitter, loss, throughput, goodput, and timeout helpers.


timeoutEstimateMs

timeoutEstimateMs(estimator = {}, options = {})


rttEstimatorUpdate

rttEstimatorUpdate(sampleRttMs, previous = null, options = {})


quicProbeTimeoutMs

quicProbeTimeoutMs(estimator = {}, options = {})


interarrivalJitterUpdate

interarrivalJitterUpdate(previousTransitMs, currentTransitMs, previousJitterMs = 0, options = {})


rtpInterarrivalJitterUpdate

rtpInterarrivalJitterUpdate(previous = null, packet = {})


core/math/PacketMath

Summary: PacketMath.js - reusable packet sequence, ACK range, fragmentation, flight, and loss helpers.


wrapPacketSequence

wrapPacketSequence(sequence, sequenceBits = PACKET_SEQUENCE_BITS_DEFAULT)


advancePacketSequence

advancePacketSequence(sequence, increment = 1, sequenceBits = PACKET_SEQUENCE_BITS_DEFAULT)


packetSequenceForwardDelta

packetSequenceForwardDelta(fromSequence, toSequence, sequenceBits = PACKET_SEQUENCE_BITS_DEFAULT)


packetSequenceSignedDelta

packetSequenceSignedDelta(fromSequence, toSequence, sequenceBits = PACKET_SEQUENCE_BITS_DEFAULT)


comparePacketSequence

comparePacketSequence(leftSequence, rightSequence, sequenceBits = PACKET_SEQUENCE_BITS_DEFAULT)


isPacketSequenceNewer

isPacketSequenceNewer(candidateSequence, baselineSequence, sequenceBits = PACKET_SEQUENCE_BITS_DEFAULT)


packetSequenceWindowReport

packetSequenceWindowReport(sequence, windowStart, windowSize, sequenceBits = PACKET_SEQUENCE_BITS_DEFAULT)


packetAckRangeReport

packetAckRangeReport(packetNumbers = [], options = {})


packetFragmentPlan

packetFragmentPlan(payloadBytes, options = {})


packetReassemblyReport

packetReassemblyReport(fragments = [], options = {})


packetLossCandidateReport

packetLossCandidateReport(sentPackets = [], options = {})


quicPacketNumberEncodingBytes

quicPacketNumberEncodingBytes(packetNumber, largestAcknowledgedPacket = null)


core/math/ProfileMath

Summary: ProfileMath.js - reusable latency, frame-budget, and stage profile summaries.


latencyStatsReport

latencyStatsReport(samplesMs, options = {})


frameBudgetReport

frameBudgetReport(frameTimeMs, options = {})


profileStageReport

profileStageReport(stages, options = {})


core/math/QuantMath

Summary: QuantMath.js - reusable scalar and array quantization primitives.


quantizationStep

quantizationStep(range, maxValue = QUANT_INT16_MAX)


quantizationMaxAbsoluteError

quantizationMaxAbsoluteError(range, maxValue = QUANT_INT16_MAX)


quantizeSignedFloat

quantizeSignedFloat(value, range, maxValue = QUANT_INT16_MAX)


dequantizeSignedFloat

dequantizeSignedFloat(quantized, range, maxValue = QUANT_INT16_MAX)


quantizeSignedFloatArray

quantizeSignedFloatArray(values, range, bitDepth = 16)


dequantizeSignedFloatArray

dequantizeSignedFloatArray(quantized, range, bitDepth = 16)


quantizeRange

quantizeRange(value, min, max, bitDepth = 16, fallback = 0)


dequantizeRange

dequantizeRange(quantized, min, max, bitDepth = 16, fallback = 0)


quantizeRangeArray

quantizeRangeArray(values, min, max, bitDepth = 16)


dequantizeRangeArray

dequantizeRangeArray(quantized, min, max, bitDepth = 16)


quantizeVec2(value, range, bitDepth = 16)


dequantizeVec2(quantized, range, bitDepth = 16)


quantizeVec3(value, range, bitDepth = 16)


dequantizeVec3(quantized, range, bitDepth = 16)


dequantizeColor

dequantizeColor(quantized, bitDepth = 8)


deltaQuantize

deltaQuantize(values, range, bitDepth = 16)


quantizationErrorReport

quantizationErrorReport(source, decoded, tolerance = 0)


quaternionOrientationErrorReport

quaternionOrientationErrorReport(source, decoded, toleranceRadians = 0)


core/math/QueueMath

Summary: QueueMath.js - reusable queue depth, delay, bucket, share, ramp, and backpressure helpers.


core/math/RadioMath

Summary: RadioMath.js - reusable RF power, noise, path-loss, channel, and link-budget helpers.


thermalNoiseFloorDbm

thermalNoiseFloorDbm(bandwidthHz, options = {})


channelCapacityBps

channelCapacityBps(bandwidthHz, options = {})


snrQualityScore

snrQualityScore(snrValueDb, options = {})


channelOverlapReport

channelOverlapReport(aCenterHz, aBandwidthHz, bCenterHz, bBandwidthHz)


signalInterferenceNoiseRatioDb

signalInterferenceNoiseRatioDb(signalDbm, noiseDbm, interferenceDbm = -Infinity)


interferenceScore

interferenceScore(interferenceDbm, signalDbm, options = {})


core/math/RobustNumericMath

Summary: RobustNumericMath.js - floating-point policy, stable sums, cancellation, and filtered predicates.


cancellationReport

cancellationReport(left, right, operation = 'subtract')


orientation2DReport(a, b, c, options = {})


core/math/SIMDLayoutMath

Summary: SIMDLayoutMath.js - WebAssembly-style v128 lane metadata and SoA/AoS layout helpers.


simdLaneByteOffset

simdLaneByteOffset(shape = 'f32x4', vectorIndex = 0, laneIndex = 0, baseOffset = 0)


simdVectorAlignmentReport

simdVectorAlignmentReport(shape = 'f32x4', byteOffset = 0, options = {})


simdChunkPlan

simdChunkPlan(elementCount, shape = 'f32x4')


simdLaneMask

simdLaneMask(shape = 'f32x4', enabledLanes = 'all')


simdTailLaneMask

simdTailLaneMask(elementCount, shape = 'f32x4')


simdSoALayoutReport

simdSoALayoutReport(componentCount, elementCount, options = {})


simdScalarFallbackReport

simdScalarFallbackReport(elementCount, shape = 'f32x4', options = {})


core/math/SamplingMath

Summary: SamplingMath.js - pure sample-grid, time-window, and sample-rate report helpers.


sampleIndexForTime

sampleIndexForTime(seconds, sampleRate = DEFAULT_SAMPLE_RATE, options = {})


sampleTimeForIndex

sampleTimeForIndex(index, sampleRate = DEFAULT_SAMPLE_RATE, options = {})


sampleFrameWindowReport

sampleFrameWindowReport(sampleCount, windowSize, hopSize, options = {})


samplePlaybackRateReport

samplePlaybackRateReport(bufferSampleRate, contextSampleRate, playbackRate = 1, options = {})


spatialBilinearSampleReport

spatialBilinearSampleReport(grid, width, height, x, y, options = {})


spatialTrilinearSampleReport

spatialTrilinearSampleReport(grid, width, height, depth, x, y, z, options = {})


catmullRomSampleReport

catmullRomSampleReport(samples, x, options = {})


spatialBicubicSampleReport

spatialBicubicSampleReport(grid, width, height, x, y, options = {})


spatialAreaSampleReport

spatialAreaSampleReport(grid, width, height, area = {}, options = {})


stratifiedSampleGridReport

stratifiedSampleGridReport(columns, rows, options = {})


weightedSampleDistributionReport

weightedSampleDistributionReport(weights, options = {})


discreteImportanceSampleReport

discreteImportanceSampleReport(weights, u, options = {})


blueNoiseSampleSetReport

blueNoiseSampleSetReport(points, options = {})


lowDiscrepancySequenceReport

lowDiscrepancySequenceReport(count, options = {})


multiJitteredSampleGridReport

multiJitteredSampleGridReport(size, options = {})


sampleSetUniformityReport

sampleSetUniformityReport(points, options = {})


core/math/SceneQueryMath

Summary: SceneQueryMath.js - pure ray/overlap/sweep query reports for engine callers.


sceneQueryHitListReport

sceneQueryHitListReport(hits, options = {})


sceneQueryFilterReport

sceneQueryFilterReport(query = {}, target = {}, options = {})


sceneQuerySweptAabbReport

sceneQuerySweptAabbReport(movingMin, movingMax, staticMin, staticMax, delta, options = {})


sceneQueryAabbOverlapReport

sceneQueryAabbOverlapReport(aMin, aMax, bMin, bMax, options = {})


sceneQuerySpherePenetrationReport

sceneQuerySpherePenetrationReport(centerA, radiusA, centerB, radiusB, options = {})


sceneQueryContactNormalReport

sceneQueryContactNormalReport(normal, options = {})


sceneQueryConvexRadiusReport

sceneQueryConvexRadiusReport(radius, options = {})


sceneQueryBroadphasePairScore

sceneQueryBroadphasePairScore(aMin, aMax, bMin, bMax, options = {})


core/math/SignalQualityMath

Summary: SignalQualityMath.js - reusable signal/link health scoring for radio and WebRTC diagnostics.


signalLevelQualityScore

signalLevelQualityScore(valueDb, options = {})


signalLatencyQualityScore

signalLatencyQualityScore(rttMs, options = {})


signalJitterQualityScore

signalJitterQualityScore(jitterMs, options = {})


signalBitrateQualityScore

signalBitrateQualityScore(bitrateBps, options = {})


webrtcStatsSignalReport

webrtcStatsSignalReport(stats, options = {})


signalQualityTrendReport

signalQualityTrendReport(samples = [], options = {})


core/math/SpatialHash

Summary: SpatialHash.js - Fast spatial queries for particles and entities Uses a grid-based hash for O(1) average-case neighbor queries.


core/math/SpatialHashCompute


core/math/TensorShapeMath

Summary: TensorShapeMath.js - reusable tensor shape, broadcast, stride, dtype, and graph memory reports.


normalizeTensorShape

normalizeTensorShape(shape, options = {})


tensorIndexToOffset

tensorIndexToOffset(indices, strides, options = {})


tensorOffsetToIndices

tensorOffsetToIndices(offset, shape, options = {})


reshapeReport

reshapeReport(inputShape, targetShape, options = {})


tensorBufferSizeReport

tensorBufferSizeReport(shape, dtype = 'float32', options = {})


reductionShape

reductionShape(shape, axes, options = {})


tensorGraphMemoryReport

tensorGraphMemoryReport(tensors, options = {})


core/math/TextMetricMath

Summary: TextMetricMath.js - grapheme, text-run, wrap, baseline, selection, and glyph-atlas reports.


textGraphemeSegments

textGraphemeSegments(text, options = {})


textGraphemeBoundaries

textGraphemeBoundaries(text, options = {})


textCursorAdvance

textCursorAdvance(text, offset = 0, direction = 1, options = {})


textLineBreakOpportunityReport

textLineBreakOpportunityReport(text, options = {})


textLineWrapReport

textLineWrapReport(text, maxWidth = Infinity, options = {})


textTruncateReport

textTruncateReport(text, maxWidth = Infinity, options = {})


textBaselineReport

textBaselineReport(metrics = {}, options = {})


textSelectionRects

textSelectionRects(wrapReport, start = 0, end = start, options = {})


glyphAtlasPlacementReport

glyphAtlasPlacementReport(glyphs = [], options = {})


core/math/TextureMath

Summary: TextureMath.js - shared UV, atlas, format, and mip pyramid helpers.


tileUV

tileUV(uv, scale = [1, 1], offset = [0, 0])


atlasUVTransform

atlasUVTransform(x, y, width, height, atlasWidth, atlasHeight = atlasWidth)


textureMipExtent3D(width, height = width, depth = 1, mipLevel = 0)


atlasPaddedExtent

atlasPaddedExtent(width, height = width, padding = 1)


atlasContentRect

atlasContentRect(x, y, width, height, padding = 1)


atlasPaddedRectFromContent

atlasPaddedRectFromContent(x, y, width, height, padding = 1)


atlasPaddedArea

atlasPaddedArea(width, height, padding = 1)


atlasRegionUVs

atlasRegionUVs(x, y, width, height, atlasWidth, atlasHeight = atlasWidth)


virtualTexturePageGrid

virtualTexturePageGrid(pageTableWidth = 2048, pageTableHeight = pageTableWidth)


virtualTexturePageId

virtualTexturePageId(pageX, pageY, pageTableWidth = 2048, pageTableHeight = pageTableWidth)


virtualTexturePageCoord

virtualTexturePageCoord(pageId, pageTableWidth = 2048, pageTableHeight = pageTableWidth)


virtualTexturePageCoordFromUV

virtualTexturePageCoordFromUV(uv, pageTableWidth = 2048, pageTableHeight = pageTableWidth)


virtualTexturePhysicalPageGrid

virtualTexturePhysicalPageGrid(cacheWidth = 4096, pageSize = 256, cacheHeight = cacheWidth)


virtualTexturePhysicalPageOrigin

virtualTexturePhysicalPageOrigin(slotIndex, cacheWidth = 4096, pageSize = 256, cacheHeight = cacheWidth)


virtualTexturePhysicalUV

virtualTexturePhysicalUV(uv, physicalPage, { pageTableWidth = 2048, pageTableHeight = pageTableWidth, pageSize = 256, cacheWidth = 4096, cacheHeight = cacheWidth, } = {})


virtualTexturePageTableEntry

virtualTexturePageTableEntry(pageId, physicalLocation, { pageTableWidth = 2048, pageTableHeight = pageTableWidth, pageSize = 256, resident = 1, reserved = 0, } = {})


virtualTextureFeedbackBufferLayout

virtualTextureFeedbackBufferLayout(pageTableWidth = 2048, pageTableHeight = pageTableWidth, bytesPerFlag = 4)


virtualTextureFeedbackBufferByteSize

virtualTextureFeedbackBufferByteSize(pageTableWidth = 2048, pageTableHeight = pageTableWidth, bytesPerFlag = 4)


virtualTextureFeedbackIndex

virtualTextureFeedbackIndex(pageId, pageTableWidth = 2048, pageTableHeight = pageTableWidth)


compactVirtualTextureFeedback

compactVirtualTextureFeedback(feedbackData, { pageTableWidth = 2048, pageTableHeight = pageTableWidth, maxRequests = Infinity, residentPages = null, } = {})


pixelToUV

pixelToUV(pixel, textureSize, centered = false)


uvToPixel

uvToPixel(uv, textureSize, centered = false)


textureMipLevelCount

textureMipLevelCount(width, height = width, depth = 1, maxMipLevels = Infinity)


textureMipExtent

textureMipExtent(width, height, mipLevel = 0)


textureMipByteSize

textureMipByteSize(width, height, bytesPerPixel = 4, mipLevels = 1, depthOrArrayLayers = 1)


textureFormatBlockInfo

textureFormatBlockInfo(format = 'rgba8unorm', fallbackBytesPerPixel = 4)


textureFormatIsSupported

textureFormatIsSupported(format = 'rgba8unorm', features = null)


textureDefaultTranscodeTargets

textureDefaultTranscodeTargets({ needsAlpha = true, preferSrgb = false } = {})


textureBytesPerPixel

textureBytesPerPixel(format = 'rgba8unorm', fallbackBytesPerPixel = 4)


textureFormatBitsPerPixel

textureFormatBitsPerPixel(format = 'rgba8unorm', fallbackBytesPerPixel = 4)


textureMipBlockExtent

textureMipBlockExtent(width, height, format = 'rgba8unorm', mipLevel = 0)


textureMipBlockExtent3D(width, height, depth = 1, format = 'rgba8unorm', mipLevel = 0)


textureFormatMipByteSize

textureFormatMipByteSize(width, height, format = 'rgba8unorm', mipLevels = 1, depthOrArrayLayers = 1)


textureContainerLevelByteSize

textureContainerLevelByteSize({ width, height = width, depth = 1, format = 'rgba8unorm', mipLevel = 0, layerCount = 1, faceCount = 1, } = {})


textureKtxLevelAlignment

textureKtxLevelAlignment(format = 'rgba8unorm', supercompressionScheme = 0)


alignByteOffset

alignByteOffset(byteOffset, alignment = 1)


textureKtxMipPadding

textureKtxMipPadding(byteOffset, format = 'rgba8unorm', supercompressionScheme = 0)


textureKtxSupercompressionLevelReport

textureKtxSupercompressionLevelReport({ byteLength = 0, uncompressedByteLength = byteLength, supercompressionScheme = 0, expectedUncompressedByteLength = null, faceCount = 1, layerCount = 1, } = {})


textureKtxSupercompressionGlobalDataRange({ byteOffset = 0, byteLength = 0, precedingByteEnd = 0, supercompressionScheme = 0, } = {})


textureKtxSupercompressionPolicy

textureKtxSupercompressionPolicy({ supercompressionScheme = 0, levels = [], expectedUncompressedByteLengths = null, sgdByteOffset = 0, sgdByteLength = 0, precedingByteEnd = 0, faceCount = 1, layerCount = 1, } = {})


textureContainerImageLayout

textureContainerImageLayout({ width, height = width, depth = 1, format = 'rgba8unorm', mipLevel = 0, layerCount = 1, faceCount = 1, } = {})


textureContainerImageByteOffset

textureContainerImageByteOffset(layout, layer = 0, face = 0, zSlice = 0)


textureWebGpuUploadLayout

textureWebGpuUploadLayout({ width, height = width, depthOrArrayLayers = 1, format = 'rgba8unorm', mipLevel = 0, offset = 0, bytesPerRowAlignment = 1, copyBufferToTexture = false, } = {})


textureKtxLevelLayout

textureKtxLevelLayout({ width, height = width, depth = 1, format = 'rgba8unorm', levelCount = textureMipLevelCount(width, height, depth)


textureMemorySavingsRatio

textureMemorySavingsRatio(width, height, compressedFormat, referenceFormat = 'rgba8unorm', mipLevels = 1)


textureQualitySizeScore

textureQualitySizeScore({ width, height = width, format = 'rgba8unorm', referenceFormat = 'rgba8unorm', mipLevels = 1, depthOrArrayLayers = 1, quality = 1, byteBudget = Infinity, budgetBytes = byteBudget, qualityWeight = 0.7, sizeWeight = 0.3, budgetWeight, } = {})


textureTranscodeTargetScore

textureTranscodeTargetScore(target, { width, height = width, referenceFormat = 'rgba8unorm', mipLevels = 1, depthOrArrayLayers = 1, supportedFeatures = null, needsAlpha = true, allowPunchthroughAlpha = false, preferSrgb = false, byteBudget = Infinity, qualityWeight = 0.7, sizeWeight = 0.3, budgetWeight, } = {})


textureRankTranscodeTargets

textureRankTranscodeTargets({ candidates = null, needsAlpha = true, preferSrgb = false, ...options } = {})


textureStreamingPriorityScore

textureStreamingPriorityScore({ priority = 0, distance = Infinity, lastUsedFrame = 0, frameIndex = 0, distanceScale = 0.01, recencyScale = 0.1, distanceWeight = 10, recencyWeight = 5, } = {})


mipLevelFromPixelSize

mipLevelFromPixelSize(pixelSize, maxMipLevel = Infinity)


core/math/UILayoutMath

Summary: UILayoutMath.js - pure CSS/UI length, constraint, and responsive layout reports.


uiCssMathFunctionReport

uiCssMathFunctionReport(value, context = {})


uiLayoutValueReport

uiLayoutValueReport(value, context = {})


uiPercentageBasisReport

uiPercentageBasisReport(value, basis, options = {})


uiViewportUnitReport

uiViewportUnitReport(value, viewport = {}, options = {})


uiSafeAreaInsetReport

uiSafeAreaInsetReport(insets = {}, options = {})


uiVisualViewportReport

uiVisualViewportReport(observed = {}, options = {})


uiLayoutClampReport

uiLayoutClampReport(value, minValue, maxValue, context = {})


uiBoxConstraintReport

uiBoxConstraintReport(style = {}, context = {})


uiFlexBasisReport

uiFlexBasisReport(style = {}, context = {})


uiIntrinsicSizePolicyReport

uiIntrinsicSizePolicyReport(value = 'auto', options = {})


uiGridTrackSizingReport

uiGridTrackSizingReport(trackList = [], options = {})


uiResponsiveStepReport

uiResponsiveStepReport(value, steps = [], options = {})


core/math/UnionFind

Summary: Union-Find specialized for 3D voxel grids


HybridConnectivity

Summary: Combines GPU flood-fill for initial/full recomputes with CPU Union-Find for incremental updates


core/math/UnitMath

Summary: UnitMath.js - deterministic scalar unit conversion helpers.


secondsToFrames

secondsToFrames(seconds, frameRate = DEFAULT_FRAME_RATE)


framesToSeconds

framesToSeconds(frames, frameRate = DEFAULT_FRAME_RATE)


millisecondsToFrames

millisecondsToFrames(milliseconds, frameRate = DEFAULT_FRAME_RATE)


framesToMilliseconds

framesToMilliseconds(frames, frameRate = DEFAULT_FRAME_RATE)


secondsToSamples

secondsToSamples(seconds, sampleRate = DEFAULT_SAMPLE_RATE)


samplesToSeconds

samplesToSeconds(samples, sampleRate = DEFAULT_SAMPLE_RATE)


sampleIndexAtTime

sampleIndexAtTime(seconds, sampleRate = DEFAULT_SAMPLE_RATE)


samplesToMilliseconds

samplesToMilliseconds(samples, sampleRate = DEFAULT_SAMPLE_RATE)


millisecondsToSamples

millisecondsToSamples(milliseconds, sampleRate = DEFAULT_SAMPLE_RATE)


beatsToSeconds

beatsToSeconds(beats, bpm = DEFAULT_BPM)


secondsToBeats

secondsToBeats(seconds, bpm = DEFAULT_BPM)


frequencyToWavelengthMeters

frequencyToWavelengthMeters(frequencyHz, waveSpeed = SPEED_OF_LIGHT)


wavelengthMetersToFrequencyHz

wavelengthMetersToFrequencyHz(wavelengthMeters, waveSpeed = SPEED_OF_LIGHT)


powerRatioToDb

powerRatioToDb(powerRatio, floorDb = -Infinity)


frequencyRatioToCents

frequencyRatioToCents(ratio, floorCents = -Infinity)


cssPixelsToDevicePixels

cssPixelsToDevicePixels(cssPixels, devicePixelRatio = 1)


devicePixelsToCssPixels

devicePixelsToCssPixels(devicePixels, devicePixelRatio = 1)


worldUnitsToGridIndex

worldUnitsToGridIndex(worldValue, cellSize = 1, origin = 0)


gridIndexToWorldUnits

gridIndexToWorldUnits(gridIndex, cellSize = 1, origin = 0, centered = false)


worldUnitsToChunkIndex

worldUnitsToChunkIndex(worldValue, chunkCells = 16, cellSize = 1, origin = 0)


chunkIndexToWorldUnits

chunkIndexToWorldUnits(chunkIndex, chunkCells = 16, cellSize = 1, origin = 0, centered = false)


worldUnitsToLocalChunkIndex

worldUnitsToLocalChunkIndex(worldValue, chunkCells = 16, cellSize = 1, origin = 0)


core/math/VideoMath

Summary: VideoMath.js - pure sequence-level video/frame math over ImageData-like frames.


videoSequenceReport

videoSequenceReport(frames, options = {})


videoTemporalBlendFrame

videoTemporalBlendFrame(referenceFrame, candidateFrame, amount = 0.5, options = {})


videoSceneListReport

videoSceneListReport(frames, options = {})


videoKeyframePlanReport

videoKeyframePlanReport(frames, options = {})


videoMotionEntropyReport

videoMotionEntropyReport(frames, options = {})


videoTemporalEntropyReport

videoTemporalEntropyReport(frames, options = {})


videoThumbnailCandidateReport

videoThumbnailCandidateReport(frames, options = {})


core/math/WGSLRegistry

Summary: WGSLRegistry.js - metadata for reusable WGSL chunks and CPU/WGSL mirror links.


wgslRegistryById

wgslRegistryById(id, registry = WGSL_REGISTRY)


wgslMirrorsForChunk

wgslMirrorsForChunk(chunkId, mirrors = WGSL_MIRROR_REGISTRY)


wgslRegistryReport

wgslRegistryReport(chunks = WGSL_CHUNK_REGISTRY, mirrors = WGSL_MIRROR_REGISTRY, moduleExports = WGSL_MODULE_EXPORTS, moduleExportClassifications = WGSL_MODULE_EXPORT_CLASSIFICATIONS)


mathRegistryWGSLMirrorReport

mathRegistryWGSLMirrorReport(mathFunctions = MATH_FUNCTION_REGISTRY, wgslMirrors = WGSL_MIRROR_REGISTRY)


wgslRegistryManifest

wgslRegistryManifest(chunks = WGSL_CHUNK_REGISTRY, mirrors = WGSL_MIRROR_REGISTRY)


core/math/XRMath

Summary: XRMath.js - pure WebXR-shaped pose, view, projection, and depth reports.


xrRigidTransformReport

xrRigidTransformReport(transform = {}, options = {})


xrPoseViewMatrix

xrPoseViewMatrix(transform = {}, options = {})


xrViewProjectionReport

xrViewProjectionReport(view = {}, options = {})


xrViewerPoseReport

xrViewerPoseReport(views = [], options = {})


xrReferenceSpaceOffsetReport

xrReferenceSpaceOffsetReport(baseTransform = {}, offsetTransform = {}, options = {})


xrDepthRawToMeters

xrDepthRawToMeters(rawDepth, rawValueToMeters = 1)


xrDepthUvTransformPoint

xrDepthUvTransformPoint(point = {}, matrix = identity4()


xrDepthSampleIndex

xrDepthSampleIndex(width, height, u, v, options = {})


xrDepthSampleMeters

xrDepthSampleMeters(depthData, width, height, u, v, options = {})


core/math/index

Summary: engine/core/math/index.js - Math Utilities Barrel Export


core/memory/ChunkBufferPool


core/memory/GPUMemoryManager

Summary: GPUMemoryManager.js - WebGPU Device Memory Management Implements: - Ring Buffer for dynamic uniform data (per-frame) - Buddy Allocator for static geometry (persistent) - Texture Atlas management with LRU eviction - BindGroup caching and deduplication Goal: Minimize GPU API calls and prevent VRAM fragmentation


RingBuffer

Summary: Circular buffer for per-frame dynamic data (uniforms, instance data). Wraps around each frame, avoiding buffer creation overhead.


BuddyAllocator

Summary: Buddy allocator for persistent GPU memory (geometry, textures). Handles allocation/deallocation without fragmentation.


StagingBufferPool

Summary: Pool of mappable staging buffers for CPU->GPU transfers. Avoids creating new buffers for every upload.


BindGroupCache

Summary: Cache for GPUBindGroup objects to avoid redundant creation. Uses content-based hashing for deduplication.


TextureManager

Summary: Manages GPU textures with LRU eviction policy.


GPUMemoryManager

Summary: Central GPU memory management facade.


getGPUMemoryManager

Summary: Get or create GPU memory manager singleton


core/memory/HostMemoryManager

Summary: Linear allocator that resets every frame. Provides zero-cost TypedArray views into a pre-allocated buffer.


ObjectPool

Summary: Generic object pool for reusable JavaScript objects. Uses LIFO (stack) for hot cache retrieval.


SoAContainer

Summary: SoA container for cache-efficient mass entity storage. All properties stored in contiguous TypedArrays.


HostMemoryManager

Summary: Central manager for all host memory allocation.


createCommonPools

Summary: Create common pools for game objects


core/memory/MappedBufferRing

Summary: MappedBufferRing - Efficient GPU data upload with pre-mapped buffers


core/memory/ObjectPool

Summary: Generic object pool with factory function


core/memory/PipelineCache

Summary: PipelineCache - Async pipeline compilation and caching


core/memory/RenderBundleCache

Summary: RenderBundleCache - Manages render bundles for voxel terrain


core/memory/SubChunkBufferPool

Summary: SubChunkBufferPool - Manages GPU buffer reuse for sub-chunk meshes


getBufferPool

Summary: Get the global buffer pool instance


initBufferPool

Summary: Initialize the global buffer pool


core/memory/UniformBufferRing

Summary: UniformBufferRing - Rotating uniform buffers


FrameUniformManager

Summary: FrameUniformManager - Manages per-frame uniforms with automatic rotation


core/memory/VertexPool

Summary: VertexPool - Manages a large persistent vertex buffer with bucket allocation


FaceOrientedVertexPool

Summary: FaceOrientedVertexPool - Vertex pool with 6 sub-buckets per chunk for true back-face culling Each chunk gets 6 smaller buckets, one per face direction


core/memory/index


core/platform/InputPlumbing


core/platform/MainLoop


core/platform/PlatformCanvas


createCanvasSurface

createCanvasSurface(gpuDevice, canvasTarget, options = {})


createViewportManager

createViewportManager(gpuDevice, options = {})


core/profiler/DualRNG

Summary: DualRNG - Manages synchronized and visual RNGs


positionHash

Summary: Position-based hash for deterministic randomness at specific coordinates Useful for terrain generation where you need same result for same position


getGlobalRNG

Summary: Get or create global DualRNG instance


initGlobalRNG

Summary: Initialize global RNG with seed (call from game init)


core/profiler/FrameBudgetManager

Summary: FrameBudgetManager - Manages per-frame time budgets


getFrameBudgetManager

Summary: Get global frame budget manager


shouldSkipWork

Summary: Quick check if we should skip work this frame


core/profiler/GameplayProfiler


core/profiler/PerformanceOptimizer

Summary: Common workgroup sizes


WorkgroupSizes

Summary: Common workgroup sizes


BufferStrategy

Summary: Buffer strategies


MemoryTier

Summary: Memory allocation tiers


FrameBudget

Summary: Frame budget targets


core/profiler/index


core/profiling/PerformanceAnalyzer


core/save/SaveSystem


core/save/index


core/scheduler/TaskScheduler

Summary: Represents a unit of work


Job

Summary: Represents a unit of work


WorkerPool

Summary: Pool of Web Workers for parallel job execution


TaskScheduler

Summary: Main task scheduler with frame budget management


workerTemplate

Summary: Template for worker script. Export this and use with URL.createObjectURL.


core/scheduler/index


core/schema/BrowserRecordContract

Summary: Shared expand-contract owner for structured browser key/value records.


BrowserRecordContractError

class BrowserRecordContractError extends Error


createBrowserRecordContract

createBrowserRecordContract({ schema, legacyKey, currentKey = `${legacyKey}.v2`, payloadKey = 'value', validate, maxBytes = 4 * 1024 * 1024, } = {})


core/schema/SchemaEvolutionRegistry

Summary: Pure registry for explicit schema readers, writers, and migration graphs. It transforms decoded values only and never reads or writes persistence.


SchemaEvolutionError

class SchemaEvolutionError extends Error


core/schema/SchemaValidator

Summary: SchemaValidator — Validates game data against JSON schemas. Lightweight validator (no external deps). Checks required fields, types, enums, min/max, and array items. Reports all errors.


core/schema/index


core/timing/DisplayRefreshEstimator

Summary: Robustly estimates the host display cadence from requestAnimationFrame intervals. Missed callbacks are filtered before estimation, so a busy frame does not incorrectly turn a 144 Hz display into a 72 Hz quality target.


core/timing/FramePacingController


core/timing/index


core/workers/WorkerPool

Summary: Web Worker Pool - Multi-threaded asset loading and processing Eliminates main thread blocking during heavy operations


ecs/ComponentHealer

Summary: ComponentHealer.js - Self-Healing Data Validation System Implements auto-repair for component data using triangulation: - Detects missing/invalid/corrupted data - Infers correct values from multiple sources (redundancy) - Applies intelligent repairs with fallbacks - Logs all healing actions for diagnostics Based on self-healing system principles: 1. Monitoring & Detection 2. Diagnostics Engine 3. Decision-Making Module 4. Execution Framework 5. Knowledge Base (schema defaults + inference rules) 6. Feedback Loop (healing log)


TriangulationContext

Summary: Triangulation context - provides multiple sources for inferring values


healComponent

healComponent(componentName, data, ctx = new TriangulationContext()

Summary: Heal a component using schema and triangulation


healAndValidate

healAndValidate(componentName, data, options = {})

Summary: Heal and validate component data before use This is the main entry point for the healing system


getHealingStats

Summary: Get healing statistics with detailed metrics


batchHealComponents

batchHealComponents(components, sharedContext = {})

Summary: Batch heal multiple components efficiently


validateComponentData

Summary: Validate component without healing - just check for issues


ecs/EntityManager

Summary: Delete an entity with full cleanup of associated resources.


deleteSelectedEntity

Summary: Delete the currently selected entity.


ecs/EntitySchema

Summary: Normalize a single field value based on its type definition


normalizeBySchema

Summary: Normalize a component value using its schema definition This is the primary function component files should use


getSchemaDefaults

Summary: Get default values from a schema


getCollisionMask

Summary: Helper: Get collision layer mask from layer names


layersCollide

layersCollide(layerA, maskA, layerB, maskB)

Summary: Helper: Check if two layer masks collide


getPhysXFlagsForCollisionMode

Summary: Helper: Get collision mode flags for PhysX Returns { pairFlags, shapeFlags } for PhysX configuration


registerComponentSchema

Summary: Register a custom component schema at runtime Allows component files to auto-register their schemas


getRegisteredSchemaNames

Summary: Get all registered component schema names


validateComponent

Summary: Validate and normalize a component value against its schema


createDefaultComponent

Summary: Create default component data


validateTransform

Summary: Validate Transform component


validatePhysicsBody

Summary: Validate PhysicsBody component


validateCollider

Summary: Validate Collider component


validateLight

Summary: Validate Light component


validateCamera

Summary: Validate Camera component


validateRenderable

Summary: Validate Renderable component


validateParticleEmitter

Summary: Validate ParticleEmitter component


validateNavAgent

Summary: Validate NavAgent component


validatePhysicsChain

Summary: Validate PhysicsChain component


createDefaultTransform

Summary: Create default Transform


createDefaultPhysicsBody

Summary: Create default PhysicsBody


createDefaultCollider

Summary: Create default Collider


createDefaultLight

Summary: Create default Light


createDefaultCamera

Summary: Create default Camera


createDefaultRenderable

Summary: Create default Renderable


createDefaultPhysicsChain

Summary: Create default PhysicsChain


createEmptyEntity

Summary: Create empty entity


createEntitySnapshot

Summary: Create entity snapshot


createWorldSnapshot

Summary: Create world snapshot


jsonReplacer

Summary: JSON replacer function for special values Use with JSON.stringify(obj, jsonReplacer)


jsonReviver

Summary: JSON reviver function for special values Use with JSON.parse(str, jsonReviver)


serializeComponent

Summary: Serialize component to JSON-safe object


deserializeComponent

deserializeComponent(componentName, json, healingContext = null)

Summary: Deserialize component from JSON with optional self-healing


serializeEntitySnapshot

Summary: Serialize entity snapshot to JSON-safe object


serializeWorldSnapshot

Summary: Serialize world snapshot to JSON-safe object


deserializeWorldSnapshot

Summary: Deserialize world snapshot from JSON


Summary: Interpolate between two vec3 values


lerpQuat

Summary: Interpolate between two quaternions (simple lerp, not slerp)


interpolateTransform

Summary: Interpolate Transform between two states


interpolatePhysicsBody

Summary: Interpolate PhysicsBody between two states


interpolateEntitySnapshot

Summary: Interpolate entity snapshot between two states


getColliderShapeId

Summary: Get collider shape ID from name


getColliderShapeName

Summary: Get collider shape name from ID


getLightTypeId

Summary: Get light type ID from name


getLightTypeName

Summary: Get light type name from ID


getCameraProjectionId

Summary: Get camera projection ID from name


getEmitterShapeId

Summary: Get emitter shape ID from name


Summary: Common field types used across components


Summary: Transform component schema


Summary: PhysicsBody component schema


Summary: Collider shapes


Summary: Collider component schema


Summary: Light types


Summary: Light component schema


Summary: Camera projection types


Summary: Camera modes


Summary: Camera component schema


Summary: Renderable component schema


Summary: Emitter shapes for particle spawning


Summary: ParticleEmitter component schema


Summary: NavAgent component schema


Summary: Chain physics backends


Summary: PhysicsChain component schema (unified: particle chains + rigid chains) mode: "particle" = PBD/GPU/PhysX particle chain (formerly PhysicsRope) mode: "rigid"    = rigid linked chain (formerly PhysicsChain)


Summary: Weld constraint types


Summary: WeldConstraint component schema - Defines a physics weld between two entities Welds merge collision shapes from child into parent, creating compound bodies. When saved: stores entity IDs and offset When loaded: recreates weld during physics init


Summary: Collision modes - determines how physics engine handles collisions Maps to PhysX PxPairFlags and shape flags


Summary: Predefined collision layers (bitmask) Each entity belongs to one layer (collisionLayer) and can collide with multiple layers (collisionMask)


Summary: EntityFlags component schema - Unified flags for collision, visibility, and editor behavior This component centralizes all entity interaction flags: - Collision: layer/mask filtering, collision mode (solid/trigger/noPush/ghost) - Visibility: render visibility, layer masks, editor-only visibility - Editor: pickable, selectable, locked, hidden in hierarchy - Physics: weldable, pushable, sleepable PhysX Integration: - collisionLayer → PxFilterData.word0 - collisionMask → PxFilterData.word1 - collisionMode → PxPairFlags (eSOLVE_CONTACT, eDETECT_DISCRETE_CONTACT, etc.)


Summary: Complete entity schema (entity + components)


Summary: Entity state snapshot (for rewind)


Summary: World snapshot schema


ecs/SceneInit

Summary: Initialize ECS world with physics sandbox scene.


createMinimalWorld

Summary: Create a minimal ECS world without physics sandbox.


ecs/components/Camera


ecs/components/Cloth


ecs/components/Collider


ecs/components/ComponentRegistry

Summary: Get schema for a component from EntitySchema


validateComponentSchema

Summary: Validate component using EntitySchema


createDefaultFromSchema

Summary: Create default component using EntitySchema


ecs/components/FluidSource


ecs/components/FluidVolume


ecs/components/Input


ecs/components/Light


ecs/components/NavAgent


ecs/components/NetReplicated


ecs/components/ParticleEmitter


ecs/components/ParticleField


ecs/components/PhysicalMaterial


ecs/components/PhysicsBody


ecs/components/PhysicsChain


ecs/components/PhysicsCloth


ecs/components/PhysicsHair


ecs/components/PhysicsRope


ecs/components/PhysicsSoftBody


ecs/components/PhysicsWire


ecs/components/Renderable


ecs/components/StickmanRagdoll


ecs/components/Transform


ecs/components/TwistedRope


ecs/components/WeldConstraint

Summary: Create a new WeldConstraint component


createWeldConstraint

Summary: Create a new WeldConstraint component


createWeld

createWeld(parentEntityId, childEntityId, options = {})

Summary: Create a weld constraint between two entities


isValidWeld

Summary: Check if a weld constraint is valid


breakWeld

Summary: Mark a weld as broken


ecs/prefabs/PrefabRegistry

Summary: PrefabRegistry - Runtime prefab system for entity templates Prefabs define reusable entity configurations including: - Default components - Geometry data - Collider configuration - Visual properties The editor uses spawnables which extend this with spawn UI logic. Runtime uses prefabs directly for instantiation.


registerPrefab

Summary: Register a prefab


getPrefab

Summary: Get a prefab by ID


getAllPrefabs

Summary: Get all registered prefabs


getPrefabsByCategory

Summary: Get prefabs by category


instantiatePrefab

Summary: Instantiate a prefab into components


clearPrefabs

Summary: Clear all prefabs (for testing)


ecs/prefabs/index

Summary: Prefab System - Runtime entity templates


ecs/query/Query


ecs/replication/ReplicationProfiles


defineReplicationProfile

defineReplicationProfile(name, definition, options = {})


resolveReplicationProfile

resolveReplicationProfile(name, overrides = {})


createReplicationProjection

createReplicationProjection(netReplicated, components, context = {})


ecs/storage/ArchetypeStorage

Summary: Fast path: update an existing component WITHOUT normalization. Use ONLY when the value is already known-valid (e.g., from physics engine output). The entity MUST already have this component — this will NOT add new components. Returns the value if successful, null if entity/component not found.


setEntityComponent

setEntityComponent(world, entityId, componentName, value)


setEntityComponentDirect

setEntityComponentDirect(world, entityId, componentName, value)


ecs/systems/CameraSystem


registerCameraSystem

registerCameraSystem(world, options = {})


ecs/systems/ClothSystem


registerClothSystem

registerClothSystem(world, options = {})


ecs/systems/FluidDebugSystem


registerFluidDebugSystem

registerFluidDebugSystem(world, options = {})


ecs/systems/FluidSystem


registerFluidSystem

registerFluidSystem(world, options = {})


ecs/systems/NavAgentSystem


registerNavAgentSystem

registerNavAgentSystem(world, options = {})


ecs/systems/ParticleDebugSystem


registerParticleDebugSystem

registerParticleDebugSystem(world, options = {})


ecs/systems/ParticleSystem


registerParticleSystem

registerParticleSystem(world, options = {})


ecs/systems/PerceptionSystem


registerPerceptionSystem

registerPerceptionSystem(world, options = {})


ecs/systems/PhysicsSystem


registerPhysicsSystem

registerPhysicsSystem(world, options = {})


ecs/systems/SystemRegistry


ecs/systems/ThirdPersonCameraSystem


registerThirdPersonCameraSystem

registerThirdPersonCameraSystem(world, options = {})


ecs/systems/WorldSystem


registerWorldSystem

registerWorldSystem(world, options = {})


ecs/world/World


getWorldDebugSnapshot

getWorldDebugSnapshot(world, options = {})


ecs/world/WorldPersistence


createWorldSavePayload

createWorldSavePayload(world, options = {})


restoreWorldFromSavePayload

restoreWorldFromSavePayload(world, payload, options = {})


gameplay/ai/InstinctGraph


gameplay/ai/NPCBrain

Summary: NPCBrain — Tiny JavaScript brain for each NPC. Inputs feed drives. The strongest LEGAL drive wins (RuleGraph filters). Memory changes the weights over time. Drives: fight, flee, protect, steal, obey, betray, comfort, digBuild, follow, reportCrime


gameplay/ai/index


gameplay/events/EventGraph

Summary: EventGraph — The event bus and event log for LIFE. Every meaningful thing in the world becomes an event. Events power: memories, dialogue, reputation, crimes, family history, item souls, resolve changes, and storylet triggers. Events are immutable once created. The log is append-only. Listeners can subscribe to event types or use wildcard '*'.


EventGraph

Summary: EventGraph — global event bus + per-entity event logs.


createEvent

Summary: Creates an immutable event object.


gameplay/events/index


gameplay/inventory/Inventory


gameplay/inventory/index


gameplay/items/ItemOwnership

Summary: ItemOwnership — Tracks who owns what, detects theft, handles transfers.


gameplay/items/ItemSoulSystem

Summary: ItemSoulSystem — Items slowly gain souls through history. Stages: Normal → Remembered → Resonant → Awakened → Talking → Contract Item Soul growth triggers: named, used often, saved someone, repaired many times, inherited, used in major battles, exposed to domains, part of a contract, emotionally important, connected to death/rescue/betrayal/redemption.


gameplay/items/index


gameplay/narrative/BackgroundMatcher

Summary: BackgroundMatcher — Extracts origin tags from player-written background text. The player types a "soul memory" and the system extracts semantic tags that drive world generation: family type, culture, social status, early hardships, resolve seeds, and starting storylets. Uses keyword/phrase matching with weighted scoring. No heavy ML needed for the first playable — just pattern matching with synonyms.


extractOriginTags

Summary: Extract origin tags from player-written background text.


mapTagsToOrigin

Summary: Map extracted tags to world generation parameters.


gameplay/narrative/DialogueSystem

Summary: DialogueSystem — Dynamic narrative template system. Pipeline: event → intent → template → mood → voice layer → relationship tone → final line NPC speech uses templates, not generative AI. The voice layer changes sentence length, glue words, confidence, politeness, swearing, emotional intensity.


gameplay/narrative/DialogueTree

Summary: DialogueRunner — Executes a dialogue tree, manages state, and produces UI output.


node

Summary: Create a dialogue node.


textNode

Summary: Shorthand builders.


gameplay/narrative/LifePhases

Summary: LifePhases — Controls the origin sequence: birth → childhood → crisis → youth → main game. Each phase runs a sequence of events and storylets, then transitions to the next. The player watches/interacts through text during early phases, then gains full control at Youth.


gameplay/narrative/OriginGenerator

Summary: Generate a full origin from mapped tags.


gameplay/narrative/SituationGraph

Summary: SituationGraph — Selects life pressure situations for the player. Situation buckets: family, survival, crime, faction, power, exploration, social, build/dig, item soul, law, domain, revenge, redemption. Chooses situations based on player background, family state, location, NPC relationships, faction reputation, active crimes, wealth, danger, resolve path, recent failures/victories.


gameplay/narrative/StoryGraph

Summary: StoryGraph — Storylet engine for LIFE. Stories are storylets, not one fixed script. A storylet is a small reusable story event that triggers when conditions are true. Each storylet has: trigger conditions, cast, stakes, choices, consequences, memories, and graph updates.


createStorylet

Summary: Create a storylet definition.


gameplay/narrative/WorldDirector

Summary: WorldDirector — Controls pacing and selects world events. Watches: player stress, supplies, family conflict, recent fights, deaths, victories, crew size, base strength, faction anger, unresolved crimes, resolve growth, domain activity. Selects events to create: pressure → relief → pressure → consequence. Not constant chaos.


gameplay/narrative/index


gameplay/narrative/storylets/core_storylets

Summary: Core Storylet Library — Initial content for the StoryGraph. Each storylet has trigger conditions, cast selection, and execution logic.


gameplay/perception/PerceptionGraph

Summary: PerceptionGraph — Controls what the player can perceive about NPCs. NPCs have hidden truth. The player sees tags based on perception skill, distance, lighting, relationship, NPC deception, disguise, and domain effects. Tags can be WRONG if the NPC is good at hiding.


gameplay/perception/index


gameplay/progression/ContractSystem


gameplay/progression/DomainGraph

Summary: DomainGraph — Local rule overrides. A domain is a personal law forced onto an area. Domains are rare and earned. They modify rules within a radius, cost stamina/resolve to maintain, and have weaknesses and failure conditions. Domain rules are priority 8 in RuleGraph — they can override local reality but not engine safety or physics.


gameplay/progression/PowerGraph


gameplay/progression/ResolveSystem


gameplay/progression/index


gameplay/rules/RuleGraph

Summary: RuleGraph — The master rule resolver for LIFE. Everything in the world passes through RuleGraph to decide what is legal. Rules have priorities (1=highest), conditions, effects, and sources. When rules conflict, the highest priority wins. Ties break by specificity. Priority levels: 1 = Engine safety (cannot crash the game) 2 = Physics / material (fire burns wood) 3 = Survival / body (hunger kills) 4 = World rules (gravity, time) 5 = Law / faction (city forbids theft) 6 = Item rules (sword needs two hands) 7 = Contract rules (guardian vow restricts solo fighting) 8 = Domain rules (domain overrides local reality) 9 = Temporary status / visual (buff, aura, particle effect)


RuleGraph

Summary: RuleGraph — singleton-style rule management and resolution.


createRule

Summary: Creates a new rule object.


gameplay/rules/index


gameplay/simulation/SimulationManager

Summary: SimulationManager — Controls simulation levels for all entities. Active:  Near player — full behavior, every tick Warm:    Same town — slower updates, simplified drives Cold:    Far away — daily summary simulation Frozen:  No updates until touched by event Transition triggers: player proximity, event targeting, faction actions.


gameplay/simulation/index


gameplay/social/SoulGraph

Summary: SoulGraph — The social nervous system of the world. Each NPC is a "neuron" node. Relationships are weighted edges. Events are signals. Mood is activation state. Memory is weight change. Actions are outputs. The graph propagates influence through connections. NPC = soul node Relationship = weighted edge (trust, fear, love, hate, loyalty, resentment, familiarity) Event = signal Mood = activation state Memory = weight change Action = output


gameplay/social/SoulGraphMessaging

Summary: Create a message.


createMessage

Summary: Create a message.


gameplay/social/index


gameplay/society/CitySystem

Summary: CitySystem — City templates, population, economy, laws, reputation.


gameplay/society/FactionGraph

Summary: FactionGraph — Group souls with politics, reputation, and actions. Factions track: leader, values, laws, territory, resources, enemies/allies, fear, morale, population, reputation toward player, domain users, crimes, contracts.


gameplay/society/LawGraph

Summary: LawGraph — Crime, witnesses, punishment, and justice. Different cities and factions have different laws. Tracks: witnesses, evidence, suspicion, reputation. Punishment: bounty, exile, prison, revenge, retaliation.


gameplay/society/index


gameplay/spells/SpellElementMixer

Summary: SpellElementMixer.js - Element Combination System Handles mixing two or more elements to create combined/hybrid elements: - Fire + Ice = Steam - Fire + Nature = Ash - Lightning + Water = Electrified - etc. Combined elements have unique visual effects and status effects.


gameplay/spells/SpellGenerator

Summary: SpellGenerator.js - Procedural Spell Creation System Generates complete spells from parameters: - Element (Fire, Ice, Lightning, Arcane, Nature, Dark, Holy) - Type (Projectile, AOE, Beam, Shield, Buff, Summon) - Modifiers (Homing, Piercing, Explosive, Chain, etc.) - Power level for stat scaling Outputs: - Visual effect (uses CustomParticleEffect SDF) - Collision shape (same SDF as visual) - Particle emitter config - Game stats (damage, mana cost, cooldown) - Sound effect hints MULTIPLAYER: All generation is deterministic via seeded RNG. Never use Math.random() or Date.now() for gameplay-affecting values.


serializeSpellForNetwork

Summary: Serialize spell to minimal format for network transmission Only includes data needed to regenerate the spell deterministically


deserializeSpellFromNetwork

Summary: Deserialize spell from network format Regenerates full spell from minimal data


validateSpellIntegrity

Summary: Validate spell data matches seed (anti-cheat) Returns true if spell stats match what seed would generate


gameplay/spells/SpellGeneratorIntegration

Summary: SpellGeneratorIntegration.js - Connect SpellGenerator to existing SpellConfig Bridges the procedural spell generator with the existing spell system: - Converts generated spells to SpellConfig format - Integrates with SpellEffectFactory for particle emitters - Provides save/load for generated spells


generatedSpellToConfig

Summary: Convert a generated spell to the existing SpellConfig format Compatible with SpellConfig.js SPELL_PRESETS structure


configToGeneratorFormat

Summary: Convert existing SpellConfig preset to generator format Allows editing existing spells in the generator


writeGeneratedSpellLibraryRecord

writeGeneratedSpellLibraryRecord(library, storage = globalThis.localStorage)


saveGeneratedSpell

async saveGeneratedSpell(generatedSpell, storage = globalThis.localStorage)

Summary: Save generated spell to library (IndexedDB via registry pattern)


getSpellLibrary

Summary: Load spell library from storage


getGeneratedSpell

Summary: Get a generated spell by ID


deleteGeneratedSpell

deleteGeneratedSpell(id, storage = globalThis.localStorage)

Summary: Delete a generated spell


getAllGeneratedSpells

Summary: Get all generated spells as array


createEmitterFromGeneratedSpell

createEmitterFromGeneratedSpell(generatedSpell, options = {})

Summary: Create particle emitter config from generated spell For use with SpellEffectFactory IMPORTANT: Physics parameters (mass, drag, bounciness, collisionEnabled) are included to ensure collision behavior matches visual expectations. The effectId links to the SAME SDF used for both rendering AND collision.


quickGenerateSpell

quickGenerateSpell(element, type, powerLevel = 1.0)

Summary: Quick generate a spell with minimal parameters


generateCombinedSpell

generateCombinedSpell(element1, element2, type, powerLevel = 1.0)

Summary: Generate a combined element spell


generateLootSpell

Summary: Generate loot-style random spell


gameplay/spells/index

Summary: Spell System Exports Barrel file for easy importing of all spell-related modules.


kaolin/index

Summary: engine/kaolin — Kaolin-equivalent 3D Geometry Toolkit WebGPU-native geometry operations inspired by NVIDIA Kaolin. Provides representation conversions, mesh ops, SDF tools, point cloud ops, and physics bridges for the engine's particle/softbody/mesh/voxel systems. Usage: import { ops } from '../kaolin/index.js'; const he = new ops.mesh.HalfEdgeMesh(positions, indices); const normals = ops.mesh.computeVertexNormals(positions, indices);


kaolin/io/MeshIO

Summary: MeshIO.js — Programmatic mesh import/export (OBJ, PLY, STL) Pure JS parsers/writers for common mesh formats. No dependencies — works with fetch() or FileReader in browser. All outputs use the Kaolin convention: positions: Float32Array stride 3 indices:   Uint32Array stride 3 normals:   Float32Array stride 3 (optional) uvs:       Float32Array stride 2 (optional) Compatible with: - MeshOps.js, MeshSubdivision.js, MeshTetrahedralize.js - Editor GLB loader (supplementary path for non-GLB formats) - EntityMeshRenderer


parseOBJ

Summary: Parse an OBJ string into mesh data.


writeOBJ

writeOBJ(positions, indices, options = {})

Summary: Write mesh data to OBJ format string.


parsePLY

Summary: Parse a PLY file (ArrayBuffer) into mesh data. Supports ASCII and binary_little_endian formats.


writePLY

writePLY(positions, indices, options = {})

Summary: Write mesh data to PLY format (ASCII).


parseSTL

Summary: Parse an STL file (ArrayBuffer) into mesh data. Auto-detects ASCII vs binary.


writeSTL

writeSTL(positions, indices, normals = null)

Summary: Write mesh data to binary STL format.


loadMesh

Summary: Load a mesh from URL (auto-detects format from extension).


downloadMesh

Summary: Download mesh as a file (browser).


kaolin/io/PointCloudIO

Summary: PointCloudIO.js — Point cloud import/export (PLY, PCD, XYZ) Pure JS parsers/writers for point cloud formats. Outputs: Float32Array positions (stride 3) + optional normals/colors. Compatible with: - PointCloudOps.js - MeshToPoints.js / PointsToMesh.js - Particle system (direct spawn from loaded points)


parsePLYPointCloud

Summary: Load a point cloud from PLY (ArrayBuffer). Ignores face data — returns only vertex positions + attributes.


writePLYPointCloud

writePLYPointCloud(points, options = {})

Summary: Write a point cloud to PLY format (ASCII string, no faces).


parseXYZ

Summary: Parse XYZ text format. Each line: x y z [nx ny nz] [r g b]


writeXYZ

Summary: Write points to XYZ text format.


parsePCD

Summary: Parse PCD text format (ASCII only).


writePCD

Summary: Write points to PCD ASCII format.


loadPointCloud

Summary: Load a point cloud from URL (auto-detects format from extension).


kaolin/io/index

Summary: Kaolin IO — Barrel exports Mesh and point cloud import/export (OBJ, PLY, STL, XYZ, PCD).


kaolin/metrics/ChamferDistance

Summary: ChamferDistance.js — Bidirectional nearest-neighbor distance metric Measures how close two point sets (or meshes) are to each other. For each point in A, find nearest in B (and vice versa), average the distances. Standard metric in 3D reconstruction / generative model evaluation. Used by: agi/ training loops, mesh quality assessment, LOD validation. CPU path with spatial hash acceleration. For GPU path, see future WebGPU compute implementation.


chamferDistance

chamferDistance(pointsA, pointsB, options = {})

Summary: Compute Chamfer Distance between two point sets. CD(A, B) = (1/|A|) Σ min_{b∈B} ||a - b||² + (1/|B|) Σ min_{a∈A} ||b - a||²


chamferDistancePerPoint

Summary: Compute per-point nearest distances from A to B. Useful for visualization (color-coded error maps).


earthMoversDistance

Summary: Approximate Earth Mover's Distance via auction algorithm. Both point sets must have the same number of points. This is O(n²) and practical only for small sets (<1000 points).


kaolin/metrics/GPUMetrics

Summary: GPUMetrics.js — WebGPU compute shader accelerated 3D distance metrics GPU-accelerated implementations of: - Chamfer Distance (bidirectional nearest-neighbor) - Hausdorff Distance (max nearest-neighbor) - Mean Distance / RMSE For each point in set A, a compute shader finds the nearest point in set B using a brute-force O(N*M) scan parallelized across workgroups. Results are reduced on the GPU via a parallel reduction pass. Falls back to CPU path (ChamferDistance.js / HausdorffDistance.js) if WebGPU is unavailable or point counts are below the GPU-beneficial threshold (~2000). Usage: const gpu = new GPUMetrics(device); const result = await gpu.chamferDistance(pointsA, pointsB);


getGPUMetrics

Summary: Get or create a singleton GPUMetrics instance.


kaolin/metrics/HausdorffDistance

Summary: HausdorffDistance.js — Maximum surface deviation metric Measures the worst-case distance between two point sets or meshes. Hausdorff(A, B) = max( max_{a∈A} min_{b∈B} ||a-b||, max_{b∈B} min_{a∈A} ||b-a|| ) Variants: - Standard Hausdorff (max of mins) - Percentile Hausdorff (e.g. 95th percentile — more robust to outliers) - Directed Hausdorff (one direction only) Used by: mesh quality validation, LOD error bounds, surface fitting.


hausdorffDistance

hausdorffDistance(pointsA, pointsB, options = {})

Summary: Compute Hausdorff distance between two point sets.


directedDistances

Summary: Compute per-point minimum distances from A to B. Returns the distance of each point in A to its nearest neighbor in B.


rmse

Summary: Compute RMSE (Root Mean Square Error) between two point sets. Symmetric: averages both directions.


meanDistance

Summary: Compute mean absolute distance between two point sets (one direction).


kaolin/metrics/VolumetricIoU

Summary: VolumetricIoU.js — Intersection over Union for 3D shapes Measures overlap between two 3D shapes by voxelizing both and computing |intersection| / |union|. Also supports direct voxel grid inputs (skip re-voxelization). Used by: agi/ training loops, mesh reconstruction quality, shape matching.


volumetricIoU

volumetricIoU(positionsA, indicesA, positionsB, indicesB, options = {})

Summary: Compute Volumetric IoU between two triangle meshes. Voxelizes both at the same resolution/origin, then counts overlap.


voxelGridIoU

Summary: Compute IoU directly from two voxel grids (same dimensions).


fScore

Summary: F-Score: harmonic mean of precision and recall at a distance threshold. Precision = fraction of predicted points within threshold of ground truth. Recall = fraction of ground truth points within threshold of prediction.


kaolin/metrics/index

Summary: Kaolin Metrics — Barrel exports 3D shape comparison metrics for training loops and quality assessment.


kaolin/ops/conversions/DualContouring

Summary: DualContouring.js — Sharp-feature-preserving isosurface extraction Implements Dual Contouring (Ju et al., 2002) for extracting triangle meshes from SDF fields while preserving sharp edges and corners that Marching Cubes rounds off. Uses Hermite data (intersection points + normals on sign-changing edges) and QEF (Quadratic Error Function) minimization to optimally place vertices within cells. Features: - QEF vertex placement via SVD-free normal equations solver - Sharp edge/corner detection via eigenvalue analysis - Adaptive sharpness threshold (user-configurable) - Manifold quad→tri output with consistent winding - Works with grid SDF arrays or analytical SDF functions Compatible with: - SDFToMesh.js (same input/output conventions) - MeshToVoxel.js voxelGridToSDF() output - CSGShape.js V2 boolean operations


dualContouringSDF

dualContouringSDF(sdf, resX, resY, resZ, options = {})

Summary: Extract an isosurface from a 3D SDF grid using Dual Contouring.


dualContouringFunction

dualContouringFunction(sdfFn, boundsMin, boundsMax, resolution = 64, options = {})

Summary: Dual Contour an analytical SDF function.


kaolin/ops/conversions/FlexiCubes

Summary: FlexiCubes.js — Flexible Marching Cubes mesh extraction An improved isosurface extraction inspired by NVIDIA's FlexiCubes (2023). Key improvements over standard Marching Cubes: 1. **Flexible edge vertices** — Instead of fixed linear interpolation along edges, vertex positions can be adjusted (flexed) to better approximate the true surface, improving triangle quality. 2. **Flexible dual vertices** — Each cube gets a "dual vertex" (interior point) that can be optimized. Quads are formed connecting dual vertices of adjacent cubes across sign-changing edges, then split into tris. 3. **Adaptive splitting** — Quad-to-triangle splitting direction is chosen to minimize the max angle, producing more uniform triangulations. 4. **Gradient-aware vertex placement** — Uses SDF gradient (surface normal) to project dual vertices onto the isosurface for better accuracy. Compatible with: - SDFToMesh.js (same API conventions) - DualContouring.js (complementary approach) - MeshToVoxel.js voxelGridToSDF() output


flexiCubesSDF

flexiCubesSDF(sdf, resX, resY, resZ, options = {})

Summary: Extract an isosurface from a 3D SDF grid using FlexiCubes.


flexiCubesFunction

flexiCubesFunction(sdfFn, boundsMin, boundsMax, resolution = 64, options = {})

Summary: FlexiCubes extraction from an analytical SDF function.


kaolin/ops/conversions/MeshToPoints

Summary: MeshToPoints.js — Sample points from triangle meshes Three sampling strategies: 1. Uniform random — area-weighted triangle sampling (fast) 2. Poisson disk — blue-noise distribution (quality) 3. Farthest point — greedy maximin spacing (LOD/coverage) Output: Float32Array of positions (stride 3) + optional normals Compatible with: - Particle system (direct spawn from sampled points) - MeshToParticlesCompute.js (CPU fallback path) - Point cloud operations (PointCloudOps.js)


sampleUniform

sampleUniform(positions, indices, numSamples, options = {})

Summary: Sample points uniformly on a triangle mesh surface. Uses area-weighted triangle selection + barycentric random point.


samplePoissonDisk

samplePoissonDisk(positions, indices, minDist, options = {})

Summary: Poisson disk sampling on a triangle mesh surface. Produces well-distributed (blue-noise) point sets. Uses dart-throwing with spatial hash acceleration.


farthestPointSample

Summary: Farthest point sampling from a set of candidate points. Iteratively picks the point farthest from all previously selected points. Produces excellent coverage for LOD and feature-preserving downsampling.


kaolin/ops/conversions/MeshToVoxel

Summary: MeshToVoxel.js — Voxelize any triangle mesh Converts a triangle surface mesh into a 3D voxel grid. Uses conservative voxelization: any voxel that overlaps a triangle is set. Approaches: 1. CPU scanline (simple, robust) — default 2. GPU compute (fast, for large meshes) — requires WebGPU device Output: Uint8Array (1 = solid, 0 = empty) indexed [x + y*resX + z*resX*resY] Compatible with: - engine/voxel/ chunk system (ChunkRegistry) - MarchingCubesMesher (feed density field) - ConnectivityCompute (structural analysis) - VoronoiFracture (fracture source)


meshToVoxel

meshToVoxel(positions, indices, options = {})

Summary: Voxelize a triangle mesh on the CPU.


voxelGridToDensity

voxelGridToDensity(grid, resX, resY, resZ)

Summary: Convert voxel grid to a density field (Float32Array) for Marching Cubes. Surface voxels get density 0, interior > 0, exterior < 0.


voxelGridToSDF

voxelGridToSDF(grid, resX, resY, resZ, voxelSize)

Summary: Compute a signed distance field from a voxel grid. Uses distance transform (chamfer approximation).


kaolin/ops/conversions/ParticlesToMesh

Summary: ParticlesToMesh.js — Convert particle positions into a triangle mesh Generates an isosurface from particle density fields using metaball-style implicit functions + Marching Cubes extraction. Use cases: - Fluid surface rendering (SPH → mesh) - Particle cloud → solid mesh for physics - Point sprite → mesh conversion for LOD Compatible with: - Particle system readback (ParticleSimWorld positions) - FluidMPM / ParticleSPH output - SDFToMesh.js (shares MC internals)


particlesToMesh

particlesToMesh(particlePositions, options = {})

Summary: Build an isosurface mesh from particle positions using metaball density. Each particle contributes a smooth falloff: d(r) = 1 - (r/radius)^2 summed at each grid point. Isosurface at threshold extracts the mesh.


particlesToMeshAnisotropic

particlesToMeshAnisotropic(positions, velocities, options = {})

Summary: Build mesh from particles with anisotropic kernels. Each particle's influence is stretched along its velocity direction.


particlesToMeshFast

particlesToMeshFast(positions, radius, resolution = 24)

Summary: Quick mesh from particles using a simple point-to-voxel splat. Faster than full metaball but lower quality. Good for preview/LOD.


kaolin/ops/conversions/PointsToMesh

Summary: PointsToMesh.js — Surface reconstruction from point clouds Converts unstructured 3D point sets into triangle meshes. Approaches: 1. Ball-Pivoting Algorithm (BPA) — requires oriented normals 2. Poisson Surface Reconstruction (simplified) — smooth, gap-filling 3. Alpha Shapes — convex hull variant with concavity control Compatible with: - MeshToPoints.js output (round-trip) - Particle system readback positions - LiDAR / scan data


ballPivoting

ballPivoting(points, normals, radius, options = {})

Summary: Ball-Pivoting Algorithm for surface reconstruction. Rolls a ball of given radius over the point cloud; when it touches exactly 3 points it creates a triangle. Requires oriented normals for consistent triangle winding.


alphaShape

Summary: Alpha-shape surface reconstruction. Computes 3D Delaunay tetrahedralization, then removes tetrahedra whose circumradius exceeds 1/alpha. Extracts boundary triangles.


convexHull

Summary: Convex hull of a 3D point set. Uses incremental algorithm. For large sets, prefer GPUConvexHull.js.


kaolin/ops/conversions/SDFToMesh

Summary: SDFToMesh.js — Extract triangle mesh from a Signed Distance Field Converts a 3D SDF volume (Float32Array grid) into a triangle mesh using Marching Cubes. This is the CPU path for Kaolin conversions; for GPU-accelerated MC see engine/voxel/MarchingCubesMesher.js. Also supports evaluating analytical SDF functions directly. Compatible with: - MeshToVoxel.js voxelGridToSDF() output - MeshSDFGenerator.js baked SDF textures - SDFCollision.js primitives - FlexiCubes (future Phase 3+)


sdfToMesh

sdfToMesh(sdf, resX, resY, resZ, options = {})

Summary: Extract an isosurface from a 3D SDF grid using Marching Cubes.


sdfFunctionToMesh

sdfFunctionToMesh(sdfFn, boundsMin, boundsMax, resolution = 64, options = {})

Summary: Mesh an analytical SDF function by evaluating it on a grid.


sdfCSGToMesh

sdfCSGToMesh(ops, boundsMin, boundsMax, resolution = 64)

Summary: Mesh a CSG combination of SDF primitives. Accepts an array of { sdf: fn(x,y,z), op: 'union'|'subtract'|'intersect' }.


sdfSphere

Summary: Sphere SDF centered at origin


sdfBox

Summary: Box SDF centered at origin


sdfTorus

Summary: Torus SDF centered at origin, in XZ plane


sdfCylinder

Summary: Cylinder SDF centered at origin, along Y axis


sdfTranslate

Summary: Translate an SDF function


sdfSmoothUnion

Summary: Smooth union of two SDF functions


kaolin/ops/conversions/index

Summary: Kaolin Conversions — Barrel exports Representation conversion modules: - Mesh ↔ Voxel - Mesh ↔ Points - Mesh ↔ SDF - Particles → Mesh


kaolin/ops/index

Summary: engine/kaolin/ops — Geometry operations Primitive processing functions for batched 3D models: meshes, voxelgrids, point clouds, and conversions between them.


kaolin/ops/mesh/MeshOps

Summary: MeshOps.js — Core Mesh Operations for Kaolin-style 3D Geometry Toolkit Provides half-edge data structure, adjacency queries, normals, area, Laplacian smoothing, validation, and mesh analysis. All operations work on flat typed arrays (GPU-friendly) with optional object wrappers. Data format (Kaolin convention): positions: Float32Array — stride 3 (x, y, z per vertex) indices:   Uint32Array  — stride 3 (v0, v1, v2 per triangle) Compatible with existing engine systems: - MeshDecimation.js (Vertex/Triangle classes) - MeshCutter.js (plain [x,y,z] arrays) - GPUSoftBody.js (SoA GPU buffers) - EntityMeshRenderer (interleaved vertex buffers)


HalfEdgeMesh

Summary: Index-based half-edge mesh representation. Each half-edge stores: vertex   — index of the vertex it points TO face     — index of the face it belongs to (-1 for boundary) twin     — index of the opposite half-edge (-1 if boundary) next     — index of the next half-edge in the face loop prev     — index of the previous half-edge in the face loop Stored as parallel typed arrays for cache efficiency.


computeFaceNormals

computeFaceNormals(positions, indices, normalize = true)

Summary: Compute per-face normals (unnormalized = area-weighted, or normalized).


computeVertexNormals

Summary: Compute per-vertex normals via area-weighted average of adjacent face normals.


computeVertexNormalsAngleWeighted

Summary: Compute per-vertex normals weighted by the angle at each vertex in each face. More accurate than area-weighted for meshes with very different triangle sizes.


computeFaceAreas

Summary: Compute area of each triangle face.


computeSurfaceArea

Summary: Total surface area of the mesh.


computeSignedVolume

Summary: Signed volume of a closed triangle mesh (divergence theorem). Positive if normals point outward with consistent winding.


computeEdgeLengths

Summary: Compute lengths of all unique edges.


computeBoundingBox

Summary: Compute axis-aligned bounding box.


buildVertexAdjacency

Summary: Build vertex-to-vertex adjacency (sparse neighbor lists).


buildVertexFaceAdjacency

Summary: Build vertex-to-face adjacency.


buildFaceAdjacency

Summary: Build face-to-face adjacency (faces sharing an edge).


laplacianSmooth

laplacianSmooth(positions, indices, iterations = 1, lambda = 0.5, pinned = null)

Summary: Uniform Laplacian smoothing (iterative). Moves each vertex toward the centroid of its neighbors.


taubinSmooth

taubinSmooth(positions, indices, iterations = 5, lambda = 0.5, mu = -0.53, pinned = null)

Summary: Taubin smoothing (λ|μ) — Laplacian smooth that preserves volume. Alternates positive (shrinking) and negative (inflating) steps.


cotangentLaplacianSmooth

cotangentLaplacianSmooth(positions, indices, lambda = 0.5, pinned = null)

Summary: Cotangent-weighted Laplacian smoothing (1 iteration). More geometrically accurate than uniform — preserves curvature better.


validateMesh

Summary: Validate mesh integrity. Returns a report object.


computeCentroid

Summary: Compute mesh centroid (average of vertex positions).


fromVertexTriangleClasses

Summary: Convert from MeshDecimation.js Vertex/Triangle classes to flat arrays.


fromArrays

Summary: Convert from plain [x,y,z] arrays (MeshCutter style) to flat Float32Array.


toArrays

Summary: Convert flat arrays to plain [x,y,z] arrays.


fromInterleavedBuffer

fromInterleavedBuffer(interleavedBuffer, stride, posOffset, indexBuffer)

Summary: Extract positions/indices from an interleaved GPU vertex buffer + index buffer.


kaolin/ops/mesh/MeshSubdivision

Summary: MeshSubdivision.js — Loop & Catmull-Clark Subdivision Subdivision surface algorithms for the Kaolin geometry toolkit. Loop Subdivision (Charles Loop, 1987): - Operates on triangle meshes only - Inserts edge midpoints, reconnects into 4 sub-triangles per face - Uses β-weighting for smooth limit surface (Warren weights) - Boundary edges get special 1/8, 3/4, 1/8 stencil Catmull-Clark Subdivision (Catmull & Clark, 1978): - Operates on quad or mixed meshes - Face points → edge points → vertex points → reconnect - Converges to C² (bi-cubic B-spline) surface away from extraordinary verts - Triangle input is first converted to all-quad via 1-to-3 split Both algorithms support: - Boundary handling (crease preservation) - Pinned vertices (kept fixed) - Multiple subdivision levels Data format matches MeshOps.js: positions: Float32Array — stride 3 indices:   Uint32Array  — stride 3 (triangles) or stride 4 (quads)


loopSubdivide

loopSubdivide(positions, indices, options = {})

Summary: Perform one level of Loop subdivision on a triangle mesh.


loopSubdivideMulti

loopSubdivideMulti(positions, indices, levels = 1, options = {})

Summary: Perform multiple levels of Loop subdivision.


catmullClarkSubdivide

catmullClarkSubdivide(positions, faceIndices, faceVertCounts, options = {})

Summary: Perform one level of Catmull-Clark subdivision. Input can be triangle or quad faces (mixed is allowed). - triangles: indices stride 3, faceVertCounts = [3, 3, ...] - quads:     indices stride 4, faceVertCounts = [4, 4, ...] - mixed:     flat indices + faceVertCounts array For simplicity, this implementation accepts two formats: 1. (positions, quadIndices) — all-quad, quadIndices = Uint32Array stride 4 2. (positions, triIndices, { triangleInput: true }) — converts tris to quads first


catmullClarkSubdivideMulti

catmullClarkSubdivideMulti(positions, faceIndices, faceVertCounts, levels = 1, options = {})

Summary: Perform multiple levels of Catmull-Clark subdivision.


trianglesToFaceList

Summary: Convert a triangle mesh to the faceIndices + faceVertCounts format expected by catmullClarkSubdivide.


quadFacesToTriangles

Summary: Convert Catmull-Clark output (all quads) to triangles for rendering. Each quad is split into 2 triangles along the shorter diagonal.


kaolin/ops/mesh/MeshTetrahedralize

Summary: MeshTetrahedralize.js — Surface Mesh → Tetrahedral Mesh Converts a closed triangle surface mesh into a tetrahedral volume mesh suitable for FEM soft body simulation (GPUSoftBody.js). Algorithm: Constrained Delaunay Tetrahedralization 1. Compute bounding box, generate interior sample points 2. Combine surface vertices + interior points 3. Build Delaunay tetrahedralization via incremental insertion 4. Remove tets outside the surface (using winding number or ray test) 5. Output: nodePositions (Float32Array stride 3) + tetIndices (Uint32Array stride 4) The output format matches GPUSoftBody.createSoftBody() exactly: nodePositions: Float32Array — [x0, y0, z0, x1, y1, z1, ...] tetIndices:    Uint32Array  — [n0, n1, n2, n3, ...] (4 per tet) References: - Si, "TetGen: A Delaunay-Based Quality Tetrahedral Mesh Generator" (2015) - Shewchuk, "Tetrahedral Mesh Generation by Delaunay Refinement" (1998) - Jacobson et al., "Robust Inside-Outside Segmentation using Generalized Winding Numbers" (2013)


tetrahedralize

tetrahedralize(positions, indices, options = {})

Summary: Tetrahedralize a closed triangle surface mesh.


tetrahedralizeGrid

tetrahedralizeGrid(positions, indices, gridRes = 6)

Summary: Quick tetrahedralize using simple grid-based approach. Faster but lower quality than full Delaunay. Good for real-time use.


computeTetQuality

Summary: Compute quality ratio for each tet (radius ratio = circumradius / inradius). Ideal = 3 (regular tet). Higher = worse (slivers).


extractTetSurface

Summary: Extract the surface triangles of a tetrahedral mesh. Surface faces are those that belong to exactly one tetrahedron.


kaolin/ops/mesh/index

Summary: engine/kaolin/ops/mesh — Core mesh operations Half-edge data structure, adjacency, normals, area, Laplacian smoothing, validation, and subdivision surfaces (Loop + Catmull-Clark).


kaolin/ops/pointcloud/PointCloudOps

Summary: PointCloudOps.js — Point cloud geometric analysis Operations on unstructured 3D point sets: - k-NN queries via spatial hash - Normal estimation (PCA on local neighborhood) - Curvature estimation (from fitted normals) - Statistical outlier removal - Voxel downsampling - Centroid / bounding box / oriented bounding box - Normal orientation propagation (MST-based) Compatible with: - MeshToPoints.js output - Particle system readback (Float32Array stride 3) - PointsToMesh.js input (provides normals for BPA)


buildSpatialHash

Summary: Build a spatial hash for fast neighbor queries.


knnQuery

knnQuery(points, grid, cellSize, qi, k, maxRadius = Infinity)

Summary: Find k nearest neighbors for a single query point.


batchKNN

Summary: Batch k-NN for all points.


estimateNormals

estimateNormals(points, k = 12, options = {})

Summary: Estimate normals for a point cloud using PCA on local neighborhoods. For each point, finds k nearest neighbors and fits a plane via PCA. The normal is the eigenvector corresponding to the smallest eigenvalue of the covariance matrix.


estimateCurvature

estimateCurvature(points, normals, k = 12)

Summary: Estimate per-point curvature from normals and neighborhood. Uses the ratio of the smallest eigenvalue to the sum of eigenvalues.


removeStatisticalOutliers

removeStatisticalOutliers(points, k = 20, stdRatio = 2.0)

Summary: Remove statistical outliers based on mean distance to k neighbors. Points with mean distance > (global_mean + stdRatio * global_std) are removed.


removeRadiusOutliers

removeRadiusOutliers(points, radius, minNeighbors = 3)

Summary: Remove points with fewer than minNeighbors within given radius.


voxelDownsample

voxelDownsample(points, voxelSize, normals = null)

Summary: Downsample a point cloud by averaging points within each voxel cell.


computeAABB

Summary: Compute axis-aligned bounding box.


computeCentroid

Summary: Compute centroid of a point cloud.


computeOBB

Summary: Compute oriented bounding box via PCA. Returns axes (3 Float32Array[3]), half-extents, and center.


cropToAABB

Summary: Crop points to an axis-aligned bounding box.


cropToSphere

cropToSphere(points, cx, cy, cz, radius)

Summary: Crop points to a sphere.


kaolin/ops/pointcloud/index

Summary: Kaolin Point Cloud — Barrel exports


kaolin/ops/voxelgrid/VoxelOps

Summary: VoxelOps.js — Voxel grid operations Operations on binary/scalar 3D voxel grids: - Fill interior (flood fill) - Hollow (keep only surface shell) - CSG boolean: union, intersect, subtract - Downsample / upsample - Morphological: dilate, erode, open, close - Extract isosurface info (surface voxels, boundary) - Connected component labeling Grid format: Uint8Array indexed [x + y*resX + z*resX*resY] 1 = solid, 0 = empty (unless scalar grid — Float32Array) Compatible with: - MeshToVoxel.js output - engine/voxel/ chunk system (ChunkRegistry) - ConnectivityCompute.js (structural analysis) - VoronoiFracture.js (fracture source)


voxelUnion

Summary: Union of two voxel grids (same dimensions required). Result = A OR B.


voxelIntersect

Summary: Intersection of two voxel grids. Result = A AND B.


voxelSubtract

Summary: Subtraction: A minus B. Result = A AND NOT B.


voxelXOR

Summary: Symmetric difference (XOR). Result = A XOR B.


voxelInvert

Summary: Invert a voxel grid.


voxelFill

Summary: Fill the interior of a closed voxel shell. Uses flood fill from boundary to mark exterior, then inverts.


voxelHollow

voxelHollow(grid, resX, resY, resZ, thickness = 1)

Summary: Hollow a voxel grid — keep only the outer shell (surface voxels). A voxel is surface if it's solid and has at least one empty 6-neighbor.


voxelDilate

voxelDilate(grid, resX, resY, resZ, radius = 1)

Summary: Dilate: expand solid voxels by `radius` voxels (6-connected).


voxelErode

voxelErode(grid, resX, resY, resZ, radius = 1)

Summary: Erode: shrink solid voxels by `radius` voxels (6-connected).


voxelOpen

voxelOpen(grid, resX, resY, resZ, radius = 1)

Summary: Morphological open: erode then dilate (removes small protrusions).


voxelClose

voxelClose(grid, resX, resY, resZ, radius = 1)

Summary: Morphological close: dilate then erode (fills small holes).


voxelDownsample

voxelDownsample(grid, resX, resY, resZ, factor = 2)

Summary: Downsample a voxel grid by factor (majority vote per super-voxel).


voxelUpsample

voxelUpsample(grid, resX, resY, resZ, factor = 2)

Summary: Upsample a voxel grid by factor (nearest-neighbor replication).


connectedComponents

connectedComponents(grid, resX, resY, resZ)

Summary: Label connected components in a voxel grid (6-connected).


removeSmallComponents

removeSmallComponents(grid, resX, resY, resZ, minSize)

Summary: Remove small connected components below a size threshold.


extractSurfaceVoxels

extractSurfaceVoxels(grid, resX, resY, resZ)

Summary: Extract surface voxels (solid voxels with at least one empty 6-neighbor).


countSolid

Summary: Count solid voxels.


computeVolume

Summary: Compute volume in world units.


computeSurfaceArea

computeSurfaceArea(grid, resX, resY, resZ, voxelSize)

Summary: Compute approximate surface area (count exposed faces × voxelSize²).


createGrid

Summary: Create an empty voxel grid.


createSphere

createSphere(resX, resY, resZ, cx, cy, cz, radius)

Summary: Create a solid sphere in a voxel grid.


createBox

createBox(resX, resY, resZ, minX, minY, minZ, maxX, maxY, maxZ)

Summary: Create a solid box in a voxel grid.


kaolin/ops/voxelgrid/index

Summary: Kaolin Voxel Grid — Barrel exports


kaolin/physics/AutoTetMesh

Summary: AutoTetMesh.js — Automatic surface mesh → tetrahedral mesh → GPUSoftBody bridge One-call pipeline: give it a triangle mesh, get back a soft body. Pipeline: 1. Validate + repair mesh (MeshOps.validateMesh) 2. Optionally decimate for performance (MeshDecimation) 3. Tetrahedralize (MeshTetrahedralize) 4. Quality check + optimization 5. Create GPUSoftBody instance Compatible with: - GPUSoftBody.createSoftBody() — exact format match - MeshDecimation.js — LOD before tet generation - EntityMeshRenderer — visual mesh binding - MeshTetrahedralize.js — Delaunay + grid methods


autoTetMesh

autoTetMesh(positions, indices, options = {})

Summary: Full pipeline: surface mesh → tet mesh ready for GPUSoftBody.


createSoftBodyFromMesh

createSoftBodyFromMesh(softBodySystem, positions, indices, material = 'rubber', options = {})

Summary: Create a GPUSoftBody from a surface mesh in one call.


createSoftBodiesBatch

Summary: Batch-create multiple soft bodies from meshes.


generateTetLODs

generateTetLODs(positions, indices, gridResolutions = [8, 5, 3])

Summary: Generate multiple LOD levels of tet meshes from a single surface mesh.


Summary: Preset configurations for different use cases.


kaolin/physics/ParticleSkinning

Summary: ParticleSkinning.js — Learned reduced deformation basis from particle sim Inspired by NVIDIA Simplicits: learn a small set of skinning weights that approximate the full FEM simulation at a fraction of the cost. Pipeline: 1. Run full sim for N frames → capture deformation snapshots 2. PCA on displacement field → extract dominant deformation modes 3. Compute skinning weights via least-squares fitting 4. At runtime: blend modes with learned weights → fast approximate deformation This enables: - Real-time soft body preview without FEM solve - LOD: near = full FEM, far = skinned approximation - Baking physics to animation for replay Compatible with: - GPUSoftBody.js — reads back node positions for training - EntityMeshRenderer — applies skinned deformation to visual mesh - SkeletalAnimation.js — similar weight/bone concept


createDeformationCapture

Summary: Capture deformation snapshots from a running soft body. Call this each frame during a training run.


captureFrame

Summary: Record a frame's deformed positions.


extractDeformationModes

extractDeformationModes(capture, numModes = 8)

Summary: Extract dominant deformation modes via PCA on displacement snapshots.


computeSkinningWeights

Summary: Compute skinning weights for each node per deformation mode. Uses least-squares: for each snapshot, find mode weights that best reconstruct the displacement.


createSkinningEvaluator

Summary: Create a runtime skinning evaluator.


evaluateSkinning

Summary: Evaluate skinned deformation with given mode coefficients.


fitCoefficients

Summary: Fit mode coefficients to match a target deformation (least-squares). Useful for transitioning from full FEM to skinned approximation.


bakeToAnimation

bakeToAnimation(capture, decomposition, fps = 60)

Summary: Bake deformation snapshots into mode coefficient keyframes. Output can drive the skinning evaluator for replay without physics.


sampleAnimation

Summary: Interpolate baked animation at a given time.


kaolin/physics/index

Summary: Kaolin Physics — Barrel exports Physics bridges: auto tet mesh generation + learned skinning.


network/capability/RouteCapability

Summary: network/capability/RouteCapability.js — capability-based route access for the Particle Global OS Network Layer (network plan §10).  Reuses the Causal State Engine's UCAN-style capability primitive (engine/state/authority/Capability.js: makeCapability/attenuate/authorizes) unmodified. A route capability names a principal (device/profile/membership signer fingerprint), the route as its object, and an allow-list of route/* verbs enforced via a caveat predicate — narrowing-only delegation comes for free from `attenuate()`. `CapabilityRegistry` (also reused as-is) tracks issuance, revocation, and single-use consumption.


makeRouteCapability

makeRouteCapability({ principal, routeId, allow = DEFAULT_ROUTE_ALLOW, constraints = {}, expiresAt = null, singleUse = false, delegable = true, } = {})

Summary: Mint a route capability. The capability's own `action` is always `'*'`; the actual allow-list is enforced by a `route-allow` caveat so it composes correctly with further `attenuateRouteCapability()` narrowing.


attenuateRouteCapability

attenuateRouteCapability(cap, { allow, predicate, key, label } = {})

Summary: Narrow an existing route capability's allow-list and/or add an arbitrary extra predicate (e.g. "only from this device fingerprint"). Cannot widen beyond the parent's allow-list — throws if it would.


authorizesRoute

authorizesRoute(cap, { principal, routeId, action, epoch, context = {} } = {})

Summary: Check whether a capability authorizes a specific route action right now.


createRouteCapabilityRegistry

Summary: Create a fresh registry to issue/revoke/consume route capabilities in.


Summary: Default allow-list for a freshly-minted route capability (network plan §10).


Summary: All route verbs the network layer currently understands.


network/carrier/AnonymityMode

Summary: network/carrier/AnonymityMode.js — connection mode selection + UI transport-truth labels (network plan §25/§42): the UI must never claim a connection is more private than it actually is.


selectAnonymityMode

selectAnonymityMode({ isSelfDevice = false, groupApproved = false, trustPending = false, highRiskOverride = false } = {})

Summary: Decide the anonymity mode for a peer relationship (network plan §25 policy: unknown/public -> anonymous; new invites -> anonymous until approved; group members -> group policy; trusted/own devices -> direct).


transportTruthLabel

Summary: Human-readable, honest transport label for the UI (§42).


allowsDirectTransport

Summary: Whether a mode permits direct (non-relayed) transport — direct may reveal network metadata to the peer (§42).


network/carrier/CarrierForwarder

Summary: network/carrier/CarrierForwarder.js — the forwarding decision a carrier node makes for a sealed packet, WITHOUT ever inspecting its payload (network plan §24/§35/§36): expiry, hop-limit (TTL), dedupe, and rate limit, in that order. Reuses `chunks/DedupeCache.js` as-is (network plan §29 dedupe applies uniformly to control/route/carrier traffic).


evaluateForward

evaluateForward({ packet, dedupeCache, rateLimiter, dedupeTtlMs = 60000, now = Date.now()

Summary: Decide whether to forward a carrier packet.


network/carrier/CarrierIdentity

Summary: network/carrier/CarrierIdentity.js — announces a node's carrier-layer (§26) ECDH onion-recipient public key to its current mesh peers. Closes the gap `CarrierRelay.js`'s own doc flagged: "another peer can only address this device as an onion hop if it learned the key out-of-band." This is that in-band announce: a tiny message sent over the SAME mesh session data channel (via `sendToPeer`, typically from `onPeerJoin`), cached locally so a future `SealedPacket.buildSealedPacket({hops, payload})` call can look up a hop's key without any prior out-of-band exchange.  Deliberately NOT signed/verified against a stronger identity (e.g. the CSE profile/device signer) — WebRTC's own DTLS already authenticates "these bytes came from the peer this data channel is connected to"; the remaining trust question (should carrier packets even be routed through this specific peer) is a routing/reputation decision for the caller, not this module's job. `handleCarrierIdentityMessage` only checks that the announce's claimed peerId matches the channel it arrived on (fails closed on mismatch — either a bug or a spoof attempt).


createCarrierIdentityRegistry

Summary: Create an empty registry of peerId -> carrier-recipient ECDH public key.


buildCarrierIdentityAnnounce

Summary: Build the announce message to hand to a mesh session's `sendToPeer`. Returns null if this node has no key to announce.


handleCarrierIdentityMessage

Summary: Feed every relevant `onOp(peerId, op)` message through this, alongside `ChunkTransport.js`/`CarrierRelay.js`/`DhtTransport.js`'s own handlers (same `(peerId, op) => boolean` chaining pattern).


lookupCarrierRecipientKey

Summary: Look up a previously-announced peer's carrier-recipient ECDH public key (raw bytes), or null.


listKnownCarrierRecipients

Summary: List peerIds this node has learned a carrier-recipient key for.


forgetCarrierRecipient

Summary: Forget a peer's announced key (e.g. on disconnect/leave).


network/carrier/CarrierPacket

Summary: network/carrier/CarrierPacket.js — the carrier layer's OUTER envelope (network plan §26): visible routing metadata (route/ttl/expiry) plus an opaque sealed payload (SealedPacket.js) that carrier nodes forward without ever decrypting.


makeCarrierPacket

makeCarrierPacket({ routeId, ttl = 4, expiresAt = null, sealed } = {})

Summary: Wrap a sealed onion packet for carrier forwarding.


decrementCarrierTtl

Summary: Return a new carrier packet with ttl decremented by 1 (does not mutate the input).


isCarrierPacketExpired

isCarrierPacketExpired(packet, now = Date.now()


network/carrier/CarrierRelay

Summary: network/carrier/CarrierRelay.js — routes a CarrierPacket across a real mesh (network plan §24/§35/§36, previously deferred: "CollabMeshTopology gossip/fanout/TTL wiring for actual multi-peer carrier mesh topology").  SealedPacket.js's onion path is an ordered peerId list chosen by the SENDER, but not every hop in that path is necessarily a live WebRTC neighbor of the previous hop — K-neighbor partial-mesh/supernode modes deliberately do NOT connect every peer to every peer (see engine/collab/CollabMeshTopology.js's header comment: "K-neighbor gossip mesh ... messages reach all N peers in ~log_K(N) hops"). This module bridges that gap: - If the addressed next hop IS a direct neighbor right now, deliver directly — cheapest path, one hop, no flood. - Otherwise, gossip-flood the envelope via CollabMeshTopology's existing TTL+dedupe fanout (`gossipWrap`/`gossipReceive`) so it propagates through the mesh until it reaches a peer who either IS the target or has it as a direct neighbor, at which point THAT peer delivers it directly instead of re-flooding.  Every touch of a carrier packet — direct delivery or gossip relay — always runs through `CarrierForwarder.evaluateForward()` first (onion-layer expiry/TTL/dedupe/rate-limit), independent of and in addition to the mesh gossip's OWN TTL/dedupe: gossip TTL bounds mesh hops for one flood attempt; carrier TTL bounds total onion hops end-to-end. Neither layer ever inspects the sealed payload itself (network plan §24's core guarantee) — only `peelSealedPacket`, called with THIS node's own private key when (and only when) this node is the addressed hop, can see anything beyond the next hop id.


createCarrierRelay

createCarrierRelay({ sendToPeer, topology, dedupeCache, rateLimiter, recipientEcdhPrivateKey = null, onPayloadReceived = ()


relayCarrierPacket

Summary: Send/relay a carrier packet toward its addressed next hop. Runs the standard forwarding check first — a caller originating a brand-new packet should still go through this (it's the same expiry/TTL/dedupe/rate-limit gate every intermediate hop uses, applied uniformly per network plan §35).


handleCarrierRelayMessage

async handleCarrierRelayMessage(relay, fromPeerId, op)

Summary: Feed every relevant `onOp(peerId, op)` message through this (e.g. from `createCollabCore({ onOp })`, alongside `ChunkTransport.js`'s own `handleChunkTransportMessage` — both follow the same "return false if not ours" chaining pattern). Handles: peeling a layer addressed to this node, delivering the final payload, direct-hop forwarding, and mesh-gossip re-forwarding.


network/carrier/RateLimiter

Summary: network/carrier/RateLimiter.js — token-bucket rate limiting for carrier forwarding (network plan §35/§36 spam controls, V1: rate limits + dedupe, no proof-of-work yet).


createRateLimiter

createRateLimiter({ capacity = 30, refillPerSecond = 10 } = {})

Summary: Create a token bucket.


tryConsume

tryConsume(limiter, cost = 1, now = Date.now()

Summary: Try to consume `cost` tokens. Returns false (caller should drop/reject) if insufficient.


availableTokens

availableTokens(limiter, now = Date.now()

Summary: Tokens currently available (after applying refill for elapsed time).