Merge branch 'feature/t1183-flame-jitter'
@@ -196,6 +196,15 @@ op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschou
196
196
en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
197
197
op het podium en daarna ga je terug naar de lobby.
198
198
199
### Raketvlam
200
201
De vlam onder een raketblok wisselt 25 keer per seconde naar een willekeurig
202
ander frame, spiegelt in de helft van de gevallen en varieert licht in
203
grootte, breedte, hoogte (elk ±6–7%) en hoek (±2,5°). Alles draait om het
204
bovenste midden van de vlam, waar hij aan het blok vastzit. Met
205
"verminderde beweging" (prefers-reduced-motion) blijft het bij 12,5 fps en
206
alleen wisselende frames.
207
199
208
### Vliegende blokken en mini-velden (vloeiend)
200
209
201
210
- Een blok dat je wegschiet vliegt **meteen** lokaal weg (geen wachten op de
@@ -196,6 +196,15 @@ op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschou196
en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden196
en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden197
op het podium en daarna ga je terug naar de lobby.197
op het podium en daarna ga je terug naar de lobby.198
198
199
### Raketvlam200
201
De vlam onder een raketblok wisselt 25 keer per seconde naar een willekeurig202
ander frame, spiegelt in de helft van de gevallen en varieert licht in203
grootte, breedte, hoogte (elk ±6–7%) en hoek (±2,5°). Alles draait om het204
bovenste midden van de vlam, waar hij aan het blok vastzit. Met205
"verminderde beweging" (prefers-reduced-motion) blijft het bij 12,5 fps en206
alleen wisselende frames.207
199
### Vliegende blokken en mini-velden (vloeiend)208
### Vliegende blokken en mini-velden (vloeiend)200
209
201
- Een blok dat je wegschiet vliegt **meteen** lokaal weg (geen wachten op de210
- Een blok dat je wegschiet vliegt **meteen** lokaal weg (geen wachten op de@@ -8180,6 +8180,163 @@ else if (typeof globalThis !== 'undefined')
8180
8180
* /workspace/meteors/src/gameCore.js
8181
8181
*/
8182
8182
8183
/*
8184
* Start File:
8185
* /workspace/meteors/src/flameFx.js
8186
*/
8187
/**
8188
* t1183 — rocket flame jitter.
8189
*
8190
* Every animation tick (FPS ticks per second) the flame picks a random
8191
* sprite frame (different from the current one), flips horizontally with
8192
* 50% chance and gets a small random scale / width / height / rotation.
8193
* All of it pivots on the top-centre of the flame, where it attaches to
8194
* the block, so that point never moves.
8195
*
8196
* Purely visual. Pure functions so it can be unit-tested.
8197
*/
8198
var FlameFx = {};
8199
8200
/** Ticks per second (was 12.5 fps = 0.08 s per frame; doubled). */
8201
FlameFx.FPS = 25;
8202
/** Reduced motion: old frame rate, no flip/scale/rotation jitter. */
8203
FlameFx.REDUCED_FPS = 12.5;
8204
/** Overall scale variation (±). */
8205
FlameFx.SCALE_VAR = 0.06;
8206
/** Extra independent width variation (±). */
8207
FlameFx.WIDTH_VAR = 0.07;
8208
/** Extra independent height variation (±). */
8209
FlameFx.HEIGHT_VAR = 0.07;
8210
/** Rotation variation in degrees (±). */
8211
FlameFx.ROT_VAR_DEG = 2.5;
8212
8213
FlameFx.reducedMotion = function ()
8214
{
8215
try
8216
{
8217
var w = typeof window !== 'undefined' ? window : null;
8218
return !!(w && w.matchMedia && w.matchMedia('(prefers-reduced-motion: reduce)').matches);
8219
}
8220
catch (e)
8221
{ return false; }
8222
};
8223
8224
/** New per-flame state; the phase is random so flames don't tick in sync. */
8225
FlameFx.create = function (frames, rand, reduced)
8226
{
8227
rand = rand || Math.random;
8228
var st = { frame: 0, timer: 0, flip: false, scale: 1, w: 1, h: 1, rot: 0, frames: frames || 1 };
8229
st.timer = rand() / FlameFx.FPS;
8230
FlameFx.roll(st, rand, !!reduced);
8231
return st;
8232
};
8233
8234
/** Random frame index in [0, frames), different from `current` when possible. */
8235
FlameFx.pickFrame = function (current, frames, rand)
8236
{
8237
rand = rand || Math.random;
8238
if (frames <= 1)
8239
{ return 0; }
8240
// Choose among the other frames-1 indices uniformly.
8241
var k = Math.floor(rand() * (frames - 1));
8242
if (k >= frames - 1)
8243
{ k = frames - 2; }
8244
return k >= current ? k + 1 : k;
8245
};
8246
8247
function flameVar (rand, amount)
8248
{
8249
return 1 + (rand() * 2 - 1) * amount;
8250
}
8251
8252
/** One animation tick: new frame, flip, scales and rotation. */
8253
FlameFx.roll = function (st, rand, reduced)
8254
{
8255
rand = rand || Math.random;
8256
st.frame = FlameFx.pickFrame(st.frame, st.frames, rand);
8257
if (reduced)
8258
{
8259
st.flip = false;
8260
st.scale = 1;
8261
st.w = 1;
8262
st.h = 1;
8263
st.rot = 0;
8264
return st;
8265
}
8266
st.flip = rand() < 0.5;
8267
st.scale = flameVar(rand, FlameFx.SCALE_VAR);
8268
st.w = flameVar(rand, FlameFx.WIDTH_VAR);
8269
st.h = flameVar(rand, FlameFx.HEIGHT_VAR);
8270
st.rot = (rand() * 2 - 1) * FlameFx.ROT_VAR_DEG;
8271
return st;
8272
};
8273
8274
/** Advance time (seconds). Returns the number of ticks that happened. */
8275
FlameFx.advance = function (st, dt, rand, reduced)
8276
{
8277
var period = 1 / (reduced ? FlameFx.REDUCED_FPS : FlameFx.FPS);
8278
st.timer += Math.max(0, dt || 0);
8279
var ticks = 0;
8280
while (st.timer >= period - 1e-9)
8281
{
8282
st.timer = Math.max(0, st.timer - period);
8283
ticks++;
8284
}
8285
// Long stall: one roll is enough, don't loop the RNG for nothing.
8286
if (ticks > 0)
8287
{ FlameFx.roll(st, rand, reduced); }
8288
return ticks;
8289
};
8290
8291
/**
8292
* Draw pose for a flame whose top-centre anchor is (ax, ay) and whose
8293
* nominal size is baseW × baseH. The framework draws sprites centred on
8294
* (x, y), rotated by `rotation` degrees (clockwise, canvas y-down) around
8295
* that centre, and mirrorX flips around the vertical centre line. The
8296
* centre is placed so the rotated, scaled top-centre lands exactly on
8297
* the anchor.
8298
*/
8299
FlameFx.pose = function (st, ax, ay, baseW, baseH)
8300
{
8301
var w = baseW * st.scale * st.w;
8302
var h = baseH * st.scale * st.h;
8303
var rad = st.rot * Math.PI / 180;
8304
return {
8305
x: ax - Math.sin(rad) * h / 2,
8306
y: ay + Math.cos(rad) * h / 2,
8307
w: w,
8308
h: h,
8309
rotation: st.rot,
8310
mirrorX: !!st.flip,
8311
frame: st.frame
8312
};
8313
};
8314
8315
/**
8316
* Where the top-centre of the drawn quad ends up for a pose — same
8317
* transform as the framework's sprite matrix (model point (0, -0.5)).
8318
* Used by tests to prove the anchor never moves.
8319
*/
8320
FlameFx.topCentreOf = function (pose)
8321
{
8322
var rad = pose.rotation * Math.PI / 180;
8323
var c = Math.cos(rad);
8324
var s = Math.sin(rad);
8325
var sy = pose.h;
8326
// x' = c*sx*u - s*sy*v + x ; y' = s*sx*u + c*sy*v + y with u = 0, v = -0.5
8327
return { x: pose.x + s * sy * 0.5, y: pose.y - c * sy * 0.5 };
8328
};
8329
8330
if (typeof globalThis !== 'undefined')
8331
{ globalThis.FlameFx = FlameFx; }
8332
if (typeof module !== 'undefined' && module.exports)
8333
{ module.exports = FlameFx; }
8334
8335
/*
8336
* End File:
8337
* /workspace/meteors/src/flameFx.js
8338
*/
8339
8183
8340
/*
8184
8341
* Start File:
8185
8342
* /workspace/meteors/src/miniLayout.js
@@ -13280,6 +13437,13 @@ function spriteFor (block)
13280
13437
return game.images[key] || game.images.gray;
13281
13438
}
13282
13439
13440
/** Frames in the flame sprite (from the loaded image, default 4). */
13441
function flameFrameCount ()
13442
{
13443
var img = typeof game !== 'undefined' && game.images ? game.images.flame : null;
13444
return img && img.subImages ? img.subImages : 4;
13445
}
13446
13283
13447
function syncSprites (dt)
13284
13448
{
13285
13449
if (!app.core || !app.scene)
@@ -13317,22 +13481,30 @@ function syncSprites (dt)
13317
13481
if (!flame)
13318
13482
{
13319
13483
flame = new GameObject(0, 0, game.images.flame, 1);
13320
flame.renderer.setAnimation('burn', 0, 0.08);
13484
// t1183: frames are chosen by FlameFx, not the framework cycle.
13485
flame.fx = FlameFx.create(flameFrameCount(), Math.random, FlameFx.reducedMotion());
13486
flame.renderer.setSubImage(flame.fx.frame);
13321
13487
app.scene.addObject(flame);
13322
13488
app.flames[block.id] = flame;
13323
13489
}
13324
13490
flame.renderer.visible = true;
13491
FlameFx.advance(flame.fx, dt, Math.random, FlameFx.reducedMotion());
13325
13492
var t = app.tile;
13326
13493
// 3x as large (length and width, t1110). Keep the top of the
13327
13494
// flame at the same overlap into the block so the extra length
13328
// extends downward under the rocket.
13495
// extends downward under the rocket. t1183: random frame, flip,
13496
// scale and rotation all pivot on that top-centre anchor.
13329
13497
var flameW = t * 0.85 * 3;
13330
13498
var flameH = t * 0.85 * 3;
13331
13499
var origCenter = app.fieldH - block.y * t + t * 0.15;
13332
13500
var origTop = origCenter - (t * 0.85) / 2;
13333
flame.transform.position.x = block.col * t + t / 2;
13334
flame.transform.position.y = origTop + flameH / 2;
13335
flame.transform.size = { x: flameW, y: flameH };
13501
var pose = FlameFx.pose(flame.fx, block.col * t + t / 2, origTop, flameW, flameH);
13502
flame.renderer.subImage = pose.frame;
13503
flame.renderer.mirrorX = pose.mirrorX;
13504
flame.transform.rotation = pose.rotation;
13505
flame.transform.position.x = pose.x;
13506
flame.transform.position.y = pose.y;
13507
flame.transform.size = { x: pose.w, y: pose.h };
13336
13508
}
13337
13509
else if (app.flames[block.id])
13338
13510
{ app.flames[block.id].renderer.visible = false; }
@@ -8180,6 +8180,163 @@ else if (typeof globalThis !== 'undefined')8180
* /workspace/meteors/src/gameCore.js8180
* /workspace/meteors/src/gameCore.js8181
*/ 8181
*/ 8182
8182
8183
/*8184
* Start File:8185
* /workspace/meteors/src/flameFx.js8186
*/ 8187
/**8188
* t1183 — rocket flame jitter.8189
*8190
* Every animation tick (FPS ticks per second) the flame picks a random8191
* sprite frame (different from the current one), flips horizontally with8192
* 50% chance and gets a small random scale / width / height / rotation.8193
* All of it pivots on the top-centre of the flame, where it attaches to8194
* the block, so that point never moves.8195
*8196
* Purely visual. Pure functions so it can be unit-tested.8197
*/8198
var FlameFx = {};8199
8200
/** Ticks per second (was 12.5 fps = 0.08 s per frame; doubled). */8201
FlameFx.FPS = 25;8202
/** Reduced motion: old frame rate, no flip/scale/rotation jitter. */8203
FlameFx.REDUCED_FPS = 12.5;8204
/** Overall scale variation (±). */8205
FlameFx.SCALE_VAR = 0.06;8206
/** Extra independent width variation (±). */8207
FlameFx.WIDTH_VAR = 0.07;8208
/** Extra independent height variation (±). */8209
FlameFx.HEIGHT_VAR = 0.07;8210
/** Rotation variation in degrees (±). */8211
FlameFx.ROT_VAR_DEG = 2.5;8212
8213
FlameFx.reducedMotion = function ()8214
{8215
try8216
{8217
var w = typeof window !== 'undefined' ? window : null;8218
return !!(w && w.matchMedia && w.matchMedia('(prefers-reduced-motion: reduce)').matches);8219
}8220
catch (e)8221
{ return false; }8222
};8223
8224
/** New per-flame state; the phase is random so flames don't tick in sync. */8225
FlameFx.create = function (frames, rand, reduced)8226
{8227
rand = rand || Math.random;8228
var st = { frame: 0, timer: 0, flip: false, scale: 1, w: 1, h: 1, rot: 0, frames: frames || 1 };8229
st.timer = rand() / FlameFx.FPS;8230
FlameFx.roll(st, rand, !!reduced);8231
return st;8232
};8233
8234
/** Random frame index in [0, frames), different from `current` when possible. */8235
FlameFx.pickFrame = function (current, frames, rand)8236
{8237
rand = rand || Math.random;8238
if (frames <= 1)8239
{ return 0; }8240
// Choose among the other frames-1 indices uniformly.8241
var k = Math.floor(rand() * (frames - 1));8242
if (k >= frames - 1)8243
{ k = frames - 2; }8244
return k >= current ? k + 1 : k;8245
};8246
8247
function flameVar (rand, amount)8248
{8249
return 1 + (rand() * 2 - 1) * amount;8250
}8251
8252
/** One animation tick: new frame, flip, scales and rotation. */8253
FlameFx.roll = function (st, rand, reduced)8254
{8255
rand = rand || Math.random;8256
st.frame = FlameFx.pickFrame(st.frame, st.frames, rand);8257
if (reduced)8258
{8259
st.flip = false;8260
st.scale = 1;8261
st.w = 1;8262
st.h = 1;8263
st.rot = 0;8264
return st;8265
}8266
st.flip = rand() < 0.5;8267
st.scale = flameVar(rand, FlameFx.SCALE_VAR);8268
st.w = flameVar(rand, FlameFx.WIDTH_VAR);8269
st.h = flameVar(rand, FlameFx.HEIGHT_VAR);8270
st.rot = (rand() * 2 - 1) * FlameFx.ROT_VAR_DEG;8271
return st;8272
};8273
8274
/** Advance time (seconds). Returns the number of ticks that happened. */8275
FlameFx.advance = function (st, dt, rand, reduced)8276
{8277
var period = 1 / (reduced ? FlameFx.REDUCED_FPS : FlameFx.FPS);8278
st.timer += Math.max(0, dt || 0);8279
var ticks = 0;8280
while (st.timer >= period - 1e-9)8281
{8282
st.timer = Math.max(0, st.timer - period);8283
ticks++;8284
}8285
// Long stall: one roll is enough, don't loop the RNG for nothing.8286
if (ticks > 0)8287
{ FlameFx.roll(st, rand, reduced); }8288
return ticks;8289
};8290
8291
/**8292
* Draw pose for a flame whose top-centre anchor is (ax, ay) and whose8293
* nominal size is baseW × baseH. The framework draws sprites centred on8294
* (x, y), rotated by `rotation` degrees (clockwise, canvas y-down) around8295
* that centre, and mirrorX flips around the vertical centre line. The8296
* centre is placed so the rotated, scaled top-centre lands exactly on8297
* the anchor.8298
*/8299
FlameFx.pose = function (st, ax, ay, baseW, baseH)8300
{8301
var w = baseW * st.scale * st.w;8302
var h = baseH * st.scale * st.h;8303
var rad = st.rot * Math.PI / 180;8304
return {8305
x: ax - Math.sin(rad) * h / 2,8306
y: ay + Math.cos(rad) * h / 2,8307
w: w,8308
h: h,8309
rotation: st.rot,8310
mirrorX: !!st.flip,8311
frame: st.frame8312
};8313
};8314
8315
/**8316
* Where the top-centre of the drawn quad ends up for a pose — same8317
* transform as the framework's sprite matrix (model point (0, -0.5)).8318
* Used by tests to prove the anchor never moves.8319
*/8320
FlameFx.topCentreOf = function (pose)8321
{8322
var rad = pose.rotation * Math.PI / 180;8323
var c = Math.cos(rad);8324
var s = Math.sin(rad);8325
var sy = pose.h;8326
// x' = c*sx*u - s*sy*v + x ; y' = s*sx*u + c*sy*v + y with u = 0, v = -0.58327
return { x: pose.x + s * sy * 0.5, y: pose.y - c * sy * 0.5 };8328
};8329
8330
if (typeof globalThis !== 'undefined')8331
{ globalThis.FlameFx = FlameFx; }8332
if (typeof module !== 'undefined' && module.exports)8333
{ module.exports = FlameFx; }8334
8335
/*8336
* End File:8337
* /workspace/meteors/src/flameFx.js8338
*/ 8339
8183
/*8340
/*8184
* Start File:8341
* Start File:8185
* /workspace/meteors/src/miniLayout.js8342
* /workspace/meteors/src/miniLayout.js@@ -13280,6 +13437,13 @@ function spriteFor (block)13280
return game.images[key] || game.images.gray;13437
return game.images[key] || game.images.gray;13281
}13438
}13282
13439
13440
/** Frames in the flame sprite (from the loaded image, default 4). */13441
function flameFrameCount ()13442
{13443
var img = typeof game !== 'undefined' && game.images ? game.images.flame : null;13444
return img && img.subImages ? img.subImages : 4;13445
}13446
13283
function syncSprites (dt)13447
function syncSprites (dt)13284
{13448
{13285
if (!app.core || !app.scene)13449
if (!app.core || !app.scene)@@ -13317,22 +13481,30 @@ function syncSprites (dt)13317
if (!flame)13481
if (!flame)13318
{13482
{13319
flame = new GameObject(0, 0, game.images.flame, 1);13483
flame = new GameObject(0, 0, game.images.flame, 1);13320
flame.renderer.setAnimation('burn', 0, 0.08);13484
// t1183: frames are chosen by FlameFx, not the framework cycle.13485
flame.fx = FlameFx.create(flameFrameCount(), Math.random, FlameFx.reducedMotion());13486
flame.renderer.setSubImage(flame.fx.frame);13321
app.scene.addObject(flame);13487
app.scene.addObject(flame);13322
app.flames[block.id] = flame;13488
app.flames[block.id] = flame;13323
}13489
}13324
flame.renderer.visible = true;13490
flame.renderer.visible = true;13491
FlameFx.advance(flame.fx, dt, Math.random, FlameFx.reducedMotion());13325
var t = app.tile;13492
var t = app.tile;13326
// 3x as large (length and width, t1110). Keep the top of the13493
// 3x as large (length and width, t1110). Keep the top of the13327
// flame at the same overlap into the block so the extra length13494
// flame at the same overlap into the block so the extra length13328
// extends downward under the rocket.13495
// extends downward under the rocket. t1183: random frame, flip,13496
// scale and rotation all pivot on that top-centre anchor.13329
var flameW = t * 0.85 * 3;13497
var flameW = t * 0.85 * 3;13330
var flameH = t * 0.85 * 3;13498
var flameH = t * 0.85 * 3;13331
var origCenter = app.fieldH - block.y * t + t * 0.15;13499
var origCenter = app.fieldH - block.y * t + t * 0.15;13332
var origTop = origCenter - (t * 0.85) / 2;13500
var origTop = origCenter - (t * 0.85) / 2;13333
flame.transform.position.x = block.col * t + t / 2;13501
var pose = FlameFx.pose(flame.fx, block.col * t + t / 2, origTop, flameW, flameH);13334
flame.transform.position.y = origTop + flameH / 2;13502
flame.renderer.subImage = pose.frame;13335
flame.transform.size = { x: flameW, y: flameH };13503
flame.renderer.mirrorX = pose.mirrorX;13504
flame.transform.rotation = pose.rotation;13505
flame.transform.position.x = pose.x;13506
flame.transform.position.y = pose.y;13507
flame.transform.size = { x: pose.w, y: pose.h };13336
}13508
}13337
else if (app.flames[block.id])13509
else if (app.flames[block.id])13338
{ app.flames[block.id].renderer.visible = false; }13510
{ app.flames[block.id].renderer.visible = false; }@@ -998,3 +998,30 @@ Tests: `test/flight-local.test.js`; browser: `test/t1181-flights-playwright.py`
998
998
Tests: `test/mini-predict.test.js`, plus de mini-meting in
999
999
`test/t1181-flights-playwright.py`.
1000
1000
1001
## t1183 — raketvlam: random frames, flip, schaal en rotatie
1002
1003
- Nieuwe sprite van Tim (`build/images/flame.png`, 4 frames op een rij)
1004
ongewijzigd gebruikt.
1005
- `src/flameFx.js` (`FlameFx`) stuurt de vlam aan in plaats van de
1006
framework-animatie `burn`:
1007
- `FPS` = 25 (was 0,08 s per frame = 12,5 fps; verdubbeld).
1008
- Elke tick een willekeurig frame dat **altijd** anders is dan het huidige
1009
(uniform uit de andere drie).
1010
- 50% kans op horizontaal spiegelen (`mirrorX`).
1011
- Onafhankelijke variatie: totale schaal ±6% (`SCALE_VAR`), breedte ±7%
1012
(`WIDTH_VAR`), hoogte ±7% (`HEIGHT_VAR`); samen maximaal ca. ±13%.
1013
- Rotatie ±2,5° (`ROT_VAR_DEG`).
1014
- Elke vlam heeft een eigen willekeurige fase, zodat meerdere raketten
1015
niet tegelijk wisselen.
1016
- Anker: het framework tekent sprites gecentreerd en roteert/spiegelt om
1017
het midden. `FlameFx.pose` zet het midden op `anker + R(θ)·(0, h/2)`, zodat
1018
het bovenste midden (waar de vlam het blok raakt) exact op dezelfde plek
1019
blijft. Het framework rondt de positie af op hele pixels (max. 0,5 px).
1020
- Verminderde beweging (`prefers-reduced-motion: reduce`): 12,5 fps, wel
1021
willekeurige frames, geen spiegelen/schalen/roteren. (Het effect had dit
1022
eerder niet; dit is de "nette" ondergrens.)
1023
- Bij een haperend frame (lange dt) wordt één keer gerold, niet tientallen
1024
keren.
1025
1026
Tests: `test/flame-fx.test.js`; browser: `test/t1183-flame-playwright.py URL TAG`.
1027
@@ -998,3 +998,30 @@ Tests: `test/flight-local.test.js`; browser: `test/t1181-flights-playwright.py`998
Tests: `test/mini-predict.test.js`, plus de mini-meting in998
Tests: `test/mini-predict.test.js`, plus de mini-meting in999
`test/t1181-flights-playwright.py`.999
`test/t1181-flights-playwright.py`.1000
1000
1001
## t1183 — raketvlam: random frames, flip, schaal en rotatie1002
1003
- Nieuwe sprite van Tim (`build/images/flame.png`, 4 frames op een rij)1004
ongewijzigd gebruikt.1005
- `src/flameFx.js` (`FlameFx`) stuurt de vlam aan in plaats van de1006
framework-animatie `burn`:1007
- `FPS` = 25 (was 0,08 s per frame = 12,5 fps; verdubbeld).1008
- Elke tick een willekeurig frame dat **altijd** anders is dan het huidige1009
(uniform uit de andere drie).1010
- 50% kans op horizontaal spiegelen (`mirrorX`).1011
- Onafhankelijke variatie: totale schaal ±6% (`SCALE_VAR`), breedte ±7%1012
(`WIDTH_VAR`), hoogte ±7% (`HEIGHT_VAR`); samen maximaal ca. ±13%.1013
- Rotatie ±2,5° (`ROT_VAR_DEG`).1014
- Elke vlam heeft een eigen willekeurige fase, zodat meerdere raketten1015
niet tegelijk wisselen.1016
- Anker: het framework tekent sprites gecentreerd en roteert/spiegelt om1017
het midden. `FlameFx.pose` zet het midden op `anker + R(θ)·(0, h/2)`, zodat1018
het bovenste midden (waar de vlam het blok raakt) exact op dezelfde plek1019
blijft. Het framework rondt de positie af op hele pixels (max. 0,5 px).1020
- Verminderde beweging (`prefers-reduced-motion: reduce`): 12,5 fps, wel1021
willekeurige frames, geen spiegelen/schalen/roteren. (Het effect had dit1022
eerder niet; dit is de "nette" ondergrens.)1023
- Bij een haperend frame (lange dt) wordt één keer gerold, niet tientallen1024
keren.1025
1026
Tests: `test/flame-fx.test.js`; browser: `test/t1183-flame-playwright.py URL TAG`.1027
@@ -19,6 +19,7 @@ FILES=(
19
19
"$SRC_DIR/blocks.js"
20
20
"$SRC_DIR/easing.js"
21
21
"$SRC_DIR/gameCore.js"
22
"$SRC_DIR/flameFx.js"
22
23
"$SRC_DIR/miniLayout.js"
23
24
"$SRC_DIR/miniPredict.js"
24
25
"$SRC_DIR/online.js"
@@ -19,6 +19,7 @@ FILES=(19
"$SRC_DIR/blocks.js"19
"$SRC_DIR/blocks.js"20
"$SRC_DIR/easing.js"20
"$SRC_DIR/easing.js"21
"$SRC_DIR/gameCore.js"21
"$SRC_DIR/gameCore.js"22
"$SRC_DIR/flameFx.js"22
"$SRC_DIR/miniLayout.js"23
"$SRC_DIR/miniLayout.js"23
"$SRC_DIR/miniPredict.js"24
"$SRC_DIR/miniPredict.js"24
"$SRC_DIR/online.js"25
"$SRC_DIR/online.js"@@ -0,0 +1,147 @@
1
/**
2
* t1183 — rocket flame jitter.
3
*
4
* Every animation tick (FPS ticks per second) the flame picks a random
5
* sprite frame (different from the current one), flips horizontally with
6
* 50% chance and gets a small random scale / width / height / rotation.
7
* All of it pivots on the top-centre of the flame, where it attaches to
8
* the block, so that point never moves.
9
*
10
* Purely visual. Pure functions so it can be unit-tested.
11
*/
12
var FlameFx = {};
13
14
/** Ticks per second (was 12.5 fps = 0.08 s per frame; doubled). */
15
FlameFx.FPS = 25;
16
/** Reduced motion: old frame rate, no flip/scale/rotation jitter. */
17
FlameFx.REDUCED_FPS = 12.5;
18
/** Overall scale variation (±). */
19
FlameFx.SCALE_VAR = 0.06;
20
/** Extra independent width variation (±). */
21
FlameFx.WIDTH_VAR = 0.07;
22
/** Extra independent height variation (±). */
23
FlameFx.HEIGHT_VAR = 0.07;
24
/** Rotation variation in degrees (±). */
25
FlameFx.ROT_VAR_DEG = 2.5;
26
27
FlameFx.reducedMotion = function ()
28
{
29
try
30
{
31
var w = typeof window !== 'undefined' ? window : null;
32
return !!(w && w.matchMedia && w.matchMedia('(prefers-reduced-motion: reduce)').matches);
33
}
34
catch (e)
35
{ return false; }
36
};
37
38
/** New per-flame state; the phase is random so flames don't tick in sync. */
39
FlameFx.create = function (frames, rand, reduced)
40
{
41
rand = rand || Math.random;
42
var st = { frame: 0, timer: 0, flip: false, scale: 1, w: 1, h: 1, rot: 0, frames: frames || 1 };
43
st.timer = rand() / FlameFx.FPS;
44
FlameFx.roll(st, rand, !!reduced);
45
return st;
46
};
47
48
/** Random frame index in [0, frames), different from `current` when possible. */
49
FlameFx.pickFrame = function (current, frames, rand)
50
{
51
rand = rand || Math.random;
52
if (frames <= 1)
53
{ return 0; }
54
// Choose among the other frames-1 indices uniformly.
55
var k = Math.floor(rand() * (frames - 1));
56
if (k >= frames - 1)
57
{ k = frames - 2; }
58
return k >= current ? k + 1 : k;
59
};
60
61
function flameVar (rand, amount)
62
{
63
return 1 + (rand() * 2 - 1) * amount;
64
}
65
66
/** One animation tick: new frame, flip, scales and rotation. */
67
FlameFx.roll = function (st, rand, reduced)
68
{
69
rand = rand || Math.random;
70
st.frame = FlameFx.pickFrame(st.frame, st.frames, rand);
71
if (reduced)
72
{
73
st.flip = false;
74
st.scale = 1;
75
st.w = 1;
76
st.h = 1;
77
st.rot = 0;
78
return st;
79
}
80
st.flip = rand() < 0.5;
81
st.scale = flameVar(rand, FlameFx.SCALE_VAR);
82
st.w = flameVar(rand, FlameFx.WIDTH_VAR);
83
st.h = flameVar(rand, FlameFx.HEIGHT_VAR);
84
st.rot = (rand() * 2 - 1) * FlameFx.ROT_VAR_DEG;
85
return st;
86
};
87
88
/** Advance time (seconds). Returns the number of ticks that happened. */
89
FlameFx.advance = function (st, dt, rand, reduced)
90
{
91
var period = 1 / (reduced ? FlameFx.REDUCED_FPS : FlameFx.FPS);
92
st.timer += Math.max(0, dt || 0);
93
var ticks = 0;
94
while (st.timer >= period - 1e-9)
95
{
96
st.timer = Math.max(0, st.timer - period);
97
ticks++;
98
}
99
// Long stall: one roll is enough, don't loop the RNG for nothing.
100
if (ticks > 0)
101
{ FlameFx.roll(st, rand, reduced); }
102
return ticks;
103
};
104
105
/**
106
* Draw pose for a flame whose top-centre anchor is (ax, ay) and whose
107
* nominal size is baseW × baseH. The framework draws sprites centred on
108
* (x, y), rotated by `rotation` degrees (clockwise, canvas y-down) around
109
* that centre, and mirrorX flips around the vertical centre line. The
110
* centre is placed so the rotated, scaled top-centre lands exactly on
111
* the anchor.
112
*/
113
FlameFx.pose = function (st, ax, ay, baseW, baseH)
114
{
115
var w = baseW * st.scale * st.w;
116
var h = baseH * st.scale * st.h;
117
var rad = st.rot * Math.PI / 180;
118
return {
119
x: ax - Math.sin(rad) * h / 2,
120
y: ay + Math.cos(rad) * h / 2,
121
w: w,
122
h: h,
123
rotation: st.rot,
124
mirrorX: !!st.flip,
125
frame: st.frame
126
};
127
};
128
129
/**
130
* Where the top-centre of the drawn quad ends up for a pose — same
131
* transform as the framework's sprite matrix (model point (0, -0.5)).
132
* Used by tests to prove the anchor never moves.
133
*/
134
FlameFx.topCentreOf = function (pose)
135
{
136
var rad = pose.rotation * Math.PI / 180;
137
var c = Math.cos(rad);
138
var s = Math.sin(rad);
139
var sy = pose.h;
140
// x' = c*sx*u - s*sy*v + x ; y' = s*sx*u + c*sy*v + y with u = 0, v = -0.5
141
return { x: pose.x + s * sy * 0.5, y: pose.y - c * sy * 0.5 };
142
};
143
144
if (typeof globalThis !== 'undefined')
145
{ globalThis.FlameFx = FlameFx; }
146
if (typeof module !== 'undefined' && module.exports)
147
{ module.exports = FlameFx; }
@@ -0,0 +1,147 @@1
/**2
* t1183 — rocket flame jitter.3
*4
* Every animation tick (FPS ticks per second) the flame picks a random5
* sprite frame (different from the current one), flips horizontally with6
* 50% chance and gets a small random scale / width / height / rotation.7
* All of it pivots on the top-centre of the flame, where it attaches to8
* the block, so that point never moves.9
*10
* Purely visual. Pure functions so it can be unit-tested.11
*/12
var FlameFx = {};13
14
/** Ticks per second (was 12.5 fps = 0.08 s per frame; doubled). */15
FlameFx.FPS = 25;16
/** Reduced motion: old frame rate, no flip/scale/rotation jitter. */17
FlameFx.REDUCED_FPS = 12.5;18
/** Overall scale variation (±). */19
FlameFx.SCALE_VAR = 0.06;20
/** Extra independent width variation (±). */21
FlameFx.WIDTH_VAR = 0.07;22
/** Extra independent height variation (±). */23
FlameFx.HEIGHT_VAR = 0.07;24
/** Rotation variation in degrees (±). */25
FlameFx.ROT_VAR_DEG = 2.5;26
27
FlameFx.reducedMotion = function ()28
{29
try30
{31
var w = typeof window !== 'undefined' ? window : null;32
return !!(w && w.matchMedia && w.matchMedia('(prefers-reduced-motion: reduce)').matches);33
}34
catch (e)35
{ return false; }36
};37
38
/** New per-flame state; the phase is random so flames don't tick in sync. */39
FlameFx.create = function (frames, rand, reduced)40
{41
rand = rand || Math.random;42
var st = { frame: 0, timer: 0, flip: false, scale: 1, w: 1, h: 1, rot: 0, frames: frames || 1 };43
st.timer = rand() / FlameFx.FPS;44
FlameFx.roll(st, rand, !!reduced);45
return st;46
};47
48
/** Random frame index in [0, frames), different from `current` when possible. */49
FlameFx.pickFrame = function (current, frames, rand)50
{51
rand = rand || Math.random;52
if (frames <= 1)53
{ return 0; }54
// Choose among the other frames-1 indices uniformly.55
var k = Math.floor(rand() * (frames - 1));56
if (k >= frames - 1)57
{ k = frames - 2; }58
return k >= current ? k + 1 : k;59
};60
61
function flameVar (rand, amount)62
{63
return 1 + (rand() * 2 - 1) * amount;64
}65
66
/** One animation tick: new frame, flip, scales and rotation. */67
FlameFx.roll = function (st, rand, reduced)68
{69
rand = rand || Math.random;70
st.frame = FlameFx.pickFrame(st.frame, st.frames, rand);71
if (reduced)72
{73
st.flip = false;74
st.scale = 1;75
st.w = 1;76
st.h = 1;77
st.rot = 0;78
return st;79
}80
st.flip = rand() < 0.5;81
st.scale = flameVar(rand, FlameFx.SCALE_VAR);82
st.w = flameVar(rand, FlameFx.WIDTH_VAR);83
st.h = flameVar(rand, FlameFx.HEIGHT_VAR);84
st.rot = (rand() * 2 - 1) * FlameFx.ROT_VAR_DEG;85
return st;86
};87
88
/** Advance time (seconds). Returns the number of ticks that happened. */89
FlameFx.advance = function (st, dt, rand, reduced)90
{91
var period = 1 / (reduced ? FlameFx.REDUCED_FPS : FlameFx.FPS);92
st.timer += Math.max(0, dt || 0);93
var ticks = 0;94
while (st.timer >= period - 1e-9)95
{96
st.timer = Math.max(0, st.timer - period);97
ticks++;98
}99
// Long stall: one roll is enough, don't loop the RNG for nothing.100
if (ticks > 0)101
{ FlameFx.roll(st, rand, reduced); }102
return ticks;103
};104
105
/**106
* Draw pose for a flame whose top-centre anchor is (ax, ay) and whose107
* nominal size is baseW × baseH. The framework draws sprites centred on108
* (x, y), rotated by `rotation` degrees (clockwise, canvas y-down) around109
* that centre, and mirrorX flips around the vertical centre line. The110
* centre is placed so the rotated, scaled top-centre lands exactly on111
* the anchor.112
*/113
FlameFx.pose = function (st, ax, ay, baseW, baseH)114
{115
var w = baseW * st.scale * st.w;116
var h = baseH * st.scale * st.h;117
var rad = st.rot * Math.PI / 180;118
return {119
x: ax - Math.sin(rad) * h / 2,120
y: ay + Math.cos(rad) * h / 2,121
w: w,122
h: h,123
rotation: st.rot,124
mirrorX: !!st.flip,125
frame: st.frame126
};127
};128
129
/**130
* Where the top-centre of the drawn quad ends up for a pose — same131
* transform as the framework's sprite matrix (model point (0, -0.5)).132
* Used by tests to prove the anchor never moves.133
*/134
FlameFx.topCentreOf = function (pose)135
{136
var rad = pose.rotation * Math.PI / 180;137
var c = Math.cos(rad);138
var s = Math.sin(rad);139
var sy = pose.h;140
// x' = c*sx*u - s*sy*v + x ; y' = s*sx*u + c*sy*v + y with u = 0, v = -0.5141
return { x: pose.x + s * sy * 0.5, y: pose.y - c * sy * 0.5 };142
};143
144
if (typeof globalThis !== 'undefined')145
{ globalThis.FlameFx = FlameFx; }146
if (typeof module !== 'undefined' && module.exports)147
{ module.exports = FlameFx; }@@ -580,6 +580,13 @@ function spriteFor (block)
580
580
return game.images[key] || game.images.gray;
581
581
}
582
582
583
/** Frames in the flame sprite (from the loaded image, default 4). */
584
function flameFrameCount ()
585
{
586
var img = typeof game !== 'undefined' && game.images ? game.images.flame : null;
587
return img && img.subImages ? img.subImages : 4;
588
}
589
583
590
function syncSprites (dt)
584
591
{
585
592
if (!app.core || !app.scene)
@@ -617,22 +624,30 @@ function syncSprites (dt)
617
624
if (!flame)
618
625
{
619
626
flame = new GameObject(0, 0, game.images.flame, 1);
620
flame.renderer.setAnimation('burn', 0, 0.08);
627
// t1183: frames are chosen by FlameFx, not the framework cycle.
628
flame.fx = FlameFx.create(flameFrameCount(), Math.random, FlameFx.reducedMotion());
629
flame.renderer.setSubImage(flame.fx.frame);
621
630
app.scene.addObject(flame);
622
631
app.flames[block.id] = flame;
623
632
}
624
633
flame.renderer.visible = true;
634
FlameFx.advance(flame.fx, dt, Math.random, FlameFx.reducedMotion());
625
635
var t = app.tile;
626
636
// 3x as large (length and width, t1110). Keep the top of the
627
637
// flame at the same overlap into the block so the extra length
628
// extends downward under the rocket.
638
// extends downward under the rocket. t1183: random frame, flip,
639
// scale and rotation all pivot on that top-centre anchor.
629
640
var flameW = t * 0.85 * 3;
630
641
var flameH = t * 0.85 * 3;
631
642
var origCenter = app.fieldH - block.y * t + t * 0.15;
632
643
var origTop = origCenter - (t * 0.85) / 2;
633
flame.transform.position.x = block.col * t + t / 2;
634
flame.transform.position.y = origTop + flameH / 2;
635
flame.transform.size = { x: flameW, y: flameH };
644
var pose = FlameFx.pose(flame.fx, block.col * t + t / 2, origTop, flameW, flameH);
645
flame.renderer.subImage = pose.frame;
646
flame.renderer.mirrorX = pose.mirrorX;
647
flame.transform.rotation = pose.rotation;
648
flame.transform.position.x = pose.x;
649
flame.transform.position.y = pose.y;
650
flame.transform.size = { x: pose.w, y: pose.h };
636
651
}
637
652
else if (app.flames[block.id])
638
653
{ app.flames[block.id].renderer.visible = false; }
@@ -580,6 +580,13 @@ function spriteFor (block)580
return game.images[key] || game.images.gray;580
return game.images[key] || game.images.gray;581
}581
}582
582
583
/** Frames in the flame sprite (from the loaded image, default 4). */584
function flameFrameCount ()585
{586
var img = typeof game !== 'undefined' && game.images ? game.images.flame : null;587
return img && img.subImages ? img.subImages : 4;588
}589
583
function syncSprites (dt)590
function syncSprites (dt)584
{591
{585
if (!app.core || !app.scene)592
if (!app.core || !app.scene)@@ -617,22 +624,30 @@ function syncSprites (dt)617
if (!flame)624
if (!flame)618
{625
{619
flame = new GameObject(0, 0, game.images.flame, 1);626
flame = new GameObject(0, 0, game.images.flame, 1);620
flame.renderer.setAnimation('burn', 0, 0.08);627
// t1183: frames are chosen by FlameFx, not the framework cycle.628
flame.fx = FlameFx.create(flameFrameCount(), Math.random, FlameFx.reducedMotion());629
flame.renderer.setSubImage(flame.fx.frame);621
app.scene.addObject(flame);630
app.scene.addObject(flame);622
app.flames[block.id] = flame;631
app.flames[block.id] = flame;623
}632
}624
flame.renderer.visible = true;633
flame.renderer.visible = true;634
FlameFx.advance(flame.fx, dt, Math.random, FlameFx.reducedMotion());625
var t = app.tile;635
var t = app.tile;626
// 3x as large (length and width, t1110). Keep the top of the636
// 3x as large (length and width, t1110). Keep the top of the627
// flame at the same overlap into the block so the extra length637
// flame at the same overlap into the block so the extra length628
// extends downward under the rocket.638
// extends downward under the rocket. t1183: random frame, flip,639
// scale and rotation all pivot on that top-centre anchor.629
var flameW = t * 0.85 * 3;640
var flameW = t * 0.85 * 3;630
var flameH = t * 0.85 * 3;641
var flameH = t * 0.85 * 3;631
var origCenter = app.fieldH - block.y * t + t * 0.15;642
var origCenter = app.fieldH - block.y * t + t * 0.15;632
var origTop = origCenter - (t * 0.85) / 2;643
var origTop = origCenter - (t * 0.85) / 2;633
flame.transform.position.x = block.col * t + t / 2;644
var pose = FlameFx.pose(flame.fx, block.col * t + t / 2, origTop, flameW, flameH);634
flame.transform.position.y = origTop + flameH / 2;645
flame.renderer.subImage = pose.frame;635
flame.transform.size = { x: flameW, y: flameH };646
flame.renderer.mirrorX = pose.mirrorX;647
flame.transform.rotation = pose.rotation;648
flame.transform.position.x = pose.x;649
flame.transform.position.y = pose.y;650
flame.transform.size = { x: pose.w, y: pose.h };636
}651
}637
else if (app.flames[block.id])652
else if (app.flames[block.id])638
{ app.flames[block.id].renderer.visible = false; }653
{ app.flames[block.id].renderer.visible = false; }@@ -0,0 +1,129 @@
1
'use strict';
2
3
// t1183: rocket flame jitter (random frame, flip, scale, rotation).
4
5
const { describe, it } = require('node:test');
6
const assert = require('node:assert/strict');
7
const FX = require('../src/flameFx.js');
8
9
function seeded (seed)
10
{
11
let s = seed >>> 0;
12
return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296);
13
}
14
15
describe('FlameFx (t1183)', () =>
16
{
17
it('runs at double the old frame rate (0.08 s → 0.04 s per frame)', () =>
18
{
19
assert.equal(FX.FPS, 25);
20
assert.equal(FX.FPS, 2 * (1 / 0.08));
21
const st = FX.create(4, seeded(1));
22
st.timer = 0;
23
assert.equal(FX.advance(st, 1, seeded(2), false), 25);
24
st.timer = 0;
25
assert.equal(FX.advance(st, 1, seeded(2), true), 12, 'reduced motion keeps the old rate');
26
});
27
28
it('picks a random frame that differs from the current one, covering all frames', () =>
29
{
30
const rand = seeded(7);
31
const seen = new Set();
32
let cur = 0;
33
for (let i = 0; i < 400; i++)
34
{
35
const next = FX.pickFrame(cur, 4, rand);
36
assert.notEqual(next, cur);
37
assert.ok(next >= 0 && next < 4);
38
seen.add(next);
39
cur = next;
40
}
41
assert.equal(seen.size, 4);
42
assert.equal(FX.pickFrame(0, 1, rand), 0);
43
assert.equal(FX.pickFrame(2, 4, () => 0.999999999), 3);
44
});
45
46
it('flips about half the time and keeps scale/size/rotation within bounds, independently', () =>
47
{
48
const rand = seeded(42);
49
const st = FX.create(4, rand);
50
let flips = 0;
51
const n = 4000;
52
const ws = [];
53
const hs = [];
54
for (let i = 0; i < n; i++)
55
{
56
FX.roll(st, rand, false);
57
if (st.flip) flips++;
58
assert.ok(Math.abs(st.scale - 1) <= FX.SCALE_VAR + 1e-12);
59
assert.ok(Math.abs(st.w - 1) <= FX.WIDTH_VAR + 1e-12);
60
assert.ok(Math.abs(st.h - 1) <= FX.HEIGHT_VAR + 1e-12);
61
assert.ok(Math.abs(st.rot) <= FX.ROT_VAR_DEG + 1e-12);
62
ws.push(st.w); hs.push(st.h);
63
}
64
assert.ok(flips / n > 0.45 && flips / n < 0.55, 'flip share ' + flips / n);
65
// width and height vary independently (low correlation).
66
const mean = (a) => a.reduce((x, y) => x + y, 0) / a.length;
67
const mw = mean(ws), mh = mean(hs);
68
let cov = 0, vw = 0, vh = 0;
69
for (let i = 0; i < n; i++)
70
{ cov += (ws[i] - mw) * (hs[i] - mh); vw += (ws[i] - mw) ** 2; vh += (hs[i] - mh) ** 2; }
71
assert.ok(Math.abs(cov / Math.sqrt(vw * vh)) < 0.1);
72
});
73
74
it('the top-centre anchor never moves, whatever the flip, scale or rotation', () =>
75
{
76
const rand = seeded(3);
77
const st = FX.create(4, rand);
78
for (let i = 0; i < 500; i++)
79
{
80
FX.roll(st, rand, false);
81
const pose = FX.pose(st, 123.5, 77.25, 90, 90);
82
const top = FX.topCentreOf(pose);
83
assert.ok(Math.abs(top.x - 123.5) < 1e-9 && Math.abs(top.y - 77.25) < 1e-9, JSON.stringify(top));
84
assert.equal(pose.rotation, st.rot);
85
assert.equal(pose.mirrorX, st.flip);
86
}
87
// Unjittered pose = the old placement (centre half a flame below the top).
88
const plain = { frame: 0, flip: false, scale: 1, w: 1, h: 1, rot: 0 };
89
assert.deepEqual(FX.pose(plain, 10, 20, 30, 40), { x: 10, y: 40, w: 30, h: 40, rotation: 0, mirrorX: false, frame: 0 });
90
});
91
92
it('reduced motion: random frame only, no flip/scale/rotation', () =>
93
{
94
const rand = seeded(9);
95
const st = FX.create(4, rand);
96
for (let i = 0; i < 50; i++)
97
{
98
const before = st.frame;
99
FX.roll(st, rand, true);
100
assert.notEqual(st.frame, before);
101
assert.equal(st.flip, false);
102
assert.equal(st.scale * st.w * st.h, 1);
103
assert.equal(st.rot, 0);
104
}
105
});
106
107
it('a long stall rolls once and keeps the remainder', () =>
108
{
109
const st = FX.create(4, seeded(5));
110
st.timer = 0;
111
let calls = 0;
112
const rand = () => { calls++; return 0.3; };
113
assert.equal(FX.advance(st, 2.01, rand, false), 50);
114
assert.ok(calls <= 6, 'one roll, not 50: ' + calls);
115
assert.ok(st.timer >= 0 && st.timer < 0.04);
116
assert.equal(FX.advance(st, 0.001, rand, false) >= 0, true);
117
});
118
});
119
120
describe('FlameFx create (t1183)', () =>
121
{
122
it('a flame created under reduced motion starts unjittered', () =>
123
{
124
const st = FX.create(4, () => 0.9, true);
125
assert.equal(st.flip, false);
126
assert.equal(st.rot, 0);
127
assert.equal(st.scale * st.w * st.h, 1);
128
});
129
});
@@ -0,0 +1,129 @@1
'use strict';2
3
// t1183: rocket flame jitter (random frame, flip, scale, rotation).4
5
const { describe, it } = require('node:test');6
const assert = require('node:assert/strict');7
const FX = require('../src/flameFx.js');8
9
function seeded (seed)10
{11
let s = seed >>> 0;12
return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296);13
}14
15
describe('FlameFx (t1183)', () =>16
{17
it('runs at double the old frame rate (0.08 s → 0.04 s per frame)', () =>18
{19
assert.equal(FX.FPS, 25);20
assert.equal(FX.FPS, 2 * (1 / 0.08));21
const st = FX.create(4, seeded(1));22
st.timer = 0;23
assert.equal(FX.advance(st, 1, seeded(2), false), 25);24
st.timer = 0;25
assert.equal(FX.advance(st, 1, seeded(2), true), 12, 'reduced motion keeps the old rate');26
});27
28
it('picks a random frame that differs from the current one, covering all frames', () =>29
{30
const rand = seeded(7);31
const seen = new Set();32
let cur = 0;33
for (let i = 0; i < 400; i++)34
{35
const next = FX.pickFrame(cur, 4, rand);36
assert.notEqual(next, cur);37
assert.ok(next >= 0 && next < 4);38
seen.add(next);39
cur = next;40
}41
assert.equal(seen.size, 4);42
assert.equal(FX.pickFrame(0, 1, rand), 0);43
assert.equal(FX.pickFrame(2, 4, () => 0.999999999), 3);44
});45
46
it('flips about half the time and keeps scale/size/rotation within bounds, independently', () =>47
{48
const rand = seeded(42);49
const st = FX.create(4, rand);50
let flips = 0;51
const n = 4000;52
const ws = [];53
const hs = [];54
for (let i = 0; i < n; i++)55
{56
FX.roll(st, rand, false);57
if (st.flip) flips++;58
assert.ok(Math.abs(st.scale - 1) <= FX.SCALE_VAR + 1e-12);59
assert.ok(Math.abs(st.w - 1) <= FX.WIDTH_VAR + 1e-12);60
assert.ok(Math.abs(st.h - 1) <= FX.HEIGHT_VAR + 1e-12);61
assert.ok(Math.abs(st.rot) <= FX.ROT_VAR_DEG + 1e-12);62
ws.push(st.w); hs.push(st.h);63
}64
assert.ok(flips / n > 0.45 && flips / n < 0.55, 'flip share ' + flips / n);65
// width and height vary independently (low correlation).66
const mean = (a) => a.reduce((x, y) => x + y, 0) / a.length;67
const mw = mean(ws), mh = mean(hs);68
let cov = 0, vw = 0, vh = 0;69
for (let i = 0; i < n; i++)70
{ cov += (ws[i] - mw) * (hs[i] - mh); vw += (ws[i] - mw) ** 2; vh += (hs[i] - mh) ** 2; }71
assert.ok(Math.abs(cov / Math.sqrt(vw * vh)) < 0.1);72
});73
74
it('the top-centre anchor never moves, whatever the flip, scale or rotation', () =>75
{76
const rand = seeded(3);77
const st = FX.create(4, rand);78
for (let i = 0; i < 500; i++)79
{80
FX.roll(st, rand, false);81
const pose = FX.pose(st, 123.5, 77.25, 90, 90);82
const top = FX.topCentreOf(pose);83
assert.ok(Math.abs(top.x - 123.5) < 1e-9 && Math.abs(top.y - 77.25) < 1e-9, JSON.stringify(top));84
assert.equal(pose.rotation, st.rot);85
assert.equal(pose.mirrorX, st.flip);86
}87
// Unjittered pose = the old placement (centre half a flame below the top).88
const plain = { frame: 0, flip: false, scale: 1, w: 1, h: 1, rot: 0 };89
assert.deepEqual(FX.pose(plain, 10, 20, 30, 40), { x: 10, y: 40, w: 30, h: 40, rotation: 0, mirrorX: false, frame: 0 });90
});91
92
it('reduced motion: random frame only, no flip/scale/rotation', () =>93
{94
const rand = seeded(9);95
const st = FX.create(4, rand);96
for (let i = 0; i < 50; i++)97
{98
const before = st.frame;99
FX.roll(st, rand, true);100
assert.notEqual(st.frame, before);101
assert.equal(st.flip, false);102
assert.equal(st.scale * st.w * st.h, 1);103
assert.equal(st.rot, 0);104
}105
});106
107
it('a long stall rolls once and keeps the remainder', () =>108
{109
const st = FX.create(4, seeded(5));110
st.timer = 0;111
let calls = 0;112
const rand = () => { calls++; return 0.3; };113
assert.equal(FX.advance(st, 2.01, rand, false), 50);114
assert.ok(calls <= 6, 'one roll, not 50: ' + calls);115
assert.ok(st.timer >= 0 && st.timer < 0.04);116
assert.equal(FX.advance(st, 0.001, rand, false) >= 0, true);117
});118
});119
120
describe('FlameFx create (t1183)', () =>121
{122
it('a flame created under reduced motion starts unjittered', () =>123
{124
const st = FX.create(4, () => 0.9, true);125
assert.equal(st.flip, false);126
assert.equal(st.rot, 0);127
assert.equal(st.scale * st.w * st.h, 1);128
});129
});@@ -0,0 +1,131 @@
1
#!/usr/bin/env python3
2
"""t1183: rocket flame jitter — sample the flame per frame and save a frame strip.
3
4
Usage: python3 test/t1183-flame-playwright.py URL TAG
5
Starts a logged-out solo game, freezes the game core (rendering keeps
6
running), places one gray rocket block with a flame and records the
7
flame's frame / flip / rotation / size and its top-centre anchor every
8
animation frame, plus a strip of close-up screenshots.
9
"""
10
import json, sys, statistics
11
from pathlib import Path
12
from playwright.sync_api import sync_playwright
13
from PIL import Image, ImageDraw
14
15
URL = sys.argv[1] if len(sys.argv) > 1 else "https://projects.timfalken.com/meteors/"
16
TAG = sys.argv[2] if len(sys.argv) > 2 else "live"
17
SHOTS = Path("/workspace/meteors-shots")
18
fails = []
19
20
def check(c, m):
21
print(("OK " if c else "FAIL ") + m)
22
if not c: fails.append(m)
23
24
with sync_playwright() as pw:
25
br = pw.chromium.launch(args=["--use-gl=angle", "--use-angle=swiftshader"])
26
ctx = br.new_context(viewport={"width": 1280, "height": 800})
27
page = ctx.new_page()
28
errors = []
29
page.on("pageerror", lambda e: errors.append(str(e)))
30
page.goto(URL + ("" if URL.endswith("/") else "/") + "index.html?t1183=" + TAG, wait_until="networkidle")
31
has = page.evaluate("() => typeof FlameFx !== 'undefined'")
32
check(has, "FlameFx present in the served game.js")
33
page.locator("#btn-play").click()
34
page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
35
page.wait_for_timeout(200)
36
page.locator("#btn-planet-go").click()
37
page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000)
38
page.wait_for_timeout(400)
39
info = page.evaluate("""() => {
40
app.core.tick = function () {};
41
for (const b of app.core.blocks.slice()) { b.y = -50; }
42
const b = app.core.createBlock(4, 7, GameCore.COLOR_GRAY, 'still');
43
b.flame = true; b.vy = 0;
44
window.__fb = b;
45
const R = window.__flame = { rows: [] };
46
const loop = () => {
47
const f = app.flames[b.id];
48
if (f) {
49
const p = { x: f.transform.position.x, y: f.transform.position.y, w: f.transform.size.x,
50
h: f.transform.size.y, rotation: f.transform.rotation, mirrorX: f.renderer.mirrorX };
51
const top = FlameFx.topCentreOf(p);
52
R.rows.push([performance.now(), f.renderer.subImage, !!f.renderer.mirrorX, +f.transform.rotation.toFixed(3),
53
+f.transform.size.x.toFixed(2), +f.transform.size.y.toFixed(2), +top.x.toFixed(3), +top.y.toFixed(3)]);
54
}
55
requestAnimationFrame(loop);
56
};
57
requestAnimationFrame(loop);
58
const cv = app.scene.canvas;
59
const c = cv.getBoundingClientRect();
60
return { tile: app.tile, col: b.col, fieldH: app.fieldH, canvas: [c.left, c.top, c.width, c.height],
61
cw: cv.width, reduced: FlameFx.reducedMotion(), fps: FlameFx.FPS,
62
vars: [FlameFx.SCALE_VAR, FlameFx.WIDTH_VAR, FlameFx.HEIGHT_VAR, FlameFx.ROT_VAR_DEG] };
63
}""")
64
page.wait_for_timeout(500)
65
# Close-up strip around the rocket.
66
t = info["tile"]; cl, ct, cwid, ch = info["canvas"]; k = cwid / info["cw"]
67
cx = cl + (info["col"] * t + t / 2) * k
68
topy = ct + (info["fieldH"] - 7 * t - t * 0.5) * k
69
clip = {"x": cx - 2.0 * t * k, "y": topy - 0.4 * t * k, "width": 4.0 * t * k, "height": 3.6 * t * k}
70
frames = []
71
for i in range(12):
72
p = SHOTS / f"t1183-{TAG}-frame-{i:02d}.png"
73
page.screenshot(path=str(p), clip=clip)
74
frames.append(p)
75
page.wait_for_timeout(45)
76
page.wait_for_timeout(1500)
77
rows = page.evaluate("() => window.__flame.rows")
78
page.screenshot(path=str(SHOTS / f"t1183-{TAG}-full.png"))
79
ctx.close()
80
# Reduced-motion context: old rate, no flip / scale / rotation.
81
ctx2 = br.new_context(viewport={"width": 1280, "height": 800}, reduced_motion="reduce")
82
p2 = ctx2.new_page()
83
p2.goto(URL + ("" if URL.endswith("/") else "/") + "index.html", wait_until="networkidle")
84
red = p2.evaluate("""() => { const s = FlameFx.create(4, Math.random, FlameFx.reducedMotion()); const r = [];
85
for (let i = 0; i < 40; i++) { FlameFx.advance(s, 0.05, Math.random, FlameFx.reducedMotion()); r.push([s.flip, s.rot, s.scale * s.w * s.h]); }
86
return { reduced: FlameFx.reducedMotion(), anyJitter: r.some(x => x[0] || x[1] !== 0 || x[2] !== 1) }; }""")
87
ctx2.close()
88
br.close()
89
90
# Strip image.
91
ims = [Image.open(p) for p in frames]
92
w, h = ims[0].size
93
strip = Image.new("RGB", (w * len(ims), h + 18), (12, 12, 24))
94
d = ImageDraw.Draw(strip)
95
for i, im in enumerate(ims):
96
strip.paste(im, (i * w, 18))
97
d.text((i * w + 4, 3), f"#{i + 1}", fill=(220, 220, 220))
98
strip_path = SHOTS / f"t1183-{TAG}-strip.png"
99
strip.save(strip_path)
100
101
# Analysis over the sampled frames (only frames where the pose changed = ticks).
102
ticks = [b for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6]]
103
dur = (rows[-1][0] - rows[0][0]) / 1000 if len(rows) > 1 else 1
104
tick_rate = len(ticks) / dur
105
frame_changes = sum(1 for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6] and a[1] != b[1])
106
same_frame_ticks = sum(1 for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6] and a[1] == b[1])
107
anchor_x = [r[6] for r in rows]; anchor_y = [r[7] for r in rows]
108
rots = [r[3] for r in rows]; flips = [r[2] for r in rows]
109
ws = [r[4] for r in rows]; hs = [r[5] for r in rows]
110
summary = {
111
"url": URL, "fps_constant": info["fps"], "variation": dict(zip(["scale", "width", "height", "rotation_deg"], info["vars"])),
112
"reduced_motion_in_main_ctx": info["reduced"], "samples": len(rows), "seconds": round(dur, 2),
113
"measured_tick_rate_hz": round(tick_rate, 1), "frames_used": sorted(set(r[1] for r in rows)),
114
"ticks_with_same_frame": same_frame_ticks, "flip_share": round(sum(flips) / len(flips), 2),
115
"rotation_range": [min(rots), max(rots)], "width_range": [min(ws), max(ws)], "height_range": [min(hs), max(hs)],
116
"anchor_spread_px": [round(max(anchor_x) - min(anchor_x), 3), round(max(anchor_y) - min(anchor_y), 3)],
117
"reduced_motion_ctx": red, "errors": errors, "strip": str(strip_path),
118
}
119
(SHOTS / f"t1183-{TAG}-metrics.json").write_text(json.dumps({"summary": summary, "rows": rows}, indent=1))
120
print(json.dumps(summary, indent=1))
121
check(len(rows) > 60, f"sampled {len(rows)} frames")
122
check(15 <= tick_rate <= 30, f"tick rate ~25 Hz (measured {tick_rate:.1f}; capped by the headless frame rate)")
123
check(set(summary["frames_used"]) == {0, 1, 2, 3}, "all 4 sprite frames used")
124
check(same_frame_ticks == 0, "every tick switches to a different frame")
125
check(0.3 <= summary["flip_share"] <= 0.7, f"flips about half the time ({summary['flip_share']})")
126
check(max(abs(min(rots)), abs(max(rots))) <= 2.5 + 1e-6 and max(rots) - min(rots) > 2, "rotation within ±2.5° and varies")
127
check(summary["anchor_spread_px"][0] < 0.01 and summary["anchor_spread_px"][1] < 0.01, f"top-centre anchor fixed {summary['anchor_spread_px']}")
128
check(red["reduced"] and not red["anyJitter"], "reduced motion: no flip/scale/rotation")
129
check(not errors, f"no page errors {errors[:2]}")
130
print("ALL OK" if not fails else f"{len(fails)} FAIL")
131
sys.exit(1 if fails else 0)
@@ -0,0 +1,131 @@1
#!/usr/bin/env python32
"""t1183: rocket flame jitter — sample the flame per frame and save a frame strip.3
4
Usage: python3 test/t1183-flame-playwright.py URL TAG5
Starts a logged-out solo game, freezes the game core (rendering keeps6
running), places one gray rocket block with a flame and records the7
flame's frame / flip / rotation / size and its top-centre anchor every8
animation frame, plus a strip of close-up screenshots.9
"""10
import json, sys, statistics11
from pathlib import Path12
from playwright.sync_api import sync_playwright13
from PIL import Image, ImageDraw14
15
URL = sys.argv[1] if len(sys.argv) > 1 else "https://projects.timfalken.com/meteors/"16
TAG = sys.argv[2] if len(sys.argv) > 2 else "live"17
SHOTS = Path("/workspace/meteors-shots")18
fails = []19
20
def check(c, m):21
print(("OK " if c else "FAIL ") + m)22
if not c: fails.append(m)23
24
with sync_playwright() as pw:25
br = pw.chromium.launch(args=["--use-gl=angle", "--use-angle=swiftshader"])26
ctx = br.new_context(viewport={"width": 1280, "height": 800})27
page = ctx.new_page()28
errors = []29
page.on("pageerror", lambda e: errors.append(str(e)))30
page.goto(URL + ("" if URL.endswith("/") else "/") + "index.html?t1183=" + TAG, wait_until="networkidle")31
has = page.evaluate("() => typeof FlameFx !== 'undefined'")32
check(has, "FlameFx present in the served game.js")33
page.locator("#btn-play").click()34
page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)35
page.wait_for_timeout(200)36
page.locator("#btn-planet-go").click()37
page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000)38
page.wait_for_timeout(400)39
info = page.evaluate("""() => {40
app.core.tick = function () {};41
for (const b of app.core.blocks.slice()) { b.y = -50; }42
const b = app.core.createBlock(4, 7, GameCore.COLOR_GRAY, 'still');43
b.flame = true; b.vy = 0;44
window.__fb = b;45
const R = window.__flame = { rows: [] };46
const loop = () => {47
const f = app.flames[b.id];48
if (f) {49
const p = { x: f.transform.position.x, y: f.transform.position.y, w: f.transform.size.x,50
h: f.transform.size.y, rotation: f.transform.rotation, mirrorX: f.renderer.mirrorX };51
const top = FlameFx.topCentreOf(p);52
R.rows.push([performance.now(), f.renderer.subImage, !!f.renderer.mirrorX, +f.transform.rotation.toFixed(3),53
+f.transform.size.x.toFixed(2), +f.transform.size.y.toFixed(2), +top.x.toFixed(3), +top.y.toFixed(3)]);54
}55
requestAnimationFrame(loop);56
};57
requestAnimationFrame(loop);58
const cv = app.scene.canvas;59
const c = cv.getBoundingClientRect();60
return { tile: app.tile, col: b.col, fieldH: app.fieldH, canvas: [c.left, c.top, c.width, c.height],61
cw: cv.width, reduced: FlameFx.reducedMotion(), fps: FlameFx.FPS,62
vars: [FlameFx.SCALE_VAR, FlameFx.WIDTH_VAR, FlameFx.HEIGHT_VAR, FlameFx.ROT_VAR_DEG] };63
}""")64
page.wait_for_timeout(500)65
# Close-up strip around the rocket.66
t = info["tile"]; cl, ct, cwid, ch = info["canvas"]; k = cwid / info["cw"]67
cx = cl + (info["col"] * t + t / 2) * k68
topy = ct + (info["fieldH"] - 7 * t - t * 0.5) * k69
clip = {"x": cx - 2.0 * t * k, "y": topy - 0.4 * t * k, "width": 4.0 * t * k, "height": 3.6 * t * k}70
frames = []71
for i in range(12):72
p = SHOTS / f"t1183-{TAG}-frame-{i:02d}.png"73
page.screenshot(path=str(p), clip=clip)74
frames.append(p)75
page.wait_for_timeout(45)76
page.wait_for_timeout(1500)77
rows = page.evaluate("() => window.__flame.rows")78
page.screenshot(path=str(SHOTS / f"t1183-{TAG}-full.png"))79
ctx.close()80
# Reduced-motion context: old rate, no flip / scale / rotation.81
ctx2 = br.new_context(viewport={"width": 1280, "height": 800}, reduced_motion="reduce")82
p2 = ctx2.new_page()83
p2.goto(URL + ("" if URL.endswith("/") else "/") + "index.html", wait_until="networkidle")84
red = p2.evaluate("""() => { const s = FlameFx.create(4, Math.random, FlameFx.reducedMotion()); const r = [];85
for (let i = 0; i < 40; i++) { FlameFx.advance(s, 0.05, Math.random, FlameFx.reducedMotion()); r.push([s.flip, s.rot, s.scale * s.w * s.h]); }86
return { reduced: FlameFx.reducedMotion(), anyJitter: r.some(x => x[0] || x[1] !== 0 || x[2] !== 1) }; }""")87
ctx2.close()88
br.close()89
90
# Strip image.91
ims = [Image.open(p) for p in frames]92
w, h = ims[0].size93
strip = Image.new("RGB", (w * len(ims), h + 18), (12, 12, 24))94
d = ImageDraw.Draw(strip)95
for i, im in enumerate(ims):96
strip.paste(im, (i * w, 18))97
d.text((i * w + 4, 3), f"#{i + 1}", fill=(220, 220, 220))98
strip_path = SHOTS / f"t1183-{TAG}-strip.png"99
strip.save(strip_path)100
101
# Analysis over the sampled frames (only frames where the pose changed = ticks).102
ticks = [b for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6]]103
dur = (rows[-1][0] - rows[0][0]) / 1000 if len(rows) > 1 else 1104
tick_rate = len(ticks) / dur105
frame_changes = sum(1 for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6] and a[1] != b[1])106
same_frame_ticks = sum(1 for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6] and a[1] == b[1])107
anchor_x = [r[6] for r in rows]; anchor_y = [r[7] for r in rows]108
rots = [r[3] for r in rows]; flips = [r[2] for r in rows]109
ws = [r[4] for r in rows]; hs = [r[5] for r in rows]110
summary = {111
"url": URL, "fps_constant": info["fps"], "variation": dict(zip(["scale", "width", "height", "rotation_deg"], info["vars"])),112
"reduced_motion_in_main_ctx": info["reduced"], "samples": len(rows), "seconds": round(dur, 2),113
"measured_tick_rate_hz": round(tick_rate, 1), "frames_used": sorted(set(r[1] for r in rows)),114
"ticks_with_same_frame": same_frame_ticks, "flip_share": round(sum(flips) / len(flips), 2),115
"rotation_range": [min(rots), max(rots)], "width_range": [min(ws), max(ws)], "height_range": [min(hs), max(hs)],116
"anchor_spread_px": [round(max(anchor_x) - min(anchor_x), 3), round(max(anchor_y) - min(anchor_y), 3)],117
"reduced_motion_ctx": red, "errors": errors, "strip": str(strip_path),118
}119
(SHOTS / f"t1183-{TAG}-metrics.json").write_text(json.dumps({"summary": summary, "rows": rows}, indent=1))120
print(json.dumps(summary, indent=1))121
check(len(rows) > 60, f"sampled {len(rows)} frames")122
check(15 <= tick_rate <= 30, f"tick rate ~25 Hz (measured {tick_rate:.1f}; capped by the headless frame rate)")123
check(set(summary["frames_used"]) == {0, 1, 2, 3}, "all 4 sprite frames used")124
check(same_frame_ticks == 0, "every tick switches to a different frame")125
check(0.3 <= summary["flip_share"] <= 0.7, f"flips about half the time ({summary['flip_share']})")126
check(max(abs(min(rots)), abs(max(rots))) <= 2.5 + 1e-6 and max(rots) - min(rots) > 2, "rotation within ±2.5° and varies")127
check(summary["anchor_spread_px"][0] < 0.01 and summary["anchor_spread_px"][1] < 0.01, f"top-centre anchor fixed {summary['anchor_spread_px']}")128
check(red["reduced"] and not red["anyJitter"], "reduced motion: no flip/scale/rotation")129
check(not errors, f"no page errors {errors[:2]}")130
print("ALL OK" if not fails else f"{len(fails)} FAIL")131
sys.exit(1 if fails else 0)