{"id":"cfsmi/chronocast","name":"chronocast","scope":"cfsmi","platform":"roblox","description":"Temporal query engine for Roblox: reconstruct past object states and query them without rewinding Workspace.","version":"0.1.0","latest":"0.1.0","versions":["0.1.0"],"license":"MIT","licenseRating":"safe","licenseCaveats":[],"licenseVerified":true,"dependencies":{},"integrity":"65d003c6008f151e9c909e209722720830c832e67df625b511868093a21ddd63","likes":0,"downloads":0,"install":"forest install cfsmi/chronocast","url":"https://forest.dev/p/roblox/cfsmi/chronocast","files":"https://api.forest.dev/ai/package/roblox/cfsmi/chronocast/files","readme":"# Chronocast\n\n**A temporal query engine for Roblox.** Chronocast records where tracked objects were, then answers questions about the past (what a ray would have hit, which hitboxes a swing would have touched) without rewinding or touching `Workspace`.\n\nIt's built for server-side **lag compensation**, and works just as well for replays, hit validation, and anything else that needs to ask \"where was everything at time T?\".\n\n![A walking dummy's recorded poses as a fading blue trail; the pose at the cast time is highlighted red, and a yellow ray hits its head where it was, not where it is now](https://raw.githubusercontent.com/cfsmi/Chronocast/main/docs/images/visualizer.jpg)\n\n*The debug visualizer's output for a walking character: past poses (blue), the pose at the query time (red), and a cast hitting the head at its historical position. The visualizer draws HandleAdornments; for this screenshot they were mirrored as parts, because Studio's capture tool doesn't render adornments.*\n\n- **Nothing is rewound.** States are reconstructed on demand from immutable snapshots; Workspace is never modified.\n- **Deterministic.** The same history, time and query always give the same result, independent of iteration order.\n- **Lazy and local.** A context reconstructs only the timelines a query actually touches, chosen by a spatial index over retained history.\n- **Per-limb hitboxes.** `Collision.FromCharacter` samples an animated rig's limbs on every capture, and hits report which limb (`hit.Name == \"Head\"`).\n- **Adapter-first.** Track Parts and Models out of the box, or anything else (custom physics, NPC simulations) through a two-function adapter.\n\n## Install\n\n**Wally**: add to `wally.toml`:\n\n```toml\n[dependencies]\nChronocast = \"cfsmi/chronocast@0.1.0\"\n```\n\n**Model file**: download `Chronocast.rbxm` from the [latest release](https://github.com/cfsmi/Chronocast/releases/latest) and insert it into `ReplicatedStorage`.\n\n**From source**: `rojo build default.project.json -o Chronocast.rbxm` (or sync `default.project.json` with Rojo or Argon).\n\n## Quick start\n\nOn the server:\n\n```lua\nlocal Chronocast = require(game.ReplicatedStorage.Chronocast)\n\n-- Track an object. Snapshots are captured automatically on Heartbeat.\nlocal part = workspace.Target\nlocal timeline = Chronocast:Track({\n\tId = \"Target\", -- stable, unique id\n\tInstance = part, -- or Adapter = { GetTransform = function(self, timeline, time) ... end }\n\tCollision = Chronocast.Collision.FromPart(part),\n\tSnapshotInterval = 1 / 30, -- seconds between captures\n\tHistoryDuration = 1, -- seconds of history kept\n})\n\n-- Later: ask about the world as it was 100 ms ago.\nlocal context = Chronocast:CreateContext(Chronocast:GetServerTime() - 0.1)\n\nlocal hit = context:Cast({ -- the first thing hit, or nil\n\tShape = \"Ray\",\n\tParameters = { Origin = Vector3.new(0, 10, 0), Direction = Vector3.xAxis, MaxDistance = 100 },\n})\nif hit then\n\tprint(hit.Timeline.Id, hit.Distance, hit.Position, hit.Normal, hit.Name)\nend\n\nlocal touching = context:Overlap({ -- everything intersecting, sorted by Timeline.Id\n\tShape = \"Sphere\",\n\tParameters = { Origin = Vector3.new(0, 10, 0), Radius = 8 },\n})\n\ncontext:Destroy()\n```\n\nFor a complete lag-compensated hitscan weapon (client fires, server rewinds to what the shooter saw, validates and applies headshot damage), see [`examples/LagCompensation`](examples/LagCompensation).\n\n## Concepts\n\n| | |\n|---|---|\n| **Timeline** | One tracked object: its adapter, its collision, and a fixed-size ring buffer of immutable snapshots. |\n| **Context** | One instant in time. Creating one does no work; states are reconstructed on first access and cached. |\n| **Cast / Overlap** | Pure queries against a context. They never modify history or Workspace. |\n| **Collision** | Local-space Box, Sphere, Capsule and Compound shapes, recorded per snapshot. |\n| **Path** | Line, Bezier, Ballistic or Custom motion for sweeping a query through space. |\n\n## API\n\n### Tracking\n\n```lua\nChronocast:Track(config) -> Timeline\nChronocast:Untrack(id)\nChronocast:CreateContext(time) -> Context\nChronocast:GetServerTime() -> number -- Workspace:GetServerTimeNow(), the shared server clock\n```\n\n`Track` config fields:\n\n| Field | Meaning |\n|---|---|\n| `Id` | Required. Unique non-empty string. |\n| `Instance` | A BasePart, or a Model with a stable `PrimaryPart`. Its transform is `CFrame` or `GetPivot()`. |\n| `Adapter` | Instead of `Instance`: `{ GetTransform, GetVelocity?, GetAngularVelocity?, Metadata? }`. |\n| `Collision` | A collision definition, or a provider `(timeline, time) -> definition?` sampled on every capture. |\n| `SnapshotInterval` | Seconds between captures. Default `0.033`. (`SnapshotRate` is accepted as an older alias.) |\n| `HistoryDuration` | Seconds of history retained. Default `5`. |\n| `Metadata` | Values, or providers `(timeline, time) -> value`, recorded with each snapshot. |\n\nA `Timeline` has `GetState(time)`, `GetSnapshots()`, `SetCollision(definitionOrProvider)` and `Destroy()`. `SetCollision` affects future captures only; old snapshots keep the collision they were recorded with. If a capture fails, Chronocast logs a warning and untracks that timeline without affecting the others.\n\n### Contexts\n\n```lua\ncontext:Cast(query) -> CastResult?\ncontext:Overlap(query) -> { OverlapResult }\ncontext:GetState(timeline) -> State?\ncontext:GetSnapshots(timeline) -> { Snapshot } -- history up to the context time\ncontext:Destroy()\n```\n\n- **Cast** takes a `Ray`, or a `Sphere`, `Box` or `Capsule` swept along a `Path`. It returns `{ Timeline, Distance, Position, Normal, Name }`. `Distance` is exact ray travel, or approximate travel along the path.\n- **Overlap** takes a `Sphere`, `Box` or `Capsule` (optionally along a `Path`). It returns one representative contact per target, `{ Timeline, Position, Normal, Name }`, sorted by `Timeline.Id`. It has no `Distance`.\n- `Position` is on the target's historical surface and `Normal` points out of it. `Name` is the hit shape's name, e.g. a limb.\n- Every query accepts an optional `Filter = function(timeline) return boolean end`.\n- Malformed queries raise errors with clear messages; results are frozen.\n- A context sees only the timelines that existed when it was created. A state, once read, is reused for the context's lifetime even after its snapshots roll out of the buffer.\n- Times outside recorded history use the nearest snapshot; Chronocast never extrapolates.\n\nQuery parameters:\n\n| Shape | Parameters |\n|---|---|\n| `Ray` | `Origin`, `Direction`, `MaxDistance?` (give one: unbounded rays scan every timeline) |\n| `Sphere` | `Origin`, `Radius` |\n| `Box` | `Origin` or `CFrame`, `Size` |\n| `Capsule` | `Origin` or `CFrame`, `Radius`, `Height` (distance between cap centres) |\n\nWith a `Path`, each sampled pose supplies the `Origin`/`CFrame`.\n\n`Context:Query` and `Chronocast:Query` are the older single-result API. They still work but are deprecated.\n\n### Collision\n\n```lua\nChronocast.Collision.Box({ Size, Offset?, Name? })\nChronocast.Collision.Sphere({ Radius, Offset?, Name? })\nChronocast.Collision.Capsule({ Radius, Height, Offset?, Name? })\nChronocast.Collision.Compound({ children }, offset?)\nChronocast.Collision.FromPart(part, reference?)    -- Ball -> Sphere, everything else -> oriented Box\nChronocast.Collision.FromModel(model, reference?)  -- bounding Box of all parts\nChronocast.Collision.FromCharacter(character, { IncludeAccessories?, Filter?, Reference? }?) -- per-limb provider\nChronocast.Collision.Custom(definition)\n```\n\nOffsets are **local to the transform the timeline's adapter returns**. `FromPart` and `FromModel` default their reference to `part.CFrame` and `model:GetPivot()`; pass the adapter's frame if it differs. `FromCharacter` skips `HumanoidRootPart` and accessories by default. Cylinders and meshes use conservative oriented boxes.\n\n### Paths\n\n```lua\nChronocast.Path.Line({ Start, End, Intervals? })\nChronocast.Path.Bezier({ P0, P1, P2, P3, Intervals? })\nChronocast.Path.Ballistic({ Origin, Velocity, Gravity?, TotalTime?, Intervals? })\nChronocast.Path.Custom({ Sample = function(self, alpha) return CFrame end, Intervals? })\n```\n\nA path is tested at `Intervals + 1` discrete poses, endpoints included (`Samples` is an older alias for `Intervals`). It is **not** continuous swept collision: a fast-moving query can step over a thin target between poses, so raise `Intervals` when that matters.\n\n### Debug visualizer\n\n```lua\nlocal viz = Chronocast.Debug.Visualizer({ Lifetime = 2 }) -- also: Parent, Adornee, Color, QueryColor, HitColor, Transparency\nviz:DrawTimeline(timeline, context)     -- historical collision at a context (or a time)\nviz:DrawTrail(timeline, { Step = 0.1 }) -- fading ghost poses through retained history\nviz:DrawCast(query, hit, context)       -- the ray or path, hit point, normal and hit target\nviz:DrawOverlap(query, results)\nviz:Clear()\nviz:Destroy()\n```\n\nIt draws HandleAdornments adorned to Terrain, so it creates no physical parts.\n\n### Types\n\n`Chronocast.Types` exports Luau types for every public shape: `TimelineConfig`, `Adapter`, `CollisionDef`, `State`, `Snapshot`, `QueryParams`, `CastResult`, `OverlapResult` and more.\n\n## Performance\n\nMeasured in Roblox Studio with `tests/Benchmark.lua`. Each timeline is one capsule in a 2000 × 2000-stud world, captured 30 times a second with 1 s of history. Each query creates and destroys its own context.\n\n| Timelines | Capture, per captured frame | Ray, 150 studs | Ray, unbounded (full scan) | Sphere overlap, r = 25 |\n|---|---|---|---|---|\n| 50 | 0.27 ms | 6.6 µs | 0.46 ms | 4.9 µs |\n| 200 | 1.04 ms | 23 µs | 1.9 ms | 12.5 µs |\n| 1000 | 6.05 ms | 67 µs | 10.6 ms | 43 µs |\n\nBounded queries only reconstruct timelines whose retained history passes near the query, so their cost follows how many objects are nearby, not the size of the world. Capture cost grows linearly with tracked timelines. At 1000 timelines it's about 6 ms on each frame that captures, so raise `SnapshotInterval` for objects that don't need fine history. Results vary by hardware; run the benchmark on yours.\n\n## Limitations\n\n- Swept queries sample discrete poses; there is no continuous collision detection.\n- Collision primitives are boxes, spheres and capsules; cylinders and meshes are approximated by oriented boxes.\n- Interpolated states use the preceding snapshot's collision. Character limb layouts are not interpolated between snapshots.\n- Overlap contacts are one representative point per target, not a full contact manifold.\n- History is bounded by `HistoryDuration`; older queries see the oldest retained snapshot.\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup, the test suites (in Studio and headless) and the checks CI runs. Background design notes are in [`docs/design`](docs/design).\n\n## License\n\n[MIT](LICENSE)\n","readmeTruncated":false}