@null3d/particles 0.0.0-stage → 0.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/LICENSE-APACHE ADDED
@@ -0,0 +1,176 @@
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
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ramesh Nair
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/lib/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export type { EmitterShape, ParticleBurst, ParticleRange, ParticleSystemOptions, SubEmitter, } from './system.js';
2
+ export { createParticles, ParticleSystem } from './system.js';
3
+ export type { ParticleTexture, ParticleTextureOptions } from './textures.js';
4
+ export { particleTextures } from './textures.js';
package/lib/index.js ADDED
@@ -0,0 +1,8 @@
1
+ // GPU particle systems for null3D sketches: emitters with shapes, rates, bursts and sub-emitters
2
+ // that fill the engine's particle buffers, and particle textures made in code. The GPU moves each
3
+ // particle in closed form, so no pass simulates them, and the same systems run on WebGPU and WebGL2.
4
+ import { checkAddonVersion } from '@null3d/engine';
5
+ import { VERSION } from './version.js';
6
+ checkAddonVersion('@null3d/particles', VERSION);
7
+ export { createParticles, ParticleSystem } from './system.js';
8
+ export { particleTextures } from './textures.js';
@@ -0,0 +1,184 @@
1
+ import type { Mesh, Object3D, ParticleBuffer, ParticleBufferOptions, ParticleValues, SketchContext, Vec3Like } from '@null3d/engine';
2
+ /**
3
+ * A number, or the smallest and the largest of a random number.
4
+ *
5
+ * @category api/particles
6
+ */
7
+ export type ParticleRange = number | readonly [number, number];
8
+ /**
9
+ * Where an emitter's particles are born, in its own space, and which way they set off. A `point`
10
+ * emits at the emitter, along `direction`. A `sphere` emits inside a ball of `radius`, or on its
11
+ * surface with `surface`, and sends particles outward. A `cone` emits on a disc of `radius` across
12
+ * the emitter's +y axis. It sends particles up within `angle` radians of that axis, as a fountain
13
+ * or a flame does. A `box` emits inside a box of `size`, centered on the emitter, along
14
+ * `direction`. A `disc` emits on a disc of `radius` across the +y axis, along `direction`.
15
+ *
16
+ * @category api/particles
17
+ */
18
+ export type EmitterShape = {
19
+ type: 'point';
20
+ } | {
21
+ type: 'sphere';
22
+ radius: number;
23
+ surface?: boolean;
24
+ } | {
25
+ type: 'cone';
26
+ radius: number;
27
+ angle: number;
28
+ } | {
29
+ type: 'box';
30
+ size: Vec3Like;
31
+ } | {
32
+ type: 'disc';
33
+ radius: number;
34
+ };
35
+ /**
36
+ * A burst: `count` particles at once, at `time` seconds after the system starts, then every
37
+ * `interval` seconds, `cycles` times in all.
38
+ *
39
+ * @category api/particles
40
+ */
41
+ export interface ParticleBurst {
42
+ /** Seconds after the system starts. */
43
+ time: number;
44
+ /** The particles of each burst. */
45
+ count: number;
46
+ /** Seconds between bursts. Without it, the burst happens once, or once per loop of a looping system. */
47
+ interval?: number;
48
+ /** How many bursts, with `interval`. The default is no limit. */
49
+ cycles?: number;
50
+ }
51
+ /**
52
+ * A sub-emitter: another system that bursts where a particle of this system dies or first meets
53
+ * the ground. A firework's rocket bursts into sparks this way, and a raindrop splashes.
54
+ *
55
+ * @category api/particles
56
+ */
57
+ export interface SubEmitter {
58
+ /** The system that bursts. */
59
+ system: ParticleSystem;
60
+ /** `death` at the end of the particle's life, or `ground` where it first meets the ground. */
61
+ on: 'death' | 'ground';
62
+ /** The particles of each burst. */
63
+ count: number;
64
+ /** The share of the particle's velocity that the burst's particles take on. The default is 0. */
65
+ inheritVelocity?: number;
66
+ }
67
+ /**
68
+ * Options of `createParticles`: the emitter, then the engine's particle buffer options, which give
69
+ * the motion and the look.
70
+ *
71
+ * @category api/particles
72
+ */
73
+ export interface ParticleSystemOptions extends Omit<ParticleBufferOptions, 'capacity'> {
74
+ /**
75
+ * The most particles alive at once. The default fits the rate and the bursts over the longest
76
+ * lifetime. A system past its capacity reuses the oldest particles' places.
77
+ */
78
+ capacity?: number;
79
+ /** Where the system sits in the world, or under `parent`. The default is the origin. */
80
+ position?: Vec3Like;
81
+ /** The object that the system moves with, as a child of it. The default is the scene's root. */
82
+ parent?: Object3D;
83
+ /**
84
+ * An object to emit from, in place of the system's own place. Its particles stay in the world
85
+ * where they were born, so a moving emitter leaves a trail, as smoke from a torch does. Without
86
+ * it, particles move with the system's object.
87
+ */
88
+ follow?: Object3D;
89
+ /** Where the particles are born. The default is a point. */
90
+ shape?: EmitterShape;
91
+ /** The way particles set off from a point, box or disc, in the emitter's space. The default is up. */
92
+ direction?: Vec3Like;
93
+ /** How far from `direction` particles set off at random, in radians. The default is 0. */
94
+ spread?: number;
95
+ /** The start speed, in meters per second. The default is 1. */
96
+ speed?: ParticleRange;
97
+ /** A velocity that every particle adds to its own at birth, in meters per second. */
98
+ velocity?: Vec3Like;
99
+ /** How long each particle lives, in seconds. The default is 1. */
100
+ lifetime?: ParticleRange;
101
+ /** Particles born per second. The default is 0. */
102
+ rate?: number;
103
+ /** Bursts of particles at set times. */
104
+ bursts?: readonly ParticleBurst[];
105
+ /**
106
+ * Seconds that the system emits for. With `loop`, it starts again after it; without, it stops.
107
+ * The default is no end.
108
+ */
109
+ duration?: number;
110
+ /** True to start again after `duration`. The default is true. */
111
+ loop?: boolean;
112
+ /** True to start as if the system had run for its longest lifetime already. The default is false. */
113
+ prewarm?: boolean;
114
+ /** Systems that burst where this system's particles die or meet the ground. */
115
+ subEmitters?: readonly SubEmitter[];
116
+ /** The seed of the system's random numbers. Systems with the same seed emit the same particles. */
117
+ seed?: number;
118
+ }
119
+ /**
120
+ * A particle system: an emitter that fills a particle buffer. `createParticles` makes one. Call
121
+ * `update()` once per frame, in `onLateUpdate`, where objects' world places are the frame's.
122
+ *
123
+ * @category api/particles
124
+ */
125
+ export declare class ParticleSystem {
126
+ protected constructor();
127
+ /** The engine's particle buffer that the system fills, with its scene object. */
128
+ readonly buffer: ParticleBuffer;
129
+ private readonly clock;
130
+ /** Particles born per second, which may change at any time. */
131
+ rate: number;
132
+ /** False to stop emitting, as the rate and the bursts say; live particles live out their lives. */
133
+ emitting: boolean;
134
+ /** Seconds since the system started, as `update` adds them up. */
135
+ time: number;
136
+ private readonly lifetime;
137
+ private readonly options;
138
+ /** True once the system is destroyed, so a parent's events skip it. */
139
+ private destroyed;
140
+ /** The followed object's world matrix in this frame and the frame before, and the system's inverse. */
141
+ private readonly emitter;
142
+ private readonly lastEmitter;
143
+ private readonly toLocal;
144
+ private hasLast;
145
+ /** This system's world matrix, and each sub-emitter's inverse world matrix. */
146
+ private readonly world;
147
+ private readonly childMatrices;
148
+ /** The frame's numbers: its start and end, its rate, and its two flags. */
149
+ private readonly frame;
150
+ /** The system's scene object: place, layers, visibility and bounds. */
151
+ get object(): Mesh;
152
+ /** Changes the motion and the look from the next frame on, as the options name them. */
153
+ set(values: ParticleValues): void;
154
+ /**
155
+ * Moves the system on by the frame's step, or by `dt` seconds: emits the particles born in that
156
+ * time, fires the sub-emitters of particles that died or met the ground, and gives the buffer
157
+ * its time. The core writes the records in one call, so `update` runs no loop over the births.
158
+ * Call it once per frame in `onLateUpdate`. It allocates nothing. A system with a `windField`
159
+ * also gives the core the field's current box and layer, so call the wind's `update()` before
160
+ * this call.
161
+ */
162
+ update(dt?: number): void;
163
+ /**
164
+ * Emits `count` particles at once, at the emitter, or at `at` in the system's space with the
165
+ * shape's spread around it. Each particle adds `velocity` to its own start velocity, in place of
166
+ * the system's `velocity` option. The core writes the records.
167
+ */
168
+ burst(count: number, at?: Vec3Like, velocity?: Vec3Like): void;
169
+ /** Reads the followed object's matrices for the frame's births. */
170
+ private readFollow;
171
+ /** Reads this system's world matrix and each sub-emitter's inverse world matrix. */
172
+ private readEvents;
173
+ /** Removes the system and its particles from the scene. */
174
+ destroy(): void;
175
+ }
176
+ /**
177
+ * Makes a particle system in the sketch's scene: an emitter, and the engine's particle buffer that
178
+ * it fills. Call the system's `update()` once per frame in `onLateUpdate`. The first system
179
+ * downloads the engine's particle code. Throws E1108 for a capacity out of range, and E1406 when
180
+ * the particle code does not download.
181
+ *
182
+ * @category api/particles
183
+ */
184
+ export declare function createParticles(context: SketchContext, options: ParticleSystemOptions): Promise<ParticleSystem>;
package/lib/system.js ADDED
@@ -0,0 +1,210 @@
1
+ // Particle systems: an emitter that fills one of the engine's particle buffers. The emitter's
2
+ // settings go to the engine's core once, and each frame the system gives the core the frame's
3
+ // span and its rate. The core makes every record of the frame, plans and fires the sub-emitters,
4
+ // and moves the time base, so the sketch starts the frame and reads settings but runs no loop over
5
+ // the births. The GPU does the rest: each particle moves, turns, changes color and dies in closed
6
+ // form, so a system of a million particles costs the CPU only its births.
7
+ //
8
+ // `update` allocates nothing: its numbers move through typed arrays and fields, never as the
9
+ // arguments or the results of calls that the engine may not inline, which would box them.
10
+ //
11
+ // Birth times are 32-bit floats on the GPU, so every 1,024 seconds a system moves the time that
12
+ // its buffer's time counts from. The core rewrites the records' birth times a share at a time,
13
+ // over many frames, and the GPU takes the move off the birth times of the records that the
14
+ // rewrite has not reached.
15
+ import { mat4 } from '@null3d/engine';
16
+ /** The thread's identity matrix, for a sub-emitter whose object is gone. */
17
+ const IDENTITY = new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
18
+ /** The smallest and the largest of a range. */
19
+ function span(range, fallback) {
20
+ if (range === undefined)
21
+ return [fallback, fallback];
22
+ return typeof range === 'number' ? [range, range] : range;
23
+ }
24
+ /**
25
+ * A particle system: an emitter that fills a particle buffer. `createParticles` makes one. Call
26
+ * `update()` once per frame, in `onLateUpdate`, where objects' world places are the frame's.
27
+ *
28
+ * @category api/particles
29
+ */
30
+ export class ParticleSystem {
31
+ buffer;
32
+ clock;
33
+ /** Particles born per second, which may change at any time. */
34
+ rate;
35
+ /** False to stop emitting, as the rate and the bursts say; live particles live out their lives. */
36
+ emitting = true;
37
+ /** Seconds since the system started, as `update` adds them up. */
38
+ time = 0;
39
+ lifetime;
40
+ options;
41
+ /** True once the system is destroyed, so a parent's events skip it. */
42
+ destroyed = false;
43
+ /** The followed object's world matrix in this frame and the frame before, and the system's inverse. */
44
+ emitter = new Float64Array(16);
45
+ lastEmitter = new Float64Array(16);
46
+ toLocal = new Float64Array(16);
47
+ hasLast = false;
48
+ /** This system's world matrix, and each sub-emitter's inverse world matrix. */
49
+ world = new Float64Array(16);
50
+ childMatrices;
51
+ /** The frame's numbers: its start and end, its rate, and its two flags. */
52
+ frame = new Float64Array(5);
53
+ /** @internal */
54
+ constructor(
55
+ /** The engine's particle buffer that the system fills, with its scene object. */
56
+ buffer, options, clock) {
57
+ this.buffer = buffer;
58
+ this.clock = clock;
59
+ this.options = options;
60
+ this.rate = options.rate ?? 0;
61
+ this.lifetime = span(options.lifetime, 1);
62
+ const subs = options.subEmitters ?? [];
63
+ this.childMatrices = subs.map(() => new Float64Array(16));
64
+ buffer.configureEmitter({
65
+ seed: options.seed ?? 1,
66
+ shape: options.shape,
67
+ direction: options.direction,
68
+ spread: options.spread,
69
+ speed: span(options.speed, 1),
70
+ velocity: options.velocity,
71
+ lifetime: this.lifetime,
72
+ bursts: options.bursts,
73
+ duration: options.duration,
74
+ loop: options.loop ?? true,
75
+ follow: options.follow !== undefined,
76
+ subEmitters: subs.map((sub) => ({
77
+ buffer: sub.system.buffer,
78
+ on: sub.on,
79
+ count: sub.count,
80
+ inheritVelocity: sub.inheritVelocity,
81
+ })),
82
+ });
83
+ }
84
+ /** The system's scene object: place, layers, visibility and bounds. */
85
+ get object() {
86
+ return this.buffer.object;
87
+ }
88
+ /** Changes the motion and the look from the next frame on, as the options name them. */
89
+ set(values) {
90
+ this.buffer.set(values);
91
+ }
92
+ /**
93
+ * Moves the system on by the frame's step, or by `dt` seconds: emits the particles born in that
94
+ * time, fires the sub-emitters of particles that died or met the ground, and gives the buffer
95
+ * its time. The core writes the records in one call, so `update` runs no loop over the births.
96
+ * Call it once per frame in `onLateUpdate`. It allocates nothing. A system with a `windField`
97
+ * also gives the core the field's current box and layer, so call the wind's `update()` before
98
+ * this call.
99
+ */
100
+ update(dt) {
101
+ let prewarm = false;
102
+ if (this.time === 0 && this.buffer.emitted === 0 && this.options.prewarm) {
103
+ // A prewarmed system emits its first span of the longest lifetime at once.
104
+ prewarm = true;
105
+ this.time = this.lifetime[1];
106
+ }
107
+ // The frame's numbers move through the typed array, as the old body's did: no fraction
108
+ // waits in a local across Math.max or a call, where the browser boxes it.
109
+ const frame = this.frame;
110
+ frame[0] = this.time;
111
+ frame[1] = this.clock.dt;
112
+ if (dt !== undefined)
113
+ frame[1] = dt;
114
+ frame[1] = frame[0] + Math.max(frame[1], 0);
115
+ frame[2] = this.rate;
116
+ frame[3] = this.emitting ? 1 : 0;
117
+ frame[4] = prewarm ? 1 : 0;
118
+ this.time = frame[1];
119
+ this.readFollow();
120
+ this.readEvents();
121
+ // The field's box follows the camera and its newest layer moves, so the core gets the field
122
+ // in every frame, before the births whose events it places.
123
+ if (this.options.windField)
124
+ this.buffer.setWind(this.options.windField, this.clock.now);
125
+ this.buffer.emitFrame(frame);
126
+ }
127
+ /**
128
+ * Emits `count` particles at once, at the emitter, or at `at` in the system's space with the
129
+ * shape's spread around it. Each particle adds `velocity` to its own start velocity, in place of
130
+ * the system's `velocity` option. The core writes the records.
131
+ */
132
+ burst(count, at, velocity) {
133
+ this.buffer.emitBurst(count, at, velocity);
134
+ }
135
+ /** Reads the followed object's matrices for the frame's births. */
136
+ readFollow() {
137
+ const follow = this.options.follow;
138
+ if (!follow)
139
+ return;
140
+ if (this.hasLast)
141
+ this.lastEmitter.set(this.emitter);
142
+ follow.getWorldMatrix(this.emitter);
143
+ this.buffer.object.getWorldMatrix(this.toLocal);
144
+ mat4.invert(this.toLocal, this.toLocal);
145
+ if (!this.hasLast) {
146
+ this.lastEmitter.set(this.emitter);
147
+ this.hasLast = true;
148
+ }
149
+ this.buffer.setEmitterFollow(this.lastEmitter, this.emitter, this.toLocal);
150
+ }
151
+ /** Reads this system's world matrix and each sub-emitter's inverse world matrix. */
152
+ readEvents() {
153
+ const subs = this.options.subEmitters;
154
+ if (!subs || subs.length === 0)
155
+ return;
156
+ this.buffer.object.getWorldMatrix(this.world);
157
+ for (let k = 0; k < subs.length; k++) {
158
+ const child = subs[k];
159
+ const local = this.childMatrices[k];
160
+ if (child.system.destroyed) {
161
+ local.set(IDENTITY);
162
+ continue;
163
+ }
164
+ child.system.object.getWorldMatrix(local);
165
+ mat4.invert(local, local);
166
+ }
167
+ this.buffer.setEmitterEvents(this.world, this.childMatrices);
168
+ }
169
+ /** Removes the system and its particles from the scene. */
170
+ destroy() {
171
+ this.destroyed = true;
172
+ this.buffer.destroy();
173
+ }
174
+ }
175
+ /** The capacity that fits a system's rate and bursts over its longest lifetime. */
176
+ function defaultCapacity(options) {
177
+ const [, longest] = span(options.lifetime, 1);
178
+ let bursts = 0;
179
+ for (const burst of options.bursts ?? []) {
180
+ const repeats = burst.interval ? Math.ceil(longest / burst.interval) + 1 : 1;
181
+ bursts += burst.count * repeats;
182
+ }
183
+ const rate = (options.rate ?? 0) * longest;
184
+ return Math.max(16, Math.ceil(rate * 1.1 + bursts + 1));
185
+ }
186
+ /**
187
+ * Makes a particle system in the sketch's scene: an emitter, and the engine's particle buffer that
188
+ * it fills. Call the system's `update()` once per frame in `onLateUpdate`. The first system
189
+ * downloads the engine's particle code. Throws E1108 for a capacity out of range, and E1406 when
190
+ * the particle code does not download.
191
+ *
192
+ * @category api/particles
193
+ */
194
+ export async function createParticles(context, options) {
195
+ const capacity = options.capacity ?? defaultCapacity(options);
196
+ const buffer = await context.scene.createParticleBuffer({ ...options, capacity });
197
+ const { object } = buffer;
198
+ if (options.parent)
199
+ object.setParent(options.parent);
200
+ const position = options.position;
201
+ if (position)
202
+ object.setPosition(position[0], position[1], position[2]);
203
+ else if (options.follow) {
204
+ // The system sits where the followed object starts, so its particles' places stay small.
205
+ const place = [0, 0, 0];
206
+ options.follow.getWorldPosition(place);
207
+ object.setPosition(place[0], place[1], place[2]);
208
+ }
209
+ return new ParticleSystem(buffer, options, context.time);
210
+ }
@@ -0,0 +1,50 @@
1
+ import type { ParticleFlipbook, Texture, Textures } from '@null3d/engine';
2
+ /**
3
+ * A particle texture made in code, and its flipbook, which `createParticles` takes in its options:
4
+ * `{ ...particleTextures.smoke(textures), ... }`.
5
+ *
6
+ * @category api/particles
7
+ */
8
+ export interface ParticleTexture {
9
+ /** The texture: white or light shades, with alpha. */
10
+ map: Texture;
11
+ /** Its frames. */
12
+ flipbook: ParticleFlipbook;
13
+ }
14
+ /**
15
+ * Options of the particle textures made in code.
16
+ *
17
+ * @category api/particles
18
+ */
19
+ export interface ParticleTextureOptions {
20
+ /** Texels along each side of one frame. The default suits the texture, from 32 to 64. */
21
+ size?: number;
22
+ /** The seed of the texture's random shapes. The default is 1. */
23
+ seed?: number;
24
+ }
25
+ /**
26
+ * Particle textures made in code. Each takes the sketch's `textures` and returns a texture with
27
+ * its flipbook.
28
+ *
29
+ * @category api/particles
30
+ */
31
+ export declare const particleTextures: {
32
+ /** A soft glow with a bright core, for fireflies, embers and magic. */
33
+ glow(textures: Textures, options?: ParticleTextureOptions): ParticleTexture;
34
+ /** A streak, bright along its middle, for sparks and tracers. Use it with the `velocity` facing. */
35
+ spark(textures: Textures, options?: ParticleTextureOptions): ParticleTexture;
36
+ /**
37
+ * Sixteen frames of a smoke puff that billows and thins, for smoke, dust and steam. It plays
38
+ * once over each particle's life.
39
+ */
40
+ smoke(textures: Textures, options?: ParticleTextureOptions): ParticleTexture;
41
+ /** Sixteen frames of a flickering flame tongue, for fires, torches and jets. It plays at 24 frames per second. */
42
+ flame(textures: Textures, options?: ParticleTextureOptions): ParticleTexture;
43
+ /** A thin raindrop streak, for rain. Use it with the `velocity` facing. */
44
+ rain(textures: Textures, options?: ParticleTextureOptions): ParticleTexture;
45
+ /**
46
+ * Four leaves of different shapes, each with a midrib and veins, for falling leaves and petals.
47
+ * Each particle keeps one leaf: give the system a random first frame that holds.
48
+ */
49
+ leaves(textures: Textures, options?: ParticleTextureOptions): ParticleTexture;
50
+ };
@@ -0,0 +1,153 @@
1
+ // Particle textures made in code, so a page downloads no image for them: soft glows, sparks, smoke
2
+ // puffs that billow and thin over a flipbook, flame tongues, raindrops and leaves. Each one is white,
3
+ // or a light shade, with its alpha, so a system's colors tint it. Each function returns the texture
4
+ // and its flipbook, which a system's options take as they are.
5
+ /** A hash of three whole numbers to a number from 0 up to 1. */
6
+ function hash3(x, y, z) {
7
+ let h = Math.imul(x, 374761393) ^ Math.imul(y, 668265263) ^ Math.imul(z, 2147483647);
8
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
9
+ return ((h ^ (h >>> 16)) >>> 8) / 16777216;
10
+ }
11
+ /** Smooth value noise in 3D, from 0 to 1. */
12
+ function noise(x, y, z) {
13
+ const ix = Math.floor(x);
14
+ const iy = Math.floor(y);
15
+ const iz = Math.floor(z);
16
+ const fx = x - ix;
17
+ const fy = y - iy;
18
+ const fz = z - iz;
19
+ const ux = fx * fx * (3 - 2 * fx);
20
+ const uy = fy * fy * (3 - 2 * fy);
21
+ const uz = fz * fz * (3 - 2 * fz);
22
+ const lerp = (a, b, t) => a + (b - a) * t;
23
+ const plane = (z0) => lerp(lerp(hash3(ix, iy, z0), hash3(ix + 1, iy, z0), ux), lerp(hash3(ix, iy + 1, z0), hash3(ix + 1, iy + 1, z0), ux), uy);
24
+ return lerp(plane(iz), plane(iz + 1), uz);
25
+ }
26
+ /** Fractal noise of four octaves, from about 0 to 1. */
27
+ function fbm(x, y, z) {
28
+ let sum = 0;
29
+ let amplitude = 0.5;
30
+ let scale = 1;
31
+ for (let k = 0; k < 4; k++) {
32
+ sum += amplitude * noise(x * scale, y * scale, z * scale + k * 17.1);
33
+ amplitude *= 0.5;
34
+ scale *= 2.03;
35
+ }
36
+ return sum / 0.9375;
37
+ }
38
+ /** A value from 0 to 1 that eases from 0 at `a` to 1 at `b`. */
39
+ function smooth(a, b, x) {
40
+ const t = Math.min(Math.max((x - a) / (b - a), 0), 1);
41
+ return t * t * (3 - 2 * t);
42
+ }
43
+ /**
44
+ * Makes a texture of `columns` by `rows` frames of `size` texels each. `shade` gives a frame's
45
+ * texel at (u, v), each from -1 to 1 with v up, as [light, alpha] from 0 to 1.
46
+ */
47
+ function atlas(textures, columns, rows, size, shade, flipbook = {}) {
48
+ const width = columns * size;
49
+ const height = rows * size;
50
+ const data = new Uint8Array(width * height * 4);
51
+ const out = new Float32Array(2);
52
+ for (let frame = 0; frame < columns * rows; frame++) {
53
+ const cx = (frame % columns) * size;
54
+ // Frame 0 is the top left one, and the first row of texels is the image's bottom.
55
+ const cy = (rows - 1 - Math.floor(frame / columns)) * size;
56
+ for (let y = 0; y < size; y++)
57
+ for (let x = 0; x < size; x++) {
58
+ shade(frame, ((x + 0.5) / size) * 2 - 1, ((y + 0.5) / size) * 2 - 1, out);
59
+ const at = ((cy + y) * width + cx + x) * 4;
60
+ const light = Math.round(Math.min(Math.max(out[0], 0), 1) * 255);
61
+ data[at] = light;
62
+ data[at + 1] = light;
63
+ data[at + 2] = light;
64
+ data[at + 3] = Math.round(Math.min(Math.max(out[1], 0), 1) * 255);
65
+ }
66
+ }
67
+ const map = textures.fromData({ width, height, data, mipmaps: true, wrap: 'clamp' });
68
+ return { map, flipbook: { columns, rows, ...flipbook } };
69
+ }
70
+ /**
71
+ * Particle textures made in code. Each takes the sketch's `textures` and returns a texture with
72
+ * its flipbook.
73
+ *
74
+ * @category api/particles
75
+ */
76
+ export const particleTextures = {
77
+ /** A soft glow with a bright core, for fireflies, embers and magic. */
78
+ glow(textures, options = {}) {
79
+ return atlas(textures, 1, 1, options.size ?? 64, (_, u, v, out) => {
80
+ const r = Math.hypot(u, v);
81
+ out[0] = 1;
82
+ out[1] = Math.exp(-r * r * 9) * 0.85 + Math.max(0, 1 - r) ** 4 * 0.15;
83
+ });
84
+ },
85
+ /** A streak, bright along its middle, for sparks and tracers. Use it with the `velocity` facing. */
86
+ spark(textures, options = {}) {
87
+ return atlas(textures, 1, 1, options.size ?? 32, (_, u, v, out) => {
88
+ const across = Math.exp(-u * u * 18);
89
+ const along = smooth(1, 0.2, Math.abs(v));
90
+ out[0] = 1;
91
+ out[1] = across * along;
92
+ });
93
+ },
94
+ /**
95
+ * Sixteen frames of a smoke puff that billows and thins, for smoke, dust and steam. It plays
96
+ * once over each particle's life.
97
+ */
98
+ smoke(textures, options = {}) {
99
+ const seed = options.seed ?? 1;
100
+ return atlas(textures, 4, 4, options.size ?? 64, (frame, u, v, out) => {
101
+ const age = frame / 15;
102
+ const r = Math.hypot(u, v);
103
+ const billow = fbm(u * 2.2 + seed * 7.3, v * 2.2 - age * 0.8, age * 1.6 + seed);
104
+ const edge = 0.55 + 0.35 * age;
105
+ const body = smooth(edge + 0.25, edge - 0.35, r + (billow - 0.5) * 0.9);
106
+ // Lit from above: the top of the puff is lighter than its underside.
107
+ out[0] = 0.72 + 0.28 * smooth(-1, 1, v + (billow - 0.5));
108
+ out[1] = body * (0.25 + 0.75 * billow) * (1 - 0.55 * age);
109
+ });
110
+ },
111
+ /** Sixteen frames of a flickering flame tongue, for fires, torches and jets. It plays at 24 frames per second. */
112
+ flame(textures, options = {}) {
113
+ const seed = options.seed ?? 1;
114
+ return atlas(textures, 4, 4, options.size ?? 64, (frame, u, v, out) => {
115
+ const t = (frame / 16) * Math.PI * 2;
116
+ const lick = fbm(u * 2.5 + seed, v * 1.8 - frame * 0.35, Math.sin(t) * 0.5 + seed);
117
+ const width = 0.55 * smooth(1.1, -0.6, v) * (0.6 + 0.8 * lick);
118
+ const core = smooth(width, width * 0.15, Math.abs(u + (lick - 0.5) * 0.4 * (v + 1)));
119
+ const tip = smooth(1, 0.2, v + (lick - 0.5) * 0.6);
120
+ const base = smooth(-1, -0.7, v);
121
+ out[0] = 0.75 + 0.25 * core;
122
+ out[1] = core * tip * base;
123
+ }, { fps: 24, randomStart: true });
124
+ },
125
+ /** A thin raindrop streak, for rain. Use it with the `velocity` facing. */
126
+ rain(textures, options = {}) {
127
+ return atlas(textures, 1, 1, options.size ?? 32, (_, u, v, out) => {
128
+ out[0] = 0.85 + 0.15 * (v + 1) * 0.5;
129
+ out[1] = Math.exp(-u * u * 40) * smooth(1, 0.6, Math.abs(v)) * (0.35 + 0.4 * (v + 1));
130
+ });
131
+ },
132
+ /**
133
+ * Four leaves of different shapes, each with a midrib and veins, for falling leaves and petals.
134
+ * Each particle keeps one leaf: give the system a random first frame that holds.
135
+ */
136
+ leaves(textures, options = {}) {
137
+ return atlas(textures, 2, 2, options.size ?? 64, (frame, u, v, out) => {
138
+ // A leaf along v: its half-width over its length, from a narrow willow to a round birch.
139
+ const round = [0.42, 0.62, 0.32, 0.5][frame];
140
+ const tipBend = [0.1, -0.08, 0.15, 0][frame];
141
+ const x = u - tipBend * (v + 1) ** 2 * 0.25;
142
+ const along = (v + 0.95) / 1.85;
143
+ const half = round * Math.sin(Math.PI * Math.min(Math.max(along, 0), 1)) ** 0.8;
144
+ const inside = smooth(half + 0.04, half - 0.04, Math.abs(x));
145
+ const stem = along < 0 && along > -0.06 && Math.abs(x) < 0.03 ? 1 : 0;
146
+ const rib = Math.exp(-x * x * 900);
147
+ const offset = ((Math.abs(x) * 1.6 - along * 4 + 10) % 0.5) - 0.25;
148
+ const vein = Math.exp(-offset * offset * 400);
149
+ out[0] = 0.78 + 0.22 * along - 0.25 * rib - 0.12 * vein * inside;
150
+ out[1] = Math.max(inside, stem);
151
+ }, { randomStart: true, hold: true });
152
+ },
153
+ };
@@ -0,0 +1 @@
1
+ export declare const VERSION = "0.0.0";
package/lib/version.js ADDED
@@ -0,0 +1,3 @@
1
+ // The package's version, which the release keeps equal to the engine's. The package checks it
2
+ // against the engine's VERSION as it loads, because an add-on and the engine ship in step.
3
+ export const VERSION = '0.0.0';
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
- "name": "@null3d/particles",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@null3d/particles",
3
+ "version": "0.0.0",
4
+ "description": "GPU particle systems for null3D sketches: emitters, bursts and sub-emitters, soft particles and flipbooks made in code, with closed-form motion that costs no simulation pass.",
5
+ "license": "MIT OR Apache-2.0",
6
+ "author": "Ramesh Nair (https://hiddentao.com)",
7
+ "homepage": "https://github.com/null3d-engine/null3d#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/null3d-engine/null3d.git",
11
+ "directory": "packages/particles"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/null3d-engine/null3d/issues"
15
+ },
16
+ "keywords": [
17
+ "null3d",
18
+ "3d",
19
+ "particles",
20
+ "vfx",
21
+ "webgpu",
22
+ "webgl2"
23
+ ],
24
+ "type": "module",
25
+ "exports": {
26
+ ".": {
27
+ "null3d-source": "./src/index.ts",
28
+ "types": "./lib/index.d.ts",
29
+ "default": "./lib/index.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "lib",
34
+ "LICENSE-MIT",
35
+ "LICENSE-APACHE"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "provenance": true
40
+ },
41
+ "scripts": {
42
+ "prepack": "bun ../../tools/build-package.ts particles"
43
+ },
44
+ "peerDependencies": {
45
+ "@null3d/engine": "0.0.0"
46
+ },
47
+ "devDependencies": {
48
+ "@null3d/engine": "0.0.0",
49
+ "@webgpu/types": "0.1.74"
50
+ }
51
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.