@margoengine/creative 0.0.0-stage → 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.
Files changed (47) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +310 -2
  4. package/dist/display-C6RC-F2-.js +3 -0
  5. package/dist/errors-XvcwUnU4.js +7 -0
  6. package/dist/gpu-DaSofAeP.js +30 -0
  7. package/dist/grass-OkjgCaF7.js +450 -0
  8. package/dist/grass-settings.d.ts +63 -0
  9. package/dist/grass-settings.js +131 -0
  10. package/dist/grass-terrain.d.ts +33 -0
  11. package/dist/grass-terrain.js +185 -0
  12. package/dist/grass.d.ts +106 -0
  13. package/dist/grass.js +1 -0
  14. package/dist/hdr-format-DXpjc3bW.js +4 -0
  15. package/dist/index.d.ts +7 -0
  16. package/dist/index.js +8 -0
  17. package/dist/msaa-8hWFieoE.js +220 -0
  18. package/dist/paint-aniso.d.ts +36 -0
  19. package/dist/paint-aniso.js +217 -0
  20. package/dist/paint.d.ts +56 -0
  21. package/dist/paint.js +167 -0
  22. package/dist/particles.d.ts +38 -0
  23. package/dist/particles.js +79 -0
  24. package/dist/pass-B5mPip-t.js +27 -0
  25. package/dist/planet-BYTix5S1.js +505 -0
  26. package/dist/planet-atmosphere.d.ts +37 -0
  27. package/dist/planet-atmosphere.js +196 -0
  28. package/dist/planet-pass.d.ts +47 -0
  29. package/dist/planet.d.ts +76 -0
  30. package/dist/planet.js +1 -0
  31. package/dist/post.d.ts +108 -0
  32. package/dist/post.js +265 -0
  33. package/dist/quality-DFm-cQWC.js +7 -0
  34. package/dist/shared/settings.d.ts +89 -0
  35. package/dist/stars-C0SH8-aJ.js +90 -0
  36. package/dist/stars.d.ts +34 -0
  37. package/dist/stars.js +1 -0
  38. package/dist/targets-depth.d.ts +35 -0
  39. package/dist/targets-depth.js +169 -0
  40. package/dist/targets.d.ts +35 -0
  41. package/dist/targets.js +42 -0
  42. package/dist/texture-target-CGqE9pOa.js +131 -0
  43. package/dist/texture-target.d.ts +49 -0
  44. package/dist/toon.d.ts +32 -0
  45. package/dist/toon.js +58 -0
  46. package/dist/view-rect-TO68f_UR.js +48 -0
  47. package/package.json +124 -4
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,311 @@
1
- # Temporary Holding Version
1
+ # @margoengine/creative
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
@@ -0,0 +1,3 @@
1
+ var e = "fn pbrNeutral(input:vec3f)->vec3f {let x=min(input.r,min(input.g,input.b));let offset=select(0.04,x-6.25*x*x,x<0.08);var v=input-offset;let peak=max(v.r,max(v.g,v.b));if(peak<0.76){return v;}let newPeak=1.0-0.24*0.24/(peak+0.24-0.76);v*=newPeak/peak;return mix(v,vec3f(newPeak),1.0-1.0/(0.15*(peak-newPeak)+1.0));}\nfn toDisplay(c:vec3f)->vec3f {let x=pbrNeutral(max(c,vec3f(0)));return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308));}\n", t = /let mapped=pbrNeutral\([\s\S]*?return vec4f\([^\n]+\);/, n = (e) => e.replace(t, "return vec4f(linear,1);");
2
+ //#endregion
3
+ export { n, e as t };
@@ -0,0 +1,7 @@
1
+ //#region ../shared/errors.js
2
+ var e = (e, t) => Object.assign(Error(t), {
3
+ name: "MargoError",
4
+ code: e
5
+ }), t = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, n = (n, r, i = n) => e(n, t(r, i)), r = (e, n) => RangeError(t(e, n));
6
+ //#endregion
7
+ export { e as n, r, n as t };
@@ -0,0 +1,30 @@
1
+ import "./msaa-8hWFieoE.js";
2
+ //#region ../shared/gpu.js
3
+ var e = "\nstruct Vertex { @builtin(position) position:vec4f,@location(0) uv:vec2f }\n@vertex fn vertex(@builtin(vertex_index) index:u32)->Vertex {\n let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[index];\n return Vertex(vec4f(p,0,1),vec2f(p.x*0.5+0.5,0.5-p.y*0.5));\n}";
4
+ function t(e, t, n) {
5
+ return e.createBindGroup({
6
+ layout: t.getBindGroupLayout(0),
7
+ entries: n.map((e, t) => ({
8
+ binding: t,
9
+ resource: e
10
+ }))
11
+ });
12
+ }
13
+ function n(e, t, n, r = {}) {
14
+ let i = e.createShaderModule({ code: t });
15
+ return e.createRenderPipeline({
16
+ layout: "auto",
17
+ vertex: {
18
+ module: i,
19
+ entryPoint: "vertex"
20
+ },
21
+ fragment: {
22
+ module: i,
23
+ entryPoint: "fragment",
24
+ targets: [{ format: n }]
25
+ },
26
+ ...r
27
+ });
28
+ }
29
+ //#endregion
30
+ export { t as n, n as r, e as t };