Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions ecs/.claude/rules/ecs/component._.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ paths:
- A key is a top-level `Symbol()` with no description, its traits declared beside it: `declare module "@adobe/ecs" { interface Components { [title]: { type: string } } }`.
- An entity reference is a component of its own, `type: Entity` with `reference: "owner"` or `"weak"`, never a field of a struct. A DOM object is `thread: "main"`.
- A derived component, `derived: true`, is defined in its own file by `Component.derive(key, { from, not })`: it's on exactly the entities some derivation of it matches, and nothing else adds or removes it.
- Shape components by how systems use their fields. A component is one array per archetype, each row's fields side by side; separate components are separate arrays. A system loads every byte of each component it reads, and kernels run four rows a vector where each field meets the same operation or a component is one value; fields combined with each other are transposed into lanes first, which costs about 2×.
- One tuple or struct for fields every system treats alike, such as a vector or color moved by `position + velocity * dt`: a tight `Vec2`, `Vec3` or `Vec4` runs at memory speed.
- Separate scalar components for fields systems compare or combine with each other (`hp` against `maxhp`, a status), or that only some systems use: health as three components ran 0.35 ns a row against 0.61 as one struct, and reading one `I32` of a 40-byte struct 0.42 against 0.17 as its own component.
- Separate components for fields written at different times: `changed`, stamps and persistence track whole components, so writing one field marks the rest changed.
- A value of each row that every field of a vector uses, such as a mass or scale, as its own scalar component, which a kernel spreads across the vector's lanes.
- Use the narrowest type that holds the value: `F32` unless the precision is needed, `I32` or `U32` for integers. Kernels compute at storage precision, so `F32` runs four lanes a vector and `number`, an f64, two, moving twice the bytes: integrating a vec3 took 0.27 ns a row in `F32` and 0.52 in `number`. Keep `F32` and `number` fields in separate components; a kernel mixing them computes the `number` ones a row at a time.
- Use a padded layout, `storage` or `vertex`, only for components the GPU reads: a vec3 padded to 16 bytes moves a third more.
7 changes: 7 additions & 0 deletions ecs/.github/instructions/ecs/component._.ts.instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,10 @@ applyTo: "**/component.*.ts"
- A key is a top-level `Symbol()` with no description, its traits declared beside it: `declare module "@adobe/ecs" { interface Components { [title]: { type: string } } }`.
- An entity reference is a component of its own, `type: Entity` with `reference: "owner"` or `"weak"`, never a field of a struct. A DOM object is `thread: "main"`.
- A derived component, `derived: true`, is defined in its own file by `Component.derive(key, { from, not })`: it's on exactly the entities some derivation of it matches, and nothing else adds or removes it.
- Shape components by how systems use their fields. A component is one array per archetype, each row's fields side by side; separate components are separate arrays. A system loads every byte of each component it reads, and kernels run four rows a vector where each field meets the same operation or a component is one value; fields combined with each other are transposed into lanes first, which costs about 2×.
- One tuple or struct for fields every system treats alike, such as a vector or color moved by `position + velocity * dt`: a tight `Vec2`, `Vec3` or `Vec4` runs at memory speed.
- Separate scalar components for fields systems compare or combine with each other (`hp` against `maxhp`, a status), or that only some systems use: health as three components ran 0.35 ns a row against 0.61 as one struct, and reading one `I32` of a 40-byte struct 0.42 against 0.17 as its own component.
- Separate components for fields written at different times: `changed`, stamps and persistence track whole components, so writing one field marks the rest changed.
- A value of each row that every field of a vector uses, such as a mass or scale, as its own scalar component, which a kernel spreads across the vector's lanes.
- Use the narrowest type that holds the value: `F32` unless the precision is needed, `I32` or `U32` for integers. Kernels compute at storage precision, so `F32` runs four lanes a vector and `number`, an f64, two, moving twice the bytes: integrating a vec3 took 0.27 ns a row in `F32` and 0.52 in `number`. Keep `F32` and `number` fields in separate components; a kernel mixing them computes the `number` ones a row at a time.
- Use a padded layout, `storage` or `vertex`, only for components the GPU reads: a vec3 padded to 16 bytes moves a third more.
2 changes: 1 addition & 1 deletion ecs/packages/ecs-architecture/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@adobe/ecs-architecture",
"version": "0.6.0",
"version": "0.6.1",
"description": "The architecture standard for @adobe/ecs applications: its checker and the agent rules for it",
"license": "MIT",
"type": "module",
Expand Down
3 changes: 3 additions & 0 deletions ecs/packages/ecs-architecture/standard.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ feature, and of its sub-features, import them, and they add no systems to an app
aim is to stay semantically immutable and gain its speed underneath, as compiled systems do, assigning new tuples in
source and allocating none.
- **Hot paths allocate nothing per frame,** and have a benchmark.
- **Model components for the systems that use them,** as `@adobe/ecs`'s component rules say: a tuple for fields every
system treats alike, scalar components for fields combined with each other or used apart, `F32` unless the precision
is needed.
- **Prefer WebGPU for drawing,** through `@adobe/ecs-gpu` and render systems, to WebGL and other older APIs: a render
system draws from the GPU copy of the components it names, which the world uploads straight from storage as rows
change, with no copy of its own.
Expand Down
4 changes: 3 additions & 1 deletion ecs/packages/ecs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,9 @@ Rule: anything that doesn't affect the API or correctness belongs in phase 2+.
1. **Kernel subset.** Kernels compile to efficient JS or WASM. Main-thread systems run as normal JS with every feature available.
- **Parser:** the bundler's own (`this.parse`, ESTree, in both Vite and Rolldown); the compiler validates the subset on that tree, and an ESLint rule can share the validator since ESLint also produces ESTree. A second JS parser would only add size and upkeep.
- **Closed world:** every input comes from the ECS (query rows, resources).
- **Precision:** a CPU kernel compiled without `kernel: true` computes as its body as written does, in f64, rounding only where it stores, in JS and WASM alike, so compiling it never changes a result: every value bit for bit, and NaN wherever the body gives NaN, its sign and payload the platform's (x86's differ from ARM's, in JavaScript as in WASM). A kernel the declaration asks for may compute at storage precision, as WASM's f32 SIMD lanes do, rounding each step: about 4.4 times faster for `move` and `chain` than one row at a time in f64, and not bit-exact with the body as written. At storage precision, arithmetic on fields declared `I32` or `U32`, and on locals only ever given such results, wraps at 32 bits as the integers they're stored as do (sums, differences, products, remainders by a literal, `I32` negations); a value JS operators make 32-bit, as `>>> 0` does, computes as written, and a `U8` promotes, as a C integer does. Its JS kernel computes as written. In every kernel an integer field declared with a `minimum` and `maximum` (`Schema.Type<{ type: "integer"; minimum: 0; maximum: 1000 }>`) bounds what the compiler proves of its arithmetic, so sums it can't overflow stay in i32; a value outside its declared range is unspecified. GPU kernels compute in f32.
- **Precision:** every CPU kernel's WASM computes at storage precision, whether or not the declaration asks for a kernel: kernels exist to run many rows fast, and SIMD lanes of the type the values are stored in are the fastest way to. Arithmetic on values of `F32` fields, on constants and the same for every row (resources, the input, shared values, literals), which convert to f32, and on its own results rounds each step to f32, as f32 lanes do, and a comparison of a row's such values compares f32s; in lanes and a row at a time alike, a row at a time in f32 instructions on f32 loads and stores, each such value the same for every row converted once a call, so every row computes the same whether or not it falls in a whole group of lanes (`wasm-kernels.test.ts`: a 120-frame simulation is bit-identical with SIMD and without). When every float field a kernel touches is an `f64` (`number`), lanes are f64x2, loaded and stored as they're stored, and compute as the body does. `integrate`, the guide's `Vec3.add(p, Vec3.scale(v, mass * delta))` with no `kernel` flag, runs 0.95 → 0.27 ns a row on an M4 Max, within 1.22× of its memory bound, and `integrate f64` 0.79 → 0.52. At storage precision, arithmetic on fields declared `I32` or `U32`, and on locals only ever given such results, wraps at 32 bits as the integers they're stored as do (sums, differences, products, remainders by a literal, `I32` negations); a value JS operators make 32-bit, as `>>> 0` does, computes as written, and a `U8` promotes, as a C integer does. Its JS kernel computes as written. In every kernel an integer field declared with a `minimum` and `maximum` (`Schema.Type<{ type: "integer"; minimum: 0; maximum: 1000 }>`) bounds what the compiler proves of its arithmetic, so sums it can't overflow stay in i32; a value outside its declared range is unspecified. NaN's sign and payload are the platform's (x86's differ from ARM's, in JavaScript as in WASM). GPU kernels compute in f32.
- **Lanes across rows:** before choosing a SIMD loop, the generator writes each local assigned once into its one read when nothing between changes what it reads, and each constant into every read (`forward-locals.ts`), so the temporaries of inlined calls leave each store its whole value. Stores to a component's leaves whose values match lane for lane then run four rows' elements as `4 × stride / 16` whole vectors (`elementsLoop`): leaves of other components of the same stride load lane for lane; values the same for every row splat; a value of each row, such as a scalar component, or a local assigned one, computes four rows at a time and is shuffled across each element's leaves (`spread`); and lanes no store writes, a leaf the body leaves or a padded vec3's padding, are stored back as loaded (`bitselect`).
- **Filtered rows in lanes:** with change filters, rows run across rows too, inside each run of passing blocks. At each eight rows aligned to eight, four f64x2 comparisons of each filter's row ticks against `lastRun` give the rows that pass; eight none of which pass are skipped whole, and the rest run as groups of a vector's rows (dense columns) or four rows' elements, branch-free, under those rows' mask: stores blend with what's there, a row's mask spread across its element's leaves as per-row values are, and row ticks stamp per lane. A group lies in one block, so a block and its chunk are stamped once its groups are done, where one stamped a row: the same ticks a row at a time gives (`wasm.test.ts`, filtered rows, bit for bit with SIMD and without over scattered, dense, alternating and clustered changes). Rows before the first aligned eight and after the last run one at a time. A branch on each row's tick mispredicts on scattered changes, about 3.7 ns a row at a random half; the masks take 0.42 for a vec3, 0.53 for a vec4 and 0.22 for an f32, whatever changed.
- **Imported functions:** kernels call pure functions and use constants from any module the build resolves to a file, the kernel's own module included: user TypeScript or JavaScript, other packages' ESM, and the package's math types. The plugin reads each module a kernel reaches, with types stripped, follows its imports and re-exports, and inlines each call compiled in its own module's scope, so tuples are scalarized and never allocate, on JS, WASM and the GPU alike. A function outside the subset fails the build at the kernel's call, with a frame naming the file and line of each inlined function down to the failure. Recursion fails, also across modules. A module's constants must be known at build time: a `let`, or a mutation at runtime, isn't seen. Editing an inlined file compiles its kernels again, in dev too.
- **Math types:** the package exports math types that are also namespaces of functions: `Vec2`, `Vec3`, `Vec4` (each `F32`, with `I32` and `U32` nested beside it), `Quat`, `Mat4x4`, and the scalars `F32`, `I32`, `U32`, each with a `schema`. They follow WGSL's semantics, and where WGSL leaves a result indeterminate they do what is fastest: integer vectors wrap, `round` rounds halfway values to even, `mod` is `x - m * floor(x / m)`, and `normalize` of a zero vector is NaN. Integer functions are defined for integers in range, and `pow` for a positive base; other inputs give indeterminate results, which may differ between the CPU and the GPU. The few that throw (`Mat4x4.inverse`, `Mat4x4.perspective`, `Mat4x4.lookAt`) can't be used in kernels.
- **WGSL builtins:** a math function whose WGSL builtin matches it declares that explicitly, in its own file (`intrinsic({ wgsl: "normalize", parameters: ["vec3f"], result: "vec3f" }, implementation)`). In a GPU kernel a call to it becomes an intrinsic region holding its operands and its inlined body: WGSL emits the builtin on vector and matrix types, nesting calls as builtins do, and JS and WASM run the body, so CPU output is unchanged. Locals keep their JS names in WGSL, and a region's result is named after its function.
Expand Down
6 changes: 6 additions & 0 deletions ecs/packages/ecs/followups.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ correctness, then optimization. Remove an item once it's decided or done.

