@zaisma/effects 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/EFFECT-FILES.md +301 -0
  2. package/LICENSE.txt +93 -0
  3. package/README.md +63 -2
  4. package/batches/chunks.js +294 -0
  5. package/batches/marks.js +160 -0
  6. package/batches/ribbons.js +233 -0
  7. package/batches/shared.js +155 -0
  8. package/batches/sprites.js +447 -0
  9. package/batches/warps.js +222 -0
  10. package/budget.js +115 -0
  11. package/debris.js +173 -0
  12. package/emit.js +143 -0
  13. package/flashes.js +113 -0
  14. package/format.js +365 -0
  15. package/index.d.ts +373 -0
  16. package/index.js +1168 -0
  17. package/library/bubbles_rising.json +47 -0
  18. package/library/bullet_impact.json +588 -0
  19. package/library/campfire.json +235 -0
  20. package/library/candle_flame.json +100 -0
  21. package/library/confetti.json +165 -0
  22. package/library/dash_burst.json +73 -0
  23. package/library/debris_glass.json +96 -0
  24. package/library/debris_metal.json +106 -0
  25. package/library/debris_stone.json +106 -0
  26. package/library/debris_wood.json +101 -0
  27. package/library/dust_motes.json +51 -0
  28. package/library/dust_puff.json +49 -0
  29. package/library/electric_sparks.json +175 -0
  30. package/library/embers_drift.json +55 -0
  31. package/library/exhaust_puff.json +62 -0
  32. package/library/explosion_air.json +232 -0
  33. package/library/explosion_large.json +373 -0
  34. package/library/explosion_magic.json +266 -0
  35. package/library/explosion_medium.json +289 -0
  36. package/library/explosion_small.json +289 -0
  37. package/library/explosion_water.json +177 -0
  38. package/library/falling_leaves.json +54 -0
  39. package/library/fire_burst.json +185 -0
  40. package/library/fire_large.json +279 -0
  41. package/library/fireball.json +288 -0
  42. package/library/fireflies.json +51 -0
  43. package/library/firework_burst.json +127 -0
  44. package/library/footstep.json +270 -0
  45. package/library/fountain_spray.json +80 -0
  46. package/library/frost_burst.json +202 -0
  47. package/library/ground_mist.json +50 -0
  48. package/library/ground_slam.json +122 -0
  49. package/library/heat_haze.json +24 -0
  50. package/library/hit_blade.json +150 -0
  51. package/library/hit_block.json +157 -0
  52. package/library/hit_critical.json +293 -0
  53. package/library/hit_heavy.json +211 -0
  54. package/library/hit_light.json +122 -0
  55. package/library/hit_magic.json +114 -0
  56. package/library/impact.json +417 -0
  57. package/library/impact_heavy.json +279 -0
  58. package/library/index.json +464 -0
  59. package/library/jump_puff.json +46 -0
  60. package/library/landing_heavy.json +105 -0
  61. package/library/landing_puff.json +75 -0
  62. package/library/level_up.json +164 -0
  63. package/library/lightning_arc.json +90 -0
  64. package/library/lightning_strike.json +387 -0
  65. package/library/magic_aura.json +127 -0
  66. package/library/magic_bolt.json +107 -0
  67. package/library/magic_bolt_impact.json +181 -0
  68. package/library/magic_cast.json +115 -0
  69. package/library/magic_charge.json +91 -0
  70. package/library/magic_heal.json +123 -0
  71. package/library/magic_shield.json +89 -0
  72. package/library/magic_teleport.json +177 -0
  73. package/library/mark_bullet_hole.json +20 -0
  74. package/library/mark_crack.json +18 -0
  75. package/library/mark_footprint.json +20 -0
  76. package/library/mark_frost.json +18 -0
  77. package/library/mark_puddle.json +18 -0
  78. package/library/mark_scorch.json +18 -0
  79. package/library/mark_slash.json +18 -0
  80. package/library/mark_splat.json +18 -0
  81. package/library/pickup_collect.json +117 -0
  82. package/library/pickup_glow.json +76 -0
  83. package/library/poison_cloud.json +107 -0
  84. package/library/portal.json +328 -0
  85. package/library/shockwave_air.json +71 -0
  86. package/library/shockwave_ground.json +95 -0
  87. package/library/slide_dust.json +48 -0
  88. package/library/smoke_column.json +93 -0
  89. package/library/smoke_puff.json +48 -0
  90. package/library/smoke_screen.json +87 -0
  91. package/library/sparks_burst.json +85 -0
  92. package/library/sparks_fountain.json +93 -0
  93. package/library/sparks_shower.json +89 -0
  94. package/library/splash_large.json +181 -0
  95. package/library/splash_small.json +111 -0
  96. package/library/steam_vent.json +64 -0
  97. package/library/summon_circle.json +494 -0
  98. package/library/swim_splash.json +77 -0
  99. package/library/torch_flame.json +219 -0
  100. package/library/trail_blade.json +39 -0
  101. package/library/trail_blade_fire.json +90 -0
  102. package/library/trail_dash.json +80 -0
  103. package/library/trail_magic.json +94 -0
  104. package/library/trail_projectile.json +31 -0
  105. package/library/trail_smoke.json +125 -0
  106. package/library/warp_pulse.json +22 -0
  107. package/library/warp_ripple.json +23 -0
  108. package/library/water_ripple.json +69 -0
  109. package/library/waterfall_mist.json +95 -0
  110. package/looks.js +162 -0
  111. package/motion.js +145 -0
  112. package/online.d.ts +79 -0
  113. package/online.js +32 -0
  114. package/package.json +69 -4
  115. package/partners.js +255 -0
  116. package/piece.json +415 -0
  117. package/piece.json.js +416 -0
  118. package/server.d.ts +55 -0
  119. package/server.js +26 -0
  120. package/shapes.js +269 -0
  121. package/sync.js +528 -0
  122. package/tables.js +109 -0
  123. package/weather.js +289 -0
