-
-
Notifications
You must be signed in to change notification settings - Fork 944
Expand file tree
/
Copy pathAbsorberInstance.ts
More file actions
415 lines (350 loc) · 12.2 KB
/
Copy pathAbsorberInstance.ts
File metadata and controls
415 lines (350 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import {
type Container,
type ICoordinates,
type IDelta,
type IRgb,
type Particle,
type PluginManager,
type RecursivePartial,
RotateDirection,
Vector,
calcPositionOrRandomFromSize,
calcPositionOrRandomFromSizeRanged,
doublePI,
getDistance,
getDistances,
getRandom,
getRangeMax,
getRangeValue,
getStyleFromRgb,
half,
identity,
isPointInside,
millisecondsToSeconds,
originPoint,
rangeColorToRgb,
} from "@tsparticles/engine";
import { Absorber } from "./Options/Classes/Absorber.js";
import type { IAbsorber } from "./Options/Interfaces/IAbsorber.js";
import type { IAbsorberSizeLimit } from "./Options/Interfaces/IAbsorberSizeLimit.js";
const squareExp = 2,
absorbFactor = 0.033,
minOrbitLength = 0,
minRadius = 0,
minMass = 0,
minAngle = 0,
maxAngle = doublePI,
maxDegreeAngle = 360,
angleIncrementFactor = identity / maxDegreeAngle,
minVelocity = 0,
defaultLifeDelay = 0,
minLifeCount = 0,
defaultSpawnDelay = 0,
defaultLifeCount = -1;
/**
* Particle extension type for Absorber orbit options
*/
export type OrbitingParticle = Particle & {
/**
* Vector representing the orbit of the particle around the absorber
*/
absorberOrbit?: Vector;
/**
* Particle orbit direction around the absorber
*/
absorberOrbitDirection?: RotateDirection;
/**
* Checks if the particle needs a new position after going inside the absorber
*/
needsNewPosition?: boolean;
};
/**
* The AbsorberInstance class manages a single absorber, handling particle attraction,
* orbit, destruction, and lifecycle management
*/
export class AbsorberInstance {
/**
* The absorber color
*/
color: IRgb;
/**
* The absorber size limit
*/
limit: IAbsorberSizeLimit;
/**
* The absorber mass, this increases the attraction force
*/
mass;
/**
* The absorber name, useful when retrieving it manually
*/
readonly name?: string;
/**
* The absorber opacity
*/
opacity;
/**
* Gets the absorber options
* @internal
*/
readonly options;
/**
* The absorber position
*/
position: Vector;
/**
* The absorber size, great size doesn't mean great mass, it depends also on the density
*/
size;
private readonly _container;
private _currentDuration;
private _currentSpawnDelay;
private _duration?: number;
private _firstSpawn;
private readonly _immortal;
private _lifeCount;
private readonly _pluginManager;
private _spawnDelay?: number;
private readonly initialPosition?: Vector;
/**
* The absorber constructor, initializes the absorber based on the given options and position
* @param pluginManager - the plugin manager
* @param container - the Container engine using the absorber plugin, containing the particles that will interact with this Absorber
* @param options - the Absorber source options
* @param position - the Absorber optional position, if not given, it will be searched in options, and if not available also there, a random one will be used
*/
constructor(
pluginManager: PluginManager,
container: Container,
options: RecursivePartial<IAbsorber>,
position?: ICoordinates,
) {
this._container = container;
this._pluginManager = pluginManager;
this._currentDuration = 0;
this._currentSpawnDelay = 0;
this.initialPosition = position ? Vector.create(position.x, position.y) : undefined;
if (options instanceof Absorber) {
this.options = options;
} else {
this.options = new Absorber();
this.options.load(options);
}
this.name = this.options.name;
this.opacity = this.options.opacity;
this.size = getRangeValue(this.options.size.value) * container.retina.pixelRatio;
this.mass = this.size * this.options.size.density * container.retina.reduceFactor;
const limit = this.options.size.limit;
this.limit = {
radius: limit.radius * container.retina.pixelRatio * container.retina.reduceFactor,
mass: limit.mass,
};
this.color = rangeColorToRgb(this._pluginManager, this.options.color) ?? {
b: 0,
g: 0,
r: 0,
};
this.position = this.initialPosition?.copy() ?? this._calcPosition();
this._firstSpawn = !this.options.life.wait;
this._lifeCount = this.options.life.count ?? defaultLifeCount;
this._immortal = this._lifeCount <= minLifeCount;
this._spawnDelay = container.retina.reduceFactor
? (getRangeValue(this.options.life.delay ?? defaultLifeDelay) * millisecondsToSeconds) /
container.retina.reduceFactor
: Infinity;
}
/**
* Absorber attraction interaction, attract the particle to the absorber
* @param particle - the particle to attract to the absorber
* @param delta - the delta time of the frame, used for calculating the force between the particles and the absorber
*/
attract(particle: OrbitingParticle, delta: IDelta): void {
const container = this._container,
options = this.options,
pos = particle.getPosition(),
{ dx, dy, distance } = getDistances(this.position, pos),
v = Vector.create(dx, dy);
v.length = (this.mass / Math.pow(distance, squareExp)) * container.retina.reduceFactor;
if (distance < this.size + particle.getRadius()) {
const sizeFactor = particle.getRadius() * absorbFactor * container.retina.pixelRatio * delta.factor;
if (
(this.size > particle.getRadius() && distance < this.size - particle.getRadius()) ||
(particle.absorberOrbit !== undefined && particle.absorberOrbit.length < minOrbitLength)
) {
if (options.destroy) {
particle.destroy();
} else {
particle.needsNewPosition = true;
this._updateParticlePosition(particle, delta, v);
}
} else {
if (options.destroy) {
particle.size.value -= sizeFactor;
}
this._updateParticlePosition(particle, delta, v);
}
if (this.limit.radius <= minRadius || this.size < this.limit.radius) {
this.size += sizeFactor;
}
if (this.limit.mass <= minMass || this.mass < this.limit.mass) {
this.mass += sizeFactor * this.options.size.density * container.retina.reduceFactor;
}
} else {
this._updateParticlePosition(particle, delta, v);
}
}
/**
* The draw method, for drawing the absorber in the canvas
* @param context - the canvas 2d context used for drawing
*/
draw(context: OffscreenCanvasRenderingContext2D): void {
context.translate(this.position.x, this.position.y);
context.beginPath();
context.arc(originPoint.x, originPoint.y, this.size, minAngle, maxAngle, false);
context.closePath();
context.fillStyle = getStyleFromRgb(this.color, this._container.hdr, this.opacity);
context.fill();
}
/**
* The resize method, for fixing the Absorber position
*/
resize(): void {
const initialPosition = this.initialPosition;
this.position =
initialPosition && isPointInside(initialPosition, this._container.canvas.size, Vector.origin)
? initialPosition
: this._calcPosition();
}
/**
* Updates the absorber state, including life management
* @param delta - the delta time of the frame
*/
update(delta: IDelta): void {
if (this._firstSpawn) {
this._firstSpawn = false;
this._currentSpawnDelay = this._spawnDelay ?? defaultSpawnDelay;
}
if (this._duration !== undefined) {
this._currentDuration += delta.value;
if (this._currentDuration >= this._duration) {
if (!this._immortal) {
this._lifeCount--;
}
if (this._lifeCount > minLifeCount || this._immortal) {
this.position = this._calcPosition();
this._spawnDelay = this._container.retina.reduceFactor
? (getRangeValue(this.options.life.delay ?? defaultLifeDelay) * millisecondsToSeconds) /
this._container.retina.reduceFactor
: Infinity;
}
this._currentDuration -= this._duration;
delete this._duration;
}
}
if (this._spawnDelay !== undefined) {
this._currentSpawnDelay += delta.value;
if (this._currentSpawnDelay >= this._spawnDelay) {
this.play();
this._currentSpawnDelay -= this._spawnDelay;
delete this._spawnDelay;
}
}
}
/**
* This method calculate the absorber position, using the provided options and position
* @internal
* @returns the calculated position for the absorber
*/
private readonly _calcPosition: () => Vector = () => {
const exactPosition = calcPositionOrRandomFromSizeRanged({
size: this._container.canvas.size,
position: this.options.position,
});
return Vector.create(exactPosition.x, exactPosition.y);
};
/**
* Prepares the absorber to die by calculating its life duration
* @internal
*/
private readonly _prepareToDie: () => void = () => {
const duration = this.options.life.duration !== undefined ? getRangeValue(this.options.life.duration) : undefined,
minDuration = 0;
if ((this._lifeCount > minLifeCount || this._immortal) && duration !== undefined && duration > minDuration) {
this._duration = duration * millisecondsToSeconds;
}
};
/**
* Updates the particle position, if the particle needs a new position
* @param particle - the particle to update
* @param delta - the delta
* @param v - the vector used for calculating the distance between the Absorber and the particle
* @internal
*/
private readonly _updateParticlePosition: (particle: OrbitingParticle, delta: IDelta, v: Vector) => void = (
particle,
delta,
v,
) => {
if (particle.destroyed) {
return;
}
const container = this._container,
canvasSize = container.canvas.size;
if (particle.needsNewPosition) {
const newPosition = calcPositionOrRandomFromSize({ size: canvasSize });
particle.position.setTo(newPosition);
particle.velocity.setTo(particle.initialVelocity);
particle.absorberOrbit = undefined;
particle.needsNewPosition = false;
}
if (this.options.orbits) {
if (particle.absorberOrbit === undefined) {
particle.absorberOrbit = Vector.origin;
particle.absorberOrbit.length = getDistance(particle.getPosition(), this.position);
particle.absorberOrbit.angle = getRandom() * maxAngle;
}
if (particle.absorberOrbit.length <= this.size && !this.options.destroy) {
const minSize = Math.min(canvasSize.width, canvasSize.height),
offset = 1,
randomOffset = 0.1,
randomFactor = 0.2;
particle.absorberOrbit.length = minSize * (offset + (getRandom() * randomFactor - randomOffset));
}
particle.absorberOrbitDirection ??=
particle.velocity.x >= minVelocity ? RotateDirection.clockwise : RotateDirection.counterClockwise;
const orbitRadius = particle.absorberOrbit.length,
orbitAngle = particle.absorberOrbit.angle,
orbitDirection = particle.absorberOrbitDirection;
particle.velocity.setTo(Vector.origin);
const maxSize = getRangeMax(particle.options.size.value) * container.retina.pixelRatio,
sizeFactor = particle.options.move.size ? particle.getRadius() / maxSize : identity,
deltaFactor = delta.factor || identity,
baseSpeed = particle.retina.moveSpeed,
moveSpeed = baseSpeed * sizeFactor * deltaFactor * half;
particle.position.x = this.position.x + orbitRadius * Math.cos(orbitAngle);
particle.position.y =
this.position.y +
orbitRadius * (orbitDirection === RotateDirection.clockwise ? identity : -identity) * Math.sin(orbitAngle);
particle.absorberOrbit.length = Math.max(minOrbitLength, particle.absorberOrbit.length - v.length);
particle.absorberOrbit.angle += moveSpeed * angleIncrementFactor * container.retina.reduceFactor;
} else {
particle.velocity.addTo(v);
}
};
/**
* Play method that prepares the absorber to be drawn and updated
*/
private readonly play: () => void = () => {
if (
!(
(this._lifeCount > minLifeCount || this._immortal || !this.options.life.count) &&
(this._firstSpawn || this._currentSpawnDelay >= (this._spawnDelay ?? defaultSpawnDelay))
)
) {
return;
}
if (this._lifeCount > minLifeCount || this._immortal) {
this._prepareToDie();
}
};
}