## Optimization

- **The interleaved loop's cost gate** (`work.spent > 0.7 × 4 × statements` in `interleavedGroups`) was tuned before
lanes across whole elements existed; measure it against one row at a time over 1M rows for bodies that mix leaves,
such as `Vec3.cross`, and loosen it where lanes still win.
- **The JS kernel computes as written,** not at storage precision, so where WASM can't run a kernel's last bits differ
from WASM's. Rounding each f32 step there with `Math.fround` would make them agree, at its cost in the fallback.

- **Owner references in bulk spawns:** `spawn tables 1M owner` takes 53 ms against 10 ms for `spawn tables 1M`, and
`spawn owned 1M` 64 ms. What's left is per row: `commands.spawnTables` places every entity of the tables and finds
each row's owner among them (about 25 ms at 1M), and the sync point links each holder to its target (about 20 ms),
Expand Down
2 changes: 1 addition & 1 deletion ecs/packages/ecs/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@adobe/ecs",
"version": "0.6.0",
"version": "0.7.0",
"description": "Adobe ECS",
"license": "MIT",
"type": "module",
Expand Down
7 changes: 7 additions & 0 deletions ecs/packages/ecs/rules/component.x.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,10 @@ glob: "**/component.*.ts"
- A key is a top-level `Symbol()` with no description, its traits declared beside it: `declare module "@adobe/ecs" { interface Components { [title]: { type: string } } }`.
- An entity reference is a component of its own, `type: Entity` with `reference: "owner"` or `"weak"`, never a field of a struct. A DOM object is `thread: "main"`.
- A derived component, `derived: true`, is defined in its own file by `Component.derive(key, { from, not })`: it's on exactly the entities some derivation of it matches, and nothing else adds or removes it.
- Shape components by how systems use their fields. A component is one array per archetype, each row's fields side by side; separate components are separate arrays. A system loads every byte of each component it reads, and kernels run four rows a vector where each field meets the same operation or a component is one value; fields combined with each other are transposed into lanes first, which costs about 2×.
- One tuple or struct for fields every system treats alike, such as a vector or color moved by `position + velocity * dt`: a tight `Vec2`, `Vec3` or `Vec4` runs at memory speed.
- Separate scalar components for fields systems compare or combine with each other (`hp` against `maxhp`, a status), or that only some systems use: health as three components ran 0.35 ns a row against 0.61 as one struct, and reading one `I32` of a 40-byte struct 0.42 against 0.17 as its own component.
- Separate components for fields written at different times: `changed`, stamps and persistence track whole components, so writing one field marks the rest changed.
- A value of each row that every field of a vector uses, such as a mass or scale, as its own scalar component, which a kernel spreads across the vector's lanes.
- Use the narrowest type that holds the value: `F32` unless the precision is needed, `I32` or `U32` for integers. Kernels compute at storage precision, so `F32` runs four lanes a vector and `number`, an f64, two, moving twice the bytes: integrating a vec3 took 0.27 ns a row in `F32` and 0.52 in `number`. Keep `F32` and `number` fields in separate components; a kernel mixing them computes the `number` ones a row at a time.
- Use a padded layout, `storage` or `vertex`, only for components the GPU reads: a vec3 padded to 16 bytes moves a third more.
7 changes: 4 additions & 3 deletions ecs/packages/ecs/src/guide/14-kernels.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# Kernels

