# projectileKit.vec
Small vector and quaternion maths on plain `{ x, y, z }` arrays (`{ [1], [2], [3] }`).
Every function is pure (no engine calls), so every peer computes the same numbers and
the tests can check them directly.
Used by `projectileKit.motion`, `projectileKit.render`, `projectileKit.api` and by
turretsKit's aiming and targeting code. Require it as `~.vec` from inside the package.
## Type
- `export type Vec = { number }`: a three-element array `{ x, y, z }`.
## Functions
Reading positions
- `of(v: any): Vec?`: reads a position from an array, a keyed table `{ x, y, z }`, a
`vector` or an entity position proxy; returns a fresh array, or `nil` when it is not a position.
Arithmetic (all return new arrays)
- `add(a, b): Vec`, `sub(a, b): Vec`, `scale(a, k): Vec`
- `dot(a, b): number`, `cross(a, b): Vec`
- `len(a): number`, `dist(a, b): number`, `flatDist(a, b): number` (ignores Y)
- `lerp(a, b, t): Vec`
- `norm(a): Vec`: unit vector; a near-zero vector returns `{ 0, 0, 1 }`.
- `segmentDistance(p, a, b): (number, number)`: distance from `p` to segment `a-b`, and
the segment parameter (0..1) of the closest point.
Angles and quaternions (quaternions are `{ x, y, z, w }`, yaw 0 faces +Z, positive pitch is up)
- `yawPitchQuat(yaw, pitch): { number }`: yaw about +Y, then pitch tilting local +Z upward.
- `lookQuat(dir: Vec): { number }`: rotation turning local +Z to point along `dir`.
- `axisQuat(axis: Vec, angle: number): { number }`: rotation of `angle` about a unit axis.
- `rotate(q, v: Vec): Vec`: rotates `v` by `q`.
- `yawPitchOf(dir: Vec): (number, number)`: yaw and pitch of a direction, in radians.
- `dirOf(yaw, pitch): Vec`: unit direction for a yaw and an upward pitch.
- `wrap(a): number`: wraps an angle to (-pi, pi].
Determinism
- `rng(seed: number): () -> number`: a seeded random stream returning numbers in [0, 1);
the same seed gives the same sequence on every peer.
# projectileKit
Pooled projectiles, beams, lightning arcs and puffs for Zero. Bullets fly straight, shells lob on a ballistic arc that lands exactly where you aim (over walls), and missiles home on a moving target. Lasers are continuous beams, lightning is jagged arcs, and puffs, bursts and rings cover flames, frost, poison clouds, explosions and muzzle flashes. Everything is drawn from **pools of reused entities**, moved with a few batched transform writes a frame. Nothing is spawned or destroyed per shot, so hundreds of shots in the air stay smooth on desktop, web and phones.
It is the projectile layer under [turretsKit](../turretsKit.package/README.md), and it works on its own for any weapon, trap or spell.
## Install
`zeromind_install` the `projectileKit` package, or install turretsKit, which brings it along. It needs nothing else.
## Use it
```lua
local PK = require("projectileKit.api")
-- a tracer that hits whatever stands on its line
PK.fire({ kind = "bullet", from = muzzle, target = enemy, aimHeight = 0.9, speed = 70, look = "tracer",
onHit = function(shot, hit) if hit.target then print("hit", hit.target) end end })
-- a mortar shell that peaks 8 m up and bursts where it lands
PK.fire({ kind = "shell", from = muzzle, to = { 10, 0, 20 }, arc = 8, look = "shell", impact = "blast",
onHit = function(shot, hit) print("landed at", hit.pos[1], hit.pos[3]) end })
-- a homing missile that climbs, then chases its target, leaving smoke
PK.fire({ kind = "missile", from = muzzle, target = enemy, speed = 22, turnRate = 160,
launchDir = { 0, 1, 0.3 }, look = "missile", trail = "smoke", impact = "blast" })
-- a laser: call every frame while it fires; it fades out on its own when you stop
PK.beam("laser-1", muzzle, enemyChest, "laserRed", 1)
-- one lightning bolt, a flame puff and an explosion
PK.arc(from, to, { look = "arcCyan", life = 0.2 })
PK.puff(pos, { look = "flame", vel = { 0, 1, 5 }, life = 0.5 })
PK.burst(pos, { look = "blast", size = 3 })
```
Positions can be `{ x, y, z }` lists, `{ x =, y =, z = }` tables, vectors or an entity's `position`. A `target` can be an entity or an entity id.
The kit spawns its own runner entity the first time anything is fired, so there is no component to add. In edit mode or in tests, drive it by hand with `PK.step(dt)`.
### `PK.fire(spec)`
| field | meaning |
|---|---|
| `kind` | `bullet` (straight), `shell` (ballistic arc) or `missile` (homing) |
| `from`, `to` | start, and aim point (defaults to the target's position) |
| `target` | entity or id: bullets and missiles hit it on contact, missiles chase it |
| `speed` | m/s (bullets and missiles) |
| `arc`, `gravity` | shells: metres above the higher end at the peak; m/s² |
| `turnRate` | missiles: degrees per second. The turn tightens the longer it flies, so a missile never orbits |
| `radius`, `aimHeight` | contact distance; height added to the target's position |
| `look`, `size` | which pooled look draws it, and a scale |
| `trail`, `trailEvery` | a puff look dropped behind it |
| `impact`, `impactSize` | a burst look where it ends |
| `draw = false` | simulate without drawing |
| `logic = false` | draw without calling `onHit` (for copies of a shot on other players' machines) |
| `onHit(shot, hit)` | `hit = { pos, target, reason = "hit" | "arrive" | "expire", aimedAt }` |
| `data` | anything; kept on the shot for `onHit` |
### Looks
43 looks ship in `projectileKit.looks`: tracers (yellow, red, blue), crossbow bolt, foam dart, pellet, steel shell, cannonball, catapult stone, rubber ball, plasma ball, missile, firework rocket, toy rocket, red/green/blue lasers, arcane ray, candy ray, sniper trail, cyan/violet/yellow lightning, flame, frost shard and mist, poison puffs, smoke, sparks, confetti, bubbles, explosion and plasma burst, shock/frost/poison/boost rings and muzzle flash. `PK.lookNames()` lists them. Add your own:
```lua
PK.defineLook("greenTracer", { color = { 0.3, 1, 0.4 } }, "tracer") -- copy tracer, change the colour
PK.defineLook("arrow", { mesh = "cube", color = { 0.5, 0.35, 0.2 }, size = { 0.05, 0.05, 0.8 }, cap = 80 })
```
A look is a built-in mesh (`cube`, `sphere`, `cylinder`, `octahedron`, `torus`, `cone`, `capsule`), `glow` or `metal` or plain plastic, a colour, a size, an optional `stretch` (tracers lengthen with speed) and a `cap` (most drawn at once).
## The budget, and why it stays smooth
- **Shots are data.** Every shot, puff and bolt is a plain table simulated in one loop. Finished tables are recycled, and so are shots that land over budget or are cleared mid-flight.
- **No garbage per frame.** A step moves every shot in place, draws it with plain numbers (`render.drawRaw`) and reads target positions into one reused table. Steady state with 300 or 1,000 shots in flight allocates nothing, and a test checks it. Measured on desktop: 300 shots in flight cost 0.2 ms a step, 600 cost 0.3 ms, 1,000 cost 1.35 ms. A shot over its look's drawing cap skips the drawing maths entirely.
- **Drawing is pooled.** Each look owns a pool of entities made once. Each frame, `render.flush` writes all their positions, rotations and scales in three batched calls per look, through typed buffers. Unused pool members are parked at zero scale; nothing toggles visibility or spawns per shot. Measured: 300 pooled entities moved this way cost about 0.07 ms, while 300 per-entity visibility toggles cost about 8 ms.
- **Pools grow gently.** At most `spawnPerFrame` new pool entities a frame, up to each look's `cap` and the global `maxVisible`. `PK.prewarm(look, n)` makes them ahead of time.
- **Over budget, nothing is lost.** Past `maxShots`, a new shot lands at once (its `onHit` still fires). Past `maxEffects`, the oldest cosmetic effect gives way.
| preset | `maxShots` (simulated) | `maxEffects` | `maxVisible` (drawn) | `spawnPerFrame` |
|---|---|---|---|---|
| `desktop` | 1500 | 900 | 600 | 12 |
| `web` | 1000 | 500 | 360 | 8 |
| `phone` | 600 | 260 | 220 | 6 |
`PK.setBudget("phone")` picks a preset, or pass a table with any of the four numbers. `PK.suggestedBudget()` names the preset that suits the machine, from the platform the engine reports (`engine.platform`) and the viewport size: `phone` on Android or when the short side of the screen is under 700 px, `web` in a browser (`engine.platform == "browser"`), else `desktop` (the desktop app). `PK.budgetFor(platform, width, height)` is the same rule for any platform and size, so a game or a test can see what a browser or a phone would get. `PK.stats()` reads it all back: shots flying, effects, beams, fired/hit/arrived/expired, instant landings, shot tables reused vs made, and pool sizes.
## Multiplayer
projectileKit draws locally and sends nothing. A game that wants every player to see a shot sends the shot's numbers to the other peers and fires it there with `logic = false`, so only one machine deals the damage. turretsKit does exactly that, batching every turret's shots into one message a frame. The flight maths is deterministic (`projectileKit.motion` has no clock), so the same numbers fly the same path on every machine.
## Reference
- `projectileKit.api`: `fire`, `kill`, `beam`, `endBeam`, `hasBeam`, `arc`, `puff`, `burst`, `ring`, `step`, `setBudget`, `budget`, `suggestedBudget`, `budgetFor`, `stats`, `resetStats`, `prewarm`, `defineLook`, `lookNames`, `clear`, `BUDGETS`, `VERSION`
- `projectileKit.motion`: `solveBallistic`, `lead`, `launch`, `step`, `predict` (pure maths)
- `projectileKit.vec`: small vector and quaternion helpers on `{ x, y, z }` lists
- `projectileKit.looks`, `projectileKit.render`: the look catalogue and the pools
- `projectileKit.Runner`: the component that ticks the loop (spawned for you)
## Tests
`tools.use("tests", "run", { suites = { "projectileKit" } })` in edit mode runs 14 tests: vector helpers, shells landing on target, bullets hitting, missiles homing on a moving target from awkward launch angles, lead, `onHit` once per shot, shot-table recycling (including over budget and after a clear), a step making no garbage, over-budget landing, pool reuse, budget presets, the automatic budget per platform (browser → web, Android or small screen → phone, desktop app → desktop), beams and effects expiring, and `hitTest` / `kill` ending shots early.
## Version
1.1.0 adds two small, general hooks and changes nothing else: a shot spec's `hitTest(shot, dt)` callback (checked after each step; return a target to end the shot as a hit on it, so a bullet can hit any of many targets, e.g. every player in a bullet-hell volley) and `PK.kill(shot, reason)` to end a shot early. Contributed by bulletPatternsKit.
1.0.2, published with turretsKit 2.1.4 from the Bastion Works world. 1.0.2 changes no code: its library description now says what you get and how to install it, and it is built on the engine library `ab1aa41`. 1.0.1 changed no code either: its docs and code comments no longer use long dashes, and its version number moved because ZeroMind publishes one content under each version.
Release history, honestly: there were no version bumps, but 1.0.0 was published several times on 2026-10-23, always under the number 1.0.0. The changes that reached it were the first build (around 17:01 UTC), the performance pass that made the shot loop garbage-free (around 17:55), and the fix that makes the automatic budget recognise a browser (around 21:45). The browser fix had two parts: the engine reports `"browser"`, which the old check (looking for "web") never matched, and the viewport size arrives as one `{ width, height }` table. Before it, browsers got the desktop budget and small screens never got the phone budget. Install the latest. 1.0.1 was published once, on 2026-10-31, with turretsKit 2.1.1. 1.0.2 was published once, on 2026-10-31, with turretsKit 2.1.4.