BlueGit

projects-timfalken-com meteors

Files

meteors / test / drag-playwright.py

drag-playwright.py

drag-playwright.py 21.1 KiB Download Raw
1#!/usr/bin/env python3
2"""Drag tests (t1104/t1106/t1107/t1109/t1110): 1:1 tracking, poisoned-pointer
3regression, cell-corner grabs, under-flyer / landed-cluster drags, flame size."""
4from __future__ import annotations
5
6import socket
7import subprocess
8import sys
9import time
10from pathlib import Path
11
12from playwright.sync_api import sync_playwright
13
14OUT = Path("/workspace/meteors-shots")
15OUT.mkdir(parents=True, exist_ok=True)
16ROOT = Path("/workspace/meteors")
17CHROME = "/usr/bin/google-chrome"
18CHROME_ARGS = [
19 "--use-gl=angle",
20 "--use-angle=swiftshader",
21 "--no-sandbox",
22 "--disable-dev-shm-usage",
23 "--disable-gpu-sandbox",
24]
25
26DESKTOP = {
27 "name": "desktop-mouse",
28 "viewport": {"width": 1280, "height": 900},
29 "device_scale_factor": 1,
30 "is_mobile": False,
31 "has_touch": False,
32 "user_agent": None,
33 "input": "mouse",
34}
35ANDROID = {
36 "name": "android-touch",
37 "viewport": {"width": 393, "height": 851},
38 "device_scale_factor": 2,
39 "is_mobile": True,
40 "has_touch": True,
41 "user_agent": (
42 "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "
43 "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
44 ),
45 "input": "touch",
46}
47ANDROID_DPR3 = {
48 "name": "android-dpr3",
49 "viewport": {"width": 393, "height": 851},
50 "device_scale_factor": 3,
51 "is_mobile": True,
52 "has_touch": True,
53 "user_agent": (
54 "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "
55 "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
56 ),
57 "input": "touch",
58}
59IOS = {
60 "name": "ios-touch",
61 "viewport": {"width": 390, "height": 844},
62 "device_scale_factor": 2,
63 "is_mobile": True,
64 "has_touch": True,
65 "user_agent": (
66 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
67 "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
68 "Mobile/15E148 Safari/604.1"
69 ),
70 "input": "touch",
71}
72
73FAILURES = []
74URL = None
75
76
77def free_port():
78 s = socket.socket()
79 s.bind(("127.0.0.1", 0))
80 port = s.getsockname()[1]
81 s.close()
82 return port
83
84
85def field_to_client(page, col, field_y):
86 return page.evaluate(
87 """([col, fieldY]) => {
88 const c = app.scene.canvas;
89 const r = c.getBoundingClientRect();
90 const w = Planet.FIELD_WIDTH;
91 const h = Planet.FIELD_HEIGHT;
92 return {
93 x: r.left + ((col + 0.5) / w) * r.width,
94 y: r.top + (1 - fieldY / h) * r.height
95 };
96 }""",
97 [col, field_y],
98 )
99
100
101def touch_start(cdp, x, y):
102 cdp.send(
103 "Input.dispatchTouchEvent",
104 {"type": "touchStart", "touchPoints": [{"x": x, "y": y, "id": 1}]},
105 )
106
107
108def touch_move(cdp, x, y):
109 cdp.send(
110 "Input.dispatchTouchEvent",
111 {"type": "touchMove", "touchPoints": [{"x": x, "y": y, "id": 1}]},
112 )
113
114
115def touch_end(cdp):
116 cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})
117
118
119def pointer_down(page, cdp, kind, x, y):
120 if kind == "mouse":
121 page.mouse.move(x, y)
122 page.mouse.down()
123 else:
124 touch_start(cdp, x, y)
125
126
127def pointer_move(page, cdp, kind, x, y):
128 if kind == "mouse":
129 page.mouse.move(x, y)
130 else:
131 touch_move(cdp, x, y)
132
133
134def pointer_up(page, cdp, kind):
135 if kind == "mouse":
136 page.mouse.up()
137 else:
138 touch_end(cdp)
139
140
141def drag_to(page, cdp, kind, x1, y1, x2, y2, steps=12, end=True):
142 pointer_down(page, cdp, kind, x1, y1)
143 for i in range(1, steps + 1):
144 t = i / steps
145 pointer_move(page, cdp, kind, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)
146 if end:
147 pointer_up(page, cdp, kind)
148
149
150def reset_board(page, stacks):
151 page.evaluate(
152 """(stacks) => {
153 const g = app.core;
154 g.spawnInterval = 1e9;
155 g.spawnTimer = 0;
156 g.blocks.length = 0;
157 g.clusters = Object.create(null);
158 g.score = 0;
159 g.drag = null;
160 g.state = 'playing';
161 g.nextBlockId = 1;
162 g.nextClusterId = 1;
163 app.selectTween = null;
164 for (const [col, colors] of Object.entries(stacks)) {
165 colors.forEach((color, row) => g.place(+col, row, color));
166 }
167 }""",
168 stacks,
169 )
170 page.wait_for_timeout(80)
171
172
173def board(page):
174 return page.evaluate(
175 """() => app.core.blocks.map((b) => ({
176 id: b.id, col: b.col, y: b.y, color: b.color, state: b.state
177 }))"""
178 )
179
180
181def col_ys(page, col):
182 return {b["color"]: b["y"] for b in board(page) if b["col"] == col}
183
184
185def check(cond, msg, device):
186 if not cond:
187 FAILURES.append(f"[{device}] {msg}")
188 print(f"FAIL [{device}] {msg}")
189 else:
190 print(f"OK [{device}] {msg}")
191 return cond
192
193
194def shot(page, name):
195 path = OUT / name
196 page.screenshot(path=str(path), full_page=False)
197 print(f"wrote {path} ({path.stat().st_size} bytes)")
198
199
200def start_play(page, kind):
201 page.goto(URL, wait_until="networkidle", timeout=20000)
202 page.wait_for_timeout(400)
203 btn = page.locator("#btn-survival")
204 btn.wait_for(state="visible", timeout=5000)
205 if kind == "touch":
206 box = btn.bounding_box()
207 cdp = page.context.new_cdp_session(page)
208 touch_start(cdp, box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
209 touch_end(cdp)
210 page.wait_for_timeout(400)
211 else:
212 cdp = None
213 btn.click()
214 page.wait_for_timeout(400)
215 if page.evaluate("() => app && app.mode") == "planet-select":
216 go = page.locator("#btn-planet-go")
217 go.wait_for(state="visible", timeout=5000)
218 go.click()
219 page.wait_for_timeout(400)
220 if page.evaluate("() => app.mode") != "playing":
221 if page.locator("#btn-survival").is_visible():
222 page.locator("#btn-survival").click()
223 page.wait_for_timeout(400)
224 if page.locator("#btn-planet-go").is_visible():
225 page.locator("#btn-planet-go").click()
226 page.wait_for_timeout(400)
227 page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)
228 page.wait_for_selector("canvas", state="visible", timeout=5000)
229 if cdp is None:
230 cdp = page.context.new_cdp_session(page)
231 return cdp
232
233
234def nearly(a, b, eps=0.15):
235 return abs(a - b) <= eps
236
237
238def run_device(browser, device):
239 name = device["name"]
240 kind = device["input"]
241 print(f"\n======== {name} ({kind}, dpr={device['device_scale_factor']}) ========")
242 kw = dict(
243 viewport=device["viewport"],
244 device_scale_factor=device["device_scale_factor"],
245 is_mobile=device["is_mobile"],
246 has_touch=device["has_touch"],
247 )
248 if device["user_agent"]:
249 kw["user_agent"] = device["user_agent"]
250 context = browser.new_context(**kw)
251 page = context.new_page()
252 bag = []
253 page.on("console", lambda m: bag.append(f"{m.type}: {m.text}"))
254 page.on("pageerror", lambda e: bag.append(f"pageerror: {e}"))
255 cdp = start_play(page, kind)
256 check(page.evaluate("() => app.mode") == "playing", "play started", name)
257
258 # --- 1 tile down ---
259 reset_board(page, {"2": [0, 1, 2, 3, 4]})
260 p0 = field_to_client(page, 2, 1.5)
261 p1 = field_to_client(page, 2, 0.5)
262 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
263 page.wait_for_timeout(60)
264 ys = col_ys(page, 2)
265 check(nearly(ys.get(1, -99), 0), f"1 tile down: grabbed color 1 at y=0, ys={ys}", name)
266 check(nearly(ys.get(0, -99), 1), f"1 tile down: swapped neighbour to y=1, ys={ys}", name)
267 check(nearly(ys.get(2, -99), 2) and nearly(ys.get(3, -99), 3) and nearly(ys.get(4, -99), 4),
268 f"1 tile down: rest of the stack unmoved, ys={ys}", name)
269
270 # --- 1 tile up ---
271 reset_board(page, {"3": [0, 1, 2, 3, 4]})
272 p0 = field_to_client(page, 3, 0.5)
273 p1 = field_to_client(page, 3, 1.5)
274 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
275 page.wait_for_timeout(60)
276 ys = col_ys(page, 3)
277 check(nearly(ys.get(0, -99), 1), f"1 tile up: grabbed color 0 at y=1, ys={ys}", name)
278 check(nearly(ys.get(1, -99), 0), f"1 tile up: neighbour at y=0, ys={ys}", name)
279 check(nearly(ys.get(2, -99), 2), f"1 tile up: rest unmoved, ys={ys}", name)
280
281 # --- 2 tiles, then stop: pointer held still, nothing else moves ---
282 reset_board(page, {"4": [0, 1, 2, 3, 4]})
283 p0 = field_to_client(page, 4, 0.5)
284 p1 = field_to_client(page, 4, 2.5)
285 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=14, end=False)
286 page.wait_for_timeout(50)
287 mid = col_ys(page, 4)
288 check(nearly(mid.get(0, -99), 2), f"2 tiles: grabbed color 0 at y=2, ys={mid}", name)
289 check(nearly(mid.get(1, -99), 0) and nearly(mid.get(2, -99), 1) and nearly(mid.get(3, -99), 3),
290 f"2 tiles: walked both neighbours, ys={mid}", name)
291 # Pointer stops: more moves at the same point, then a short wait.
292 for _ in range(6):
293 pointer_move(page, cdp, kind, p1["x"], p1["y"])
294 page.wait_for_timeout(30)
295 after = col_ys(page, 4)
296 check(after == mid, f"pointer stopped: stack stays put, mid={mid} after={after}", name)
297 pointer_up(page, cdp, kind)
298 page.wait_for_timeout(80)
299 end = col_ys(page, 4)
300 check(end == mid, f"after release: still at the pointer row, mid={mid} end={end}", name)
301 shot(page, f"t1104-drag-{name}.png")
302
303 # --- t1109: press at cell corners grabs the occupant (mouse and touch)
304 run_cell_corner_grabs(page, cdp, kind, name)
305
306 # --- t1107: still stack under a flying cluster is draggable
307 run_under_flyer_drag(page, cdp, kind, name)
308
309 # --- t1107: drag within a landed cluster
310 run_landed_cluster_drag(page, cdp, kind, name)
311
312 # --- t1110: flame is 3x, with a visual screenshot (once per device)
313 run_flame_size(page, name)
314
315 if bag:
316 print(f"console [{name}]: {bag[:8]}")
317 context.close()
318
319
320def field_point(page, fx, fy):
321 """Map exact field coordinates (not cell-centres) to client pixels."""
322 return page.evaluate(
323 """([fx, fy]) => {
324 const c = app.scene.canvas;
325 const r = c.getBoundingClientRect();
326 return {
327 x: r.left + (fx / 10) * r.width,
328 y: r.top + (1 - fy / 13) * r.height
329 };
330 }""",
331 [fx, fy],
332 )
333
334
335def grab_id(page):
336 return page.evaluate(
337 """() => {
338 const g = app.core;
339 if (!g.drag) return null;
340 const b = g.blockById(g.drag.blockId);
341 return b ? { id: b.id, col: b.col, y: b.y, color: b.color } : null;
342 }"""
343 )
344
345
346def run_cell_corner_grabs(page, cdp, kind, name):
347 reset_board(page, {"2": [0, 1, 2]})
348 page.wait_for_timeout(50)
349 target = page.evaluate(
350 """() => {
351 const b = app.core.blocks.find((x) => x.col === 2 && Math.abs(x.y - 1) < 0.01);
352 return b ? b.id : null;
353 }"""
354 )
355 corners = [(2.05, 1.05, "bottom-left"), (2.05, 1.95, "top-left"),
356 (2.95, 1.05, "bottom-right"), (2.95, 1.95, "top-right")]
357 for fx, fy, label in corners:
358 pt = field_point(page, fx, fy)
359 pointer_down(page, cdp, kind, pt["x"], pt["y"])
360 page.wait_for_timeout(30)
361 grabbed = grab_id(page)
362 check(
363 grabbed is not None and grabbed["id"] == target,
364 f"t1109 corner {label} ({kind}) grabs cell occupant, grabbed={grabbed} want id={target}",
365 name,
366 )
367 pointer_up(page, cdp, kind)
368 page.wait_for_timeout(40)
369 shot(page, f"t1109-corners-{name}.png")
370
371
372def run_under_flyer_drag(page, cdp, kind, name):
373 reset_board(page, {"3": [0, 1, 2]})
374 page.evaluate(
375 """() => {
376 const g = app.core;
377 const cluster = { id: g.nextClusterId++, jumpHeight: 3, vy: 0, decel: 0, phase: 'up' };
378 g.clusters[cluster.id] = cluster;
379 const b = g.createBlock(3, 8, g.constructor.COLOR_GRAY, 'flying');
380 b.clusterId = cluster.id;
381 b.vy = 0;
382 b.flame = true;
383 }"""
384 )
385 page.wait_for_timeout(40)
386 p0 = field_to_client(page, 3, 0.5)
387 p1 = field_to_client(page, 3, 1.5)
388 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
389 page.wait_for_timeout(60)
390 info = page.evaluate(
391 """() => {
392 const g = app.core;
393 const still = g.blocks.filter((b) => b.state === 'still' && b.col === 3)
394 .map((b) => ({ color: b.color, y: b.y }));
395 const flyer = g.blocks.find((b) => b.state === 'flying' && b.col === 3);
396 return { still, flyerY: flyer ? flyer.y : null, flyerState: flyer ? flyer.state : null };
397 }"""
398 )
399 ys = {b["color"]: b["y"] for b in info["still"]}
400 check(nearly(ys.get(0, -99), 1), f"t1107 under-flyer: color 0 moved to y=1, info={info}", name)
401 check(nearly(ys.get(1, -99), 0), f"t1107 under-flyer: color 1 swapped to y=0, info={info}", name)
402 check(info["flyerState"] == "flying" and info["flyerY"] is not None and info["flyerY"] > 6,
403 f"t1107 under-flyer: flyer left alone, info={info}", name)
404
405
406def run_landed_cluster_drag(page, cdp, kind, name):
407 page.evaluate(
408 """() => {
409 const g = app.core;
410 g.spawnInterval = 1e9;
411 g.spawnTimer = 0;
412 g.blocks.length = 0;
413 g.clusters = Object.create(null);
414 g.drag = null;
415 g.state = 'playing';
416 g.nextBlockId = 1;
417 g.nextClusterId = 1;
418 const cluster = { id: g.nextClusterId++, jumpHeight: 3, vy: 0, decel: 0, phase: 'landed' };
419 g.clusters[cluster.id] = cluster;
420 const specs = [[0, -1], [1, 1], [2, 2]];
421 for (const [y, color] of specs) {
422 const b = g.createBlock(6, y, color, 'settling');
423 b.clusterId = cluster.id;
424 b.vy = 0;
425 b.settleTime = 0;
426 }
427 }"""
428 )
429 page.wait_for_timeout(50)
430 p0 = field_to_client(page, 6, 0.5)
431 p1 = field_to_client(page, 6, 2.2)
432 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=12, end=True)
433 page.wait_for_timeout(60)
434 info = page.evaluate(
435 """() => app.core.blocks.map((b) => ({
436 color: b.color, y: b.y, state: b.state, clusterId: b.clusterId
437 }))"""
438 )
439 by_y = {round(b["y"]): b for b in info}
440 check(
441 by_y.get(2) is not None and by_y[2]["color"] == -1 and by_y[2]["clusterId"] is not None,
442 f"t1107 landed: grey dragged within cluster to y=2, info={info}",
443 name,
444 )
445
446
447def run_flame_size(page, name):
448 page.evaluate(
449 """() => {
450 const g = app.core;
451 g.spawnInterval = 1e9;
452 g.spawnTimer = 0;
453 g.blocks.length = 0;
454 g.clusters = Object.create(null);
455 g.drag = null;
456 g.state = 'playing';
457 g.nextBlockId = 1;
458 g.nextClusterId = 1;
459 g.place(1, 0, 2);
460 g.place(2, 0, 2);
461 g.place(3, 0, 2);
462 g.resolveMatches();
463 }"""
464 )
465 # Let the view sync and the rockets rise a little so the flames are visible.
466 page.wait_for_timeout(200)
467 info = page.evaluate(
468 """() => {
469 const t = app.tile;
470 const flames = Object.keys(app.flames).map((id) => {
471 const f = app.flames[id];
472 return {
473 visible: !!(f.renderer && f.renderer.visible),
474 sx: f.transform.size.x,
475 sy: f.transform.size.y
476 };
477 }).filter((f) => f.visible);
478 return {
479 t,
480 expected: t * 0.85 * 3,
481 flames,
482 flying: app.core.blocks.filter((b) => b.flame).length
483 };
484 }"""
485 )
486 ok = (
487 info
488 and info["flying"] >= 3
489 and info["flames"]
490 and all(abs(f["sx"] - info["expected"]) < 0.51 and abs(f["sy"] - info["expected"]) < 0.51
491 for f in info["flames"])
492 )
493 check(ok, f"t1110 flame is 3x (w and h), info={info}", name)
494 shot(page, f"t1110-flame-{name}.png")
495
496
497def run_poisoned_pointer_regression(browser):
498 """t1106: pointermoves poisoned to fieldY 9.5, touchmoves correct to 1.5.
499 Before the fix the block teleported to y=9; after, it stops at y=1.
500 This is the regression that failed on the old pointer-only path.
501 """
502 name = "poisoned-pointer"
503 print(f"\n======== {name} ========")
504 kw = dict(
505 viewport={"width": 412, "height": 915},
506 device_scale_factor=2.625,
507 is_mobile=True,
508 has_touch=True,
509 user_agent=(
510 "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 "
511 "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
512 ),
513 )
514 context = browser.new_context(**kw)
515 page = context.new_page()
516 start_play(page, "touch")
517 reset_board(page, {"2": [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]})
518 page.wait_for_timeout(50)
519 result = page.evaluate(
520 """() => {
521 const c = app.scene.canvas;
522 const r = c.getBoundingClientRect();
523 const toClient = (fy) => ({
524 x: r.left + (2.5 / 10) * r.width,
525 y: r.top + (1 - fy / 13) * r.height
526 });
527 const p0 = toClient(0.5);
528 const pGood = toClient(1.5);
529 const pBad = toClient(9.5);
530 const fireP = (type, x, y) => {
531 const ev = new PointerEvent(type, {
532 bubbles: true, cancelable: true, composed: true,
533 pointerId: 42, pointerType: 'touch', isPrimary: true,
534 clientX: x, clientY: y, pageX: x, pageY: y,
535 buttons: type === 'pointerup' ? 0 : 1, width: 28, height: 28,
536 pressure: type === 'pointerup' ? 0 : 0.5
537 });
538 (type === 'pointerdown' ? c : window).dispatchEvent(ev);
539 };
540 const fireT = (type, x, y) => {
541 const t = new Touch({
542 identifier: 1, target: c, clientX: x, clientY: y,
543 pageX: x, pageY: y, screenX: x, screenY: y,
544 radiusX: 14, radiusY: 14, force: 0.5
545 });
546 const ev = new TouchEvent(type, {
547 bubbles: true, cancelable: true, composed: true,
548 touches: type.includes('end') || type.includes('cancel') ? [] : [t],
549 targetTouches: type.includes('end') || type.includes('cancel') ? [] : [t],
550 changedTouches: [t]
551 });
552 c.dispatchEvent(ev);
553 document.dispatchEvent(ev);
554 };
555 fireP('pointerdown', p0.x, p0.y);
556 fireT('touchstart', p0.x, p0.y);
557 const midYs = [];
558 const steps = 8;
559 for (let i = 1; i <= steps; i++) {
560 const t = i / steps;
561 fireP('pointermove', p0.x, p0.y + (pBad.y - p0.y) * t);
562 fireT('touchmove', p0.x, p0.y + (pGood.y - p0.y) * t);
563 const b = app.core.blockById(app.core.drag && app.core.drag.blockId);
564 if (b) midYs.push(Math.round(b.y * 100) / 100);
565 }
566 fireT('touchend', pGood.x, pGood.y);
567 fireP('pointerup', pGood.x, pGood.y);
568 const colors = app.core.blocks
569 .filter((b) => b.col === 2)
570 .sort((a, b) => a.y - b.y)
571 .map((b) => ({ color: b.color, y: Math.round(b.y * 100) / 100, state: b.state }));
572 const moved = colors.find((b) => b.color === 0);
573 return { moved, colors, midYs, drag: app.core.drag };
574 }"""
575 )
576 moved = result.get("moved") or {}
577 # Must end at y=1 (one tile up), never at the top (y=9).
578 ok = moved.get("y") is not None and abs(moved["y"] - 1) <= 0.15
579 check(
580 ok,
581 f"t1106 poisoned pointer + correct touch leaves color 0 at y=1, result={result}",
582 name,
583 )
584 check(
585 moved.get("y") is None or moved["y"] < 4,
586 f"t1106 must not teleport to the top, y={moved.get('y')}",
587 name,
588 )
589 context.close()
590
591
592def main():
593 global URL
594 port = free_port()
595 URL = f"http://127.0.0.1:{port}/"
596 print("serving", URL, "from", ROOT / "build")
597 httpd = subprocess.Popen(
598 ["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", str(ROOT / "build")],
599 stdout=subprocess.DEVNULL,
600 stderr=subprocess.DEVNULL,
601 )
602 try:
603 time.sleep(0.4)
604 with sync_playwright() as p:
605 browser = p.chromium.launch(
606 executable_path=CHROME,
607 args=CHROME_ARGS,
608 headless=True,
609 )
610 for device in (DESKTOP, ANDROID, ANDROID_DPR3, IOS):
611 run_device(browser, device)
612 run_poisoned_pointer_regression(browser)
613 browser.close()
614 finally:
615 httpd.terminate()
616 try:
617 httpd.wait(timeout=3)
618 except Exception:
619 httpd.kill()
620
621 print("\n======== summary ========")
622 if FAILURES:
623 print(f"{len(FAILURES)} failure(s):")
624 for f in FAILURES:
625 print(" -", f)
626 return 1
627 print("all drag tests passed")
628 return 0
629
630
631if __name__ == "__main__":
632 sys.exit(main())