A *kernel* is a body the build compiles to run once per row, each row on its own, so the world can split the rows
across workers and run them as WASM, with results the same as the body as written.
across workers and run them as WASM. As WASM it computes at the precision its values are stored in: arithmetic on `F32`
values rounds each step to 32 bits, as SIMD lanes do, and on `I32` and `U32` values wraps at 32 bits, so a result can
differ in its last bits from the body as written. `number` values compute in 64 bits.

The build makes a kernel of any row system whose body reads and writes only data, calls math, and touches no module
state, without being asked: [`move`](14-kernels.ts#L21-L23) is one. Two flags change that:

- `kernel: true` asserts it. The build fails, saying why, if [the body](14-kernels.ts#L25-L27) can't be one. It also
computes `F32` values at 32 bits, which is faster on dense rows.
- `kernel: true` asserts it. The build fails, saying why, if [the body](14-kernels.ts#L25-L27) can't be one.
- `kernel: false` runs [the body as written](14-kernels.ts#L29-L31), on its thread: to step through it in a
debugger, say.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export type KernelExplanation = {
readonly columns: readonly string[];
readonly upColumns: readonly string[];
readonly signature: Signature;
readonly storagePrecision: boolean;
/** Each accumulator's operator, in its description's `reductions` order. */
readonly operators: readonly Reduction[];
};
Expand Down Expand Up @@ -183,7 +182,6 @@ export const compileKernel = (declaration: ObjectExpression, body: Node, module:
columns: [...unit.columnIndex.keys()],
upColumns: [...unit.upColumnIndex.keys()],
signature: unit.signature,
storagePrecision: !unit.tried,
operators: unit.accumulators.map(entry => unit.signature.reduced[entry.reduced]?.operator ?? fail(declaration, "unknown reduction")),
});
return {
Expand All @@ -206,7 +204,6 @@ export const compileKernel = (declaration: ObjectExpression, body: Node, module:
`url: ${url},`,
`program: ${serialize(program)},`,
`reducedShapes: [${[...unit.reducedShapes].join(", ")}],`,
...unit.tried ? [] : ["storagePrecision: true,"],
`reductions: [${unit.accumulators.map(entry => {
const { resource, operator } = reduced[entry.reduced] ?? fail(declaration, "unknown reduction");
return `{ resource: ${resource}, operator: ${JSON.stringify(operator)}, path: ${JSON.stringify(entry.path)} }`;
Expand Down
Loading