package/flashes.js ADDED
@@ -0,0 +1,113 @@
1
+ // Flash lights: the light an effect throws on the scene. Every flash that's alive is ranked by how much it lights
2
+ // what the camera sees (its brightness, its reach, how near it is); the best few get a real light and the rest only
3
+ // glow, so twenty explosions cost the frame rate what two do.
4
+ //
5
+ // The real lights are a fixed pool of three's point lights, always in the scene (dark when unused), because adding
6
+ // or removing a light makes three build every material's shader again. This file is the one seam to the scene's
7
+ // lights: when the lighting piece brings its own cheap lights, flashes go through those from here.
8
+ import * as THREE from "three";
9
+ import { valueOverLife } from "./format.js";
10
+ import { PARTICLE_FLASH_COUNT } from "./batches/shared.js";
11
+
12
+ const place = new THREE.Vector3();
13
+
14
+ export function createFlashes({ scene, sharedUniforms }) {
15
+ const lights = [];
16
+ const flashes = new Set();
17
+ const ranked = [];
18
+
19
+ function setLightCount(lightCount) {
20
+ while (lights.length > lightCount) {
21
+ const light = lights.pop();
22
+ scene.remove(light);
23
+ light.dispose();
24
+ }
25
+ while (lights.length < lightCount) {
26
+ const light = new THREE.PointLight(0xffffff, 0, 1, 2);
27
+ light.name = "zaisma_effect_flash";
28
+ scene.add(light);
29
+ lights.push(light);
30
+ }
31
+ }
32
+
33
+ /**
34
+ * A flash: { play, offset: Vector3, color: Color, strengthLux, radiusM, startSec, durationSec, strengthKeys (0 to
35
+ * 100), flickerShare, loopDurationSec (0 when it shines once) }. Answers it, for remove.
36
+ */
37
+ function add(flash) {
38
+ flashes.add(flash);
39
+ return flash;
40
+ }
41
+
42
+ function strengthNow(flash, nowSec) {
43
+ let sinceSec = nowSec - flash.startSec;
44
+ if (sinceSec < 0) return 0;
45
+ if (flash.loopDurationSec > 0) {
46
+ if (flash.play.stopSec !== null && nowSec > flash.play.stopSec) return 0;
47
+ sinceSec %= flash.loopDurationSec;
48
+ }
49
+ if (sinceSec >= flash.durationSec) return 0;
50
+ let strength = flash.strengthLux * (valueOverLife(flash.strengthKeys, (sinceSec / flash.durationSec) * 100) / 100) * flash.play.strengthShare * flash.play.scaleShare;
51
+ // Two flickers that never line up, like a flame.
52
+ if (flash.flickerShare > 0) strength *= 1 - flash.flickerShare * 0.5 * (1 + Math.sin(nowSec * 23.7 + flash.startSec * 5) * Math.sin(nowSec * 9.1 + flash.startSec));
53
+ return strength;
54
+ }
55
+
56
+ function update(nowSec, cameraPosition, isEnabled) {
57
+ ranked.length = 0;
58
+ for (const flash of flashes) {
59
+ const isOver = flash.loopDurationSec > 0 ? flash.play.isEnded : nowSec - flash.startSec >= flash.durationSec;
60
+ if (isOver || flash.play.isEnded) {
61
+ flashes.delete(flash);
62
+ continue;
63
+ }
64
+ const strength = isEnabled ? strengthNow(flash, nowSec) : 0;
65
+ if (strength <= 0) continue;
66
+ place.copy(flash.offset).multiplyScalar(flash.play.scaleShare).add(flash.play.place);
67
+ const radiusM = flash.radiusM * flash.play.scaleShare;
68
+ flash.nowStrength = strength;
69
+ flash.nowRadiusM = radiusM;
70
+ flash.nowX = place.x;
71
+ flash.nowY = place.y;
72
+ flash.nowZ = place.z;
73
+ flash.score = (strength * radiusM * radiusM) / Math.max(place.distanceToSquared(cameraPosition), 1);
74
+ ranked.push(flash);
75
+ }
76
+ ranked.sort((first, second) => second.score - first.score);
77
+ for (let index = 0; index < lights.length; index += 1) {
78
+ const light = lights[index];
79
+ const flash = ranked[index];
80
+ if (!flash) {
81
+ light.intensity = 0;
82
+ continue;
83
+ }
84
+ light.position.set(flash.nowX, flash.nowY, flash.nowZ);
85
+ light.color.copy(flash.color).multiply(flash.play.tint);
86
+ light.intensity = flash.nowStrength;
87
+ light.distance = flash.nowRadiusM;
88
+ }
89
+ for (let index = 0; index < PARTICLE_FLASH_COUNT; index += 1) {
90
+ const flash = ranked[index];
91
+ if (flash) {
92
+ sharedUniforms.uFlashPlace.value[index].set(flash.nowX, flash.nowY, flash.nowZ, flash.nowRadiusM);
93
+ sharedUniforms.uFlashColor.value[index].copy(flash.color).multiply(flash.play.tint).multiplyScalar(flash.nowStrength);
94
+ } else sharedUniforms.uFlashColor.value[index].setRGB(0, 0, 0);
95
+ }
96
+ }
97
+
98
+ return {
99
+ setLightCount,
100
+ add,
101
+ update,
102
+ get liveCount() {
103
+ return flashes.size;
104
+ },
105
+ get lightCount() {
106
+ return lights.length;
107
+ },
108
+ dispose() {
109
+ setLightCount(0);
110
+ flashes.clear();
111
+ },
112
+ };
113
+ }
package/format.js ADDED
@@ -0,0 +1,365 @@
1
+ // The effect file: what an effect is, as data. One table states every field with what it takes, its range, its default
2
+ // and what it's for; the check, the defaults, the workbench's sliders and EFFECT-FILES.md all read this table, so
3
+ // there's never a second statement of the format. No engine here: it runs in a browser, in node and on a game server.
4
+ //
5
+ // An effect says what happens, never how it's drawn: its particles name a material (smoke, fire, spark) and the look
6
+ // in use decides the shape, the edge and the light (looks.js). So one file plays in every look.
7
+
8
+ export const EFFECT_FORMAT_VERSION_NUMBER = 1;
9
+
10
+ export const QUALITY_LEVEL_NAMES = ["low", "medium", "high"];
11
+ export const LOOK_NAMES = ["cartoon", "glowing", "faceted", "realistic"];
12
+ export const IMPORTANCE_NAMES = ["low", "normal", "high"];
13
+ export const FAMILY_NAMES = ["hits", "explosions", "magic", "fire", "smoke", "sparks", "water", "trails", "shockwaves", "marks", "warps", "debris", "character", "weather", "ambient", "other"];
14
+ /** What a particle is made of: the look draws each its own way. */
15
+ export const MATERIAL_NAMES = ["fire", "smoke", "spark", "ember", "dust", "water", "mist", "magic", "glow", "energy", "snow", "leaf", "stone", "wood", "metal", "glass"];
16
+ /** The shapes the piece draws for itself, for a particle that names one instead of taking the look's. */
17
+ export const SHAPE_NAMES = ["soft", "disc", "puff", "flame", "streak", "star", "ring", "shard", "drop", "flake", "splat", "leaf", "cross", "wisp", "bubble", "diamond", "crescent", "angular_flame"];
18
+ export const MARK_SHAPE_NAMES = ["scorch", "crack", "splat", "slash", "hole", "print", "puddle", "frost"];
19
+ /** What a surface is, for an effect that differs by what was hit. */
20
+ // The same words the other pieces use for what a thing is made of (physics bodies, footsteps, sounds).
21
+ export const SURFACE_KINDS = ["stone", "concrete", "metal", "wood", "dirt", "gravel", "sand", "grass", "mud", "water", "snow", "ice", "glass", "carpet", "flesh"];
22
+ export const ELEMENT_KINDS = ["particles", "debris", "ribbon", "beam", "flash", "mark", "warp", "shake"];
23
+ export const FROM_KINDS = ["point", "sphere", "ring", "box", "line"];
24
+ export const DIRECTION_KINDS = ["outward", "along", "up", "random", "inward"];
25
+ export const FACING_KINDS = ["camera", "velocity", "ground", "along"];
26
+ export const WARP_KINDS = ["ripple", "pulse", "haze"];
27
+
28
+ export const EFFECT_NAME_PATTERN = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/;
29
+ const COLOR_PATTERN = /^#[0-9a-f]{6}$/;
30
+ export const MAXIMUM_ELEMENT_COUNT = 16;
31
+ export const MAXIMUM_EFFECT_NAME_CHARACTER_COUNT = 40;
32
+
33
+ // ---- Field statements ----
34
+
35
+ const number = (minimumNumber, maximumNumber, defaultValue, summary) => ({ valueKind: "number", minimumNumber, maximumNumber, defaultValue, summary });
36
+ const integer = (minimumNumber, maximumNumber, defaultValue, summary) => ({ valueKind: "integer", minimumNumber, maximumNumber, defaultValue, summary });
37
+ const boolean = (defaultValue, summary) => ({ valueKind: "boolean", defaultValue, summary });
38
+ const choice = (choices, defaultValue, summary) => ({ valueKind: "choice", choices, defaultValue, summary });
39
+ const color = (defaultValue, summary) => ({ valueKind: "color", defaultValue, summary });
40
+ const text = (maximumCharacterCount, defaultValue, summary) => ({ valueKind: "text", maximumCharacterCount, defaultValue, summary });
41
+ /** A list of numbers: minimumCount to maximumCount of them, each in the range. */
42
+ const numbers = (minimumCount, maximumCount, minimumNumber, maximumNumber, defaultValue, summary) => ({ valueKind: "numbers", minimumCount, maximumCount, minimumNumber, maximumNumber, defaultValue, summary });
43
+ const colors = (minimumCount, maximumCount, defaultValue, summary) => ({ valueKind: "colors", minimumCount, maximumCount, defaultValue, summary });
44
+ /** A list of words from a closed list, or null for all of them. */
45
+ const choicesOrNull = (choices, summary) => ({ valueKind: "choices_or_null", choices, defaultValue: null, summary });
46
+ const choiceOrNull = (choices, summary) => ({ valueKind: "choice_or_null", choices, defaultValue: null, summary });
47
+ const textOrNull = (maximumCharacterCount, summary) => ({ valueKind: "text_or_null", maximumCharacterCount, defaultValue: null, summary });
48
+ const numberOrNull = (minimumNumber, maximumNumber, summary) => ({ valueKind: "number_or_null", minimumNumber, maximumNumber, defaultValue: null, summary });
49
+ const required = (statement) => ({ ...statement, isRequired: true });
50
+
51
+ /** The fields at the top of an effect file. */
52
+ export const EFFECT_FIELDS = {
53
+ effect_format_version_number: required(integer(1, EFFECT_FORMAT_VERSION_NUMBER, 1, "The format this file is written in: 1.")),
54
+ name: required(text(MAXIMUM_EFFECT_NAME_CHARACTER_COUNT, "", "The effect's name, what play() takes: lowercase words joined by underscores.")),
55
+ summary: text(200, "", "A sentence on what it looks like and what it's for."),
56
+ family: choice(FAMILY_NAMES, "other", "The group it's listed under in the workbench."),
57
+ importance: choice(IMPORTANCE_NAMES, "normal", "Which effects thin out first when the device's budget is spent: low goes first, high last."),
58
+ is_looping: boolean(false, "Whether it plays until stopped (a campfire, an aura) instead of once."),
59
+ duration_sec: number(0.01, 600, 1, "How long its emitters run. A looping effect starts over each time this passes."),
60
+ };
61
+
62
+ /** The fields every element has, whatever its kind. */
63
+ export const COMMON_ELEMENT_FIELDS = {
64
+ element_kind: required(choice(ELEMENT_KINDS, "particles", "What this element is.")),
65
+ start_delay_sec: number(0, 60, 0, "How long after the effect starts this element does."),
66
+ surface_kinds: choicesOrNull(SURFACE_KINDS, "The surfaces this element plays on, from the play's surfaceKind: sparks on metal, splinters on wood. null plays on any."),
67
+ look_names: choicesOrNull(LOOK_NAMES, "The looks this element plays in. null plays in every look."),
68
+ minimum_quality_level: choice(QUALITY_LEVEL_NAMES, "low", "The lowest quality level this element plays at: an extra layer of smoke only strong devices draw."),
69
+ };
70
+
71
+ const SPREAD = number(0, 180, 0, "How far from its direction a particle may start, in degrees: 0 is exact, 180 is anywhere.");
72
+ const GRAVITY = (defaultValue) => number(-1000, 1000, defaultValue, "How much of gravity pulls it down: 100 falls like a stone, 0 floats, below 0 rises like smoke.");
73
+
74
+ /** Each element kind's own fields. A group (emit, move, fade) is a nested object of fields. */
75
+ export const ELEMENT_FIELDS = {
76
+ particles: {
77
+ material: required(choice(MATERIAL_NAMES, "smoke", "What the particles are made of. The look in use draws each material its own way.")),
78
+ shape: choiceOrNull(SHAPE_NAMES, "A shape to draw instead of the look's own for this material. null takes the look's."),
79
+ emit: {
80
+ burst_count: integer(0, 2000, 0, "How many particles it throws at once as it starts, and again each time a looping effect starts over."),
81
+ per_sec: number(0, 5000, 0, "How many particles it gives off each second while it runs."),
82
+ emit_duration_sec: numberOrNull(0.01, 600, "How long it gives off particles. null runs as long as the effect."),
83
+ from_kind: choice(FROM_KINDS, "point", "Where particles start: a point, inside a sphere, on a flat ring, inside a box, or along a line through the effect's direction."),
84
+ from_radius_m: number(0, 200, 0, "The sphere's or ring's radius, or half the line's length, in metres."),
85
+ from_size_m: numbers(3, 3, 0, 400, [1, 1, 1], "The box's width, height and depth, in metres."),
86
+ is_from_edge: boolean(false, "Whether particles start only on the sphere's shell or the ring's rim, never inside."),
87
+ },
88
+ move: {
89
+ direction_kind: choice(DIRECTION_KINDS, "outward", "Which way particles set off: outward from the centre, along the play's direction, up, any way at random, or inward toward the centre."),
90
+ spread_deg: SPREAD,
91
+ speed_m_per_sec: number(0, 200, 1, "How fast a particle sets off."),
92
+ speed_variation_pct: number(0, 100, 30, "How much each particle's speed differs from that, either way."),
93
+ gravity_pct: GRAVITY(0),
94
+ drag_per_sec: number(0, 30, 0, "How quickly the air slows it: 0 keeps its speed, 3 loses most of it in a second."),
95
+ wind_pct: number(0, 400, 0, "How much the wind carries it: 0 ignores the wind, 100 drifts with it like smoke."),
96
+ turbulence_m: number(0, 20, 0, "How far it wanders off its path, in metres: embers that waver, smoke that curls."),
97
+ turbulence_per_sec: number(0.05, 20, 1, "How quickly it wanders: low is a slow curl, high a jitter."),
98
+ swirl_deg_per_sec: number(-3600, 3600, 0, "How fast particles circle the effect's axis: a vortex, a spell winding up."),
99
+ pull_pct: number(-100, 100, 0, "How far particles are drawn to the centre over their life: 100 arrives there as it ends (a charge gathering), below 0 pushes away."),
100
+ is_attached: boolean(false, "Whether live particles move with the effect when it moves (an aura), instead of staying where they were let go (a trail)."),
101
+ },
102
+ fade: {
103
+ life_sec: number(0.02, 120, 1, "How long a particle lasts."),
104
+ life_variation_pct: number(0, 100, 25, "How much each particle's life differs from that, either way."),
105
+ size_over_life_m: numbers(2, 4, 0, 200, [0.2, 0.2], "How big across it is through its life, in metres: 2 to 4 values spread evenly from birth to end."),
106
+ size_variation_pct: number(0, 100, 25, "How much each particle's size differs, either way."),
107
+ colors_over_life: colors(1, 4, ["#ffffff"], "Its colour through its life: 1 to 4 colours spread evenly from birth to end."),
108
+ opacity_over_life_pct: numbers(2, 4, 0, 100, [100, 0], "How solid it is through its life: 2 to 4 values spread evenly."),
109
+ glow_pct: number(0, 3000, 100, "How bright it is against its colour: 100 as coloured, above that it shines and blooms."),
110
+ facing_kind: choice(FACING_KINDS, "camera", "How it turns: to face the camera, stretched along its own motion (sparks, rain), flat on the ground (a ring spreading), or flat across the effect's direction."),
111
+ streak_duration_sec: number(0, 1, 0.03, "With facing_kind velocity: it's drawn as long as the way it travels in this time."),
112
+ spin_deg_per_sec: number(0, 3600, 0, "How fast it turns on itself; each particle turns its own way."),
113
+ is_upright: boolean(true, "With a flame or a drop facing the camera: whether it stands upright and sways (a campfire), or turns its own way like the rest (flames churning round a fireball in flight)."),
114
+ },
115
+ },
116
+ debris: {
117
+ material: required(choice(MATERIAL_NAMES, "stone", "What the chunks are made of: their shape and how they catch the light.")),
118
+ count: integer(1, 200, 8, "How many chunks fly off."),
119
+ from_radius_m: number(0, 50, 0.1, "How far from the centre chunks start, in metres."),
120
+ direction_kind: choice(DIRECTION_KINDS, "outward", "Which way chunks set off."),
121
+ spread_deg: SPREAD,
122
+ speed_m_per_sec: number(0, 100, 5, "How fast a chunk sets off."),
123
+ speed_variation_pct: number(0, 100, 40, "How much each chunk's speed differs, either way."),
124
+ gravity_pct: GRAVITY(100),
125
+ bounce_pct: number(0, 100, 40, "How much of its speed a chunk keeps when it bounces."),
126
+ grip_pct: number(0, 100, 50, "How much a surface slows a chunk sliding along it."),
127
+ size_m: number(0.01, 5, 0.12, "How big a chunk is across, in metres."),
128
+ size_variation_pct: number(0, 100, 50, "How much each chunk's size differs, either way."),
129
+ life_sec: number(0.1, 120, 3, "How long a chunk lasts before it shrinks away."),
130
+ colors: colors(1, 4, ["#8a8a8a"], "The chunks' colours: each chunk takes one."),
131
+ spin_deg_per_sec: number(0, 3600, 360, "How fast a chunk tumbles in the air."),
132
+ bounce_effect_name: textOrNull(MAXIMUM_EFFECT_NAME_CHARACTER_COUNT, "An effect played small where a chunk first lands: a puff of dust. null plays none."),
133
+ },
134
+ ribbon: {
135
+ life_sec: number(0.02, 10, 0.3, "How long each part of the trail lasts behind what it follows."),
136
+ width_over_length_m: numbers(2, 4, 0, 20, [0.2, 0], "How wide it is from its head to its tail, in metres: 2 to 4 values spread evenly."),
137
+ colors_over_length: colors(1, 4, ["#ffffff"], "Its colour from its head to its tail."),
138
+ opacity_over_length_pct: numbers(2, 4, 0, 100, [100, 0], "How solid it is from its head to its tail."),
139
+ glow_pct: number(0, 3000, 100, "How bright it is against its colour."),
140
+ minimum_step_m: number(0.005, 5, 0.05, "How far what it follows must move before the trail gains a point: smaller is smoother."),
141
+ from_offset_m: numbers(3, 3, -50, 50, [0, 0, 0], "Where the trail's edge is on what it follows, in that object's own space: a blade's base."),
142
+ to_offset_m: numbers(3, 3, -50, 50, [0, 0, 0], "The trail's other edge: a blade's tip. The same as from_offset_m draws a ribbon of its width facing the camera."),
143
+ },
144
+ beam: {
145
+ life_sec: number(0.02, 60, 0.15, "How long it shows."),
146
+ width_m: number(0.005, 20, 0.1, "How wide it is, in metres."),
147
+ segment_count: integer(1, 64, 1, "How many straight parts it's made of: 1 is a straight line, more lets it be jagged."),
148
+ jitter_m: number(0, 10, 0, "How far each joint strays off the straight line, in metres: lightning."),
149
+ rejitter_per_sec: number(0, 120, 0, "How often it takes a new jagged path while it shows; 0 keeps its first."),
150
+ reach_m: number(0.05, 200, 10, "With no toPositionM given: how far it reaches along the effect's direction, in metres, scaled with the effect."),
151
+ spread_deg: number(0, 180, 0, "With no toPositionM given: how far each path turns off the effect's direction, at random: 180 strikes any way, crackling electricity."),
152
+ tip_width_pct: number(0, 100, 100, "How wide it is at its far end, as a share of its width: below 100 it tapers like an arc or a branch."),
153
+ colors_over_life: colors(1, 4, ["#ffffff"], "Its colour through its life."),
154
+ opacity_over_life_pct: numbers(2, 4, 0, 100, [100, 0], "How solid it is through its life."),
155
+ glow_pct: number(0, 3000, 300, "How bright it is against its colour."),
156
+ },
157
+ flash: {
158
+ color: color("#ffd9a0", "The light's colour."),
159
+ strength_lux: number(0, 2000, 20, "How bright it lights a surface one metre away, on the lighting piece's scale: its sun at noon is about 3."),
160
+ radius_m: number(0.1, 200, 8, "How far the light reaches, in metres."),
161
+ duration_sec: number(0.01, 600, 0.2, "How long it shines. In a looping effect it starts over with the effect."),
162
+ strength_over_life_pct: numbers(2, 4, 0, 100, [100, 0], "How bright it is through its life: 2 to 4 values spread evenly."),
163
+ flicker_pct: number(0, 100, 0, "How much it flickers, like a flame."),
164
+ offset_m: numbers(3, 3, -50, 50, [0, 0, 0], "Where the light is from the effect's place, in metres: a little above the ground, so the ground is lit."),
165
+ },
166
+ mark: {
167
+ shape: required(choice(MARK_SHAPE_NAMES, "scorch", "What's left on the surface.")),
168
+ size_m: number(0.01, 50, 0.5, "How big it is across, in metres."),
169
+ size_variation_pct: number(0, 100, 20, "How much each mark's size differs, either way."),
170
+ life_sec: number(0.1, 600, 20, "How long it stays before it fades."),
171
+ color: color("#1a1410", "Its colour."),
172
+ opacity_pct: number(0, 100, 80, "How solid it is."),
173
+ glow_color: color("#ff6a1a", "The colour it glows while hot."),
174
+ glow_duration_sec: number(0, 60, 0, "How long it glows before it cools; 0 never glows."),
175
+ search_distance_m: number(0, 50, 1.5, "How far from the effect's place a surface is looked for, against the play's normal (or down), in metres."),
176
+ },
177
+ warp: {
178
+ warp_kind: choice(WARP_KINDS, "ripple", "How it bends the picture: a ring spreading out, a bulge, or the shimmer over heat."),
179
+ life_sec: number(0.02, 600, 0.5, "How long it lasts. A haze in a looping effect lasts while the effect plays."),
180
+ radius_over_life_m: numbers(2, 4, 0, 200, [0.2, 3], "How far it reaches through its life, in metres."),
181
+ strength_over_life_pct: numbers(2, 4, 0, 100, [60, 0], "How hard it bends the picture through its life."),
182
+ thickness_pct: number(5, 100, 30, "How thick a ripple's ring is, against its radius."),
183
+ },
184
+ shake: {
185
+ strength_pct: number(0, 100, 30, "How hard the camera shakes for a player standing at the effect."),
186
+ duration_sec: number(0.02, 10, 0.3, "How long it shakes, fading out."),
187
+ radius_m: number(0.5, 500, 15, "How far away it's felt, fading with distance, in metres."),
188
+ },
189
+ };
190
+
191
+ // ---- The check ----
192
+
193
+ function problem(code, message, field, fix) {
194
+ return { code, message, field, fix };
195
+ }
196
+
197
+ function valueProblem(statement, value, field) {
198
+ const says = (message, fix) => problem("bad_effect_field", `${field} ${message}`, field, fix);
199
+ const numberProblem = (one, where) => {
200
+ if (typeof one !== "number" || !Number.isFinite(one)) return says(`${where}isn't a number.`, `Give a number from ${statement.minimumNumber} to ${statement.maximumNumber}.`);
201
+ if (one < statement.minimumNumber || one > statement.maximumNumber) return says(`${where}is ${one}, outside ${statement.minimumNumber} to ${statement.maximumNumber}.`, `Give a number from ${statement.minimumNumber} to ${statement.maximumNumber}.`);
202
+ return null;
203
+ };
204
+ const colorProblem = (one, where) => (typeof one === "string" && COLOR_PATTERN.test(one) ? null : says(`${where}isn't a colour.`, 'Give a colour as six hex digits in lowercase, like "#ff7a1a".'));
205
+ const listProblem = (each) => {
206
+ const count = `${statement.minimumCount === statement.maximumCount ? statement.minimumCount : `${statement.minimumCount} to ${statement.maximumCount}`}`;
207
+ if (!Array.isArray(value) || value.length < statement.minimumCount || value.length > statement.maximumCount) return says(`isn't a list of ${count}.`, `Give a list of ${count} values.`);
208
+ for (let index = 0; index < value.length; index += 1) {
209
+ const found = each(value[index], `has an entry (${index}) that `);
210
+ if (found) return found;
211
+ }
212
+ return null;
213
+ };
214
+ switch (statement.valueKind) {
215
+ case "number":
216
+ return numberProblem(value, "");
217
+ case "integer":
218
+ return numberProblem(value, "") ?? (Number.isInteger(value) ? null : says("isn't a whole number.", "Give a whole number."));
219
+ case "number_or_null":
220
+ return value === null ? null : numberProblem(value, "");
221
+ case "boolean":
222
+ return typeof value === "boolean" ? null : says("isn't true or false.", "Give true or false.");
223
+ case "choice":
224
+ return statement.choices.includes(value) ? null : says(`is ${JSON.stringify(value)}, which isn't one of its choices.`, `Give one of: ${statement.choices.join(", ")}.`);
225
+ case "choice_or_null":
226
+ return value === null || statement.choices.includes(value) ? null : says(`is ${JSON.stringify(value)}, which isn't one of its choices.`, `Give null, or one of: ${statement.choices.join(", ")}.`);
227
+ case "choices_or_null":
228
+ if (value === null) return null;
229
+ if (!Array.isArray(value) || value.length === 0 || value.some((one) => !statement.choices.includes(one))) return says("isn't null or a list of its choices.", `Give null, or a list of any of: ${statement.choices.join(", ")}.`);
230
+ return null;
231
+ case "color":
232
+ return colorProblem(value, "");
233
+ case "text":
234
+ return typeof value === "string" && value.length <= statement.maximumCharacterCount ? null : says(`isn't text of up to ${statement.maximumCharacterCount} characters.`, `Give text of up to ${statement.maximumCharacterCount} characters.`);
235
+ case "text_or_null":
236
+ return value === null || (typeof value === "string" && value.length > 0 && value.length <= statement.maximumCharacterCount) ? null : says(`isn't null or text of up to ${statement.maximumCharacterCount} characters.`, `Give null, or text of up to ${statement.maximumCharacterCount} characters.`);
237
+ case "numbers":
238
+ return listProblem(numberProblem);
239
+ case "colors":
240
+ return listProblem(colorProblem);
241
+ default:
242
+ return says("has a kind the check doesn't know.", "Run the newest version of the piece.");
243
+ }
244
+ }
245
+
246
+ const isGroup = (statement) => statement.valueKind === undefined;
247
+ const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
248
+
249
+ function checkFields(statements, given, path, problems) {
250
+ if (!isPlainObject(given)) {
251
+ problems.push(problem("bad_effect_field", `${path || "The effect"} isn't an object.`, path || null, "Give an object with its fields."));
252
+ return;
253
+ }
254
+ const at = (name) => (path ? `${path}.${name}` : name);
255
+ for (const name of Object.keys(given)) {
256
+ if (!(name in statements)) problems.push(problem("unknown_effect_field", `${at(name)} isn't a field.`, at(name), `Give only: ${Object.keys(statements).join(", ")}.`));
257
+ }
258
+ for (const [name, statement] of Object.entries(statements)) {
259
+ if (isGroup(statement)) {
260
+ if (given[name] !== undefined) checkFields(statement, given[name], at(name), problems);
261
+ continue;
262
+ }
263
+ if (given[name] === undefined) {
264
+ if (statement.isRequired) problems.push(problem("missing_effect_field", `${at(name)} is missing.`, at(name), `Add ${name}: ${statement.summary}`));
265
+ continue;
266
+ }
267
+ const found = valueProblem(statement, given[name], at(name));
268
+ if (found) problems.push(found);
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Checks an effect file. Answers every problem found, each { code, message, field, fix }; none means it plays.
274
+ * field is the path of what's wrong, like "elements[2].move.speed_m_per_sec".
275
+ */
276
+ export function checkEffect(effect) {
277
+ const problems = [];
278
+ if (!isPlainObject(effect)) return [problem("bad_effect_file", "The effect isn't an object.", null, "Give the effect file's JSON, parsed: an object with name, duration_sec and elements.")];
279
+ const { elements, ...top } = effect;
280
+ checkFields(EFFECT_FIELDS, top, "", problems);
281
+ if (typeof effect.name === "string" && !EFFECT_NAME_PATTERN.test(effect.name)) problems.push(problem("bad_effect_field", `name is ${JSON.stringify(effect.name)}, which isn't lowercase words joined by underscores.`, "name", 'Name it like "fire_burst".'));
282
+ if (!Array.isArray(elements) || elements.length === 0 || elements.length > MAXIMUM_ELEMENT_COUNT) {
283
+ problems.push(problem("bad_effect_field", `elements isn't a list of 1 to ${MAXIMUM_ELEMENT_COUNT} elements.`, "elements", `Give 1 to ${MAXIMUM_ELEMENT_COUNT} elements, each with an element_kind: ${ELEMENT_KINDS.join(", ")}.`));
284
+ return problems;
285
+ }
286
+ elements.forEach((element, index) => {
287
+ const path = `elements[${index}]`;
288
+ if (!isPlainObject(element) || !ELEMENT_KINDS.includes(element.element_kind)) {
289
+ problems.push(problem("bad_effect_field", `${path}.element_kind isn't an element kind.`, `${path}.element_kind`, `Give one of: ${ELEMENT_KINDS.join(", ")}.`));
290
+ return;
291
+ }
292
+ checkFields({ ...COMMON_ELEMENT_FIELDS, ...ELEMENT_FIELDS[element.element_kind] }, element, path, problems);
293
+ if (element.element_kind === "particles" && isPlainObject(element.emit) && !(element.emit.burst_count > 0)) {
294
+ const flowSec = element.emit.emit_duration_sec ?? effect.duration_sec ?? EFFECT_FIELDS.duration_sec.defaultValue;
295
+ if (!(element.emit.per_sec > 0)) {
296
+ problems.push(problem("effect_emits_nothing", `${path} gives off no particles: its burst_count and per_sec are both 0.`, `${path}.emit`, "Give emit.burst_count for particles thrown at once, or emit.per_sec for a steady flow."));
297
+ } else if (typeof flowSec === "number" && element.emit.per_sec * flowSec < 1) {
298
+ problems.push(problem("effect_emits_nothing", `${path} gives off no particles: at ${element.emit.per_sec} a second it's over before the first is born.`, `${path}.emit`, "Raise emit.per_sec, let it run longer (emit.emit_duration_sec, or the effect's duration_sec), or give emit.burst_count."));
299
+ }
300
+ }
301
+ });
302
+ return problems;
303
+ }
304
+
305
+ function completeFields(statements, given = {}) {
306
+ const complete = {};
307
+ for (const [name, statement] of Object.entries(statements)) {
308
+ if (isGroup(statement)) complete[name] = completeFields(statement, given[name]);
309
+ else if (given[name] === undefined) complete[name] = Array.isArray(statement.defaultValue) ? [...statement.defaultValue] : statement.defaultValue;
310
+ else complete[name] = Array.isArray(given[name]) ? [...given[name]] : given[name];
311
+ }
312
+ return complete;
313
+ }
314
+
315
+ /** An effect with every field there, the ones it left out at their defaults. Give it one that passed checkEffect. */
316
+ export function completeEffect(effect) {
317
+ const { elements, ...top } = effect;
318
+ return { ...completeFields(EFFECT_FIELDS, top), elements: elements.map((element) => completeFields({ ...COMMON_ELEMENT_FIELDS, ...ELEMENT_FIELDS[element.element_kind] }, element)) };
319
+ }
320
+
321
+ /** Every field of an element kind as a flat list, for a tuning panel: { path, groupName, name, statement }. */
322
+ export function listElementFields(elementKind) {
323
+ const listed = [];
324
+ const walk = (statements, groupName) => {
325
+ for (const [name, statement] of Object.entries(statements)) {
326
+ if (isGroup(statement)) walk(statement, name);
327
+ else listed.push({ path: groupName ? `${groupName}.${name}` : name, groupName, name, statement });
328
+ }
329
+ };
330
+ walk({ ...COMMON_ELEMENT_FIELDS, ...ELEMENT_FIELDS[elementKind] }, null);
331
+ return listed;
332
+ }
333
+
334
+ // ---- Numbers every side agrees on ----
335
+
336
+ /** A whole-number hash of up to four whole numbers: the same on every device. */
337
+ export function hashNumbers(first, second = 0, third = 0, fourth = 0) {
338
+ let hash = (first | 0) ^ 0x9e3779b9;
339
+ for (const one of [second, third, fourth]) {
340
+ hash = Math.imul(hash ^ (one | 0), 0x85ebca6b);
341
+ hash ^= hash >>> 13;
342
+ hash = Math.imul(hash, 0xc2b2ae35);
343
+ hash ^= hash >>> 16;
344
+ }
345
+ return hash >>> 0;
346
+ }
347
+
348
+ /** Random numbers from 0 up to 1 that follow from a seed: the same seed gives the same numbers on every device. */
349
+ export function randomFrom(seedNumber) {
350
+ let state = seedNumber >>> 0;
351
+ return function next() {
352
+ state = (state + 0x6d2b79f5) >>> 0;
353
+ let mixed = state;
354
+ mixed = Math.imul(mixed ^ (mixed >>> 15), mixed | 1);
355
+ mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61);
356
+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;
357
+ };
358
+ }
359
+
360
+ /** A value read off 2 to 4 keys spread evenly over 0 to 1. */
361
+ export function valueOverLife(keys, sharePct) {
362
+ const place = Math.min(Math.max(sharePct / 100, 0), 1) * (keys.length - 1);
363
+ const index = Math.min(Math.floor(place), keys.length - 2);
364
+ return keys[index] + (keys[index + 1] - keys[index]) * (place - index);
365
+ }