diff --git a/packages/cli/README.md b/packages/cli/README.md index 35449a9d..3bf4407e 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -547,6 +547,59 @@ export default defineClientPlugin({ }) ``` +### Particle effects + +A plugin can add particle effects from `setup` with `ctx.registerParticle`. They show in the editor's Particles tab with the plugin's name, can be placed in scenes (a `ParticleEffect` object) and are played by logic graphs (Spawn Effect, Play / Stop / Burst Effect). Their name in scene files and graphs is `:`, which `registerParticle` returns. Build them from the engine's emitters: `PooledEmitter` simulates particles with gravity, drag, wind, bouncing and settling, and only needs to know where each one starts. Load textures from the plugin's assets with `ctx.assetUrl()`. Particle effects only exist on the client: + +```ts +// client.ts +import type { PooledParticle } from '@mavonengine/core/Particles/System/PooledEmitter' +import type { Vector3 } from 'three' +import ParticleEffect from '@mavonengine/core/Particles/System/ParticleEffect' +import PooledEmitter from '@mavonengine/core/Particles/System/PooledEmitter' +import { defineClientPlugin } from '@mavonengine/core/Plugins/types' + +class HailEmitter extends PooledEmitter { + constructor(position: Vector3) { + super(position, { + maxParticles: 400, + rate: 120, + lifetime: [4, 4], + size: [0.05, 0.05], + color: [0xE8F0FF, 0xE8F0FF], + gravity: 9.8, + bounce: 0.3, + restFor: [1, 2], + }) + } + + protected spawn(particle: PooledParticle) { + particle.position.set((Math.random() - 0.5) * 20, 12, (Math.random() - 0.5) * 20) + } +} + +class Hail extends ParticleEffect { + constructor(position: Vector3) { + super() + this.emitters.push(new HailEmitter(position)) + } +} + +export default defineClientPlugin({ + setup(ctx) { + // 'my-custom-plugin:Hail' + ctx.registerParticle('Hail', { + preview: { + cameraPosition: [0, 4, 12], + cameraTarget: [0, 2, 0] + }, + spawn: position => new Hail(position), + icon: ctx.assetUrl('icons/hail.svg'), + }) + }, +}) +``` + ### Brushes The editor's Brushes panel comes with sculpt brushes (raise, lower, smooth, flatten, noise) for a `Terrain`, paint brushes for its material layers, and scatter brushes that paint models onto anything. A plugin can add to both kinds. diff --git a/packages/core/src/Editor/EditorHelper.ts b/packages/core/src/Editor/EditorHelper.ts index ca5b0ce7..01305b4e 100644 --- a/packages/core/src/Editor/EditorHelper.ts +++ b/packages/core/src/Editor/EditorHelper.ts @@ -12,6 +12,10 @@ export type PropertyField | { type: 'checkbox', label: string, getValue(): boolean, setValue(v: boolean): void } /** A choice from a list. `refresh` updates the options, called when the field shows */ | { type: 'select', label: string, options(): { value: string, label: string }[], getValue(): string, setValue(v: string): void, refresh?(): Promise } + /** A row of buttons, for actions rather than values (Play, Stop...) */ + | { type: 'buttons', label: string, buttons: { label: string, onClick(): void }[] } + /** A small looping preview of the registered particle effect `getValue()` names, by itself */ + | { type: 'particlePreview', label: string, getValue(): string } export interface EditorHelperAttachment { addBindings?(folder: ContainerApi): void diff --git a/packages/core/src/Game.ts b/packages/core/src/Game.ts index d75dbc7e..dffa2634 100644 --- a/packages/core/src/Game.ts +++ b/packages/core/src/Game.ts @@ -15,6 +15,7 @@ import Camera from './Camera' import { registerTslNode } from './Graph/Material/tslNodes' import { pluginNodeType, registerNode } from './Graph/NodeRegistry' import InputManager from './InputManager' +import { pluginParticleName, registerParticle } from './Particles/System/ParticlePreviewRegistry' import ParticleSystem from './Particles/System/ParticleSystem' import { onPluginMessage } from './Plugins/devMessages' import PluginHost from './Plugins/PluginHost' @@ -219,6 +220,11 @@ export default class Game extends BaseGame { assetUrl: path => `${pluginAssetBase(loaded.package)}${path.replace(LEADING_SLASHES_RE, '')}`, registerPrefab: prefab => registerPrefab({ ...prefab, plugin: loaded.package }), registerBrush: brush => registerBrush({ ...brush, plugin: loaded.package }), + registerParticle: (name, entry) => { + const key = pluginParticleName(loaded.package, name) + registerParticle(key, { label: name, ...entry, plugin: loaded.package }) + return key + }, registerNode: (definition, tsl) => { const type = pluginNodeType(loaded.package, definition.type) registerNode({ ...definition, type, plugin: loaded.package }) diff --git a/packages/core/src/Graph/Logic/GraphPreview.ts b/packages/core/src/Graph/Logic/GraphPreview.ts new file mode 100644 index 00000000..bc210e1a --- /dev/null +++ b/packages/core/src/Graph/Logic/GraphPreview.ts @@ -0,0 +1,163 @@ +import type { Object3D } from 'three' +import type { ParticleHost } from '../../Particles/ParticleEffectObject' +import type { GraphEntity } from '../NodeRegistry' +import type { GraphData, GraphValue } from '../types' +import { BoxGeometry, EdgesGeometry, Group, LineBasicMaterial, LineSegments, Vector3 } from 'three' +import { ParticleEffectObject, PARTICLES_FINISHED, spawnedEffectId } from '../../Particles/ParticleEffectObject' +import { getParticleNames } from '../../Particles/System/ParticlePreviewRegistry' +import { GraphRuntime } from './GraphRuntime' + +/** The id Self has in a preview */ +export const PREVIEW_SELF = 'self' + +export interface GraphPreviewOptions { + /** The registered particle effect Self is. Without one Self is a box marker */ + selfEffect?: string + /** Where its Log nodes write */ + log?(message: string): void + /** Told each step as it runs */ + onStep?(node: string): void +} + +/** Reads and moves the Object3D `target()` gives at the time */ +function objectEntity(id: string, target: () => Object3D): GraphEntity { + return { + id, + getPosition: () => target().position.toArray(), + setPosition: ([x = 0, y = 0, z = 0]) => { + target().position.set(x, y, z) + }, + getRotation: () => { + const { x, y, z } = target().rotation + return [x, y, z] + }, + setRotation: ([x = 0, y = 0, z = 0]) => { + target().rotation.set(x, y, z) + }, + getScale: () => target().scale.toArray(), + setScale: ([x = 1, y = 1, z = 1]) => { + target().scale.set(x, y, z) + }, + } +} + +/** + * A logic graph running in a world of its own, for the graph editor: what it spawns and moves lives under `root`, + * which the preview draws, so the scene stays as it is. Self is a particle effect or a marker; the scene's objects + * aren't there, and messages it sends only reach itself. + */ +export class GraphPreview { + /** What the preview draws */ + readonly root = new Group() + runtime?: GraphRuntime + private readonly effects = new Map() + private readonly marker: LineSegments + private self: Object3D + + constructor() { + const box = new BoxGeometry(0.6, 0.6, 0.6) + this.marker = new LineSegments(new EdgesGeometry(box), new LineBasicMaterial({ color: 0xFFAA00 })) + box.dispose() + this.self = this.marker + } + + private readonly particles: ParticleHost = { + find: id => this.effects.get(id), + spawn: (effect, [x = 0, y = 0, z = 0], burst) => { + if (!getParticleNames().includes(effect)) + return undefined + const id = spawnedEffectId(effect, id => this.effects.has(id)) + const object = this.addEffect(id, effect, new Vector3(x, y, z), burst > 0) + object.spawned = true + if (burst > 0) + object.burst(burst) + return object + }, + } + + private addEffect(id: string, effect: string, position: Vector3, once: boolean): ParticleEffectObject { + const object = new ParticleEffectObject(id, { effect, playing: !once }, position, { + parent: this.root, + onFinished: finished => this.runtime?.trigger(PARTICLES_FINISHED, { effect: finished.id }), + removeWhenFinished: once, + }) + // Away from the scene: its colliders aren't here + if (object.effect) + object.effect.collideWithScene = false + this.effects.set(id, object) + return object + } + + /** Run `graph` from the start, in a fresh world. Throws when it has problems, as GraphRuntime does */ + run(graph: GraphData, options: GraphPreviewOptions = {}) { + // Checked before anything is torn down, so a broken graph leaves the last one running + const runtime = new GraphRuntime(graph, { + // Whatever Self is once the world below is set up + self: objectEntity(PREVIEW_SELF, () => this.self), + find: (id) => { + const object = this.effects.get(id) + return object + ? objectEntity(id, () => object.instance) + : undefined + }, + services: { particles: this.particles }, + log: options.log, + onStep: options.onStep, + }) + + this.clear() + if (options.selfEffect && getParticleNames().includes(options.selfEffect)) { + const object = this.addEffect(PREVIEW_SELF, options.selfEffect, new Vector3(), false) + this.self = object.instance + } + else { + this.self = this.marker + this.root.add(this.marker) + } + + this.runtime = runtime + runtime.start() + } + + /** Fire `event` in the graph, as the game would: `keydown` with `{ code }`, a plugin's own... */ + trigger(event: string, payload: Record = {}) { + this.runtime?.trigger(event, payload) + } + + /** What a Send Message node would send */ + message(name: string, value: GraphValue = 0) { + this.runtime?.message(name, value) + } + + /** Move time on: the graph, then the effects */ + update(delta: number) { + this.runtime?.update(delta) + for (const [id, object] of this.effects) { + if (!object.garbageCollect) + object.update(delta) + if (object.garbageCollect) + this.effects.delete(id) + } + } + + /** How many effects are out, Self's included */ + get effectCount(): number { + return this.effects.size + } + + private clear() { + this.effects.forEach(object => object.destroy()) + this.effects.clear() + this.marker.position.set(0, 0, 0) + this.marker.rotation.set(0, 0, 0) + this.marker.scale.set(1, 1, 1) + this.marker.removeFromParent() + } + + dispose() { + this.clear() + this.runtime = undefined + this.marker.geometry.dispose() + ;(this.marker.material as LineBasicMaterial).dispose() + } +} diff --git a/packages/core/src/Graph/Logic/GraphRuntime.ts b/packages/core/src/Graph/Logic/GraphRuntime.ts index e79f3a13..913fed1e 100644 --- a/packages/core/src/Graph/Logic/GraphRuntime.ts +++ b/packages/core/src/Graph/Logic/GraphRuntime.ts @@ -18,6 +18,8 @@ export interface GraphRuntimeOptions { emit?(name: string, value: GraphValue): void /** Told each step as it runs, for debugging */ onStep?(node: string): void + /** What the graph's nodes act on instead of the game's own, by name, see `NodeEvalContext.services` */ + services?: Record /** The most steps one event may run, so a loop in the exec edges can't hang the game. Default 10 000 */ maxSteps?: number } @@ -141,6 +143,7 @@ export class GraphRuntime { ? this.options.find?.(target) : self, variables: this.variables, + services: this.options.services, } } diff --git a/packages/core/src/Graph/NodeRegistry.ts b/packages/core/src/Graph/NodeRegistry.ts index 6c75b061..89b169a8 100644 --- a/packages/core/src/Graph/NodeRegistry.ts +++ b/packages/core/src/Graph/NodeRegistry.ts @@ -45,6 +45,11 @@ export interface NodeEvalContext { entity?(id: string): GraphEntity | undefined /** The graph's variables, in a logic graph */ variables?: Map + /** + * What the side running a logic graph offers its nodes, by name (e.g. `particles`). Unset in the scene, where nodes + * use the game's own; a preview sets its own so the graph acts on the preview's world instead + */ + services?: Record } /** What a `run` implementation (a step of a logic graph) gets besides its inputs */ diff --git a/packages/core/src/Particles/Effects/Debris.ts b/packages/core/src/Particles/Effects/Debris.ts new file mode 100644 index 00000000..ebc0606e --- /dev/null +++ b/packages/core/src/Particles/Effects/Debris.ts @@ -0,0 +1,60 @@ +import type { Vector3 } from 'three/webgpu' +import type { PooledParticle } from '../System/PooledEmitter' +import { NormalBlending } from 'three/webgpu' +import ParticleEffect from '../System/ParticleEffect' +import { registerParticle } from '../System/ParticlePreviewRegistry' +import PooledEmitter, { randomDirection } from '../System/PooledEmitter' + +/** + * Chunks of rock and dirt thrown up, falling and bouncing off whatever they land on (terrain, primitives, scattered + * rocks), rolling to a stop and fading + */ +export class DebrisEmitter extends PooledEmitter { + constructor(position: Vector3) { + super(position, { + maxParticles: 120, + // A handful every so often while it plays; burst it where something hits + repeat: { every: 2.5, count: 20 }, + lifetime: [3, 4.5], + size: [0.13, 0.1], + color: [0x7A6A58, 0x5E544A], + fadeIn: 0, + // Solid until the last fifth of its life + fadeOut: 0.2, + gravity: 9.8, + drag: 0.1, + bounce: 0.4, + friction: 0.35, + // Too heavy for the wind + windInfluence: 0, + blending: NormalBlending, + hardness: 0.85, + }) + } + + protected spawn(particle: PooledParticle): void { + particle.position.set(0, 0.3, 0) + randomDirection(particle.velocity, 1).multiplyScalar(2.5 + Math.random() * 3.5) + // Thrown up more than out + particle.velocity.y = Math.abs(particle.velocity.y) + 2 + } +} + +const preview = { + cameraPosition: [0, 2.5, 7] as [number, number, number], + cameraTarget: [0, 0.8, 0] as [number, number, number], +} + +registerParticle('Debris', { + preview, + spawn: position => new Debris(position), + icon: ``, +}) + +/** Rocks and dirt thrown up and bouncing off the ground and what's on it: playing, a handful every few seconds */ +export default class Debris extends ParticleEffect { + constructor(position: Vector3) { + super() + this.emitters.push(new DebrisEmitter(position)) + } +} diff --git a/packages/core/src/Particles/Effects/DustPuff.ts b/packages/core/src/Particles/Effects/DustPuff.ts new file mode 100644 index 00000000..d5bd54c2 --- /dev/null +++ b/packages/core/src/Particles/Effects/DustPuff.ts @@ -0,0 +1,53 @@ +import type { Vector3 } from 'three/webgpu' +import type { PooledParticle } from '../System/PooledEmitter' +import { NormalBlending } from 'three/webgpu' +import ParticleEffect from '../System/ParticleEffect' +import { registerParticle } from '../System/ParticlePreviewRegistry' +import PooledEmitter from '../System/PooledEmitter' + +/** A ring of dust thrown out along the ground, slowing, spreading and settling */ +export class DustEmitter extends PooledEmitter { + constructor(position: Vector3) { + super(position, { + maxParticles: 120, + // A puff every so often while it plays; burst it for one where something lands + repeat: { every: 1.6, count: 24 }, + lifetime: [1, 2], + size: [0.35, 1.6], + color: [0xA0907A, 0x8C806E], + opacity: 0.45, + fadeIn: 0.08, + gravity: 0.4, + drag: 2.8, + windInfluence: 1, + blending: NormalBlending, + hardness: 0, + }) + } + + protected spawn(particle: PooledParticle): void { + const angle = Math.random() * Math.PI * 2 + const out = 1.2 + Math.random() * 1.8 + particle.position.set(Math.cos(angle) * 0.2, 0.1, Math.sin(angle) * 0.2) + particle.velocity.set(Math.cos(angle) * out, 0.3 + Math.random() * 0.6, Math.sin(angle) * out) + } +} + +const preview = { + cameraPosition: [0, 1.6, 5] as [number, number, number], + cameraTarget: [0, 0.3, 0] as [number, number, number], +} + +registerParticle('Dust Puff', { + preview, + spawn: position => new DustPuff(position), + icon: ``, +}) + +/** A puff of dust where something lands, falls or skids: puffing every so often while it plays */ +export default class DustPuff extends ParticleEffect { + constructor(position: Vector3) { + super() + this.emitters.push(new DustEmitter(position)) + } +} diff --git a/packages/core/src/Particles/Effects/Explosion.ts b/packages/core/src/Particles/Effects/Explosion.ts new file mode 100644 index 00000000..bf0d8933 --- /dev/null +++ b/packages/core/src/Particles/Effects/Explosion.ts @@ -0,0 +1,106 @@ +import type { PooledEmitterOptions, PooledParticle } from '../System/PooledEmitter' +import { AdditiveBlending, NormalBlending, Vector3 } from 'three/webgpu' +import ParticleEffect from '../System/ParticleEffect' +import { registerParticle } from '../System/ParticlePreviewRegistry' +import PooledEmitter, { randomDirection } from '../System/PooledEmitter' +import { SparkEmitter } from './Sparks' + +/** How often a playing explosion goes off (s), and how big a bang that is (what burst() is told) */ +const EVERY = 3 +const BANG = 30 + +/** One part of the bang: its particles start near the middle and fly out at a speed between `speed`'s two */ +class BlastEmitter extends PooledEmitter { + constructor(position: Vector3, options: PooledEmitterOptions, private readonly speed: [number, number], private readonly up = 0.3) { + super(position, options) + } + + protected spawn(particle: PooledParticle): void { + const [slowest, fastest] = this.speed + randomDirection(particle.velocity, this.up).multiplyScalar(slowest + Math.random() * (fastest - slowest)) + particle.position.copy(particle.velocity).multiplyScalar(0.05) + particle.position.y += 0.5 + } +} + +const repeat = { every: EVERY, count: BANG } + +/** The flash: a couple of big, short-lived glows */ +export function flashEmitter(position: Vector3): PooledEmitter { + return new BlastEmitter(position, { + maxParticles: 4, + repeat, + burstScale: 2 / BANG, + lifetime: [0.12, 0.22], + size: [3, 5], + color: [0xFFFBE6, 0xFFC04D], + fadeIn: 0, + windInfluence: 0, + blending: AdditiveBlending, + hardness: 0, + }, [0, 0.2]) +} + +/** The fireball: hot gas thrown out and stopped by the air */ +export function fireballEmitter(position: Vector3): PooledEmitter { + return new BlastEmitter(position, { + maxParticles: 60, + repeat, + burstScale: 1, + lifetime: [0.45, 0.9], + size: [0.9, 1.8], + color: [0xFFE08A, 0xC2260A], + opacity: 0.9, + fadeIn: 0.05, + gravity: -1.5, + drag: 3.5, + windInfluence: 0.3, + blending: AdditiveBlending, + hardness: 0.05, + }, [2, 6]) +} + +/** The smoke left behind, rising and blowing away */ +export function blastSmokeEmitter(position: Vector3): PooledEmitter { + return new BlastEmitter(position, { + maxParticles: 40, + repeat, + burstScale: 0.7, + lifetime: [2, 3.5], + size: [1, 3.2], + color: [0x4A4744, 0x8A8682], + opacity: 0.55, + fadeIn: 0.15, + gravity: -0.5, + drag: 1.8, + windInfluence: 1, + blending: NormalBlending, + hardness: 0, + }, [1, 3], 0.6) +} + +const preview = { + cameraPosition: [0, 3, 11] as [number, number, number], + cameraTarget: [0, 1.5, 0] as [number, number, number], +} + +registerParticle('Explosion', { + preview, + spawn: position => new Explosion(position), + icon: ``, +}) + +/** A bang: a flash, a fireball, sparks and the smoke left behind. Playing, it goes off every few seconds */ +export default class Explosion extends ParticleEffect { + constructor(position: Vector3) { + super() + const at = () => new Vector3().copy(position) + const sparks = new SparkEmitter(at(), { + rate: 0, + repeat, + speed: [5, 12], + burstScale: 1.5, + }) + this.emitters.push(flashEmitter(at()), fireballEmitter(at()), sparks, blastSmokeEmitter(at())) + } +} diff --git a/packages/core/src/Particles/Effects/Fire.ts b/packages/core/src/Particles/Effects/Fire.ts new file mode 100644 index 00000000..51478058 --- /dev/null +++ b/packages/core/src/Particles/Effects/Fire.ts @@ -0,0 +1,84 @@ +import type { Vector3 } from 'three/webgpu' +import type { PooledParticle } from '../System/PooledEmitter' +import { AdditiveBlending } from 'three/webgpu' +import ParticleEffect from '../System/ParticleEffect' +import { registerParticle } from '../System/ParticlePreviewRegistry' +import PooledEmitter from '../System/PooledEmitter' + +/** A point in a disc of `radius` on the ground, into `out` */ +function inDisc(out: Vector3, radius: number): Vector3 { + const angle = Math.random() * Math.PI * 2 + const r = Math.sqrt(Math.random()) * radius + return out.set(Math.cos(angle) * r, 0, Math.sin(angle) * r) +} + +/** Tongues of flame rising from a small disc, yellow at the base and red as they burn out */ +export class FlameEmitter extends PooledEmitter { + constructor(position: Vector3) { + super(position, { + maxParticles: 140, + rate: 70, + burstScale: 1, + lifetime: [0.5, 1.1], + size: [0.75, 0.15], + color: [0xFFD36B, 0xE0300A], + opacity: 0.85, + fadeIn: 0.15, + // Hot air: it speeds up as it rises + gravity: -2, + drag: 1.2, + windInfluence: 0.6, + blending: AdditiveBlending, + hardness: 0.05, + }) + } + + protected spawn(particle: PooledParticle): void { + inDisc(particle.position, 0.3) + particle.velocity.set((Math.random() - 0.5) * 0.4, 0.8 + Math.random() * 0.8, (Math.random() - 0.5) * 0.4) + } +} + +/** Glowing embers drifting up out of the fire, carried by the wind */ +export class EmberEmitter extends PooledEmitter { + constructor(position: Vector3) { + super(position, { + maxParticles: 40, + rate: 8, + burstScale: 0.5, + lifetime: [1.5, 3.5], + size: [0.07, 0.03], + color: [0xFFB347, 0xD2381B], + fadeIn: 0.05, + gravity: -0.3, + drag: 0.6, + windInfluence: 1, + blending: AdditiveBlending, + hardness: 0.6, + }) + } + + protected spawn(particle: PooledParticle): void { + inDisc(particle.position, 0.25).y = 0.4 + particle.velocity.set((Math.random() - 0.5) * 0.8, 1 + Math.random() * 1.5, (Math.random() - 0.5) * 0.8) + } +} + +const preview = { + cameraPosition: [0, 1.4, 4] as [number, number, number], + cameraTarget: [0, 0.8, 0] as [number, number, number], +} + +registerParticle('Fire', { + preview, + spawn: position => new Fire(position), + icon: ``, +}) + +/** A campfire: flames and the embers they throw up */ +export default class Fire extends ParticleEffect { + constructor(position: Vector3) { + super() + this.emitters.push(new FlameEmitter(position), new EmberEmitter(position.clone())) + } +} diff --git a/packages/core/src/Particles/Effects/Rain.ts b/packages/core/src/Particles/Effects/Rain.ts index b5dcfca8..9afca11c 100644 --- a/packages/core/src/Particles/Effects/Rain.ts +++ b/packages/core/src/Particles/Effects/Rain.ts @@ -1,10 +1,13 @@ import { float, mod, uniform, vec3, vec4 } from 'three/tsl' -import { PointsNodeMaterial } from 'three/webgpu' +import { PointsNodeMaterial, Vector3 } from 'three/webgpu' import Game from '../../Game' import Emitter from '../System/Emitter' import ParticleEffect from '../System/ParticleEffect' import { registerParticle } from '../System/ParticlePreviewRegistry' +/** How fast the drops fall (m/s) */ +const FALL_SPEED = 7 + export class RainEmitter extends Emitter { static preview = { cameraPosition: [0, 5, 10] as [number, number, number], @@ -14,6 +17,12 @@ export class RainEmitter extends Emitter { readonly uniforms = { uTime: uniform(0), + /** 1 raining, 0 gone: the drops don't decay, so stopping fades them out */ + uFade: uniform(1), + /** The wind (m/s) in the emitter's space, see windVelocity() */ + uWind: uniform(new Vector3()), + /** Where the box of drops is centred sideways, in the emitter's space: the camera with `aroundCamera` */ + uCenter: uniform(new Vector3()), } constructor() { @@ -33,19 +42,42 @@ export class RainEmitter extends Emitter { // Falling, and back to the top once below the 20 unit box const start = this.positionNode - const y = mod(start.y.sub(this.uniforms.uTime.mul(7)).add(20), 20).sub(10) - this.material.positionNode = vec3(start.x, y, start.z) + const y = mod(start.y.sub(this.uniforms.uTime.mul(FALL_SPEED)).add(20), 20).sub(10) + // Blown sideways by the wind for as long as it has been falling: slanted rain + const falling = float(10).sub(y).div(FALL_SPEED) + const blown = this.uniforms.uWind.mul(falling) + // Around the centre: a drop past its box's edge comes back in on the other side, so the box can follow the camera + const center = this.uniforms.uCenter + const x = mod(start.x.sub(center.x).add(10), 20).sub(10).add(center.x) + const z = mod(start.z.sub(center.z).add(10), 20).sub(10).add(center.z) + this.material.positionNode = vec3(x.add(blown.x), y, z.add(blown.z)) this.material.sizeNode = float(2) - this.material.colorNode = vec4(1, 1, 1, 0.8) + this.material.colorNode = vec4(1, 1, 1, this.uniforms.uFade.mul(0.8)) + } + + get alive(): boolean { + return this.uniforms.uFade.value > 0 + } + + clear(): void { + this.uniforms.uFade.value = 0 } update(delta: number): void { this.uniforms.uTime.value += delta + this.windVelocity(this.uniforms.uWind.value) + this.cameraOffset(this.uniforms.uCenter.value) + // In or out over a second + const fade = this.uniforms.uFade.value + (this.emitting + ? delta + : -delta) + this.uniforms.uFade.value = Math.min(1, Math.max(0, fade)) } } registerParticle('Rain', { preview: RainEmitter.preview, + icon: ``, spawn: () => new Rain(), }) diff --git a/packages/core/src/Particles/Effects/Smoke.ts b/packages/core/src/Particles/Effects/Smoke.ts index 40773549..61a6d64c 100644 --- a/packages/core/src/Particles/Effects/Smoke.ts +++ b/packages/core/src/Particles/Effects/Smoke.ts @@ -1,11 +1,23 @@ import type { BufferAttribute, Texture } from 'three' -import { texture, uniform, uv, vec2, vec4 } from 'three/tsl' +import { smoothstep, texture, uniform, uv, vec2, vec3, vec4 } from 'three/tsl' import { NormalBlending, PointsNodeMaterial, Vector3 } from 'three/webgpu' import Game from '../../Game' import Emitter from '../System/Emitter' import Particle from '../System/Particle' import ParticleEffect from '../System/ParticleEffect' import { registerParticle } from '../System/ParticlePreviewRegistry' +import { focalScale } from '../System/particleShapes' + +/** World units across a puff per unit of its scale, which grows from 2 as it ages */ +const PUFF_SIZE = 0.35 + +/** The project's `smokeTexture` resource, if it has one */ +function smokeTexture(): Texture | undefined { + const tex = Game.instance().resources.items.smokeTexture + return tex && (tex as Texture).isTexture + ? tex as Texture + : undefined +} export class SmokeParticle extends Particle { startAlpha = 0.5 @@ -26,9 +38,14 @@ export class SmokeParticle extends Particle { this.position.set(0, 0, 0) } + /** Carried by the wind (m/s), more as it rises away from the source: fully after its first second and a half */ + drift(wind: Vector3, delta: number) { + this.position.addScaledVector(wind, delta * Math.min(1, this.age / 1.5)) + } + update(delta: number): void { this.position.y += delta * 0.1 - this.scale = new Vector3(2 + this.age) + this.scale.setScalar(2 + this.age) // Update position this.position.x += this.velocity.x * delta @@ -43,12 +60,7 @@ export class SmokeEmitter extends Emitter { static preview = { cameraPosition: [0, 4, 10] as [number, number, number], cameraTarget: [0, 3, 0] as [number, number, number], - create: () => { - const tex = Game.instance().resources.items.smokeTexture as Texture | undefined - return tex - ? new SmokeEmitter(tex, new Vector3(0, 0, 0)) - : null - }, + create: () => new SmokeEmitter(smokeTexture(), new Vector3(0, 0, 0)), } declare particles: SmokeParticle[] @@ -56,19 +68,28 @@ export class SmokeEmitter extends Emitter { uTime: uniform(0), } - constructor(smokeTexture: Texture, position: Vector3) { + /** Without a texture each puff is a soft grey disc */ + constructor(smokeTexture: Texture | undefined, position: Vector3) { super(position, new PointsNodeMaterial({ transparent: true, blending: NormalBlending, depthWrite: false, - sizeAttenuation: false, + // A size in the world, so a puff looks smaller the further away it is. Without it each puff was a fixed number of + // pixels: small up close and huge from afar + sizeAttenuation: true, }), 20, 10) - // Pixels across, like gl_PointSize was - this.material.sizeNode = this.scaleNode.mul(40) - // Top down, like gl_PointCoord - const tex = texture(smokeTexture, vec2(uv().x, uv().y.oneMinus())) - this.material.colorNode = vec4(tex.rgb, tex.a.mul(this.alphaNode)) + // Attenuated, a size of 1 covers 1 / tan(fov / 2) units: times the projection's [1][1] (which is that) it is units + this.material.sizeNode = this.scaleNode.mul(PUFF_SIZE).mul(focalScale) + if (smokeTexture) { + // Top down, like gl_PointCoord + const tex = texture(smokeTexture, vec2(uv().x, uv().y.oneMinus())) + this.material.colorNode = vec4(tex.rgb, tex.a.mul(this.alphaNode)) + } + else { + const edge = smoothstep(0.5, 0.1, uv().sub(0.5).length()) + this.material.colorNode = vec4(vec3(0.75), edge.mul(this.alphaNode)) + } for (let i = 0; i < this.maxParticles; i++) { const particle = new SmokeParticle(Math.random() * this.maxLifeTimeParticle + 1, position) @@ -78,18 +99,34 @@ export class SmokeEmitter extends Emitter { } } + /** Puffs out the particles that are done first, then the oldest */ + burst(count: number): void { + const order = this.particles + .map((particle, i) => ({ i, done: particle.age >= particle.decay, age: particle.age })) + .sort((a, b) => Number(b.done) - Number(a.done) || b.age - a.age) + for (const { i } of order.slice(0, Math.max(0, Math.floor(count)))) + this.particles[i].reset() + } + + private readonly wind = new Vector3() + update(delta: number): void { this.uniforms.uTime.value += delta + this.windVelocity(this.wind) for (let i = 0; i < this.maxParticles; i++) { const particle = this.particles[i] if (particle.age >= particle.decay) { - // Respawn particle - particle.reset() + // Respawn the particle, or leave it hidden once stopped + if (this.emitting) + particle.reset() + else + this.alphas[i] = 0 } else { particle.update(delta) + particle.drift(this.wind, delta) // Update position buffer this.positions[i * 3] = particle.position.x @@ -101,6 +138,8 @@ export class SmokeEmitter extends Emitter { } } + // The scales too: the puffs grow as they age + (this.geometry.getAttribute('aScale') as BufferAttribute).needsUpdate = true; (this.geometry.getAttribute('aAlpha') as BufferAttribute).needsUpdate = true; (this.geometry.getAttribute('position') as BufferAttribute).needsUpdate = true } @@ -108,29 +147,39 @@ export class SmokeEmitter extends Emitter { registerParticle('Smoke', { preview: SmokeEmitter.preview, + icon: ``, spawn: position => new Smoke(position), }) export default class Smoke extends ParticleEffect { smokeEmitter?: SmokeEmitter + private readonly offLoaded?: () => void + constructor(position: Vector3) { super() + const resources = Game.instance().resources const create = () => { - const tex = Game.instance().resources.items.smokeTexture as Texture | undefined - if (tex) { - this.smokeEmitter = new SmokeEmitter(tex, position) + if (!this.smokeEmitter && !this.garbageCollect) { + this.smokeEmitter = new SmokeEmitter(smokeTexture(), position.clone()) this.emitters.push(this.smokeEmitter) } } - const tex = Game.instance().resources.items.smokeTexture as Texture | undefined - if (tex) { + if (smokeTexture() || resources.loaded >= resources.toLoad) { create() } else { - Game.instance().resources.on('loaded', create) + // A `smokeTexture` resource may still be loading + resources.on('loaded', create) + this.offLoaded = () => resources.off('loaded', create) } } + + destroy(): void { + // Removed before the texture loaded: no emitter afterwards + this.offLoaded?.() + super.destroy() + } } diff --git a/packages/core/src/Particles/Effects/Snow.ts b/packages/core/src/Particles/Effects/Snow.ts new file mode 100644 index 00000000..a827bc6f --- /dev/null +++ b/packages/core/src/Particles/Effects/Snow.ts @@ -0,0 +1,102 @@ +import type { Vector3 } from 'three/webgpu' +import type { PooledParticle } from '../System/PooledEmitter' +import { NormalBlending } from 'three/webgpu' +import ParticleEffect from '../System/ParticleEffect' +import { registerParticle } from '../System/ParticlePreviewRegistry' +import PooledEmitter from '../System/PooledEmitter' + +/** The area the flakes come down over around the emitter (m across), and how high above it they start */ +const AREA = 40 +const HEIGHT = 14 +/** How fast they fall (m/s): the drag holds them to it */ +const FALL_SPEED = 1.1 +const GRAVITY = 2 +/** How hard they sway from side to side */ +const SWAY = 0.7 +/** New flakes a second: as many to the square metre as ever, over the bigger area */ +const RATE = 190 + +/** + * Snowflakes falling over an area around the emitter, swaying and blown by the wind, that settle where they land and + * melt away after a while. They land on the effect's own ground, or with its collider on on whatever is in the scene + * (terrain, primitives, scatter) + */ +export class SnowEmitter extends PooledEmitter { + /** The sky starts full rather than empty: the first update lets out a whole fall's worth at every height */ + private filled = false + private filling = false + + constructor(position: Vector3) { + super(position, { + // Falling (RATE × ~13 s) and lying (RATE × ~11 s) + maxParticles: 5000, + rate: RATE, + // Long enough to come down from the top: it lies a while (`restFor`) once it has + lifetime: [40, 40], + size: [0.08, 0.08], + sizeVariation: 0.5, + color: [0xFFFFFF, 0xF4F8FF], + opacity: 0.9, + fadeIn: 0.02, + fadeOut: 0.15, + gravity: GRAVITY, + drag: GRAVITY / FALL_SPEED, + stick: true, + restFor: [8, 15], + windInfluence: 1, + blending: NormalBlending, + hardness: 0.3, + }) + } + + protected spawn(particle: PooledParticle): void { + const height = this.filling + ? Math.random() * HEIGHT + : HEIGHT + // Upwind by as far as the wind takes it on the way down, so it comes down over the area + const falling = height / FALL_SPEED + particle.position.set( + (Math.random() - 0.5) * AREA - this.wind.x * falling, + height, + (Math.random() - 0.5) * AREA - this.wind.z * falling, + ) + particle.velocity.set(0, -FALL_SPEED, 0) + } + + /** Each flake sways at its own pace */ + protected steer(particle: PooledParticle, delta: number): void { + const phase = particle.seed * Math.PI * 2 + particle.velocity.x += Math.sin(particle.age * 1.1 + phase) * SWAY * delta + particle.velocity.z += Math.cos(particle.age * 0.8 + phase * 1.7) * SWAY * delta + } + + update(delta: number): void { + if (!this.filled && this.emitting) { + this.filled = true + this.filling = true + for (let n = 0; n < RATE * HEIGHT / FALL_SPEED; n++) + this.emitOne() + this.filling = false + } + super.update(delta) + } +} + +const preview = { + cameraPosition: [0, 4, 12] as [number, number, number], + cameraTarget: [0, 3, 0] as [number, number, number], +} + +registerParticle('Snow', { + preview, + spawn: position => new Snow(position), + icon: ``, +}) + +/** Snow falling around where it is placed, swaying, blown by the wind and settling a while where it lands */ +export default class Snow extends ParticleEffect { + constructor(position: Vector3) { + super() + this.emitters.push(new SnowEmitter(position)) + } +} diff --git a/packages/core/src/Particles/Effects/Sparks.ts b/packages/core/src/Particles/Effects/Sparks.ts new file mode 100644 index 00000000..3d54edac --- /dev/null +++ b/packages/core/src/Particles/Effects/Sparks.ts @@ -0,0 +1,57 @@ +import type { Vector3 } from 'three/webgpu' +import type { PooledEmitterOptions, PooledParticle } from '../System/PooledEmitter' +import { AdditiveBlending } from 'three/webgpu' +import ParticleEffect from '../System/ParticleEffect' +import { registerParticle } from '../System/ParticlePreviewRegistry' +import PooledEmitter, { randomDirection } from '../System/PooledEmitter' + +/** Hot sparks flying out and up, falling and bouncing off the ground as they cool */ +export class SparkEmitter extends PooledEmitter { + private readonly speed: [number, number] + + /** `speed`: how fast they fly out (m/s), between the two. The rest as PooledEmitter's */ + constructor(position: Vector3, options: Pick & { speed?: [number, number] } = {}) { + super(position, { + maxParticles: 200, + rate: options.rate ?? 40, + repeat: options.repeat, + burstScale: options.burstScale ?? 1, + lifetime: [0.4, 1.1], + size: [0.07, 0.02], + color: [0xFFF4C2, 0xFF5A14], + fadeIn: 0, + gravity: 9.8, + drag: 0.4, + bounce: 0.35, + windInfluence: 0.15, + blending: AdditiveBlending, + hardness: 0.7, + }) + this.speed = options.speed ?? [2.5, 6] + } + + protected spawn(particle: PooledParticle): void { + particle.position.set(0, 0.05, 0) + const [slowest, fastest] = this.speed + randomDirection(particle.velocity, 0.85).multiplyScalar(slowest + Math.random() * (fastest - slowest)) + } +} + +const preview = { + cameraPosition: [0, 1.5, 5] as [number, number, number], + cameraTarget: [0, 0.6, 0] as [number, number, number], +} + +registerParticle('Sparks', { + preview, + spawn: position => new Sparks(position), + icon: ``, +}) + +/** A shower of sparks, like a grinder's. Burst it for one bang of sparks */ +export default class Sparks extends ParticleEffect { + constructor(position: Vector3) { + super() + this.emitters.push(new SparkEmitter(position)) + } +} diff --git a/packages/core/src/Particles/ParticleEffectObject.ts b/packages/core/src/Particles/ParticleEffectObject.ts new file mode 100644 index 00000000..1f69f4dd --- /dev/null +++ b/packages/core/src/Particles/ParticleEffectObject.ts @@ -0,0 +1,233 @@ +import type { Object3D } from 'three' +import type ParticleEffect from './System/ParticleEffect' +import { Group, Vector3 } from 'three' +import { WithEditorHelper } from '../Editor/WithEditorHelper' +import Game from '../Game' +import { triggerGraphEvent } from '../Graph/Logic/logicGraphObject' +import GameObject from '../World/GameObject' +import { createParticleEffect, getParticleNames } from './System/ParticlePreviewRegistry' + +/* + * Particle effects as objects a scene saves and logic graphs act on. A `ParticleEffect` scene object plays one of the + * registered effects (see registerParticle()) in a group of its own, which its transform moves. Graphs reach it, and + * the effects they spawn, through a ParticleHost: the scene's by default, a preview's own in the graph editor. + */ + +export const PARTICLE_EFFECT_TYPE = 'ParticleEffect' + +/** The graph event an effect fires once it is stopped and its last particle is gone, with `{ effect: }` */ +export const PARTICLES_FINISHED = 'particles.finished' + +export interface ParticleEffectProps { + /** The registered effect it plays, e.g. `Smoke` */ + effect?: string + /** Whether it plays from the start. Default true; false waits for a graph (or code) to play or burst it */ + playing?: boolean + /** Whether a Wind in the scene moves its particles. Default true */ + wind?: boolean + /** + * Whether its particles that bounce or settle (Sparks, Debris) hit the scene's colliders: terrain, primitives, + * scatter. Default false: no physics checks, they use the effect's own flat ground + */ + collider?: boolean + /** + * Whether new particles start around the camera rather than where it is placed, for weather that goes where the + * player goes (Snow, Rain). Those already out stay where they are. Default false + */ + aroundCamera?: boolean +} + +export interface ParticleEffectObjectOptions { + /** Where its group goes. Default the game's scene */ + parent?: Object3D + /** Told once it is stopped and its last particle is gone. Default: the logic graphs on this side get On Effect Finished */ + onFinished?(object: ParticleEffectObject): void + /** Remove itself once finished: a one-off burst spawned by a graph */ + removeWhenFinished?: boolean +} + +/** + * One registered particle effect, played in a group of its own (`instance`) that the editor and graphs move. Control + * it with `play()`, `stop()` and `burst()`, from code or a graph + */ +export class ParticleEffectObject extends WithEditorHelper(GameObject) { + /** Holds the effect's emitters: moving it moves the effect */ + readonly instance = new Group() + readonly props: ParticleEffectProps + effect: ParticleEffect | null = null + /** Spawned by a graph rather than placed in the scene */ + spawned = false + private wasAlive = false + + constructor(id: string | undefined, props: ParticleEffectProps | undefined, position: Vector3, private readonly options: ParticleEffectObjectOptions = {}) { + super(id, position.clone()) + this.props = { ...props } + this.instance.position.copy(position) + this.instance.name = this.props.effect ?? PARTICLE_EFFECT_TYPE + ;(options.parent ?? Game.instance().scene).add(this.instance) + this.setEffect(this.props.effect) + } + + /** Play another registered effect instead, from the start. Undefined, or a name that isn't registered, plays none */ + setEffect(name: string | undefined) { + this.effect?.destroy() + this.effect = null + this.wasAlive = false + this.props.effect = name + if (!name || !getParticleNames().includes(name)) + return + + // At the group's origin: the group puts it in place + this.effect = createParticleEffect(name, new Vector3()) + if (this.effect && this.props.playing === false) + this.effect.stop(true) + if (this.effect) { + this.effect.wind = this.props.wind !== false + this.effect.collideWithScene = this.props.collider === true + this.effect.aroundCamera = this.props.aroundCamera === true + } + this.adopt() + } + + /** Whether a Wind in the scene moves its particles */ + get wind(): boolean { + return this.props.wind !== false + } + + set wind(value: boolean) { + this.props.wind = value + ? undefined + : false + if (this.effect) + this.effect.wind = value + } + + /** Whether its particles hit the scene's colliders, see `collider` */ + get collider(): boolean { + return this.props.collider === true + } + + set collider(value: boolean) { + this.props.collider = value || undefined + if (this.effect) + this.effect.collideWithScene = value + } + + /** Whether new particles start around the camera, see `aroundCamera` */ + get aroundCamera(): boolean { + return this.props.aroundCamera === true + } + + set aroundCamera(value: boolean) { + this.props.aroundCamera = value || undefined + if (this.effect) + this.effect.aroundCamera = value + } + + get playing(): boolean { + return this.effect?.playing ?? false + } + + /** Whether any of its particles are out */ + get alive(): boolean { + return this.effect?.alive ?? false + } + + play() { + this.effect?.play() + } + + /** No new particles. The ones out decay, or with `clear` go at once */ + stop(clear = false) { + this.effect?.stop(clear) + } + + /** Let out `count` particles at once, playing or not */ + burst(count: number) { + this.effect?.burst(count) + } + + /** The effect's emitters into the group, also ones it only adds later. Emitters add themselves to the game's scene */ + private adopt() { + for (const emitter of this.effect?.emitters ?? []) { + if (emitter.mesh.parent !== this.instance) + this.instance.add(emitter.mesh) + // Clicking the particles selects the object + if (this.editorHelper && emitter.mesh.userData.editorHelper !== this.editorHelper) + this.tagWithHelper(emitter.mesh) + } + } + + update(delta: number): void { + const effect = this.effect + if (!effect) + return + effect.update(delta) + this.adopt() + + const alive = effect.alive + if (this.wasAlive && !alive && !effect.playing) + this.finished() + this.wasAlive = alive + } + + private finished() { + if (this.options.onFinished) + this.options.onFinished(this) + else + triggerGraphEvent(PARTICLES_FINISHED, { effect: this.id }) + if (this.options.removeWhenFinished) + this.destroy() + } + + destroy(): void { + this.effect?.destroy() + this.effect = null + this.instance.removeFromParent() + super.destroy() + } +} + +/** Where a logic graph's particle nodes find and spawn effects */ +export interface ParticleHost { + /** The effect with this id: a scene object, or one a graph spawned */ + find(id: string): ParticleEffectObject | undefined + /** + * Start a registered effect at `position`, not part of the scene. With `burst` above 0 it lets out that many + * particles once and removes itself when they are gone, otherwise it plays until stopped or removed + */ + spawn(effect: string, position: number[], burst: number, options?: { collider?: boolean }): ParticleEffectObject | undefined +} + +let spawnedCount = 0 + +/** An id for a spawned effect that nothing in `taken` has */ +export function spawnedEffectId(effect: string, taken: (id: string) => boolean): string { + const base = `fx_${effect.toLowerCase().replace(/\W/g, '_')}` + let id = `${base}_${++spawnedCount}` + while (taken(id)) + id = `${base}_${++spawnedCount}` + return id +} + +/** The game's world: effects placed in the scene and those graphs spawned, by their id */ +export const sceneParticles: ParticleHost = { + find(id) { + const object = Game.instance().world.entities.items.get(id) + return object instanceof ParticleEffectObject && !object.garbageCollect + ? object + : undefined + }, + spawn(effect, [x = 0, y = 0, z = 0], burst, options = {}) { + if (!getParticleNames().includes(effect)) + return undefined + const items = Game.instance().world.entities.items + const id = spawnedEffectId(effect, id => items.has(id)) + const object = new ParticleEffectObject(id, { effect, playing: burst <= 0, collider: options.collider || undefined }, new Vector3(x, y, z), { removeWhenFinished: burst > 0 }) + object.spawned = true + if (burst > 0) + object.burst(burst) + Game.instance().world.add({ [id]: object }) + return object + }, +} diff --git a/packages/core/src/Particles/System/Emitter.ts b/packages/core/src/Particles/System/Emitter.ts index 8ec092f0..3de839c9 100644 --- a/packages/core/src/Particles/System/Emitter.ts +++ b/packages/core/src/Particles/System/Emitter.ts @@ -1,15 +1,21 @@ -import type { Vector3 } from 'three' import type { Node, PointsNodeMaterial } from 'three/webgpu' import type Particle from './Particle' +import { Quaternion, Vector3 } from 'three' import { instancedBufferAttribute } from 'three/tsl' import { BufferGeometry, InstancedBufferAttribute, Sprite } from 'three/webgpu' import Game from '../../Game' +import { skyState } from '../../Prefab/Sky/skyState' import GameObject from '../../World/GameObject' +const _at = new Vector3() +const _turn = new Quaternion() + +/** Where the editor's preview of an effect looks from */ export interface EmitterPreviewConfig { cameraPosition: [number, number, number] cameraTarget: [number, number, number] - create(): InstanceType | null + /** No longer used: the preview plays the whole effect, as its registry entry spawns it */ + create?(): InstanceType | null } /** @@ -31,6 +37,35 @@ export default abstract class Emitter extends GameObject { */ garbageCollect = false + /** + * Whether it lets out new particles. Stopped, the ones already out keep going until they decay. An emitter whose + * particles don't decay (like Rain's) fades out instead + */ + emitting = true + + /** + * How much a Wind in the scene carries its particles: 1 with the air, 0 not at all. Read it in `update()` through + * `windVelocity()`, which is zero without a Wind + */ + windInfluence = 1 + + /** + * Whether its particles hit the colliders of the game's physics world, for emitters whose particles bounce or stick. + * Off by default: no physics checks at all, they bounce off or settle on the emitter's own ground (its y = 0). The + * editor's previews, which play effects away from the scene, never turn it on + */ + collideWithScene = false + + /** + * Whether new particles start around the camera rather than the emitter, for weather and the like: an area that + * goes where the player goes. Only sideways: they keep their height against the emitter. The particles already out + * stay where they are in the world + */ + aroundCamera = false + + /** Whether the wind moves it at all: a switch for whoever uses the effect, beside the effect's own `windInfluence` */ + windEnabled = true + material: PointsNodeMaterial /** Holds the particle attributes as `position`, `aScale` and `aAlpha` */ geometry: BufferGeometry @@ -85,12 +120,58 @@ export default abstract class Emitter extends GameObject { } /** - * Remove everything from the scene + * The air's velocity at the emitter (m/s, see skyState.windAt) times `windInfluence`, turned into the emitter's own + * space like its particles' positions. Zero without a Wind in the scene + */ + windVelocity(out = new Vector3()): Vector3 { + if (!this.windEnabled || !this.windInfluence || !skyState.wind) + return out.set(0, 0, 0) + this.mesh.getWorldPosition(_at) + skyState.windAt(_at.x, _at.z, out).multiplyScalar(this.windInfluence) + return out.applyQuaternion(this.mesh.getWorldQuaternion(_turn).invert()) + } + + /** + * How far the camera is from the emitter sideways (y = 0), in the emitter's own space: where `aroundCamera` puts + * new particles. Zero with it off + */ + cameraOffset(out = new Vector3()): Vector3 { + if (!this.aroundCamera) + return out.set(0, 0, 0) + const camera = Game.instance().camera?.worldPosition + if (!camera) + return out.set(0, 0, 0) + this.mesh.getWorldPosition(_at) + out.set(camera.x - _at.x, 0, camera.z - _at.z) + return out.applyQuaternion(this.mesh.getWorldQuaternion(_turn).invert()) + } + + /** Whether any of its particles are still out */ + get alive(): boolean { + return this.particles.some(particle => particle.age < particle.decay) + } + + /** Let out up to `count` particles at once, emitting or not. Does nothing for an emitter that can't */ + burst(_count: number): void {} + + /** Take the particles that are out away at once */ + clear(): void { + for (const particle of this.particles) + particle.age = particle.decay + this.alphas.fill(0) + this.geometry.attributes.aAlpha.needsUpdate = true + } + + /** + * Remove everything from the scene. Only the first call does anything */ destroy() { + if (this.garbageCollect && !this.mesh.parent) + return super.destroy() - Game.instance().scene.remove(this.mesh) + // Wherever it was put: the game's scene, an effect's group or a preview's scene + this.mesh.removeFromParent() this.geometry.dispose() this.material.dispose() } @@ -98,9 +179,10 @@ export default abstract class Emitter extends GameObject { update(_delta: number): void { // Mark attribute as needing update this.geometry.attributes.aScale.needsUpdate = true + this.geometry.attributes.aAlpha.needsUpdate = true this.geometry.attributes.position.needsUpdate = true - if (!this.continoues && !this.particles.some(particle => particle.age < particle.decay)) { + if (!this.continoues && !this.alive) { this.destroy() } } diff --git a/packages/core/src/Particles/System/ParticleEffect.ts b/packages/core/src/Particles/System/ParticleEffect.ts index 150e7d16..4bd5a0bd 100644 --- a/packages/core/src/Particles/System/ParticleEffect.ts +++ b/packages/core/src/Particles/System/ParticleEffect.ts @@ -7,11 +7,62 @@ import GameObject from '../../World/GameObject' /** * A particle effect can be made up of multiple emitters. * For example a gunshot has smoke and sparks as individual emmiters. + * + * `play()`, `stop()` and `burst()` act on all of them, also on emitters an effect only adds later (e.g. once a + * texture has loaded). */ export default class ParticleEffect extends WithEditorHelper(GameObject) implements EditorHelperAttachment { emitters: Emitter[] = [] persistent = false + /** Whether a Wind in the scene moves its particles. Each emitter's `windInfluence` says how much */ + wind = true + + /** Whether its particles hit the scene's colliders, see Emitter.collideWithScene. Off by default */ + collideWithScene = false + + /** Whether new particles start around the camera, see Emitter.aroundCamera. Off by default */ + aroundCamera = false + + private _playing = true + /** The emitters the play state was handed to */ + private readonly known = new WeakSet() + + /** Whether its emitters let out new particles */ + get playing(): boolean { + return this._playing + } + + /** Whether any particles are still out. A stopped effect is finished once this turns false */ + get alive(): boolean { + return this.emitters.some(emitter => emitter.alive) + } + + /** Let out new particles again */ + play(): void { + this._playing = true + this.emitters.forEach((emitter) => { + this.known.add(emitter) + emitter.emitting = true + }) + } + + /** No new particles: the ones out decay, or with `clear` are taken away at once */ + stop(clear = false): void { + this._playing = false + this.emitters.forEach((emitter) => { + this.known.add(emitter) + emitter.emitting = false + if (clear) + emitter.clear() + }) + } + + /** Let out `count` particles at once from each emitter, playing or not */ + burst(count: number): void { + this.emitters.forEach(emitter => emitter.burst(count)) + } + destroy(): void { this.emitters.forEach(e => e.destroy()) this.emitters = [] @@ -23,7 +74,22 @@ export default class ParticleEffect extends WithEditorHelper(GameObject) impleme } update(delta: number): void { - this.emitters.forEach(emitter => emitter.update(delta)) + for (const emitter of this.emitters) { + if (this.known.has(emitter)) + continue + // Added since play() / stop(): it starts the way the effect is + this.known.add(emitter) + emitter.emitting = this._playing + if (!this._playing) + emitter.clear() + } + + this.emitters.forEach((emitter) => { + emitter.windEnabled = this.wind + emitter.collideWithScene = this.collideWithScene + emitter.aroundCamera = this.aroundCamera + emitter.update(delta) + }) this.emitters = this.emitters.filter((emitter) => { if (emitter.garbageCollect) { emitter.destroy() diff --git a/packages/core/src/Particles/System/ParticlePreviewRegistry.ts b/packages/core/src/Particles/System/ParticlePreviewRegistry.ts index e13ef078..e62036b7 100644 --- a/packages/core/src/Particles/System/ParticlePreviewRegistry.ts +++ b/packages/core/src/Particles/System/ParticlePreviewRegistry.ts @@ -1,30 +1,74 @@ import type { Vector3 } from 'three' import type { EmitterPreviewConfig } from './Emitter' import type ParticleEffect from './ParticleEffect' -import Logger from '../../Utils/Logger' export interface ParticleRegistryEntry { preview: EmitterPreviewConfig spawn(position: Vector3): ParticleEffect + /** Its icon in the editor's asset list: SVG markup (a 64 × 64 viewBox) or an image URL */ + icon?: string + /** Shown in the editor. Defaults to the name it is registered under */ + label?: string + /** npm package of the plugin that registered it, unset for the engine's and the project's */ + plugin?: string } const registry: Record = {} -// eslint-disable-next-line node/prefer-global/process -const logger = new Logger(process.env.NODE_ENV === 'production' - ? 'error' - : 'debug') +/** A plugin's effect's name: `:`, as scene files and graphs refer to it */ +export function pluginParticleName(pkg: string, name: string): string { + return `${pkg}:${name}` +} + +/** What the editor calls an effect: its label, or the name it is registered under */ +export function particleLabel(name: string): string { + return registry[name]?.label ?? name +} + +/** The effects to pick from in the editor: a plugin's say whose they are, `Hail (@acme/weather)` */ +export function particleChoices(): { value: string, label: string }[] { + return Object.entries(registry).map(([name, entry]) => ({ + value: name, + label: entry.plugin + ? `${particleLabel(name)} (${entry.plugin})` + : particleLabel(name), + })) +} + +/** + * Register an effect by name. Effects register as their modules load, so this must not need the game yet. A plugin + * registers its own with `ctx.registerParticle()`, which keys them by its package + */ export function registerParticle(name: string, entry: ParticleRegistryEntry) { registry[name] = entry - logger.info(`Particle registered: ${name}`) +} + +export function unregisterParticle(name: string) { + delete registry[name] +} + +/** An effect's registry entry, by name */ +export function getParticle(name: string): ParticleRegistryEntry | undefined { + return registry[name] } export function getPreviewMap(): Record { return Object.fromEntries(Object.entries(registry).map(([k, v]) => [k, v.preview])) } +/** The names of the registered particle effects */ +export function getParticleNames(): string[] { + return Object.keys(registry) +} + +/** A new effect of a registered kind at `position`, nothing else done with it. Null for a name that isn't one */ +export function createParticleEffect(name: string, position: Vector3): ParticleEffect | null { + return registry[name]?.spawn(position) ?? null +} + +/** A new effect with an editor helper of its own, not part of the scene. Place a `ParticleEffect` scene object to save it */ export function spawnParticle(name: string, position: Vector3): ParticleEffect | null { - const effect = registry[name]?.spawn(position) ?? null + const effect = createParticleEffect(name, position) if (effect) { effect.persistent = true effect.registerEditorHelper(position, name, effect) diff --git a/packages/core/src/Particles/System/PooledEmitter.ts b/packages/core/src/Particles/System/PooledEmitter.ts new file mode 100644 index 00000000..2a4b884f --- /dev/null +++ b/packages/core/src/Particles/System/PooledEmitter.ts @@ -0,0 +1,350 @@ +import type { Ray, World } from '@dimforge/rapier3d-compat' +import type { Blending, BufferAttribute, ColorRepresentation, Texture } from 'three' +import type { Node } from 'three/webgpu' +import RAPIER from '@dimforge/rapier3d-compat' +import { instancedBufferAttribute, mix, texture, uniform, uv, vec2, vec4 } from 'three/tsl' +import { AdditiveBlending, Color, InstancedBufferAttribute, Matrix4, PointsNodeMaterial, Quaternion, Vector3 } from 'three/webgpu' +import Game from '../../Game' +import Emitter from './Emitter' +import Particle from './Particle' +import { recordParticleContact } from './particleContacts' +import { focalScale, softDisc } from './particleShapes' + +/** A particle of a PooledEmitter: dead (age past its decay) until the emitter lets it out */ +export class PooledParticle extends Particle { + readonly velocity = new Vector3() + /** 0 – 1, picked when it is let out: for sizes and colors that differ from particle to particle */ + seed = 0 + /** It stuck where it hit (see `stick`): it stays put until it decays */ + landed = false + + constructor() { + super(0, new Vector3()) + } +} + +export interface PooledEmitterOptions { + /** The most particles out at once */ + maxParticles: number + /** Particles a second while emitting. 0 for an emitter that only bursts */ + rate?: number + /** While emitting, burst `count` particles every `every` seconds (a puff, a bang), the first at once */ + repeat?: { every: number, count: number } + /** What `burst(count)` lets out is `count` times this: an explosion's flash lets out fewer than its sparks */ + burstScale?: number + /** How long a particle lives (s), picked between the two */ + lifetime: [number, number] + /** World units across, at the start and the end of its life */ + size: [number, number] + /** Its color at the start and the end of its life */ + color: [ColorRepresentation, ColorRepresentation] + /** Its opacity at its fullest */ + opacity?: number + /** The part of its life it takes to fade in (0 – 1). Default 0.1 */ + fadeIn?: number + /** The part of its life, at the end, it fades out over (0 – 1). Default 1: all along */ + fadeOut?: number + /** Downward acceleration (m/s²): 9.8 falls like a stone, a negative one rises like hot air. Default 0 */ + gravity?: number + /** How fast the air slows it (per second). Default 0 */ + drag?: number + /** + * Bounces off what it hits, keeping this much of its speed away from the surface; unset to pass through everything. + * It hits the colliders of the game's physics world (terrain, primitives, scatter, the ground), see `collideWithScene`; + * without one, the ground of the emitter (its y = 0) + */ + bounce?: number + /** How much of its speed along the surface it loses on each bounce, and each moment it lies on it (0 – 1). Default 0.3 */ + friction?: number + /** + * Stays where it first hits something, as `bounce` would find it, instead of bouncing: snow settling, drops on a + * window. Lying there it no longer moves or casts rays, so it costs next to nothing + */ + stick?: boolean + /** How long a particle that stuck stays (s), picked between the two, before it decays. Default: the rest of its life */ + restFor?: [number, number] + /** How much particles' sizes differ (0 – 1): 0.4 makes some up to 40% smaller. Default 0 */ + sizeVariation?: number + /** How much a Wind in the scene carries it, see Emitter.windInfluence. Default 1 */ + windInfluence?: number + blending?: Blending + /** Each particle's look: this texture, or a round dot */ + texture?: Texture + /** For the round dot: 0 a soft glow, near 1 crisp. Default 0.2 */ + hardness?: number +} + +const _from = new Vector3() +const _step = new Vector3() +const _normal = new Vector3() +const _hitAt = new Vector3() +const _offset = new Vector3() +const _toLocal = new Matrix4() +const _turn = new Quaternion() +/** Made on first use: Rapier is loaded by then, as the game has a physics world */ +let _ray: Ray | undefined +/** How far off a surface a particle is put back (m) */ +const SKIN = 0.01 +/** Slower than this away from a surface (m/s), it stops bouncing and lies on it */ +const REST_SPEED = 0.4 + +/** + * Bounce `velocity` off a surface with normal `n` (unit length, both in the same space): what goes into the surface + * comes back out times `bounce`, what goes along it loses `friction`. Slow enough, it stays on the surface + */ +export function bounceOff(velocity: Vector3, n: Vector3, bounce: number, friction: number): void { + const into = velocity.dot(n) + if (into >= 0) + return + velocity.addScaledVector(n, -into).multiplyScalar(1 - friction) + const away = -into * bounce + if (away > REST_SPEED) + velocity.addScaledVector(n, away) +} + +/** + * An emitter that simulates its particles on the CPU from a pool: let out at a rate, in bursts or both, each moving + * with its velocity, gravity, drag and the wind, growing or shrinking and changing color over its life. Subclasses + * say where a new particle starts and how fast it goes, in `spawn()`. Positions are relative to the emitter. + */ +export default abstract class PooledEmitter extends Emitter { + declare particles: PooledParticle[] + readonly options: Required> & Pick + /** The wind its particles move with this update (m/s, in its own space), for `spawn()` and `steer()` */ + protected readonly wind = new Vector3() + /** Each particle's age against its life, 0 – 1, for the color */ + readonly lives: Float32Array + readonly lifeNode: Node<'float'> + readonly uniforms = { + startColor: uniform(new Color()), + endColor: uniform(new Color()), + } + + /** Particles owed to the rate, carried to the next update */ + private owed = 0 + /** Seconds to the next repeat burst */ + private nextRepeat = 0 + /** Where the search for a free particle starts */ + private cursor = 0 + + constructor(position: Vector3, options: PooledEmitterOptions) { + super(position, new PointsNodeMaterial({ + transparent: true, + depthWrite: false, + blending: options.blending ?? AdditiveBlending, + sizeAttenuation: true, + }), options.maxParticles, options.lifetime[1]) + + this.options = { + rate: 0, + burstScale: 1, + opacity: 1, + fadeIn: 0.1, + fadeOut: 1, + gravity: 0, + drag: 0, + windInfluence: 1, + friction: 0.3, + stick: false, + sizeVariation: 0, + blending: AdditiveBlending, + hardness: 0.2, + ...options, + } + this.windInfluence = this.options.windInfluence + + for (let i = 0; i < this.maxParticles; i++) + this.particles.push(new PooledParticle()) + + this.lives = new Float32Array(this.maxParticles) + const lifeAttribute = new InstancedBufferAttribute(this.lives, 1) + this.geometry.setAttribute('aLife', lifeAttribute) + this.lifeNode = instancedBufferAttribute(lifeAttribute, 'float') as unknown as Node<'float'> + + this.uniforms.startColor.value.set(options.color[0]) + this.uniforms.endColor.value.set(options.color[1]) + const shape = options.texture + ? texture(options.texture, vec2(uv().x, uv().y.oneMinus())).a + : softDisc(this.options.hardness) + const color = mix(this.uniforms.startColor, this.uniforms.endColor, this.lifeNode) + this.material.sizeNode = this.scaleNode.mul(focalScale) + this.material.colorNode = vec4(color, shape.mul(this.alphaNode)) + } + + /** Set a new particle going: where it starts (`particle.position`) and how fast (`particle.velocity`) */ + protected abstract spawn(particle: PooledParticle): void + + /** Let one particle out, if one is free */ + protected emitOne(): boolean { + for (let n = 0; n < this.maxParticles; n++) { + const i = (this.cursor + n) % this.maxParticles + const particle = this.particles[i] + if (particle.age < particle.decay) + continue + this.cursor = (i + 1) % this.maxParticles + const [shortest, longest] = this.options.lifetime + particle.age = 0 + particle.decay = shortest + Math.random() * (longest - shortest) + particle.seed = Math.random() + particle.landed = false + particle.position.set(0, 0, 0) + particle.velocity.set(0, 0, 0) + this.spawn(particle) + particle.position.add(this.cameraOffset(_offset)) + return true + } + return false + } + + /** Extra forces on a particle in flight, each update before it moves: a sway, a pull. Change its velocity */ + protected steer(_particle: PooledParticle, _delta: number): void {} + + /** Off the emitter's own ground, y = 0 */ + private hitGround(particle: PooledParticle, bounce: number, friction: number) { + particle.position.y = 0 + this.bounceOrStick(particle, _normal.set(0, 1, 0), bounce, friction) + } + + private bounceOrStick(particle: PooledParticle, n: Vector3, bounce: number, friction: number) { + if (!this.options.stick) { + bounceOff(particle.velocity, n, bounce, friction) + return + } + particle.landed = true + particle.velocity.set(0, 0, 0) + const restFor = this.options.restFor + if (restFor) + particle.decay = particle.age + restFor[0] + Math.random() * (restFor[1] - restFor[0]) + } + + /** + * Off the first collider the step from `_from` to the particle's position crosses: put back on the surface, just + * off it, and its velocity bounced. A step starting inside a collider passes through, so nothing sticks + */ + private hitScene(physics: World, particle: PooledParticle, bounce: number, friction: number) { + const matrix = this.mesh.matrixWorld + _from.applyMatrix4(matrix) + _step.copy(particle.position).applyMatrix4(matrix).sub(_from) + const length = _step.length() + if (length < 1e-6) + return + _step.divideScalar(length) + const ray = _ray ??= new RAPIER.Ray({ x: 0, y: 0, z: 0 }, { x: 0, y: -1, z: 0 }) + ray.origin = { x: _from.x, y: _from.y, z: _from.z } + ray.dir = { x: _step.x, y: _step.y, z: _step.z } + const hit = physics.castRayAndGetNormal(ray, length, true) + if (!hit || hit.timeOfImpact <= 0) + return + + const n = _normal.set(hit.normal.x, hit.normal.y, hit.normal.z) + // For the physics debug view, which can't see particles otherwise + if (Game.instance().physicsDebugRender?.enabled) + recordParticleContact(_hitAt.copy(_from).addScaledVector(_step, hit.timeOfImpact), n) + // Just off the surface, so the next step starts outside it + particle.position.copy(_from).addScaledVector(_step, hit.timeOfImpact).addScaledVector(n, SKIN).applyMatrix4(_toLocal) + this.bounceOrStick(particle, n.applyQuaternion(_turn), bounce, friction) + } + + /** `count` times its `burstScale`, at least one for any count */ + burst(count: number): void { + if (count <= 0) + return + const scaled = Math.max(1, Math.round(count * this.options.burstScale)) + for (let n = 0; n < scaled; n++) { + if (!this.emitOne()) + return + } + } + + update(delta: number): void { + const { rate, repeat, gravity, drag, friction, stick, size, sizeVariation, opacity, fadeIn, fadeOut } = this.options + // Sticking particles hit things as bouncing ones do, and stay + const bounce = this.options.bounce ?? (stick + ? 0 + : undefined) + + if (this.emitting) { + this.owed += rate * delta + while (this.owed >= 1) { + this.owed-- + this.emitOne() + } + if (repeat) { + this.nextRepeat -= delta + if (this.nextRepeat <= 0) { + this.nextRepeat += repeat.every + // Not a pile of bursts after a long pause + this.nextRepeat = Math.max(this.nextRepeat, 0) + this.burst(repeat.count) + } + } + } + else { + this.owed = 0 + // Playing again bursts at once + this.nextRepeat = 0 + } + + const wind = this.windVelocity(this.wind) + const slow = Math.max(0, 1 - drag * delta) + const physics = bounce !== undefined && this.collideWithScene + ? Game.instance().physicsWorld + : undefined + if (physics) { + this.mesh.updateMatrixWorld() + _toLocal.copy(this.mesh.matrixWorld).invert() + this.mesh.getWorldQuaternion(_turn).invert() + } + for (let i = 0; i < this.maxParticles; i++) { + const particle = this.particles[i] + if (particle.age >= particle.decay) { + this.alphas[i] = 0 + continue + } + particle.age += delta + const t = Math.min(1, particle.age / particle.decay) + + if (!particle.landed) { + const velocity = particle.velocity + this.steer(particle, delta) + velocity.y -= gravity * delta + velocity.multiplyScalar(slow) + _from.copy(particle.position) + particle.position.addScaledVector(velocity, delta).addScaledVector(wind, delta) + if (bounce !== undefined) { + if (physics) + this.hitScene(physics, particle, bounce, friction) + else if (particle.position.y < 0 && velocity.y < 0) + this.hitGround(particle, bounce, friction) + } + } + + this.positions[i * 3] = particle.position.x + this.positions[i * 3 + 1] = particle.position.y + this.positions[i * 3 + 2] = particle.position.z + this.scales[i] = (size[0] + (size[1] - size[0]) * t) * (1 - sizeVariation * particle.seed) + this.alphas[i] = opacity * Math.min(1, fadeIn > 0 + ? t / fadeIn + : 1) * Math.min(1, (1 - t) / Math.max(fadeOut, 1e-3)) + this.lives[i] = t + } + + for (const name of [ + 'position', + 'aScale', + 'aAlpha', + 'aLife', + ]) + (this.geometry.getAttribute(name) as BufferAttribute).needsUpdate = true + } +} + +/** A random direction, `out` set to it at length 1. With `up` 0 – 1, that share of those pointing down point up instead */ +export function randomDirection(out: Vector3, up = 0): Vector3 { + let y = Math.random() * 2 - 1 + if (y < 0 && Math.random() < up) + y = -y + const angle = Math.random() * Math.PI * 2 + const ring = Math.sqrt(1 - y * y) + return out.set(Math.cos(angle) * ring, y, Math.sin(angle) * ring) +} diff --git a/packages/core/src/Particles/System/particleContacts.ts b/packages/core/src/Particles/System/particleContacts.ts new file mode 100644 index 00000000..e80e0644 --- /dev/null +++ b/packages/core/src/Particles/System/particleContacts.ts @@ -0,0 +1,67 @@ +import type { Vector3 } from 'three' + +/* + * Where particles hit the physics world, for the physics debug view: particles aren't bodies or colliders, they cast + * rays through the world, so Rapier has nothing of theirs to draw. Each hit is drawn for a moment as a short line + * along the surface's normal. + */ + +/** How long a hit is shown (s) */ +const SHOWN_FOR = 1 +/** How long its line is (m) */ +const LENGTH = 0.3 +/** The most hits kept: the oldest go first */ +const MOST = 512 +/** Orange, apart from the colliders' own colors */ +const COLOR = [1, 0.55, 0.1, 1] + +interface Contact { x: number, y: number, z: number, nx: number, ny: number, nz: number, at: number } + +const contacts: Contact[] = [] + +function now() { + return performance.now() / 1000 +} + +/** A particle hit the world at `point`, on a surface facing `normal` (unit length). Both in world space */ +export function recordParticleContact(point: Vector3, normal: Vector3): void { + if (contacts.length >= MOST) + contacts.shift() + contacts.push({ + x: point.x, + y: point.y, + z: point.z, + nx: normal.x, + ny: normal.y, + nz: normal.z, + at: now(), + }) +} + +/** The recent hits as line segments, in the shape of Rapier's `debugRender()`: 2 points and 2 RGBA colors each */ +export function particleContactLines(): { vertices: Float32Array, colors: Float32Array } { + const since = now() - SHOWN_FOR + while (contacts.length && contacts[0].at < since) + contacts.shift() + + const vertices = new Float32Array(contacts.length * 6) + const colors = new Float32Array(contacts.length * 8) + contacts.forEach((c, i) => { + vertices.set([ + c.x, + c.y, + c.z, + c.x + c.nx * LENGTH, + c.y + c.ny * LENGTH, + c.z + c.nz * LENGTH, + ], i * 6) + colors.set(COLOR, i * 8) + colors.set(COLOR, i * 8 + 4) + }) + return { vertices, colors } +} + +/** For tests */ +export function _clearParticleContacts(): void { + contacts.length = 0 +} diff --git a/packages/core/src/Particles/System/particleShapes.ts b/packages/core/src/Particles/System/particleShapes.ts new file mode 100644 index 00000000..0455cb4c --- /dev/null +++ b/packages/core/src/Particles/System/particleShapes.ts @@ -0,0 +1,17 @@ +import type { Node } from 'three/webgpu' +import { cameraProjectionMatrix, float, smoothstep, uv } from 'three/tsl' + +/** + * 1 / tan(fov / 2) of the camera drawing: its projection's [1][1], as three's own Background reads it. An attenuated + * point size (`sizeAttenuation: true`) times this is a size in world units, for any field of view + */ +export const focalScale = (cameraProjectionMatrix as unknown as { element(i: number): { element(i: number): Node<'float'> } }).element(1).element(1) + +/** + * A round particle: 1 in the middle, 0 at the edge of its quad. `hardness` (0 – 1) is how far out it stays full before + * fading: 0 a soft glow, near 1 a crisp dot + */ +export function softDisc(hardness = 0.2): Node<'float'> { + const inner = float(0.5).mul(Math.min(0.99, Math.max(0, hardness))) + return smoothstep(float(0.5), inner, uv().sub(0.5).length()) as unknown as Node<'float'> +} diff --git a/packages/core/src/Particles/particleNodes.ts b/packages/core/src/Particles/particleNodes.ts new file mode 100644 index 00000000..4c35a61d --- /dev/null +++ b/packages/core/src/Particles/particleNodes.ts @@ -0,0 +1,157 @@ +import type { NodeDefinition, NodeEvalContext, NodeRunContext, PortSpec } from '../Graph/NodeRegistry' +import type { GraphData, GraphKind, GraphValue } from '../Graph/types' +import type { ParticleEffectObject, ParticleHost } from './ParticleEffectObject' +import { getNode, registerNode } from '../Graph/NodeRegistry' +import { asFloat, asVector } from '../Graph/Nodes/values' +import { PARTICLES_FINISHED, sceneParticles } from './ParticleEffectObject' + +/* + * Logic graph nodes for particle effects: spawn one, play, stop or burst one placed in the scene (or spawned), and + * hear when one has finished. Client only: the server draws no particles. An Effect input left empty is the graph's + * Self, so a Logic Graph object targeting a Particle Effect drives it without wiring. + */ + +const LOGIC: GraphKind[] = ['logic'] +/** The nodes' category in the editor's node list */ +export const PARTICLES = 'Particles' +const exec: PortSpec = { type: 'exec', label: '' } +const run = { run: exec } +const then = { then: exec } +const effectInput: PortSpec = { type: 'entity', label: 'Effect', default: '' } + +/** The preview's host in the graph editor, the scene's otherwise */ +function host(context: NodeEvalContext): ParticleHost { + return (context.services?.particles as ParticleHost | undefined) ?? sceneParticles +} + +/** The effect an Effect input names, Self when it is empty */ +function target(inputs: Record, context: NodeEvalContext): ParticleEffectObject | undefined { + const id = String(inputs.effect ?? '') || context.self?.id + return id + ? host(context).find(id) + : undefined +} + +/** A step acting on one effect, which logs when there is none */ +function action(type: string, label: string, description: string, inputs: Record, act: (object: ParticleEffectObject, inputs: Record, context: NodeRunContext) => void): NodeDefinition { + return { + type: `particles.${type}`, + label, + category: PARTICLES, + description: `${description}. Client only`, + kinds: LOGIC, + inputs: { + ...run, + effect: effectInput, + ...inputs, + }, + outputs: then, + run: (values, context) => { + const object = target(values, context) + if (object) + act(object, values, context) + else + context.log(`${label}: no particle effect "${String(values.effect ?? '') || context.self?.id || ''}"`) + }, + } +} + +export const PARTICLE_NODES: NodeDefinition[] = [ + { + type: 'particles.spawn', + label: 'Spawn Effect', + category: PARTICLES, + description: 'Start a particle effect at a position, not part of the scene. Burst 0 plays it until Stop Effect or Remove Effect; more lets out that many particles once and removes it when they are gone. Collider lets its bouncing particles hit the scene\'s colliders. Client only', + kinds: LOGIC, + settings: { + kind: { type: 'string', label: 'Effect', default: 'Smoke' }, + }, + inputs: { + ...run, + position: { + type: 'vec3', + label: 'Position', + default: [0, 0, 0], + }, + burst: { type: 'int', label: 'Burst', default: 0 }, + collider: { type: 'bool', label: 'Collider', default: false }, + }, + outputs: { + ...then, + effect: { type: 'entity', label: 'Effect' }, + }, + run: (inputs, context) => { + const kind = String(context.values.kind ?? 'Smoke') + const object = host(context).spawn(kind, asVector(inputs.position, 3), Math.max(0, Math.floor(asFloat(inputs.burst))), { collider: !!inputs.collider }) + if (!object) + context.log(`Spawn Effect: there is no particle effect named "${kind}"`) + return { + outputs: { effect: object?.id ?? '' }, + } + }, + }, + action('play', 'Play Effect', 'Let a particle effect out new particles again', {}, object => object.play()), + action('stop', 'Stop Effect', 'No new particles: the ones out decay, or with Clear go at once', { + clear: { type: 'bool', label: 'Clear', default: false }, + }, (object, inputs) => object.stop(!!inputs.clear)), + action('burst', 'Burst Effect', 'Let out a number of particles at once, playing or not', { + count: { type: 'int', label: 'Count', default: 10 }, + }, (object, inputs) => object.burst(Math.max(0, Math.floor(asFloat(inputs.count))))), + action('remove', 'Remove Effect', 'Remove an effect a Spawn Effect started. One placed in the scene stays: stop it instead', {}, (object, _, context) => { + if (object.spawned) + object.destroy() + else + context.log(`Remove Effect: ${object.id} is part of the scene, stop it instead`) + }), + { + type: 'particles.state', + label: 'Effect State', + category: PARTICLES, + description: 'Whether a particle effect is playing, and whether any of its particles are still out. Client only', + kinds: LOGIC, + inputs: { effect: effectInput }, + outputs: { + playing: { type: 'bool', label: 'Playing' }, + alive: { type: 'bool', label: 'Particles Out' }, + }, + eval: (inputs, context) => { + const object = target(inputs, context) + return { playing: object?.playing ?? false, alive: object?.alive ?? false } + }, + }, + { + type: 'particles.onFinished', + label: 'On Effect Finished', + category: PARTICLES, + description: 'When a stopped or bursting particle effect\'s last particle is gone: the one picked, or any with none picked. Client only', + kinds: LOGIC, + trigger: PARTICLES_FINISHED, + settings: { + effect: { type: 'entity', label: 'Effect', default: '' }, + }, + inputs: {}, + outputs: { + ...then, + effect: { type: 'entity', label: 'Effect' }, + }, + run: (_, { event, values }) => { + const want = String(values.effect ?? '') + if (want && want !== event.effect) + return false + return { + outputs: { effect: event.effect ?? '' }, + } + }, + }, +] + +/** Whether a graph uses any node of the Particles category, the engine's or a plugin's */ +export function usesParticleNodes(graph: Pick): boolean { + return graph.nodes.some(node => getNode(node.type)?.category === PARTICLES) +} + +/** Registering again replaces them */ +export function registerParticleNodes() { + for (const node of PARTICLE_NODES) + registerNode(node) +} diff --git a/packages/core/src/Plugins/types.ts b/packages/core/src/Plugins/types.ts index 38290ef3..084602ea 100644 --- a/packages/core/src/Plugins/types.ts +++ b/packages/core/src/Plugins/types.ts @@ -12,6 +12,7 @@ import type { AuthorizeResult, Identity } from '../Networking/identity' import type { AdminApi } from '../Networking/Server/Admin/types' import type Server from '../Networking/Server/Server' import type { Notifiable, NotificationLike } from '../Notifications/Notifiable' +import type { ParticleRegistryEntry } from '../Particles/System/ParticlePreviewRegistry' import type { PrefabDefinition } from '../Prefab/PrefabRegistry' import type Queue from '../Queue/Queue' import type { SceneObjectDefinition } from '../Scene/SceneObjectRegistry' @@ -80,6 +81,13 @@ export interface ClientPluginContext extends PluginContextBase:`, which is returned. Only matters in the editor; registering it in a release does nothing */ registerBrush(brush: Omit): string + /** + * Add a particle effect: in the editor's Particles tab, placeable in scenes and played by graphs (Spawn Effect). + * Its name in scene files and graphs is `:`, which is returned; the editor shows `label` (default + * `name`). Build it from the engine's emitters (`PooledEmitter`, `Emitter`) in a `ParticleEffect`, and load its + * textures from `assetUrl()` + */ + registerParticle(name: string, entry: Omit): string /** * Add a node type to graphs, with its TSL implementation for material graphs (see `registerTslNode()`). Its key in * graph files is `:`, which is returned diff --git a/packages/core/src/Renderer/PhysicsRenderer.ts b/packages/core/src/Renderer/PhysicsRenderer.ts index 59f59b9b..5e6d3f26 100644 --- a/packages/core/src/Renderer/PhysicsRenderer.ts +++ b/packages/core/src/Renderer/PhysicsRenderer.ts @@ -2,7 +2,18 @@ import type RAPIER from '@dimforge/rapier3d-compat' import type { Scene } from 'three' import { BufferAttribute, BufferGeometry, LineBasicMaterial, LineSegments } from 'three' import Game from '../Game' +import { particleContactLines } from '../Particles/System/particleContacts' +function join(a: Float32Array, b: Float32Array): Float32Array { + if (!b.length) + return a + const out = new Float32Array(a.length + b.length) + out.set(a) + out.set(b, a.length) + return out +} + +/** Draws the physics world's colliders, and where particles hit them (see particleContacts) */ export class RapierDebugRenderer { mesh world @@ -46,8 +57,10 @@ export class RapierDebugRenderer { update() { if (this.enabled) { const { vertices, colors } = this.world.debugRender() - this.mesh.geometry.setAttribute('position', new BufferAttribute(vertices, 3)) - this.mesh.geometry.setAttribute('color', new BufferAttribute(colors, 4)) + // And where particles hit the colliders: they aren't in the world themselves + const hits = particleContactLines() + this.mesh.geometry.setAttribute('position', new BufferAttribute(join(vertices, hits.vertices), 3)) + this.mesh.geometry.setAttribute('color', new BufferAttribute(join(colors, hits.colors), 4)) this.mesh.visible = true this.stats.bodies = 0 diff --git a/packages/core/src/Scene/builtinSceneObjects.ts b/packages/core/src/Scene/builtinSceneObjects.ts index 98ee76c6..9a6c340e 100644 --- a/packages/core/src/Scene/builtinSceneObjects.ts +++ b/packages/core/src/Scene/builtinSceneObjects.ts @@ -2,6 +2,7 @@ import type { Group, Light, LightShadow } from 'three' import type { GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js' import type { LogicGraphProps, LogicGraphSide } from '../Graph/Logic/logicGraphObject' import type { GraphValue } from '../Graph/types' +import type { ParticleEffectProps } from '../Particles/ParticleEffectObject' import type { LightPrimitive } from '../Prefab/Lights/index' import type { Primitive } from '../Prefab/Primitives/index' import type GameScene from './GameScene' @@ -12,6 +13,9 @@ import { WithEditorHelper } from '../Editor/WithEditorHelper' import Game from '../Game' import { LOGIC_GRAPH_TYPE, LogicGraphObject, runsOn } from '../Graph/Logic/logicGraphObject' import { materialGraphs } from '../Graph/Material/MaterialGraphs' +import { PARTICLE_EFFECT_TYPE, ParticleEffectObject } from '../Particles/ParticleEffectObject' +import { registerParticleNodes } from '../Particles/particleNodes' +import { particleChoices, particleLabel } from '../Particles/System/ParticlePreviewRegistry' import { LIGHT_REGISTRY } from '../Prefab/Lights/index' import { getPrefab, spawnPrefab } from '../Prefab/PrefabRegistry' import { PRIMITIVE_REGISTRY } from '../Prefab/Primitives/index' @@ -24,6 +28,15 @@ import { TERRAIN_TYPE } from '../Terrain/terrainData' import GameObject from '../World/GameObject' import { primitiveOptionsFromProps, primitiveType } from './primitiveSceneObjects' import { registerSceneObject, registerSceneObjectResolver } from './SceneObjectRegistry' +// The effects that come with the engine register themselves +import '../Particles/Effects/Debris' +import '../Particles/Effects/DustPuff' +import '../Particles/Effects/Explosion' +import '../Particles/Effects/Fire' +import '../Particles/Effects/Rain' +import '../Particles/Effects/Smoke' +import '../Particles/Effects/Snow' +import '../Particles/Effects/Sparks' /** * The client side of the scene object types that come with the engine. None of them exist on the server, @@ -38,6 +51,11 @@ import { registerSceneObject, registerSceneObjectResolver } from './SceneObjectR * - `Model` props: resource (name of a loaded gltfModel), castShadow, receiveShadow * - `prefab:` any prefab of the prefab registry, by its key. The sky's (`prefab:Sun`, `prefab:Sky`, `prefab:Atmosphere`, * `prefab:Wind`, `prefab:Clouds`) save their settings as props, see Prefab/Sky/skySystem + * - `ParticleEffect` props: effect (a registered particle effect's name, e.g. `Smoke`), playing (false waits for a + * graph or code to play it), wind (false: a Wind in the scene doesn't move it), collider (true: its bouncing + * particles hit the scene's colliders, otherwise its own flat ground), aroundCamera (true: new particles start + * around the camera, for weather). See Particles/ParticleEffectObject; logic + * graphs drive it with the Particles nodes * - `LogicGraph` props: graph, side ('client' | 'server' | 'both'), target, parameters. Runs a logic graph, see * Graph/Logic/logicGraphObject (which the server registers too) * - `Terrain` props: see TerrainProps. A heightmap with painted material layers; the server builds its heightfield @@ -282,6 +300,110 @@ class ClientLogicGraph extends WithEditorHelper(LogicGraphObject) { } } +/** + * A particle effect in the scene, with an editor helper to select, move, set up and try it by + */ +class ClientParticleEffect extends ParticleEffectObject { + /** Where the helper was last put: when the group is elsewhere, something else (a graph) moved it */ + private readonly synced = new Vector3() + + constructor(data: SceneObjectData, scene: GameScene | undefined) { + super(data.id, data.props as ParticleEffectProps | undefined, new Vector3(...data.transform.position)) + this.synced.copy(this.instance.position) + + const setProp = (changes: Partial) => scene?.setProps(this.id, { + ...this.props, + ...changes, + }) + this.registerEditorHelper(this.instance.position.clone(), `Particles: ${this.props.effect + ? particleLabel(this.props.effect) + : 'none'}`, { + onMove: () => { + if (!this.editorHelper) + return + this.instance.position.copy(this.editorHelper.mesh.position) + this.synced.copy(this.instance.position) + }, + properties: [ + { + type: 'particlePreview', + label: 'preview', + getValue: () => this.props.effect ?? '', + }, + { + type: 'select', + label: 'effect', + options: () => [ + { value: '', label: 'None' }, + ...particleChoices(), + ], + getValue: () => this.props.effect ?? '', + setValue: v => setProp({ effect: v || undefined }), + }, + { + type: 'checkbox', + label: 'plays on start', + getValue: () => this.props.playing !== false, + setValue: v => setProp({ + playing: v + ? undefined + : false, + }), + }, + { + type: 'checkbox', + label: 'wind', + getValue: () => this.wind, + setValue: v => setProp({ + wind: v + ? undefined + : false, + }), + }, + { + type: 'checkbox', + label: 'around camera', + getValue: () => this.aroundCamera, + setValue: v => setProp({ aroundCamera: v || undefined }), + }, + { + type: 'checkbox', + label: 'collider', + getValue: () => this.collider, + setValue: v => setProp({ collider: v || undefined }), + }, + { + type: 'buttons', + label: 'try', + buttons: [ + { + label: 'Play', + onClick: () => this.play(), + }, + { + label: 'Stop', + onClick: () => this.stop(), + }, + { + label: 'Burst', + onClick: () => this.burst(10), + }, + ], + }, + ], + }) + } + + update(delta: number): void { + super.update(delta) + // The helper follows the group when a graph moves it + if (this.editorHelper && !this.instance.position.equals(this.synced)) { + this.editorHelper.mesh.position.copy(this.instance.position) + this.synced.copy(this.instance.position) + } + } +} + let registered = false export function registerBuiltinSceneObjects() { @@ -341,6 +463,15 @@ export function registerBuiltinSceneObjects() { serialize: object => ({ ...object.props }), }) + registerSceneObject({ + type: PARTICLE_EFFECT_TYPE, + label: 'Particle Effect', + client: (data, { scene }) => new ClientParticleEffect(data, scene), + serialize: object => ({ ...object.props }), + transformTarget: object => object.instance, + }) + registerParticleNodes() + registerSceneObject({ type: TERRAIN_TYPE, label: 'Terrain', diff --git a/packages/core/tests/Game.test.ts b/packages/core/tests/Game.test.ts index e1c77449..d49e295e 100644 --- a/packages/core/tests/Game.test.ts +++ b/packages/core/tests/Game.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import Game from '../src/Game' +import { getParticle, particleLabel, unregisterParticle } from '../src/Particles/System/ParticlePreviewRegistry' import { getPrefab, unregisterPrefab } from '../src/Prefab/PrefabRegistry' import Resources from '../src/Utils/Resources' @@ -310,6 +311,34 @@ describe('game', () => { unregisterPrefab('forest:Tree') }) + it('registers plugin particle effects under the plugin', () => { + let key: string | undefined + Game.usePlugins([ + { + package: 'weather', + options: {}, + plugin: { + setup: (ctx) => { + key = ctx.registerParticle('Hail', { + preview: { + cameraPosition: [0, 0, 5], + cameraTarget: [0, 0, 0], + }, + spawn: vi.fn(), + }) + }, + }, + }, + ]) + + void new Game([]) + + expect(key).toBe('weather:Hail') + expect(getParticle('weather:Hail')).toMatchObject({ plugin: 'weather', label: 'Hail' }) + expect(particleLabel('weather:Hail')).toBe('Hail') + unregisterParticle('weather:Hail') + }) + it('runs the editor hook when the editor boots', () => { const editorHook = vi.fn() Game.usePlugins([ diff --git a/packages/core/tests/Particles/effects.test.ts b/packages/core/tests/Particles/effects.test.ts new file mode 100644 index 00000000..e6810da6 --- /dev/null +++ b/packages/core/tests/Particles/effects.test.ts @@ -0,0 +1,215 @@ +import type { PooledParticle } from '../../src/Particles/System/PooledEmitter' +import { Object3D, Vector3 } from 'three' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createParticleEffect, getParticleNames } from '../../src/Particles/System/ParticlePreviewRegistry' +import PooledEmitter from '../../src/Particles/System/PooledEmitter' +import '../../src/Particles/Effects/Debris' +import '../../src/Particles/Effects/DustPuff' +import '../../src/Particles/Effects/Explosion' +import '../../src/Particles/Effects/Fire' +import '../../src/Particles/Effects/Rain' +import '../../src/Particles/Effects/Smoke' +import '../../src/Particles/Effects/Snow' +import '../../src/Particles/Effects/Sparks' + +const game = vi.hoisted(() => ({ + scene: undefined as unknown as Object3D, + camera: { worldPosition: undefined as unknown }, + resources: { + items: {}, + loaded: 0, + toLoad: 0, + on: () => {}, + off: () => {}, + }, +})) +vi.mock('../../src/Game', () => ({ + default: { + instance: () => game, + }, +})) + +/** Lets particles out straight up at 1 m/s from the origin */ +class TestEmitter extends PooledEmitter { + protected spawn(particle: PooledParticle): void { + particle.velocity.set(0, 1, 0) + } +} + +function out(emitter: PooledEmitter) { + return emitter.particles.filter(particle => particle.age < particle.decay).length +} + +beforeEach(() => { + game.scene = new Object3D() + game.camera.worldPosition = new Vector3() +}) + +describe('pooledEmitter', () => { + it('lets particles out at its rate, never more than its pool', () => { + const emitter = new TestEmitter(new Vector3(), { + maxParticles: 5, + rate: 10, + lifetime: [10, 10], + size: [1, 1], + color: [0xFFFFFF, 0xFFFFFF], + }) + expect(emitter.alive).toBe(false) + emitter.update(0.25) + expect(out(emitter)).toBe(2) + emitter.update(1) + expect(out(emitter)).toBe(5) + }) + + it('stops letting them out, and they die off', () => { + const emitter = new TestEmitter(new Vector3(), { + maxParticles: 10, + rate: 10, + lifetime: [0.5, 0.5], + size: [1, 1], + color: [0xFFFFFF, 0xFFFFFF], + }) + emitter.update(0.3) + emitter.emitting = false + emitter.update(0.6) + expect(emitter.alive).toBe(false) + expect([...emitter.alphas].every(alpha => alpha === 0)).toBe(true) + }) + + it('bursts by its burst scale, at least one', () => { + const emitter = new TestEmitter(new Vector3(), { + maxParticles: 50, + burstScale: 0.1, + lifetime: [1, 1], + size: [1, 1], + color: [0xFFFFFF, 0xFFFFFF], + }) + emitter.burst(30) + expect(out(emitter)).toBe(3) + emitter.burst(1) + expect(out(emitter)).toBe(4) + emitter.burst(0) + expect(out(emitter)).toBe(4) + }) + + it('repeats its burst while emitting, at once and then every so often', () => { + const emitter = new TestEmitter(new Vector3(), { + maxParticles: 50, + repeat: { every: 1, count: 5 }, + lifetime: [10, 10], + size: [1, 1], + color: [0xFFFFFF, 0xFFFFFF], + }) + emitter.update(0.1) + expect(out(emitter)).toBe(5) + emitter.update(0.5) + expect(out(emitter)).toBe(5) + emitter.update(0.5) + expect(out(emitter)).toBe(10) + }) + + it('moves them, grows them over their life, and bounces them off the ground', () => { + const emitter = new TestEmitter(new Vector3(), { + maxParticles: 1, + lifetime: [2, 2], + size: [1, 3], + color: [0xFFFFFF, 0xFFFFFF], + gravity: 5, + bounce: 0.5, + fadeIn: 0, + }) + emitter.burst(1) + emitter.update(0.1) + expect(emitter.positions[1]).toBeGreaterThan(0) + expect(emitter.scales[0]).toBeCloseTo(1.1) + for (let i = 0; i < 5; i++) + emitter.update(0.1) + const particle = emitter.particles[0] + expect(particle.position.y).toBeGreaterThanOrEqual(0) + expect(emitter.lives[0]).toBeCloseTo(0.3) + }) +}) + +describe('around the camera', () => { + it('starts new particles around the camera sideways, and leaves those out where they are', () => { + const emitter = new TestEmitter(new Vector3(2, 0, 0), { + maxParticles: 2, + lifetime: [10, 10], + size: [1, 1], + color: [0xFFFFFF, 0xFFFFFF], + }) + game.scene.add(emitter.mesh) + emitter.aroundCamera = true + ;(game.camera.worldPosition as Vector3).set(10, 5, -4) + emitter.burst(1) + // From the emitter at x = 2 to the camera, at the emitter's height + expect(emitter.particles[0].position.toArray()).toEqual([8, 0, -4]) + + ;(game.camera.worldPosition as Vector3).set(-20, 5, 0) + emitter.burst(1) + expect(emitter.particles[0].position.toArray()).toEqual([8, 0, -4]) + expect(emitter.particles[1].position.toArray()).toEqual([-22, 0, 0]) + }) + + it('is off unless asked for', () => { + const emitter = new TestEmitter(new Vector3(), { + maxParticles: 1, + lifetime: [10, 10], + size: [1, 1], + color: [0xFFFFFF, 0xFFFFFF], + }) + ;(game.camera.worldPosition as Vector3).set(10, 5, -4) + emitter.burst(1) + expect(emitter.particles[0].position.toArray()).toEqual([0, 0, 0]) + }) + + it('centres the rain on the camera', () => { + const effect = createParticleEffect('Rain', new Vector3())! + effect.aroundCamera = true + ;(game.camera.worldPosition as Vector3).set(30, 2, 7) + effect.update(0.1) + const rain = effect.emitters[0] as unknown as { uniforms: { uCenter: { value: Vector3 } } } + expect(rain.uniforms.uCenter.value.toArray()).toEqual([30, 0, 7]) + effect.destroy() + }) +}) + +describe('the built-in effects', () => { + it('are all registered', () => { + expect(getParticleNames()).toEqual(expect.arrayContaining([ + 'Debris', + 'Dust Puff', + 'Explosion', + 'Fire', + 'Rain', + 'Smoke', + 'Snow', + 'Sparks', + ])) + }) + + it.each([ + 'Debris', + 'Dust Puff', + 'Explosion', + 'Fire', + 'Rain', + 'Smoke', + 'Snow', + 'Sparks', + ])('%s plays, stops and finishes', (name) => { + const effect = createParticleEffect(name, new Vector3(1, 0, 2))! + expect(effect.emitters.length).toBeGreaterThan(0) + for (let i = 0; i < 30; i++) + effect.update(0.1) + expect(effect.alive).toBe(true) + + effect.burst(5) + effect.stop() + for (let i = 0; i < 400; i++) + effect.update(0.1) + expect(effect.alive).toBe(false) + effect.destroy() + expect(game.scene.children).toHaveLength(0) + }) +}) diff --git a/packages/core/tests/Particles/emitterWind.test.ts b/packages/core/tests/Particles/emitterWind.test.ts new file mode 100644 index 00000000..45194524 --- /dev/null +++ b/packages/core/tests/Particles/emitterWind.test.ts @@ -0,0 +1,74 @@ +import { Object3D, Vector3 } from 'three' +import { PointsNodeMaterial } from 'three/webgpu' +import { afterEach, describe, expect, it, vi } from 'vitest' +import Emitter from '../../src/Particles/System/Emitter' +import { skyState } from '../../src/Prefab/Sky/skyState' + +const game = vi.hoisted(() => ({ scene: undefined as unknown as Object3D })) +vi.mock('../../src/Game', () => ({ + default: { + instance: () => game, + }, +})) + +class TestEmitter extends Emitter {} + +function emitter() { + game.scene = new Object3D() + return new TestEmitter(new Vector3(), new PointsNodeMaterial(), 4, 1) +} + +afterEach(() => { + skyState.useWind(undefined) +}) + +describe('emitter wind', () => { + it('has none without a Wind', () => { + expect(emitter().windVelocity().toArray()).toEqual([0, 0, 0]) + }) + + it('follows the Wind, scaled by its influence and turned into its own space', () => { + skyState.useWind({ + speed: 4, + from: 90, + gustiness: 0, + gustPeriod: 5, + veer: 0, + }) + skyState.advance(10) + const e = emitter() + const air = skyState.windAt(0, 0) + expect(air.length()).toBeGreaterThan(0) + expect(e.windVelocity().distanceTo(air)).toBeLessThan(1e-6) + + e.windInfluence = 0.5 + expect(e.windVelocity().distanceTo(air.clone().multiplyScalar(0.5))).toBeLessThan(1e-6) + + // Turned half way round, the air comes the other way in its own space + e.windInfluence = 1 + e.mesh.rotation.y = Math.PI + e.mesh.updateMatrixWorld() + const local = e.windVelocity() + expect(local.x).toBeCloseTo(-air.x) + expect(local.z).toBeCloseTo(-air.z) + + e.windInfluence = 0 + expect(e.windVelocity().toArray()).toEqual([0, 0, 0]) + }) +}) + +describe('turning the wind off', () => { + it('leaves the emitter still in a Wind', () => { + skyState.useWind({ + speed: 4, + from: 90, + gustiness: 0, + gustPeriod: 5, + veer: 0, + }) + skyState.advance(10) + const e = emitter() + e.windEnabled = false + expect(e.windVelocity().toArray()).toEqual([0, 0, 0]) + }) +}) diff --git a/packages/core/tests/Particles/particleCollisions.test.ts b/packages/core/tests/Particles/particleCollisions.test.ts new file mode 100644 index 00000000..b8c3e5d3 --- /dev/null +++ b/packages/core/tests/Particles/particleCollisions.test.ts @@ -0,0 +1,194 @@ +import type { World } from '@dimforge/rapier3d-compat' +import type { PooledEmitterOptions, PooledParticle } from '../../src/Particles/System/PooledEmitter' +import RAPIER from '@dimforge/rapier3d-compat' +import { Object3D, Vector3 } from 'three' +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { _clearParticleContacts, particleContactLines } from '../../src/Particles/System/particleContacts' +import PooledEmitter, { bounceOff } from '../../src/Particles/System/PooledEmitter' + +const game = vi.hoisted(() => ({ + scene: undefined as unknown as Object3D, + physicsWorld: undefined as World | undefined, + physicsDebugRender: undefined as { enabled: boolean } | undefined, +})) +vi.mock('../../src/Game', () => ({ + default: { + instance: () => game, + }, +})) + +/** Drops its particles from `from`, still */ +class DropEmitter extends PooledEmitter { + constructor(position: Vector3, private readonly from: Vector3, options: Partial = {}) { + super(position, { + maxParticles: 1, + lifetime: [100, 100], + size: [1, 1], + color: [0xFFFFFF, 0xFFFFFF], + gravity: 9.8, + bounce: 0.5, + friction: 0, + ...options, + }) + this.collideWithScene = true + } + + protected spawn(particle: PooledParticle): void { + particle.position.copy(this.from) + } +} + +/** Run `seconds` of it in small steps, the lowest height the particle went to and whether it ever went up */ +function run(emitter: PooledEmitter, seconds: number) { + let lowest = Infinity + let rose = false + for (let t = 0; t < seconds; t += 1 / 60) { + emitter.update(1 / 60) + const particle = emitter.particles[0] + lowest = Math.min(lowest, particle.position.y) + rose ||= particle.velocity.y > 0 + } + return { lowest, rose } +} + +beforeAll(async () => { + await RAPIER.init() +}) + +beforeEach(() => { + game.scene = new Object3D() + const world = new RAPIER.World({ x: 0, y: 0, z: 0 }) + // A table: its top at y = 1, from x = -2 to 2 + world.createCollider(RAPIER.ColliderDesc.cuboid(2, 0.5, 2).setTranslation(0, 0.5, 0)) + world.step() + game.physicsWorld = world +}) + +describe('bounceOff', () => { + it('sends back what goes into the surface, less its bounce, and keeps what goes along it, less friction', () => { + const velocity = new Vector3(2, -4, 0) + bounceOff(velocity, new Vector3(0, 1, 0), 0.5, 0.25) + expect(velocity.x).toBeCloseTo(1.5) + expect(velocity.y).toBeCloseTo(2) + }) + + it('lets a slow one lie on the surface', () => { + const velocity = new Vector3(0, -0.5, 0) + bounceOff(velocity, new Vector3(0, 1, 0), 0.5, 0) + expect(velocity.y).toBe(0) + }) + + it('leaves one moving away from the surface', () => { + const velocity = new Vector3(0, 3, 0) + bounceOff(velocity, new Vector3(0, 1, 0), 0.5, 0) + expect(velocity.y).toBe(3) + }) +}) + +describe('colliding particles', () => { + it('bounce off a collider of the physics world, and come to rest on it', () => { + const emitter = new DropEmitter(new Vector3(), new Vector3(0, 3, 0)) + emitter.burst(1) + const { lowest, rose } = run(emitter, 4) + expect(rose).toBe(true) + expect(lowest).toBeGreaterThan(0.99) + expect(emitter.particles[0].position.y).toBeCloseTo(1, 1) + expect(Math.abs(emitter.particles[0].velocity.y)).toBeLessThan(0.5) + }) + + it('hit it in the world, wherever the emitter is', () => { + // The emitter 5 m up: its particle starts 2 m above the table + const emitter = new DropEmitter(new Vector3(0, 5, 0), new Vector3(0, -2, 0)) + game.scene.add(emitter.mesh) + emitter.burst(1) + run(emitter, 4) + // In the emitter's space, the table's top is 4 m down + expect(emitter.particles[0].position.y).toBeCloseTo(-4, 1) + }) + + it('fall off its edge onto nothing', () => { + const emitter = new DropEmitter(new Vector3(), new Vector3(3, 3, 0)) + emitter.burst(1) + expect(run(emitter, 2).lowest).toBeLessThan(-5) + }) + + it('record where they hit for the physics debug view, only while it shows', () => { + _clearParticleContacts() + const emitter = new DropEmitter(new Vector3(), new Vector3(0, 3, 0)) + emitter.burst(1) + run(emitter, 1) + expect(particleContactLines().vertices).toHaveLength(0) + + game.physicsDebugRender = { enabled: true } + emitter.burst(1) + emitter.particles[0].position.set(0, 3, 0) + emitter.particles[0].velocity.set(0, 0, 0) + run(emitter, 1) + game.physicsDebugRender = undefined + const { vertices } = particleContactLines() + expect(vertices.length).toBeGreaterThanOrEqual(6) + // On the table's top, pointing up + expect(vertices[1]).toBeCloseTo(1, 2) + expect(vertices[4]).toBeGreaterThan(vertices[1]) + }) + + it('use the emitter\'s own ground when not colliding with the scene', () => { + const emitter = new DropEmitter(new Vector3(), new Vector3(0, 3, 0)) + emitter.collideWithScene = false + emitter.burst(1) + const { lowest, rose } = run(emitter, 2) + expect(rose).toBe(true) + expect(lowest).toBeCloseTo(0, 5) + }) + + it('use the emitter\'s own ground without a physics world', () => { + game.physicsWorld = undefined + const emitter = new DropEmitter(new Vector3(), new Vector3(0, 3, 0)) + emitter.burst(1) + expect(run(emitter, 2).lowest).toBeCloseTo(0, 5) + }) + + it('pass through when they start inside a collider, rather than stick', () => { + const emitter = new DropEmitter(new Vector3(), new Vector3(0, 0.5, 0)) + emitter.burst(1) + expect(run(emitter, 1).lowest).toBeLessThan(-1) + }) + + it('stick where they land and stay there for their rest, wind or not', () => { + const emitter = new DropEmitter(new Vector3(), new Vector3(0, 3, 0), { + bounce: undefined, + stick: true, + restFor: [5, 5], + }) + emitter.burst(1) + run(emitter, 2) + const particle = emitter.particles[0] + expect(particle.landed).toBe(true) + expect(particle.position.y).toBeCloseTo(1, 1) + const landedAt = particle.position.clone() + // Lying there it doesn't move, nor cast rays + const cast = vi.spyOn(game.physicsWorld!, 'castRayAndGetNormal') + run(emitter, 2) + expect(particle.position.equals(landedAt)).toBe(true) + expect(cast).not.toHaveBeenCalled() + // It decays its rest after it landed, not at its 100 s lifetime + expect(particle.decay).toBeLessThan(10) + run(emitter, 4) + expect(emitter.alive).toBe(false) + }) + + it('stick to the emitter\'s own ground without the collider', () => { + const emitter = new DropEmitter(new Vector3(), new Vector3(0, 3, 0), { bounce: undefined, stick: true }) + emitter.collideWithScene = false + emitter.burst(1) + run(emitter, 2) + expect(emitter.particles[0].landed).toBe(true) + expect(emitter.particles[0].position.y).toBe(0) + }) + + it('pass through everything without a bounce', () => { + const emitter = new DropEmitter(new Vector3(), new Vector3(0, 3, 0), { bounce: undefined }) + emitter.burst(1) + expect(run(emitter, 2).lowest).toBeLessThan(-5) + }) +}) diff --git a/packages/core/tests/Particles/particleGraph.test.ts b/packages/core/tests/Particles/particleGraph.test.ts new file mode 100644 index 00000000..ec3a2090 --- /dev/null +++ b/packages/core/tests/Particles/particleGraph.test.ts @@ -0,0 +1,294 @@ +import type Emitter from '../../src/Particles/System/Emitter' +import { Object3D, Vector3 } from 'three' +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { GraphPreview, PREVIEW_SELF } from '../../src/Graph/Logic/GraphPreview' +import { parseGraphData } from '../../src/Graph/types' +import { ParticleEffectObject, sceneParticles } from '../../src/Particles/ParticleEffectObject' +import { registerParticleNodes, usesParticleNodes } from '../../src/Particles/particleNodes' +import ParticleEffect from '../../src/Particles/System/ParticleEffect' +import { registerParticle } from '../../src/Particles/System/ParticlePreviewRegistry' + +const game = vi.hoisted(() => ({ + scene: undefined as unknown as Object3D, + world: { + entities: { + items: new Map(), + }, + add(objects: Record) { + for (const [id, object] of Object.entries(objects)) + game.world.entities.items.set(id, object) + }, + }, + logger: { + info: vi.fn(), + warn: vi.fn(), + }, +})) +vi.mock('../../src/Game', () => ({ + default: { + instance: () => game, + }, +})) +vi.mock('../../src/BaseGame', () => ({ + default: { + instance: () => game, + }, +})) + +/** Keeps 3 particles out while emitting, and loses one a tick once stopped */ +class FakeEmitter { + mesh = new Object3D() + emitting = true + garbageCollect = false + out = 0 + get alive() { + return this.out > 0 + } + + burst(count: number) { + this.out += count + } + + clear() { + this.out = 0 + } + + update() { + this.out = this.emitting + ? Math.max(this.out, 3) + : Math.max(0, this.out - 1) + } + + destroy() { + this.garbageCollect = true + this.mesh.removeFromParent() + } +} + +class FakeEffect extends ParticleEffect { + constructor() { + super() + this.emitters.push(new FakeEmitter() as unknown as Emitter) + } +} + +function emitterOf(object: ParticleEffectObject) { + return object.effect!.emitters[0] as unknown as FakeEmitter +} + +/** A graph from nodes and `from.port -> to.port` edges */ +function graph(nodes: { id: string, type: string, values?: Record }[], edges: string[]) { + return parseGraphData({ + kind: 'logic', + name: 'test', + nodes, + edges: edges.map((edge) => { + const [from, to] = edge.split(' -> ').map(end => end.split('.')) + return { + from: { node: from[0], port: from[1] }, + to: { node: to[0], port: to[1] }, + } + }), + }) +} + +beforeAll(() => { + registerParticleNodes() + registerParticle('Fake', { + preview: { + cameraPosition: [0, 0, 1], + cameraTarget: [0, 0, 0], + create: () => null, + }, + spawn: () => new FakeEffect(), + }) +}) + +beforeEach(() => { + game.scene = new Object3D() + game.world.entities.items.clear() +}) + +describe('particleEffect', () => { + it('stops, finishes once its particles are gone, and plays again', () => { + const finished = vi.fn() + const object = new ParticleEffectObject('fx', { effect: 'Fake' }, new Vector3(1, 2, 3), { onFinished: finished }) + expect(object.instance.parent).toBe(game.scene) + expect(object.instance.position.toArray()).toEqual([1, 2, 3]) + expect(emitterOf(object).mesh.parent).toBe(object.instance) + + object.update(0.1) + expect(object.alive).toBe(true) + object.stop() + for (let i = 0; i < 5; i++) + object.update(0.1) + expect(object.alive).toBe(false) + expect(finished).toHaveBeenCalledTimes(1) + + object.play() + object.update(0.1) + expect(object.alive).toBe(true) + }) + + it('starts stopped with playing false, and hands that to emitters added later', () => { + const object = new ParticleEffectObject('fx', { effect: 'Fake', playing: false }, new Vector3()) + object.update(0.1) + expect(object.alive).toBe(false) + + const late = new FakeEmitter() + late.out = 3 + object.effect!.emitters.push(late as unknown as Emitter) + object.update(0.1) + expect(late.emitting).toBe(false) + expect(late.out).toBe(0) + expect(late.mesh.parent).toBe(object.instance) + }) + + it('hands its wind switch to its emitters, also when changed later', () => { + const object = new ParticleEffectObject('fx', { effect: 'Fake', wind: false }, new Vector3()) + const emitter = emitterOf(object) as unknown as { windEnabled?: boolean } + object.update(0.1) + expect(object.wind).toBe(false) + expect(emitter.windEnabled).toBe(false) + + object.wind = true + object.update(0.1) + expect(emitter.windEnabled).toBe(true) + expect(object.props.wind).toBeUndefined() + }) + + it('checks the scene\'s colliders only with its collider on', () => { + const off = new ParticleEffectObject('a', { effect: 'Fake' }, new Vector3()) + expect(off.collider).toBe(false) + expect(off.effect!.collideWithScene).toBe(false) + + const on = new ParticleEffectObject('b', { effect: 'Fake', collider: true }, new Vector3()) + expect(on.effect!.collideWithScene).toBe(true) + on.collider = false + expect(on.effect!.collideWithScene).toBe(false) + expect(on.props.collider).toBeUndefined() + }) + + it('hands its around camera switch to its effect', () => { + const object = new ParticleEffectObject('fx', { effect: 'Fake' }, new Vector3()) + expect(object.effect!.aroundCamera).toBe(false) + object.aroundCamera = true + expect(object.effect!.aroundCamera).toBe(true) + expect(object.props.aroundCamera).toBe(true) + expect(new ParticleEffectObject('fx2', { effect: 'Fake', aroundCamera: true }, new Vector3()).effect!.aroundCamera).toBe(true) + }) + + it('plays no effect for a name that is not registered', () => { + const object = new ParticleEffectObject('fx', { effect: 'Nope' }, new Vector3()) + expect(object.effect).toBeNull() + object.update(0.1) + }) +}) + +describe('particle nodes in the scene', () => { + it('spawns with the collider when asked', () => { + expect(sceneParticles.spawn('Fake', [0, 0, 0], 0)!.collider).toBe(false) + expect(sceneParticles.spawn('Fake', [0, 0, 0], 0, { collider: true })!.effect!.collideWithScene).toBe(true) + }) + + it('spawns a burst into the world, which removes itself when done', () => { + const object = sceneParticles.spawn('Fake', [0, 1, 0], 2)! + expect(game.world.entities.items.get(object.id)).toBe(object) + expect(sceneParticles.find(object.id)).toBe(object) + expect(object.playing).toBe(false) + for (let i = 0; i < 4; i++) + object.update(0.1) + expect(object.garbageCollect).toBe(true) + expect(sceneParticles.find(object.id)).toBeUndefined() + }) +}) + +describe('usesParticleNodes', () => { + it('finds a node of the Particles category', () => { + expect(usesParticleNodes(graph([ + { id: 'start', type: 'event.start' }, + ], []))).toBe(false) + expect(usesParticleNodes(graph([ + { id: 'burst', type: 'particles.burst' }, + ], []))).toBe(true) + }) +}) + +describe('graphPreview', () => { + it('spawns into its own world and hears when a burst finishes', () => { + const log = vi.fn() + const preview = new GraphPreview() + preview.run(graph([ + { id: 'start', type: 'event.start' }, + { + id: 'spawn', + type: 'particles.spawn', + values: { kind: 'Fake', burst: 2 }, + }, + { id: 'done', type: 'particles.onFinished' }, + { + id: 'print', + type: 'action.log', + values: { value: 'done' }, + }, + ], [ + 'start.then -> spawn.run', + 'done.then -> print.run', + ]), { log }) + + expect(preview.effectCount).toBe(1) + const spawned = preview.root.children.find(child => child.type === 'Group') + expect(spawned).toBeDefined() + expect(game.scene.children).toHaveLength(0) + expect(game.world.entities.items.size).toBe(0) + + for (let i = 0; i < 4; i++) + preview.update(0.1) + expect(log).toHaveBeenCalledWith('done') + expect(preview.effectCount).toBe(0) + }) + + it('drives Self as an effect: an empty Effect input is Self', () => { + const preview = new GraphPreview() + preview.run(graph([ + { id: 'start', type: 'event.start' }, + { id: 'stop', type: 'particles.stop' }, + { + id: 'move', + type: 'entity.setPosition', + values: { + position: [0, 5, 0], + }, + }, + ], [ + 'start.then -> stop.run', + 'stop.then -> move.run', + ]), { selfEffect: 'Fake' }) + + preview.update(0.1) + const self = (preview as unknown as { effects: Map }).effects.get(PREVIEW_SELF)! + expect(self.playing).toBe(false) + expect(self.instance.position.y).toBe(5) + }) + + it('logs instead of failing when there is no effect', () => { + const log = vi.fn() + const preview = new GraphPreview() + preview.run(graph([ + { id: 'start', type: 'event.start' }, + { id: 'burst', type: 'particles.burst' }, + ], ['start.then -> burst.run']), { log }) + expect(log).toHaveBeenCalledWith(expect.stringContaining('no particle effect')) + }) + + it('keeps the last graph running when a new one has problems', () => { + const preview = new GraphPreview() + preview.run(graph([ + { id: 'start', type: 'event.start' }, + ], []), { selfEffect: 'Fake' }) + expect(() => preview.run(graph([ + { id: 'x', type: 'nope' }, + ], []))).toThrow() + expect(preview.effectCount).toBe(1) + }) +}) diff --git a/packages/editor/src/Editor/UI/Assets/Assets.tsx b/packages/editor/src/Editor/UI/Assets/Assets.tsx index 6d147d10..0f6e6bb3 100644 --- a/packages/editor/src/Editor/UI/Assets/Assets.tsx +++ b/packages/editor/src/Editor/UI/Assets/Assets.tsx @@ -6,7 +6,8 @@ import type { SVGResult } from 'three/examples/jsm/loaders/SVGLoader.js' import type { RawImage } from './TextureViewer' import EditorHelper from '@mavonengine/core/Editor/EditorHelper' import Game from '@mavonengine/core/Game' -import { getPreviewMap, spawnParticle } from '@mavonengine/core/Particles/System/ParticlePreviewRegistry' +import { PARTICLE_EFFECT_TYPE } from '@mavonengine/core/Particles/ParticleEffectObject' +import { getParticle, getPreviewMap, spawnParticle } from '@mavonengine/core/Particles/System/ParticlePreviewRegistry' import { LIGHT_REGISTRY } from '@mavonengine/core/Prefab/Lights/index' import { getPrefabs, spawnPrefab } from '@mavonengine/core/Prefab/PrefabRegistry' import { PRIMITIVE_REGISTRY } from '@mavonengine/core/Prefab/Primitives/index' @@ -74,7 +75,15 @@ export default () => { const PREFABS = getPrefabs().map(prefab => ({ ...prefab, label: prefab.label ?? prefab.name })) - const PARTICLES = Object.keys(getPreviewMap()).map(name => ({ name, label: name })) + const PARTICLES = Object.keys(getPreviewMap()).map((name) => { + const entry = getParticle(name) + return { + name, + label: entry?.label ?? name, + icon: entry?.icon, + plugin: entry?.plugin, + } + }) interface OpenAsset { id: number, title: string, item: GLTF | Texture | CubeTexture | AudioBuffer | SVGResult | Font | { particleName: string } } @@ -222,6 +231,15 @@ export default () => { const dropPos = new Vector3() window.Game.rayCaster.ray.intersectPlane(groundPlane, dropPos) + // Part of the scene: saved with it, and logic graphs can drive it + if (window.Game.activeScene) { + if (placeInScene(PARTICLE_EFFECT_TYPE, dropPos, { effect: particleName })) { + window.Game.editor?.trigger('assetDropped') + window.Game.logger?.info(`Placed ${particleName} particle effect at ${dropPos.toArray()}`) + } + return + } + const effect = spawnParticle(particleName, dropPos) if (effect) { window.Game.world.add({ [`particle_${particleName.toLowerCase()}_${Date.now()}`]: effect }) @@ -552,29 +570,27 @@ export default () => { ? PARTICLES .filter(p => p.label.toLowerCase().includes(search.toLowerCase())) .map(particle => ( -
+
onParticleDragStart(e, particle.name)} - onDoubleClick={() => openAsset(particle.name, { particleName: particle.name })} + onDoubleClick={() => openAsset(particle.label, { particleName: particle.name })} draggable > - {particle.name === 'Rain' - ? ( - - - - - - - - - ) + {particle.icon + ? : ( - - - + + + + )}
diff --git a/packages/editor/src/Editor/UI/Assets/ParticleViewer.tsx b/packages/editor/src/Editor/UI/Assets/ParticleViewer.tsx index 931fd20e..eef05017 100644 --- a/packages/editor/src/Editor/UI/Assets/ParticleViewer.tsx +++ b/packages/editor/src/Editor/UI/Assets/ParticleViewer.tsx @@ -1,54 +1,37 @@ -import type { Object3D } from 'three' import Game from '@mavonengine/core/Game' -import { getPreviewMap } from '@mavonengine/core/Particles/System/ParticlePreviewRegistry' +import { createParticleEffect, getParticle } from '@mavonengine/core/Particles/System/ParticlePreviewRegistry' import { useEffect, useRef } from 'react' -import { PerspectiveCamera, Scene } from 'three' +import { PerspectiveCamera, Scene, Vector3 } from 'three' import { WebGPURenderer } from 'three/webgpu' import { themeColor } from '../theme' import styles from './ModelViewer.module.css' -function createEmitter(particleName: string, previewScene: Scene) { - const entry = getPreviewMap()[particleName] - if (!entry) - return null - - const captured: Object3D[] = [] - const gameScene = Game.instance().scene - const origAdd = gameScene.add.bind(gameScene) - - ;(gameScene).add = (...objects: Object3D[]) => { - objects.forEach((obj) => { - captured.push(obj) - previewScene.add(obj) - }) - return gameScene - } - - const emitter = entry.create() - - gameScene.add = origAdd - - return emitter -} - +/** A registered particle effect playing by itself, all its emitters, in its own renderer */ export default ({ particleName }: { particleName: string }) => { const canvasRef = useRef(null) useEffect(() => { const canvas = canvasRef.current - if (!canvas) + const entry = getParticle(particleName) + if (!canvas || !entry) return const previewScene = new Scene() - const emitter = createEmitter(particleName, previewScene) - - if (!emitter) + const effect = createParticleEffect(particleName, new Vector3()) + if (!effect) return + // Away from the scene: its colliders aren't here, the effect's own ground is + effect.collideWithScene = false + // Emitters add themselves to the game's scene: into the preview's instead, also ones the effect adds later + const adopt = () => effect.emitters.forEach((emitter) => { + if (emitter.mesh.parent !== previewScene) + previewScene.add(emitter.mesh) + }) + adopt() - const cfg = getPreviewMap()[particleName] const camera = new PerspectiveCamera(50, 1, 0.01, 200) - camera.position.set(...cfg.cameraPosition) - camera.lookAt(...cfg.cameraTarget) + camera.position.set(...entry.preview.cameraPosition) + camera.lookAt(...entry.preview.cameraTarget) // The particles' materials are TSL, which only this renderer draws. On the game's backend const renderer = new WebGPURenderer({ canvas, antialias: true, forceWebGL: !Game.instance().renderer.isWebGPU }) @@ -57,7 +40,8 @@ export default ({ particleName }: { particleName: string }) => { void renderer.init() const onUpdate = (delta: number) => { - emitter.update(delta) + effect.update(delta) + adopt() if (renderer.hasInitialized()) renderer.render(previewScene, camera) } @@ -76,9 +60,8 @@ export default ({ particleName }: { particleName: string }) => { return () => { Game.instance().unregisterOnUpdate(onUpdate) observer.disconnect() + effect.destroy() previewScene.clear() - emitter.geometry.dispose() - emitter.material.dispose() renderer.dispose() } }, [particleName]) diff --git a/packages/editor/src/Editor/UI/Graphs/GraphNode.tsx b/packages/editor/src/Editor/UI/Graphs/GraphNode.tsx index 7a337544..e79858a0 100644 --- a/packages/editor/src/Editor/UI/Graphs/GraphNode.tsx +++ b/packages/editor/src/Editor/UI/Graphs/GraphNode.tsx @@ -5,6 +5,7 @@ import type { NodeProps } from '@xyflow/react' import type { FlowNode } from './graphModel' import { getNode } from '@mavonengine/core/Graph/NodeRegistry' import { GRAPH_COMMENT, GRAPH_GROUP } from '@mavonengine/core/Graph/types' +import { particleChoices } from '@mavonengine/core/Particles/System/ParticlePreviewRegistry' import { Handle, NodeResizer, Position } from '@xyflow/react' import { createContext, memo, useContext } from 'react' import { Color } from 'three' @@ -270,6 +271,11 @@ function GraphNode({ id, data, selected }: NodeProps) { return pick(SUBGRAPH_PORT_TYPES, false) if (key === 'id' && data.type === 'entity.byId') return pick(entities) + if (key === 'kind' && data.type === 'particles.spawn') + return pick(particleChoices(), false) + // An event's filter: empty takes any + if (spec.type === 'entity') + return pick(entities, 'Any') return setValue(id, key, v)} /> })()}
diff --git a/packages/editor/src/Editor/UI/Graphs/Graphs.module.css b/packages/editor/src/Editor/UI/Graphs/Graphs.module.css index af316e37..20d1fa70 100644 --- a/packages/editor/src/Editor/UI/Graphs/Graphs.module.css +++ b/packages/editor/src/Editor/UI/Graphs/Graphs.module.css @@ -542,3 +542,32 @@ border-radius: 2px; background: var(--accent) !important; } + +.logicPreviewBar { + position: absolute; + top: var(--spacing-sm); + left: var(--spacing-sm); + right: var(--spacing-sm); + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--spacing-sm); + pointer-events: none; +} + +.logicPreviewBar > * { + pointer-events: auto; +} + +.logicPreviewLog { + position: absolute; + left: var(--spacing-sm); + bottom: var(--spacing-sm); + max-width: calc(100% - 2 * var(--spacing-sm)); + padding: var(--spacing-xs) var(--spacing-sm); + border-radius: var(--r-sm); + background: var(--panel-inset); + font-family: var(--font-mono); + font-size: 11px; + pointer-events: none; +} diff --git a/packages/editor/src/Editor/UI/Graphs/GraphsView.tsx b/packages/editor/src/Editor/UI/Graphs/GraphsView.tsx index 1303b4a6..26f9a9ff 100644 --- a/packages/editor/src/Editor/UI/Graphs/GraphsView.tsx +++ b/packages/editor/src/Editor/UI/Graphs/GraphsView.tsx @@ -15,6 +15,7 @@ import { registerBuiltinNodes } from '@mavonengine/core/Graph/Nodes/builtin' import { isFunctionGraph, SubgraphError, subgraphType } from '@mavonengine/core/Graph/Nodes/subgraph' import { GRAPH_COMMENT, GRAPH_GROUP, GRAPH_NAME_RE, parseGraphName } from '@mavonengine/core/Graph/types' import { analyzeGraph } from '@mavonengine/core/Graph/validate' +import { usesParticleNodes } from '@mavonengine/core/Particles/particleNodes' import { GRAPH_SAVE_PATH } from '@mavonengine/core/Plugins/types' import { Background, Controls, ReactFlow, ReactFlowProvider, useEdgesState, useNodesState, useReactFlow } from '@xyflow/react' import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' @@ -23,6 +24,7 @@ import { Color, Texture } from 'three' import { commentLayout, defaultLogicGraph, defaultMaterialGraph, defaultSubgraph, defaultValue, edgeId, fromFlow, graphKey, groupLayout, groupsFirst, newNodeId, PIN_COLORS, toFlow } from './graphModel' import GraphNode, { GraphContext } from './GraphNode' import styles from './Graphs.module.css' +import LogicPreview from './LogicPreview' import MaterialPreview from './MaterialPreview' import '@xyflow/react/dist/style.css' @@ -640,6 +642,20 @@ function GraphEditor({ initial, onSaved, onCopied }: { initial: GraphData, onSav
) + // A logic graph with particle nodes: it runs by itself over the top half, the nodes under it + if (graph.kind === 'logic' && !isFunction && usesParticleNodes(graph)) { + return ( + + + 0} /> + + + + {canvas} + + + ) + } // A material: its preview over the top half, the nodes under it return graph.kind === 'material' && !isFunction ? ( diff --git a/packages/editor/src/Editor/UI/Graphs/LogicPreview.tsx b/packages/editor/src/Editor/UI/Graphs/LogicPreview.tsx new file mode 100644 index 00000000..0219199b --- /dev/null +++ b/packages/editor/src/Editor/UI/Graphs/LogicPreview.tsx @@ -0,0 +1,175 @@ +import type { GraphData } from '@mavonengine/core/Graph/types' +import Game from '@mavonengine/core/Game' +import { GraphPreview } from '@mavonengine/core/Graph/Logic/GraphPreview' +import { LOGIC_GRAPH_TYPE } from '@mavonengine/core/Graph/Logic/logicGraphObject' +import { PARTICLE_EFFECT_TYPE } from '@mavonengine/core/Particles/ParticleEffectObject' +import { particleChoices } from '@mavonengine/core/Particles/System/ParticlePreviewRegistry' +import { useEffect, useRef, useState } from 'react' +import { AmbientLight, GridHelper, PerspectiveCamera, Scene } from 'three' +import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' +import { WebGPURenderer } from 'three/webgpu' +import { themeColor } from '../theme' +import styles from './Graphs.module.css' + +/** Lines of the graph's log the preview keeps */ +const LOG_LINES = 5 + +/** The effect of the Particle Effect object a Logic Graph object running `graph` acts on in the scene, if any */ +function sceneSelfEffect(graph: string): string { + const scene = Game.instance().activeScene + for (const entry of scene?.getEntries() ?? []) { + if (entry.data.type !== LOGIC_GRAPH_TYPE || entry.data.props?.graph !== graph) + continue + const target = scene?.get(String(entry.data.props?.target ?? '')) + if (target?.data.type === PARTICLE_EFFECT_TYPE && typeof target.data.props?.effect === 'string') + return target.data.props.effect + } + return '' +} + +/** + * A logic graph running by itself, in a world of its own: the particle effects it spawns, plays and bursts, and Self + * (a particle effect, or a box) as it moves. It starts over on every change to the graph. Keys pressed on it go to + * the graph's On Key nodes; Send fires its On Message nodes. The scene isn't touched + */ +export default function LogicPreview({ graph, version, broken }: { graph: GraphData, version: string, broken: boolean }) { + const canvasRef = useRef(null) + const previewRef = useRef(null) + const [self, setSelf] = useState(() => sceneSelfEffect(graph.name)) + const [restarts, setRestarts] = useState(0) + const [message, setMessage] = useState('') + const [log, setLog] = useState([]) + const [error, setError] = useState() + // The graph as of `version`, read when it changes + const graphRef = useRef(graph) + graphRef.current = graph + + useEffect(() => { + const canvas = canvasRef.current + if (!canvas) + return + + const preview = new GraphPreview() + previewRef.current = preview + const scene = new Scene() + scene.add(new AmbientLight(0xFFFFFF, 1)) + const grid = new GridHelper(20, 20, themeColor('--line-control', '#555'), themeColor('--line', '#333')) + scene.add(grid, preview.root) + + const camera = new PerspectiveCamera(50, 1, 0.05, 200) + camera.position.set(6, 5, 9) + const controls = new OrbitControls(camera, canvas) + controls.target.set(0, 1, 0) + controls.enableDamping = true + controls.update() + + // The particles' materials are TSL, which only this renderer draws. On the game's backend + const renderer = new WebGPURenderer({ canvas, antialias: true, forceWebGL: !Game.instance().renderer.isWebGPU }) + renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) + renderer.setClearColor(themeColor('--panel-inset', 'black')) + let stopped = false + void renderer.init().then(() => { + if (stopped) + return + let last = performance.now() + void renderer.setAnimationLoop((now) => { + // Not more than a tenth of a second at once, e.g. after the tab was hidden + const delta = Math.min(0.1, (now - last) / 1000) + last = now + preview.update(delta) + controls.update() + renderer.render(scene, camera) + }) + }) + + const observer = new ResizeObserver(([entry]) => { + const { width, height } = entry!.contentRect + if (!width || !height) + return + camera.aspect = width / height + camera.updateProjectionMatrix() + renderer.setSize(width, height, false) + }) + observer.observe(canvas) + + return () => { + stopped = true + observer.disconnect() + void renderer.setAnimationLoop(null) + controls.dispose() + preview.dispose() + grid.dispose() + renderer.dispose() + previewRef.current = null + } + }, []) + + // Start over when the graph changes, Self changes or Restart is pressed. A graph with problems leaves the last running + useEffect(() => { + const preview = previewRef.current + if (!preview || broken) + return + try { + setLog([]) + preview.run(graphRef.current, { + selfEffect: self || undefined, + log: line => setLog(lines => [...lines, line].slice(-LOG_LINES)), + }) + setError(undefined) + } + catch (err) { + setError((err as Error).message) + } + }, [version, self, restarts, broken]) + + const send = () => { + if (message) + previewRef.current?.message(message, 0) + } + + return ( +
+ { + // The graph's, not the editor's shortcuts + e.stopPropagation() + previewRef.current?.trigger('keydown', { code: e.code }) + }} + /> +
+ + + setMessage(e.target.value)} + onKeyDown={(e) => { + e.stopPropagation() + if (e.key === 'Enter') + send() + }} + /> + +
+ {(error || log.length > 0) && ( +
+ {error + ?
{error}
+ : log.map((line, i) =>
{line}
)} +
+ )} +
+ ) +} diff --git a/packages/editor/src/Editor/UI/PropertiesPanel.module.css b/packages/editor/src/Editor/UI/PropertiesPanel.module.css index 94b628f4..c869699f 100644 --- a/packages/editor/src/Editor/UI/PropertiesPanel.module.css +++ b/packages/editor/src/Editor/UI/PropertiesPanel.module.css @@ -363,3 +363,33 @@ font-family: var(--font-mono); font-size: 11px; } + +.buttonGroup { + display: flex; + flex: 1; + gap: 4px; + min-width: 0; +} + +.actionButton { + flex: 1; + min-width: 0; + height: 28px; + padding: 0 8px; + border: 1px solid var(--line-control); + border-radius: var(--r-md); + background-color: var(--bg); + color: var(--text); + font-size: 11px; +} + +.actionButton:hover { + border-color: var(--accent); +} + +.previewBox { + height: 160px; + border: 1px solid var(--line); + border-radius: var(--r-md); + overflow: hidden; +} diff --git a/packages/editor/src/Editor/UI/PropertiesPanel.tsx b/packages/editor/src/Editor/UI/PropertiesPanel.tsx index 86e2529b..89165c2b 100644 --- a/packages/editor/src/Editor/UI/PropertiesPanel.tsx +++ b/packages/editor/src/Editor/UI/PropertiesPanel.tsx @@ -6,6 +6,7 @@ import { getSceneObject } from '@mavonengine/core/Scene/SceneObjectRegistry' import { useCallback, useEffect, useRef, useState } from 'react' import { Mesh } from 'three' import { Pane } from 'tweakpane' +import ParticleViewer from './Assets/ParticleViewer' import Icon from './Icon' import { objectIcon } from './objectIcon' import styles from './PropertiesPanel.module.css' @@ -592,6 +593,30 @@ export default function PropertiesPanel() { /> ) } + if (field.type === 'buttons') { + return ( +
+ {field.label} +
+ {field.buttons.map(button => ( + + ))} +
+
+ ) + } + if (field.type === 'particlePreview') { + const name = field.getValue() + return name + ? ( +
+ +
+ ) + : null + } if (field.type === 'checkbox') { return ( ({ })) vi.mock('@mavonengine/core/Particles/System/ParticlePreviewRegistry', () => ({ getPreviewMap: () => ({}), + getParticleNames: () => [], + getParticle: () => undefined, + createParticleEffect: () => null, spawnParticle: vi.fn().mockReturnValue(new Object3D()), registerParticle: vi.fn(), })) @@ -296,6 +299,29 @@ describe('dropped assets appear in SceneExplorer', () => { expect(handler).toHaveBeenCalled() }) + it('particle dropped with a scene open is placed in the scene as a Particle Effect', () => { + const create = vi.fn().mockReturnValue({ + data: { id: 'particleeffect_1' }, + }) + ;(game as unknown as { activeScene: unknown }).activeScene = { create } + render() + + const handler = vi.fn() + editor.on('assetDropped', handler) + + act(() => { + game.canvas.dispatchEvent( + createDropEvent('application/mavonengine-particle', 'Rain'), + ) + }) + + expect(create).toHaveBeenCalledWith('ParticleEffect', expect.objectContaining({ + props: { effect: 'Rain' }, + })) + expect(game.world.add).not.toHaveBeenCalled() + expect(handler).toHaveBeenCalled() + }) + it('drop event with no matching resource does not call world.add', () => { render() diff --git a/packages/editor/vite.config.mjs b/packages/editor/vite.config.mjs index 4e239650..9c503787 100644 --- a/packages/editor/vite.config.mjs +++ b/packages/editor/vite.config.mjs @@ -6,7 +6,8 @@ import { glob } from 'glob' import { defineConfig } from 'vite' import glsl from 'vite-plugin-glsl' -const EXTENDS_RE = /\bclass\s+\w+\s+extends\s+(?:ParticleEffect|Emitter)\b/ +// An effect, or an emitter of any kind (Emitter, PooledEmitter, a project's own base), not an EventEmitter +const EXTENDS_RE = /\bclass\s+\w+\s+extends\s+(?:ParticleEffect|(?!Event)\w*Emitter)\b/ const ASSETS_RE = /Assets\.tsx$/ const TS_EXT_RE = /\.ts$/ const WITH_SELECTOR_RE = /^use-sync-external-store\/shim\/with-selector(?:\.js)?$/ @@ -28,7 +29,15 @@ async function findParticleFiles(projectRoot) { const results = await Promise.all( searchRoots.map(cwd => glob('**/*.ts', { cwd, - ignore: ['**/node_modules/**', '**/*.d.ts'], + // Not tests: their fake effects aren't the project's + ignore: [ + '**/node_modules/**', + '**/dist/**', + '**/*.d.ts', + '**/tests/**', + '**/*.test.ts', + '**/*.spec.ts', + ], absolute: true, })), )