@margoengine/creative 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,307 +1,311 @@
1
- # @margoengine/creative
2
-
3
- Import `margoengine/creative` from the `margoengine` package, or `@margoengine/creative` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
-
5
- WebGPU grass, a planet renderer, a leaf/weather particle preset, toon shading, HDR targets and a grading post effect (fog, god rays, focus blur, ACES, grain) for Margo Engine.
6
-
7
- Each capability has one implementation: `GPUParticles` is a preset over `@margoengine/vfx`, bloom is `Bloom` from `@margoengine/post/bloom`, and sky backdrops are `Sky` from `@margoengine/sky`.
8
-
9
- For grass on terrain, use the [scatter heightmap and density-map example](../scatter/README.md#density-maps-a-grid-that-follows-the-camera-and-stored-tiles).
10
- Scatter also provides [interaction and trampling](../scatter/README.md#interaction-and-trampling-margoenginescatterinteract)
11
- and [streamed grass chunks with three LOD meshes](../scatter/README.md#tile-input-storage).
12
-
13
- Package name: `@margoengine/creative`, version `0.1.0`. Build from source or install a local tarball until the renamed package is published.
14
-
15
- ```sh
16
- npm install @margoengine/core@1.0.0 @margoengine/creative@1.0.0
17
- ```
18
-
19
- ```ts
20
- import { Engine } from 'margoengine/core';
21
- import { GPUParticles } from 'margoengine/creative/particles';
22
-
23
- const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
24
- const engine = await Engine.create(canvas, { backend: 'webgpu' });
25
- GPUParticles.attach(engine, { count: 5000, sort: true, curl: 0.2 });
26
- engine.start();
27
- ```
28
-
29
- Call `engine.dispose()` on teardown. Creative rendering requires supported WebGPU hardware on HTTPS or localhost.
30
-
31
- Use a feature subpath for a static import or an on-demand `import()`:
32
-
33
- | Subpath | Feature |
34
- | --- | --- |
35
- | `@margoengine/creative/particles` | `GPUParticles` (a `@margoengine/vfx` preset) and particle option types |
36
- | `@margoengine/creative/targets` | `HDRRenderTarget`, `TextureRenderTarget` |
37
- | `@margoengine/creative/toon` | `ToonShading` and toon option types |
38
- | `@margoengine/creative/paint` | `Painterly`: Kuwahara, watercolour wash and sketch, in an LDR PostStack |
39
- | `@margoengine/creative/post` | `PostProcessing` (fog, god rays, focus blur, grading, grain) and its option types |
40
- | `@margoengine/creative/grass` | `GrassField` and grass option types |
41
- | `@margoengine/creative/planet` | `Planet` and planet option types |
42
-
43
- ```ts
44
- const {Planet} = await import('margoengine/creative/planet'); // loaded only when this line runs
45
- ```
46
-
47
- `GPUParticles({count, gravity, wind, size, curl, obstacles, sort, texture})` keeps `count` particles drifting
48
- inside a 6 m cube centred on the origin, re-entering on the opposite face. It is a `VFX` from `@margoengine/vfx/base`
49
- (`instanceof VFX` of that entry, with the obstacles, wrap, sort and texture features only; plugin name `gpu-particles`): `wind` is added to `gravity`, `curl` is VFX `turbulence`, and
50
- `size` is the sprite half-width. Use `VFX` directly for emitters, lifetimes, bursts or up to 1,000,000 particles.
51
-
52
- `PostProcessing` grades the HDR scene: exponential height fog, screen-space god rays, a depth-of-field focus
53
- blur, exposure/contrast/saturation/gain/lift (contrast is a power about 18% grey, so it deepens shadows without
54
- clipping them to black; contrast 0 is flat 18% grey, black included), the PBR Neutral display transform and grain. It has no bloom and no sky backdrop; passing
55
- `bloom`, `threshold` or `atmosphere.sky`/`scattering`/`anisotropy` throws with the replacement. Alone it owns
56
- scene capture. For bloom, or to combine it with SSAO, DOF or FXAA, add it to a `PostStack` from
57
- `@margoengine/post/stack` as the display effect: `PostStack.attach(engine, [new SSAO(), new Bloom({strength:
58
- 0.3}), new PostProcessing({atmosphere: {density: 0.02}}), new FXAA()])`. In a stack its `target` is undefined.
59
- The grain clock (`post.time`) moves in the frame update (`post.advanceTime(delta)`), once a frame however many views
60
- draw (before 2026-11-16 the capture pass moved it, which a seek does not run), so `seek` from `@margoengine/cutscene/seek` starts a film scene on
61
- the grain a continuous run shows; a PostProcessing no frame update reaches moves it per draw.
62
- For a sky behind the fog, attach `Sky` from `@margoengine/sky`.
63
-
64
- `PostProcessing` and `Painterly` detach from their owning scene on disposal,
65
- including stack members. Device restoration keeps their registrations. For a
66
- secondary scene, attach the stack with `scene.use()`:
67
-
68
- ```ts
69
- import {Engine} from 'margoengine/core';
70
- import {PostStack} from 'margoengine/post/stack';
71
- import {PostProcessing} from 'margoengine/creative/post';
72
- import {Painterly} from 'margoengine/creative/paint';
73
- const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
74
- const product = engine.createScene('product');
75
- const stack = new PostStack([new PostProcessing(), new Painterly()]);
76
- product.use(stack);
77
- stack.dispose();
78
- engine.dispose();
79
- ```
80
-
81
- Each subpath loads that feature and its dependencies. Existing named imports from `@margoengine/creative` remain available and can be tree-shaken by a bundler. `await import('@margoengine/creative')` loads the complete pack namespace; use a subpath when loading one feature independently. The stage's `addParticles` and `addEffects` (`@margoengine/stage/particles`, `/effects`) load only `/particles` and `/post`.
82
-
83
- Attach a grass field directly to an existing Stage, without extending the facade:
84
-
85
- ```ts
86
- import {createStage} from 'margoengine';
87
- import {GrassField} from 'margoengine/creative/grass';
88
-
89
- const stage = await createStage('#viewport', {backend: 'webgpu'});
90
- const meadow = GrassField.attach(stage.engine, {
91
- blades: 100_000, area: [50, 50], bladeHeight: 1.2, windSpeed: 1.2, spores: true,
92
- });
93
- meadow.windStrength = 0.6;
94
- // Remove this field early, or let stage.dispose() release it with the scene.
95
- meadow.dispose();
96
- ```
97
-
98
- `GrassField.attach(engine, options)` takes any core engine (`new GrassField({engine}, options)` is the older form). It advances `windTime` by the frame delta, supports multiple fields, and rebuilds GPU resources after device restoration. Do not add a second time increment in `onTick`. All roots lie on Y=0 in a rectangle centered on the origin.
99
-
100
- `meadow.dispose()` (and its deprecated alias `meadow.destroy()`) is an idempotent teardown: remove the field's compute, grass and optional spore passes before destroying its GPU buffers. The field registers no tick listeners. Both indirect instance counters are cleared with `encoder.clearBuffer()` before each culling dispatch; the compute pass ends before the separate render passes read the compacted lists and indirect arguments.
101
-
102
- | Option | Default | Meaning |
103
- | --- | --- | --- |
104
- | `blades` | `100_000` | Positive integer, bounded by device storage and dispatch limits |
105
- | `area` | `[50, 50]` | Positive X/Z dimensions, up to 100,000 world units |
106
- | `bladeHeight` | `1.2` | Positive blade height, up to 100; instances vary from 0.7× to 1.25× |
107
- | `windSpeed` | `1.2` | Noise scrolling and spore drift speed, 0-100; mutable on the field |
108
- | `windStrength` | `0.45` | Bend strength, 0-2; mutable on the field |
109
- | `windDirection` | `[1, 0.35]` | Nonzero X/Z direction, normalized at creation; mutable on the field (assign any nonzero pair) |
110
- | `drawDistance` | `100` | Positive distance cutoff, up to 100,000 world units |
111
- | `spores` | `false` | Draw 240 drifting white dandelion particles |
112
-
113
- The compute pass culls conservative blade bounds against all six camera planes and distance, then compacts two GPU instance lists. Indirect draws use seven-vertex near blades and three-vertex far blades, with stable density thinning beyond 70% of draw distance. The three near segments preserve their lengths during wind bending. Curved normals, root-to-tip color, wrap lighting and backlight transmission use the engine's existing lighting. Grass writes Reversed-Z depth; spores blend additively without writing depth. Both canvas and HDR/post-processing targets are supported.
114
-
115
- Instance data, uniforms, bind groups and pass descriptors are allocated at creation. The initial pipeline variant is built during setup; additional supported target variants are cached on first use. Stable frames reuse these resources. There is no production CPU visibility readback. Frame rate depends on hardware, resolution and visible density; 60 FPS is a target, not a guarantee. Grass is not a core mesh and does not participate in mesh picking, Stage fitting, section clipping or shadows.
116
-
117
- Run `npx vite --host 127.0.0.1` from the repository root and open `/examples/windy-meadow.html` for wind, density and seed controls, the optional Sky package's daylight/moonlight and moving clouds, and Bloom's HDR/AgX presentation. The demo uses the shared 4× MSAA desktop default; mobile uses 1× MSAA, a DPR cap of 1 and 35,000 blades, with collapsible settings. Orbit, pinch, keyboard navigation and reset remain available while motion is paused; reduced motion pauses the grass, seeds and clouds. Run `node --test tests/modern-grass.test.js` and `node scripts/modern-grass-tests.js` after building the creative, sky and post packages for the unit and GPU checks.
118
-
119
- ## Planet
120
-
121
- The source checkout also exports `Planet` and `PlanetOptions`. Planet is an opt-in WebGPU plugin; neither core nor the Stage facade imports its shaders.
122
-
123
- ```ts
124
- import {createStage} from 'margoengine';
125
- import {Planet} from 'margoengine/creative/planet';
126
-
127
- const stage = await createStage('#viewport', {backend: 'webgpu'});
128
- const earth = await Planet.attach(stage.engine, {
129
- dayMap: '/earth_day.jpg',
130
- nightMap: '/earth_night.jpg',
131
- specularRoughnessMap: '/earth_oceans.png',
132
- clouds: '/earth_clouds.jpg',
133
- radius: 1,
134
- tilt: 23.4,
135
- atmosphere: {color: [0.3, 0.6, 1], intensity: 1.2},
136
- });
137
- earth.setSunDirection([-1, 0.2, 0.5]);
138
- stage.onTick(dt => {
139
- earth.rotation.y += 0.05 * dt;
140
- earth.clouds.offsetU += 0.01 * dt;
141
- });
142
- window.addEventListener('pagehide', () => stage.dispose(), {once: true});
143
- ```
144
-
145
- `Planet.create` loads maps and attaches through the existing `engine.use()` API. It rejects unsupported WebGL2 engines, disposed engines, invalid options, HTTP/decode failures and oversized images. Supply `signal` to cancel creation. Loading is also aborted when the engine or Planet is disposed; failed creation removes its plugin and partial resources. Remove a ready Planet with `earth.dispose()` or `stage.engine.removePlugin(earth.name)`. One Planet is supported per engine.
146
-
147
- Use `await earth.updateMaps({dayMap, nightMap, specularRoughnessMap, normalMap, clouds, signal})` to replace a ready Planet's complete map set after a preview is visible. The current surface, clouds and atmosphere remain drawable during downloads and decoding; the new set becomes active only after GPU validation. Omitted optional maps use their usual fallbacks. A failed or canceled update keeps the complete previous set, and a second update is rejected while one is pending. The same Planet, transform accessors, tilt, sun and cloud drift survive the swap and device restoration. Distinct committed plus pending decoded images share the 256 MiB budget. Rendering retains the existing linear sampler and single mip level; rebuilding/uploading the replacement pass can still cause a device-dependent hitch.
148
-
149
- Only `dayMap` is required. All maps accept a URL or string, including relative URLs. `dayMap` and optional `nightMap` are sRGB color; night lights are boosted 3× before tone mapping and fade across twilight (`NdotL` from 0.05 to −0.15). `specularRoughnessMap` is linear data with ocean specular strength in red and roughness in green (0 = smooth, 1 = rough). An omitted map gives matte terrain. Optional `normalMap` is a linear RGB tangent-space normal map (+Y convention); it affects shading, not the silhouette. `clouds` is a linear grayscale coverage map, with black transparent and white opaque. Maps must be equirectangular, north at the top. Downloads are limited to 32 MiB per map; retained decoded maps are limited to 256 MiB in total and the current device's texture dimension limit.
150
-
151
- Radius defaults to 1, tilt to 23.4 degrees, sun direction to `[-1, 0.2, 0.5]`, and atmosphere color/intensity to `[0.3, 0.6, 1]` / 1.2. `earth.rotation` uses the existing stable transform accessors in radians. `earth.clouds.offsetU` is finite and wraps to `[0, 1)`. `setSunDirection` normalizes a nonzero world-space vector. GPU restoration preserves spin, drift and decoded maps; full disposal closes those images.
152
-
153
- Rendering adds two indexed draws: a surface with depth writes, then a front-facing cloud/rim shell at `radius * 1.01` that tests scene depth without writing it. Both share retained sphere buffers and use reversed depth. The shell produces geometric cloud parallax; UV drift animates it independently. The atmospheric rim is an analytical Fresnel approximation. Clouds and glow share one altitude, and the camera must remain outside the shell. Textures currently use linear filtering without mipmaps, so distant views can alias. The initial pipeline variant is built during setup; additional supported canvas and HDR target variants are cached on first use. Stable frames reuse these resources, and existing post-processing works with the same attachments.
154
-
155
- Planet-owned arrays, GPU resources and render-pass descriptors are retained across steady frames. Browser/WebGPU command objects and the rest of the engine can still allocate, and actual FPS depends on the browser, display and GPU. Custom planet draws do not participate in the base `pick()`, `stats.drawCalls`, or `Stage.fit()` APIs; position the camera explicitly and inspect recorded commands for draw counts.
156
-
157
- ### Earth demo and module checks
158
-
159
- From the repository root:
160
-
161
- ```sh
162
- npm run dev --workspace @margoengine/creative
163
- # Opens /examples/earth/ in your browser (the dev server has no page at /).
164
- npm run test --workspace @margoengine/creative
165
- npm run test:browser --workspace @margoengine/creative
166
- ```
167
-
168
- The demo combines Planet's linear HDR surface/cloud/rim output with optional Bloom and AgX tone mapping. It presents a complete local 1k Earth map set first, then atomically upgrades all five maps to 2k on desktop while keeping that preview visible. Mobile keeps the complete 1k set. It includes damped OrbitControls with exterior zoom limits, a switchable procedural starfield, sun direction, independent rotation/cloud speeds, bloom and exposure controls. Desktop uses the shared 4× MSAA default; mobile uses 1× MSAA, a DPR cap of 1 and collapsible settings. Reduced-motion preferences pause rotation and cloud drift and disable navigation damping; keyboard and pinch navigation remain available. [Texture attribution and licenses](examples/earth/assets/ATTRIBUTION.md) travel with the example.
169
-
170
- The build and prepack commands write only this package's `dist` and license copy. Checks and screenshots write to this package's `test-results`; they use existing core artifacts without rebuilding the base. The browser check uses Edge by default (or installed Playwright Chromium as a fallback); set `BROWSER_CHANNEL` to choose another installed Chromium channel. The unit checks cover loading, lifecycle, validation, resource retention and bundle isolation. The WebGPU checks cover shaders, rendered pixels, depth, HDR and device restoration.
171
-
172
- This ESM package includes TypeScript declarations, requires `@margoengine/core` 1.0.0 and depends on `@margoengine/vfx` for particles. See the effect options and limitations.
173
-
174
- Apache-2.0 licensed.
175
-
176
- ## Texture targets
177
-
178
- `TextureRenderTarget` adds color-only cube faces, array layers, mip levels and 3D depth slices to the optional
179
- `/targets` entry. It works on native WebGPU. Passing a WebGL2 engine's `gpu` (null) throws a `MargoError` with
180
- `code: 'unsupported'` and a help link. It does not capture the core scene; the caller records draws into its pass.
181
-
182
- ```ts
183
- import {TextureRenderTarget} from 'margoengine/creative/targets';
184
-
185
- const adapter = await navigator.gpu.requestAdapter();
186
- if (!adapter) throw new Error('WebGPU adapter required');
187
- const device = await adapter.requestDevice();
188
- const cube = new TextureRenderTarget(device, {kind: 'cube', width: 32, mipLevelCount: 2});
189
- const encoder = device.createCommandEncoder();
190
- for (let mip = 0; mip < 2; mip++) {
191
- for (let layer = 0; layer < 6; layer++) {
192
- const pass = cube.begin(encoder, {mip, layer, clearColor: [layer / 5, mip, 0, 1]});
193
- // Set a single-sample rgba8unorm pipeline and draw here, if needed.
194
- pass.end();
195
- }
196
- }
197
- device.queue.submit([encoder.finish()]);
198
- await device.queue.onSubmittedWorkDone();
199
- // cube.view is a cube sampling view; cube.texture supports copyTextureToBuffer.
200
- cube.dispose();
201
- device.destroy();
202
- ```
203
-
204
- | Option | Default | Range |
205
- | --- | --- | --- |
206
- | `kind` | required | `cube`, `array`, `3d` |
207
- | `width` | required | Positive integer, device maxTextureDimension2D or maxTextureDimension3D |
208
- | `height` | width | Same limits as width; cube must be square |
209
- | `depthOrLayers` | 6 for cube, otherwise 1 | Cube fixed at 6; array bounded by maxTextureArrayLayers; 3D by maxTextureDimension3D |
210
- | `mipLevelCount` | 1 | 1 through the complete mip chain; array layers never shrink, 3D depth does |
211
- | `format` | `rgba8unorm` | `rgba8unorm` or `rgba16float` |
212
-
213
- Total logical allocation including mips is capped at 256 MiB. Cube layer order is +X, -X, +Y, -Y, +Z, -Z.
214
- `mipSize(mip = 0)` returns logical [width, height, depth/layers]. `begin(encoder, surface = {})` selects `mip = 0`
215
- and `layer = 0` by default. `layer` means face, layer or slice at that mip. `loadOp` defaults to `clear`; `load`
216
- preserves earlier pixels. `clearColor` defaults to [0, 0, 0, 0], with four finite components in 0..1 for rgba8unorm
217
- or -65504..65504 for rgba16float. The pass stores its output. Views are cached per surface (per mip for 3D).
218
- There is no depth attachment, MSAA, automatic camera setup or mip filtering/generation. Sample with the whole
219
- resource `view` (cube, 2d-array or 3d) after ending its render pass. Texture contents are initially zero.
220
-
221
- The target owns its texture; `dispose()` and `[Symbol.dispose]()` are idempotent and terminal. After device loss,
222
- call `restore(newDevice)`, fetch fresh `texture`/`view` handles, rebuild dependent bind groups and redraw every
223
- surface. Options survive; pixels do not. Restoration validates the new device limits before replacing resources.
224
- Do not retain surface views or use handles from a lost device. Invalid options and subresources fail before any
225
- pass is begun. GPU allocation/validation errors still follow WebGPU error scopes.
226
-
227
- Proof: `node --test --test-timeout=30000 packages/creative/tests/targets.test.js` and
228
- `node scripts/run-with-timeout.mjs --max=5 -- node packages/creative/scripts/test-targets.js`.
229
- The generated color fixture checks 78 subresources with full pixel readback, HDR, partial draws with load,
230
- WebGL2 rejection and replacement-device restoration. Other browser/GPU implementations and speed are unmeasured.
231
-
232
- ## Painterly post effects
233
-
234
- Import only `@margoengine/creative/paint` (or `margoengine/creative/paint`). It stays out of the creative root.
235
- Install the optional `@margoengine/post` peer alongside creative for this entry. Painterly works in display space
236
- after tonemapping, with no texture or scene input to provide. All options are live and validated each frame.
237
-
238
- ```ts
239
- import { Engine } from 'margoengine/core';
240
- import { Painterly } from 'margoengine/creative/paint';
241
-
242
- const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
243
- const engine = await Engine.create(canvas, { backend: 'webgpu' });
244
- engine.scene.background = '#406080';
245
- const paint = Painterly.attach(engine, { mode: 'watercolour', radius: 3, strength: 1 });
246
- engine.start();
247
- // Live changes: paint.options.mode = 'sketch'; paint.enabled = false;
248
- // On teardown: paint.dispose(); engine.dispose();
249
- ```
250
-
251
- For an existing stack, add `new Painterly(options)` after its display effect using
252
- `PostStack.attach(engine, [/* HDR/display effects, then */ new Painterly()])` from `@margoengine/post/stack`. On a scene
253
- that already has a PostStack, `Painterly.attach` and `AnisotropicPainterly.attach` add the effect to it after its last
254
- LDR effect; disposing the effect takes it out again.
255
- The stack owns its effects. `Painterly.attach` creates and owns a stack by itself; disposing the returned effect
256
- releases both. Disposal is terminal, idempotent and supports `using` / `Symbol.dispose`.
257
-
258
- | Option | Default | Meaning |
259
- | --- | --- | --- |
260
- | `mode` | `'kuwahara'` | `'kuwahara'`, `'watercolour'` or `'sketch'` |
261
- | `radius` | `3` | Integer 1..8 pixels; sketch uses this for gradient spacing |
262
- | `strength` | `1` | Finite 0..1 blend; zero is an exact input copy |
263
- | `enabled` | `true` | False is an exact input copy |
264
-
265
- Kuwahara chooses the mean of the lowest summed RGB-variance quadrant among four overlapping squares, with the
266
- first quadrant winning equal computed variances. This classic filter can produce square artifacts and flicker on
267
- noisy near-ties; it is not the anisotropic tensor filter. Watercolour adds eight-level colour quantization, a pale
268
- wash, Sobel edge darkening and a fixed 17-value paper pattern. Sketch draws Sobel outlines and two diagonal hatch
269
- families at six-pixel spacing, selected by source luminance. These are single-frame stylizations, not fluid,
270
- pigment or pencil simulations. Each preserves the centre alpha, clamps neighbours to its viewport and keeps
271
- uniforms separate per view. RGB is filtered as supplied by the LDR stack, without alpha-weighted filtering.
272
-
273
- WebGPU only; native WebGL2 throws coded `unsupported` with a help link. Invalid options throw linked RangeError;
274
- attachment/state/disposal errors are coded. Device restoration rebuilds GPU resources automatically through the
275
- stack. A maximum-radius Kuwahara or watercolour pixel reads 324 neighbourhood samples plus the centre (watercolour
276
- also reads eight Sobel neighbours); sketch reads eight neighbours plus the centre. Entry: 7504 B minified,
277
- 3073 B gzip with bare dependencies external. No speed, aesthetic quality or other-device claim. Tests use
278
- generated images as stand-ins on a real RTX A6000, against an independent CPU pixel reference. Run
279
- `npm run test:gpu:paint --workspace @margoengine/creative`.
280
-
281
- ### Attaching from a second scene
282
-
283
- `createTerrainGrass` remembers the scene that is active when you call it, before its first await, and joins that scene when it finishes. Start it inside a second scene's plugin `setup` and the plugin belongs to that scene; start it anywhere else and it belongs to the default scene. An abort or a failure leaves nothing in either scene.
284
-
285
- ## Sliders: `@margoengine/creative/grass-settings`
286
-
287
- `GrassField` keeps its blade height, reach, density, wind, blade colours and back-light in its frame uniform and rewrites it every frame, so they change while the scene runs. The setters are `bladeHeight`, `drawDistance`, `density` (0 to 1: the kept fraction of blades, the same blades each time), `windSpeed`, `windStrength`, `windDirection`, `rootColor`, `tipColor`, `tipVariantColor`, `translucencyColor` and `translucency` (0 to 4, default 0.4). `@margoengine/creative/grass-settings` lists them as a table for sliders and panels: `GRASS_SETTINGS` has 12 rows (each has `name`, `group`, `kind`, `default`, `min`, `max`, `step`, `unit`, `about` and `live`), all `live`. `applyGrassSettings(grass, values)` writes a set of values (a name left out takes its default), and `GRASS_LOOKS` names `natural`, `dry` and `windy`. An unknown name throws `TypeError`, a value outside its row `RangeError`, and a wind direction of 0 and 0 `RangeError`. The defaults are the colours and strength the shader had as constants, so a field with no settings draws as before. Not rows: blade count, area and spores (they size buffers at construction). Proof on a real GPU (`npm run test:settings:browser`, native WebGPU and the WebGL2 layer): the defaults written draw the frame exact, 60 frames of every row create no pipeline, buffer or texture, and the last frame equals writing the values once.
288
-
289
- ```ts
290
- import {Engine} from 'margoengine/core';
291
- import {GrassField} from 'margoengine/creative/grass';
292
- import {GRASS_LOOKS, applyGrassSettings} from 'margoengine/creative/grass-settings';
293
-
294
- const engine = await Engine.create(document.querySelector('canvas')!, {backend: 'webgpu'});
295
- const meadow = GrassField.attach(engine, {blades: 60000, area: [30, 30]});
296
- let time = 0;
297
- engine.onFrame((_, delta) => {
298
- time += delta;
299
- // The meadow dries out over the shot.
300
- const dry = Math.min(time / 6, 1);
301
- applyGrassSettings(meadow, {...GRASS_LOOKS.dry, 'field.density': 1 - 0.3 * dry, 'translucency.strength': 0.4 + dry});
302
- });
303
- ```
304
-
305
- ## Preview tier contract
306
-
307
- GPU-only attachments refuse the small WebGL2 preview during setup with `MargoError` code `unsupported` and a help link. Native WebGPU and the full WebGL2 compatibility layer expose the WebGPU-shaped device these passes need. Use [automatic escalation](../webgl2-compat/README.md#automatic-escalation) with awaited setup to load the full layer when required. Existing real preview routes remain available.
1
+ # @margoengine/creative
2
+
3
+ Import `margoengine/creative` from the `margoengine` package, or `@margoengine/creative` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ WebGPU grass, a planet renderer, a leaf/weather particle preset, toon shading, HDR targets and a grading post effect (fog, god rays, focus blur, ACES, grain) for Margo Engine.
6
+
7
+ Each capability has one implementation: `GPUParticles` is a preset over `@margoengine/vfx`, bloom is `Bloom` from `@margoengine/post/bloom`, and sky backdrops are `Sky` from `@margoengine/sky`.
8
+
9
+ For grass on terrain, use the [scatter heightmap and density-map example](../scatter/README.md#density-maps-a-grid-that-follows-the-camera-and-stored-tiles).
10
+ Scatter also provides [interaction and trampling](../scatter/README.md#interaction-and-trampling-margoenginescatterinteract)
11
+ and [streamed grass chunks with three LOD meshes](../scatter/README.md#tile-input-storage).
12
+
13
+ Package name: `@margoengine/creative`, version `1.0.0`. Build from source or install a local tarball until the renamed package is published.
14
+
15
+ ```sh
16
+ npm install @margoengine/core@1.0.0 @margoengine/creative@1.0.0
17
+ ```
18
+
19
+ ```ts
20
+ import { Engine } from 'margoengine/core';
21
+ import { GPUParticles } from 'margoengine/creative/particles';
22
+
23
+ const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
24
+ const engine = await Engine.create(canvas, { backend: 'webgpu' });
25
+ GPUParticles.attach(engine, { count: 5000, sort: true, curl: 0.2 });
26
+ engine.start();
27
+ ```
28
+
29
+ Call `engine.dispose()` on teardown. Creative rendering requires supported WebGPU hardware on HTTPS or localhost.
30
+
31
+ Use a feature subpath for a static import or an on-demand `import()`:
32
+
33
+ | Subpath | Feature |
34
+ | --- | --- |
35
+ | `@margoengine/creative/particles` | `GPUParticles` (a `@margoengine/vfx` preset) and particle option types |
36
+ | `@margoengine/creative/targets` | `HDRRenderTarget`, `TextureRenderTarget` |
37
+ | `@margoengine/creative/toon` | `ToonShading` and toon option types |
38
+ | `@margoengine/creative/paint` | `Painterly`: Kuwahara, watercolour wash and sketch, in an LDR PostStack |
39
+ | `@margoengine/creative/post` | `PostProcessing` (fog, god rays, focus blur, grading, grain) and its option types |
40
+ | `@margoengine/creative/grass` | `GrassField` and grass option types |
41
+ | `@margoengine/creative/planet` | `Planet` and planet option types |
42
+
43
+ ```ts
44
+ const {Planet} = await import('margoengine/creative/planet'); // loaded only when this line runs
45
+ ```
46
+
47
+ `GPUParticles({count, gravity, wind, size, curl, obstacles, sort, texture})` keeps `count` particles drifting
48
+ inside a 6 m cube centred on the origin, re-entering on the opposite face. It is a `VFX` from `@margoengine/vfx/base`
49
+ (`instanceof VFX` of that entry, with the obstacles, wrap, sort and texture features only; plugin name `gpu-particles`): `wind` is added to `gravity`, `curl` is VFX `turbulence`, and
50
+ `size` is the sprite half-width. Use `VFX` directly for emitters, lifetimes, bursts or up to 1,000,000 particles.
51
+
52
+ `PostProcessing` grades the HDR scene: exponential height fog, screen-space god rays, a depth-of-field focus
53
+ blur, exposure/contrast/saturation/gain/lift (contrast is a power about 18% grey, so it deepens shadows without
54
+ clipping them to black; contrast 0 is flat 18% grey, black included), the PBR Neutral display transform and grain. It has no bloom and no sky backdrop; passing
55
+ `bloom`, `threshold` or `atmosphere.sky`/`scattering`/`anisotropy` throws with the replacement. Alone it owns
56
+ scene capture. For bloom, or to combine it with SSAO, DOF or FXAA, add it to a `PostStack` from
57
+ `@margoengine/post/stack` as the display effect: `PostStack.attach(engine, [new SSAO(), new Bloom({strength:
58
+ 0.3}), new PostProcessing({atmosphere: {density: 0.02}}), new FXAA()])`. In a stack its `target` is undefined.
59
+ The grain clock (`post.time`) moves in the frame update (`post.advanceTime(delta)`), once a frame however many views
60
+ draw (before 2026-11-16 the capture pass moved it, which a seek does not run), so `seek` from `@margoengine/cutscene/seek` starts a film scene on
61
+ the grain a continuous run shows; a PostProcessing no frame update reaches moves it per draw.
62
+ For a sky behind the fog, attach `Sky` from `@margoengine/sky`.
63
+
64
+ `PostProcessing` and `Painterly` detach from their owning scene on disposal,
65
+ including stack members. Device restoration keeps their registrations. For a
66
+ secondary scene, attach the stack with `scene.use()`:
67
+
68
+ ```ts
69
+ import {Engine} from 'margoengine/core';
70
+ import {PostStack} from 'margoengine/post/stack';
71
+ import {PostProcessing} from 'margoengine/creative/post';
72
+ import {Painterly} from 'margoengine/creative/paint';
73
+ const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
74
+ const product = engine.createScene('product');
75
+ const stack = new PostStack([new PostProcessing(), new Painterly()]);
76
+ product.use(stack);
77
+ stack.dispose();
78
+ engine.dispose();
79
+ ```
80
+
81
+ Each subpath loads that feature and its dependencies. Existing named imports from `@margoengine/creative` remain available and can be tree-shaken by a bundler. `await import('@margoengine/creative')` loads the complete pack namespace; use a subpath when loading one feature independently. The stage's `addParticles` and `addEffects` (`@margoengine/stage/particles`, `/effects`) load only `/particles` and `/post`.
82
+
83
+ Attach a grass field directly to an existing Stage, without extending the facade:
84
+
85
+ ```ts
86
+ import {createStage} from 'margoengine';
87
+ import {GrassField} from 'margoengine/creative/grass';
88
+
89
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
90
+ const meadow = GrassField.attach(stage.engine, {
91
+ blades: 100_000, area: [50, 50], bladeHeight: 1.2, windSpeed: 1.2, spores: true,
92
+ });
93
+ meadow.windStrength = 0.6;
94
+ // Remove this field early, or let stage.dispose() release it with the scene.
95
+ meadow.dispose();
96
+ ```
97
+
98
+ `GrassField.attach(engine, options)` takes any core engine (`new GrassField({engine}, options)` is the older form). It advances `windTime` by the frame delta, supports multiple fields, and rebuilds GPU resources after device restoration. Do not add a second time increment in `onTick`. All roots lie on Y=0 in a rectangle centered on the origin.
99
+
100
+ `meadow.dispose()` (and its deprecated alias `meadow.destroy()`) is an idempotent teardown: remove the field's compute, grass and optional spore passes before destroying its GPU buffers. The field registers no tick listeners. Both indirect instance counters are cleared with `encoder.clearBuffer()` before each culling dispatch; the compute pass ends before the separate render passes read the compacted lists and indirect arguments.
101
+
102
+ | Option | Default | Meaning |
103
+ | --- | --- | --- |
104
+ | `blades` | `100_000` | Positive integer, bounded by device storage and dispatch limits |
105
+ | `area` | `[50, 50]` | Positive X/Z dimensions, up to 100,000 world units |
106
+ | `bladeHeight` | `1.2` | Positive blade height, up to 100; instances vary from 0.7× to 1.25× |
107
+ | `windSpeed` | `1.2` | Noise scrolling and spore drift speed, 0-100; mutable on the field |
108
+ | `windStrength` | `0.45` | Bend strength, 0-2; mutable on the field |
109
+ | `windDirection` | `[1, 0.35]` | Nonzero X/Z direction, normalized at creation; mutable on the field (assign any nonzero pair) |
110
+ | `drawDistance` | `100` | Positive distance cutoff, up to 100,000 world units |
111
+ | `spores` | `false` | Draw 240 drifting white dandelion particles |
112
+
113
+ The compute pass culls conservative blade bounds against all six camera planes and distance, then compacts two GPU instance lists. Indirect draws use seven-vertex near blades and three-vertex far blades, with stable density thinning beyond 70% of draw distance. The three near segments preserve their lengths during wind bending. Curved normals, root-to-tip color, wrap lighting and backlight transmission use the engine's existing lighting. Grass writes Reversed-Z depth; spores blend additively without writing depth. Both canvas and HDR/post-processing targets are supported.
114
+
115
+ Instance data, uniforms, bind groups and pass descriptors are allocated at creation. The initial pipeline variant is built during setup; additional supported target variants are cached on first use. Stable frames reuse these resources. There is no production CPU visibility readback. Frame rate depends on hardware, resolution and visible density; 60 FPS is a target, not a guarantee. Grass is not a core mesh and does not participate in mesh picking, Stage fitting, section clipping or shadows.
116
+
117
+ Run `npx vite --host 127.0.0.1` from the repository root and open `/examples/windy-meadow.html` for wind, density and seed controls, the optional Sky package's daylight/moonlight and moving clouds, and Bloom's HDR/AgX presentation. The demo uses the shared 4× MSAA desktop default; mobile uses 1× MSAA, a DPR cap of 1 and 35,000 blades, with collapsible settings. Orbit, pinch, keyboard navigation and reset remain available while motion is paused; reduced motion pauses the grass, seeds and clouds. Run `node --test tests/modern-grass.test.js` and `node scripts/modern-grass-tests.js` after building the creative, sky and post packages for the unit and GPU checks.
118
+
119
+ ## Planet
120
+
121
+ The source checkout also exports `Planet` and `PlanetOptions`. Planet is an opt-in WebGPU plugin; neither core nor the Stage facade imports its shaders.
122
+
123
+ ```ts
124
+ import {createStage} from 'margoengine';
125
+ import {Planet} from 'margoengine/creative/planet';
126
+
127
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
128
+ const earth = await Planet.attach(stage.engine, {
129
+ dayMap: '/earth_day.jpg',
130
+ nightMap: '/earth_night.jpg',
131
+ specularRoughnessMap: '/earth_oceans.png',
132
+ clouds: '/earth_clouds.jpg',
133
+ radius: 1,
134
+ tilt: 23.4,
135
+ atmosphere: {color: [0.3, 0.6, 1], intensity: 1.2},
136
+ });
137
+ earth.setSunDirection([-1, 0.2, 0.5]);
138
+ stage.onTick(dt => {
139
+ earth.rotation.y += 0.05 * dt;
140
+ earth.clouds.offsetU += 0.01 * dt;
141
+ });
142
+ window.addEventListener('pagehide', () => stage.dispose(), {once: true});
143
+ ```
144
+
145
+ `Planet.create` loads maps and attaches through the existing `engine.use()` API. It rejects unsupported WebGL2 engines, disposed engines, invalid options, HTTP/decode failures and oversized images. Supply `signal` to cancel creation. Loading is also aborted when the engine or Planet is disposed; failed creation removes its plugin and partial resources. Remove a ready Planet with `earth.dispose()` or `stage.engine.removePlugin(earth.name)`. One Planet is supported per engine.
146
+
147
+ Use `await earth.updateMaps({dayMap, nightMap, specularRoughnessMap, normalMap, clouds, signal})` to replace a ready Planet's complete map set after a preview is visible. The current surface, clouds and atmosphere remain drawable during downloads and decoding; the new set becomes active only after GPU validation. Omitted optional maps use their usual fallbacks. A failed or canceled update keeps the complete previous set, and a second update is rejected while one is pending. The same Planet, transform accessors, tilt, sun and cloud drift survive the swap and device restoration. Distinct committed plus pending decoded images share the 256 MiB budget. Rendering retains the existing linear sampler and single mip level; rebuilding/uploading the replacement pass can still cause a device-dependent hitch.
148
+
149
+ Only `dayMap` is required. All maps accept a URL or string, including relative URLs. `dayMap` and optional `nightMap` are sRGB color; night lights are boosted 3× before tone mapping and fade across twilight (`NdotL` from 0.05 to −0.15). `specularRoughnessMap` is linear data with ocean specular strength in red and roughness in green (0 = smooth, 1 = rough). An omitted map gives matte terrain. Optional `normalMap` is a linear RGB tangent-space normal map (+Y convention); it affects shading, not the silhouette. `clouds` is a linear grayscale coverage map, with black transparent and white opaque. Maps must be equirectangular, north at the top. Downloads are limited to 32 MiB per map; retained decoded maps are limited to 256 MiB in total and the current device's texture dimension limit.
150
+
151
+ Radius defaults to 1, tilt to 23.4 degrees, sun direction to `[-1, 0.2, 0.5]`, and atmosphere color/intensity to `[0.3, 0.6, 1]` / 1.2. `earth.rotation` uses the existing stable transform accessors in radians. `earth.clouds.offsetU` is finite and wraps to `[0, 1)`. `setSunDirection` normalizes a nonzero world-space vector. GPU restoration preserves spin, drift and decoded maps; full disposal closes those images.
152
+
153
+ Rendering adds two indexed draws: a surface with depth writes, then a front-facing cloud/rim shell at `radius * 1.01` that tests scene depth without writing it. Both share retained sphere buffers and use reversed depth. The shell produces geometric cloud parallax; UV drift animates it independently. The atmospheric rim is an analytical Fresnel approximation. Clouds and glow share one altitude, and the camera must remain outside the shell. Textures currently use linear filtering without mipmaps, so distant views can alias. The initial pipeline variant is built during setup; additional supported canvas and HDR target variants are cached on first use. Stable frames reuse these resources, and existing post-processing works with the same attachments.
154
+
155
+ Planet-owned arrays, GPU resources and render-pass descriptors are retained across steady frames. Browser/WebGPU command objects and the rest of the engine can still allocate, and actual FPS depends on the browser, display and GPU. Custom planet draws do not participate in the base `pick()`, `stats.drawCalls`, or `Stage.fit()` APIs; position the camera explicitly and inspect recorded commands for draw counts.
156
+
157
+ ### Earth demo and module checks
158
+
159
+ From the repository root:
160
+
161
+ ```sh
162
+ npm run dev --workspace @margoengine/creative
163
+ # Opens /examples/earth/ in your browser (the dev server has no page at /).
164
+ npm run test --workspace @margoengine/creative
165
+ npm run test:browser --workspace @margoengine/creative
166
+ ```
167
+
168
+ The demo combines Planet's linear HDR surface/cloud/rim output with optional Bloom and AgX tone mapping. It presents a complete local 1k Earth map set first, then atomically upgrades all five maps to 2k on desktop while keeping that preview visible. Mobile keeps the complete 1k set. It includes damped OrbitControls with exterior zoom limits, a switchable procedural starfield, sun direction, independent rotation/cloud speeds, bloom and exposure controls. Desktop uses the shared 4× MSAA default; mobile uses 1× MSAA, a DPR cap of 1 and collapsible settings. Reduced-motion preferences pause rotation and cloud drift and disable navigation damping; keyboard and pinch navigation remain available. [Texture attribution and licenses](examples/earth/assets/ATTRIBUTION.md) travel with the example.
169
+
170
+ The build and prepack commands write only this package's `dist` and license copy. Checks and screenshots write to this package's `test-results`; they use existing core artifacts without rebuilding the base. The browser check uses Edge by default (or installed Playwright Chromium as a fallback); set `BROWSER_CHANNEL` to choose another installed Chromium channel. The unit checks cover loading, lifecycle, validation, resource retention and bundle isolation. The WebGPU checks cover shaders, rendered pixels, depth, HDR and device restoration.
171
+
172
+ This ESM package includes TypeScript declarations, requires `@margoengine/core` 1.0.0 and depends on `@margoengine/vfx` for particles. See the effect options and limitations.
173
+
174
+ Apache-2.0 licensed.
175
+
176
+ ## Texture targets
177
+
178
+ `TextureRenderTarget` adds color-only cube faces, array layers, mip levels and 3D depth slices to the optional
179
+ `/targets` entry. It works on native WebGPU. Passing a WebGL2 engine's `gpu` (null) throws a `MargoError` with
180
+ `code: 'unsupported'` and a help link. It does not capture the core scene; the caller records draws into its pass.
181
+
182
+ ```ts
183
+ import {TextureRenderTarget} from 'margoengine/creative/targets';
184
+
185
+ const adapter = await navigator.gpu.requestAdapter();
186
+ if (!adapter) throw new Error('WebGPU adapter required');
187
+ const device = await adapter.requestDevice();
188
+ const cube = new TextureRenderTarget(device, {kind: 'cube', width: 32, mipLevelCount: 2});
189
+ const encoder = device.createCommandEncoder();
190
+ for (let mip = 0; mip < 2; mip++) {
191
+ for (let layer = 0; layer < 6; layer++) {
192
+ const pass = cube.begin(encoder, {mip, layer, clearColor: [layer / 5, mip, 0, 1]});
193
+ // Set a single-sample rgba8unorm pipeline and draw here, if needed.
194
+ pass.end();
195
+ }
196
+ }
197
+ device.queue.submit([encoder.finish()]);
198
+ await device.queue.onSubmittedWorkDone();
199
+ // cube.view is a cube sampling view; cube.texture supports copyTextureToBuffer.
200
+ cube.dispose();
201
+ device.destroy();
202
+ ```
203
+
204
+ | Option | Default | Range |
205
+ | --- | --- | --- |
206
+ | `kind` | required | `cube`, `array`, `3d` |
207
+ | `width` | required | Positive integer, device maxTextureDimension2D or maxTextureDimension3D |
208
+ | `height` | width | Same limits as width; cube must be square |
209
+ | `depthOrLayers` | 6 for cube, otherwise 1 | Cube fixed at 6; array bounded by maxTextureArrayLayers; 3D by maxTextureDimension3D |
210
+ | `mipLevelCount` | 1 | 1 through the complete mip chain; array layers never shrink, 3D depth does |
211
+ | `format` | `rgba8unorm` | `rgba8unorm` or `rgba16float` |
212
+
213
+ Total logical allocation including mips is capped at 256 MiB. Cube layer order is +X, -X, +Y, -Y, +Z, -Z.
214
+ `mipSize(mip = 0)` returns logical [width, height, depth/layers]. `begin(encoder, surface = {})` selects `mip = 0`
215
+ and `layer = 0` by default. `layer` means face, layer or slice at that mip. `loadOp` defaults to `clear`; `load`
216
+ preserves earlier pixels. `clearColor` defaults to [0, 0, 0, 0], with four finite components in 0..1 for rgba8unorm
217
+ or -65504..65504 for rgba16float. The pass stores its output. Views are cached per surface (per mip for 3D).
218
+ There is no depth attachment, MSAA, automatic camera setup or mip filtering/generation. Sample with the whole
219
+ resource `view` (cube, 2d-array or 3d) after ending its render pass. Texture contents are initially zero.
220
+
221
+ The target owns its texture; `dispose()` and `[Symbol.dispose]()` are idempotent and terminal. After device loss,
222
+ call `restore(newDevice)`, fetch fresh `texture`/`view` handles, rebuild dependent bind groups and redraw every
223
+ surface. Options survive; pixels do not. Restoration validates the new device limits before replacing resources.
224
+ Do not retain surface views or use handles from a lost device. Invalid options and subresources fail before any
225
+ pass is begun. GPU allocation/validation errors still follow WebGPU error scopes.
226
+
227
+ Proof: `node --test --test-timeout=30000 packages/creative/tests/targets.test.js` and
228
+ `node scripts/run-with-timeout.mjs --max=5 -- node packages/creative/scripts/test-targets.js`.
229
+ The generated color fixture checks 78 subresources with full pixel readback, HDR, partial draws with load,
230
+ WebGL2 rejection and replacement-device restoration. Other browser/GPU implementations and speed are unmeasured.
231
+
232
+ ## Painterly post effects
233
+
234
+ Import only `@margoengine/creative/paint` (or `margoengine/creative/paint`). It stays out of the creative root.
235
+ Install the optional `@margoengine/post` peer alongside creative for this entry. Painterly works in display space
236
+ after tonemapping, with no texture or scene input to provide. All options are live and validated each frame.
237
+
238
+ ```ts
239
+ import { Engine } from 'margoengine/core';
240
+ import { Painterly } from 'margoengine/creative/paint';
241
+
242
+ const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
243
+ const engine = await Engine.create(canvas, { backend: 'webgpu' });
244
+ engine.scene.background = '#406080';
245
+ const paint = Painterly.attach(engine, { mode: 'watercolour', radius: 3, strength: 1 });
246
+ engine.start();
247
+ // Live changes: paint.options.mode = 'sketch'; paint.enabled = false;
248
+ // On teardown: paint.dispose(); engine.dispose();
249
+ ```
250
+
251
+ For an existing stack, add `new Painterly(options)` after its display effect using
252
+ `PostStack.attach(engine, [/* HDR/display effects, then */ new Painterly()])` from `@margoengine/post/stack`. On a scene
253
+ that already has a PostStack, `Painterly.attach` and `AnisotropicPainterly.attach` add the effect to it after its last
254
+ LDR effect; disposing the effect takes it out again.
255
+ The stack owns its effects. `Painterly.attach` creates and owns a stack by itself; disposing the returned effect
256
+ releases both. Disposal is terminal, idempotent and supports `using` / `Symbol.dispose`.
257
+
258
+ | Option | Default | Meaning |
259
+ | --- | --- | --- |
260
+ | `mode` | `'kuwahara'` | `'kuwahara'`, `'watercolour'` or `'sketch'` |
261
+ | `radius` | `3` | Integer 1..8 pixels; sketch uses this for gradient spacing |
262
+ | `strength` | `1` | Finite 0..1 blend; zero is an exact input copy |
263
+ | `enabled` | `true` | False is an exact input copy |
264
+
265
+ Kuwahara chooses the mean of the lowest summed RGB-variance quadrant among four overlapping squares, with the
266
+ first quadrant winning equal computed variances. This classic filter can produce square artifacts and flicker on
267
+ noisy near-ties; it is not the anisotropic tensor filter. Watercolour adds eight-level colour quantization, a pale
268
+ wash, Sobel edge darkening and a fixed 17-value paper pattern. Sketch draws Sobel outlines and two diagonal hatch
269
+ families at six-pixel spacing, selected by source luminance. These are single-frame stylizations, not fluid,
270
+ pigment or pencil simulations. Each preserves the centre alpha, clamps neighbours to its viewport and keeps
271
+ uniforms separate per view. RGB is filtered as supplied by the LDR stack, without alpha-weighted filtering.
272
+
273
+ WebGPU only; native WebGL2 throws coded `unsupported` with a help link. Invalid options throw linked RangeError;
274
+ attachment/state/disposal errors are coded. Device restoration rebuilds GPU resources automatically through the
275
+ stack. A maximum-radius Kuwahara or watercolour pixel reads 324 neighbourhood samples plus the centre (watercolour
276
+ also reads eight Sobel neighbours); sketch reads eight neighbours plus the centre. Entry: 7504 B minified,
277
+ 3073 B gzip with bare dependencies external. No speed, aesthetic quality or other-device claim. Tests use
278
+ generated images as stand-ins on a real RTX A6000, against an independent CPU pixel reference. Run
279
+ `npm run test:gpu:paint --workspace @margoengine/creative`.
280
+
281
+ ### Attaching from a second scene
282
+
283
+ `createTerrainGrass` remembers the scene that is active when you call it, before its first await, and joins that scene when it finishes. Start it inside a second scene's plugin `setup` and the plugin belongs to that scene; start it anywhere else and it belongs to the default scene. An abort or a failure leaves nothing in either scene.
284
+
285
+ ## Sliders: `@margoengine/creative/grass-settings`
286
+
287
+ `GrassField` keeps its blade height, reach, density, wind, blade colours and back-light in its frame uniform and rewrites it every frame, so they change while the scene runs. The setters are `bladeHeight`, `drawDistance`, `density` (0 to 1: the kept fraction of blades, the same blades each time), `windSpeed`, `windStrength`, `windDirection`, `rootColor`, `tipColor`, `tipVariantColor`, `translucencyColor` and `translucency` (0 to 4, default 0.4). `@margoengine/creative/grass-settings` lists them as a table for sliders and panels: `GRASS_SETTINGS` has 12 rows (each has `name`, `group`, `kind`, `default`, `min`, `max`, `step`, `unit`, `about` and `live`), all `live`. `applyGrassSettings(grass, values)` writes a set of values (a name left out takes its default), and `GRASS_LOOKS` names `natural`, `dry` and `windy`. An unknown name throws `TypeError`, a value outside its row `RangeError`, and a wind direction of 0 and 0 `RangeError`. The defaults are the colours and strength the shader had as constants, so a field with no settings draws as before. Not rows: blade count, area and spores (they size buffers at construction). Proof on a real GPU (`npm run test:settings:browser`, native WebGPU and the WebGL2 layer): the defaults written draw the frame exact, 60 frames of every row create no pipeline, buffer or texture, and the last frame equals writing the values once.
288
+
289
+ ```ts
290
+ import {Engine} from 'margoengine/core';
291
+ import {GrassField} from 'margoengine/creative/grass';
292
+ import {GRASS_LOOKS, applyGrassSettings} from 'margoengine/creative/grass-settings';
293
+
294
+ const engine = await Engine.create(document.querySelector('canvas')!, {backend: 'webgpu'});
295
+ const meadow = GrassField.attach(engine, {blades: 60000, area: [30, 30]});
296
+ let time = 0;
297
+ engine.onFrame((_, delta) => {
298
+ time += delta;
299
+ // The meadow dries out over the shot.
300
+ const dry = Math.min(time / 6, 1);
301
+ applyGrassSettings(meadow, {...GRASS_LOOKS.dry, 'field.density': 1 - 0.3 * dry, 'translucency.strength': 0.4 + dry});
302
+ });
303
+ ```
304
+
305
+ ## Core compatibility at engine boundaries
306
+
307
+ Each engine-bound entry (`.`, `/paint`, `/paint-aniso`, `/particles`, `/toon`, `/post`, `/grass`, `/grass-terrain`, `/planet`, `/planet-atmosphere` and `/stars`) carries the core version its build was made for, stamped into its plugins and `engineRuntime` calls, and checks the engine's core when it attaches or its plugin is set up, before it reads or changes the engine. A mismatched core version, or a second core module in the page (two installs, or one bundled twice), throws MargoError `'version'` naming both cores and the package, with the help link https://margoengine.com/errors#version. The cure is one core: dedupe or rebuild the packages against the same core build (`npm ls @margoengine/core` lists the copies); do not catch the error and go on. The check keeps no global state, and importing an entry registers nothing and attaches nothing. Details: [One core per engine](../core/README.md#one-core-per-engine-version-checks-extension) in the core README. `/targets`, `/targets-depth` and `/grass-settings` are engine-free: they hold settings tables and render-target descriptions, carry no check and run without an engine.
308
+
309
+ ## Preview tier contract
310
+
311
+ GPU-only attachments refuse the small WebGL2 preview during setup with `MargoError` code `unsupported` and a help link. Native WebGPU and the full WebGL2 compatibility layer expose the WebGPU-shaped device these passes need. Use [automatic escalation](../webgl2-compat/README.md#automatic-escalation) with awaited setup to load the full layer when required. Existing real preview routes remain available.