Spaces:
Paused

File size: 34,363 Bytes
f8aaa7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
"""Question-driven picture, animation, and browser-side parameter laboratory."""

from __future__ import annotations

import json
import math
import re
from typing import Any


VISUAL_TOPIC_OPTIONS = (
    "Automatic detection",
    "Vertical motion / falling masses",
    "Collision / momentum",
    "Train / speed-time motion",
    "Beam / moments",
    "Friction on a plane",
    "Connected particles / pulley",
    "Vector motion",
    "Equilibrium / strings",
)


def _finite(value: Any, default: float) -> float:
    try:
        result = float(value)
    except (TypeError, ValueError):
        return float(default)
    return result if math.isfinite(result) else float(default)


def _control(
    key: str,
    label: str,
    value: Any,
    minimum: float,
    maximum: float,
    step: float,
    unit: str,
) -> dict[str, Any]:
    value = min(maximum, max(minimum, _finite(value, minimum)))
    return {
        "key": key,
        "label": label,
        "value": value,
        "min": minimum,
        "max": maximum,
        "step": step,
        "unit": unit,
    }


def _payload(
    scene: str,
    title: str,
    concept: str,
    controls: list[dict[str, Any]],
    **extra: Any,
) -> dict[str, Any]:
    return {
        "scene": scene,
        "title": title,
        "concept": concept,
        "controls": controls,
        **extra,
    }


def question_visual_payload(question: dict[str, Any] | None) -> str:
    """Translate any generated question into the universal visualizer schema."""
    if not question:
        return json.dumps(_payload("vertical", "Question concept", "Motion under gravity", []))
    kind = question.get("diagram_kind", "vertical")
    data = question.get("diagram_data", {})
    title = question.get("title", "Question concept")

    if kind in {"collision", "custom_collision"}:
        controls = [
            _control("m1", "Mass P", data.get("m1", 4), 1, 20, 0.5, "kg"),
            _control("m2", "Mass Q", data.get("m2", 7), 1, 20, 0.5, "kg"),
            _control("u1", "Velocity P", data.get("u1", 8), -20, 20, 0.5, "m/s"),
            _control("u2", "Velocity Q", data.get("u2", 3), -20, 20, 0.5, "m/s"),
            _control("distance", "Initial separation", data.get("distance", 12), 3, 30, 0.5, "m"),
            _control("restitution", "Restitution", data.get("restitution", 0), 0, 1, 0.05, ""),
        ]
        return json.dumps(_payload(
            "collision", title, "Signed momentum, impulse and rebound", controls,
            join=kind == "collision" or str(data.get("impact_model", "")).startswith("Join"),
        ), separators=(",", ":"))

    if kind in {"vertical", "custom_rocket"}:
        controls = [
            _control("mass1", "Mass", data.get("mass_kg", 2), 0.5, 500, 0.5, "kg"),
            _control("height", "Initial height", data.get("height", data.get("h", 8)), 0, 80, 1, "m"),
            _control("velocity", "Initial upward velocity", data.get("u", 14), -30, 80, 1, "m/s"),
            _control("gravity", "Downward acceleration", data.get("g", 9.8), 1, 15, 0.1, "m/s²"),
        ]
        return json.dumps(_payload(
            "vertical", title, "Vertical motion with constant gravitational acceleration", controls,
            object_count=int(data.get("object_count", 1)), rocket=kind == "custom_rocket",
        ), separators=(",", ":"))

    if kind in {"speed_time", "custom_train"}:
        controls = [
            _control("mass", "Train mass", data.get("mass_tonnes", 90), 20, 200, 5, "t"),
            _control("initial_speed", "Initial speed", data.get("u", 0), 0, 35, 0.5, "m/s"),
            _control("top_speed", "Maximum speed", data.get("top_speed", data.get("speed", 20)), 2, 60, 1, "m/s"),
            _control("accel_time", "Acceleration time", data.get("t_acc", 10), 2, 30, 1, "s"),
            _control("cruise_time", "Cruise time", data.get("t_cruise", data.get("t_const", 60)), 2, 180, 2, "s"),
            _control("brake_time", "Braking time", data.get("braking_time", data.get("t_dec", 20)), 2, 60, 1, "s"),
        ]
        return json.dumps(_payload(
            "train", title, "Speed-time graph: gradient gives acceleration and area gives distance", controls,
        ), separators=(",", ":"))

    if kind == "beam":
        controls = [
            _control("length", "Beam length", data.get("length", 6), 3, 15, 0.5, "m"),
            _control("weight", "Beam weight", data.get("weight", 90), 10, 300, 5, "N"),
            _control("support_x", "Left support position", data.get("x", 2), 0.3, 8, 0.1, "m"),
            _control("separation", "Support separation", data.get("separation", 3), 0.5, 8, 0.1, "m"),
            _control("left_tension", "Left tension", data.get("tc", 60), 0, 250, 5, "N"),
            _control("right_tension", "Right tension", data.get("td", 30), 0, 250, 5, "N"),
        ]
        return json.dumps(_payload("beam", title, "Rigid-body equilibrium: forces and moments", controls), separators=(",", ":"))

    if kind in {"friction", "custom_trolley"}:
        controls = [
            _control("mass", "Mass", data.get("mass_kg", data.get("mass", 5)), 1, 60, 0.5, "kg"),
            _control("force", "Applied force", data.get("force", 45), 0, 150, 1, "N"),
            _control("angle", "Pulling angle", data.get("angle", data.get("theta", 25)), 0, 50, 1, "°"),
            _control("mu", "Friction coefficient", data.get("mu", 0.3), 0, 0.8, 0.02, ""),
            _control("velocity", "Initial velocity", data.get("u", 0), 0, 20, 0.5, "m/s"),
        ]
        return json.dumps(_payload("friction", title, "Resolved forces, reaction, friction and Newton's second law", controls), separators=(",", ":"))

    if kind == "connected":
        controls = [
            _control("m1", "Mass on plane", data.get("m1", 6), 1, 20, 0.5, "kg"),
            _control("m2", "Hanging mass", data.get("m2", 8), 1, 20, 0.5, "kg"),
            _control("angle", "Plane angle", data.get("angle", 36.87), 5, 60, 1, "°"),
            _control("mu", "Friction coefficient", data.get("mu", 0.2), 0, 0.8, 0.02, ""),
            _control("gravity", "Gravity", 9.8, 1, 15, 0.1, "m/s²"),
        ]
        return json.dumps(_payload("connected", title, "Connected motion, tension and friction", controls), separators=(",", ":"))

    if kind == "vectors":
        controls = [
            _control("ux", "Initial east velocity", data.get("ux", 4), -15, 15, 0.5, "m/s"),
            _control("uy", "Initial north velocity", data.get("uy", 3), -15, 15, 0.5, "m/s"),
            _control("ax", "East acceleration", data.get("ax", 1), -6, 6, 0.25, "m/s²"),
            _control("ay", "North acceleration", data.get("ay", 2), -6, 6, 0.25, "m/s²"),
            _control("time", "Observation time", data.get("t", 5), 1, 12, 0.5, "s"),
        ]
        return json.dumps(_payload("vectors", title, "Two-dimensional constant-acceleration motion", controls), separators=(",", ":"))

    controls = [
        _control("weight", "Particle weight", data.get("weight", 8), 1, 30, 0.5, "N"),
        _control("angle", "String angle to vertical", data.get("beta", 45), 5, 80, 1, "°"),
        _control("force", "Perpendicular force", data.get("force", 5), 0, 30, 0.5, "N"),
        _control("tension", "String tension", data.get("tension", 5), 0, 30, 0.5, "N"),
    ]
    return json.dumps(_payload("equilibrium", title, "Vector equilibrium of a particle", controls), separators=(",", ":"))


def _numbers_with_unit(text: str, unit_pattern: str) -> list[float]:
    pattern = rf"([-+]?\d+(?:\.\d+)?)\s*(?:{unit_pattern})"
    return [_finite(match, 0) for match in re.findall(pattern, text, flags=re.I)]


def _near_value(text: str, words: str, default: float) -> float:
    before = re.search(rf"(?:{words})[^\d+\-]{{0,28}}([-+]?\d+(?:\.\d+)?)", text, flags=re.I)
    if before:
        return _finite(before.group(1), default)
    after = re.search(rf"([-+]?\d+(?:\.\d+)?)[^\n]{{0,24}}(?:{words})", text, flags=re.I)
    return _finite(after.group(1), default) if after else default


def infer_visual_payload(text: str, topic_hint: str = "Automatic detection", title: str = "Imported question") -> dict[str, Any]:
    """Infer a safe editable concept model from an imported question."""
    clean = " ".join(str(text or "").replace("−", "-").split())
    low = clean.lower()
    hint = topic_hint.lower()
    if "collision" in hint or re.search(r"\b(collid|impact|rebound|restitution|momentum)\w*", low):
        scene = "collision"
    elif "connected" in hint or re.search(r"\b(pulley|inextensible|string connects|connected particle)\w*", low):
        scene = "connected"
    elif "train" in hint or "speed-time" in hint or re.search(r"\b(train|speed[ -]?time|velocity[ -]?time)\b", low):
        scene = "train"
    elif "beam" in hint or re.search(r"\b(beam|rod|moment about|hinge|support reaction)\b", low):
        scene = "beam"
    elif "friction" in hint or re.search(r"\b(rough|friction|coefficient of friction)\b", low):
        scene = "friction"
    elif "vector" in hint or re.search(r"\b(bearing|unit vector|\bi\b.*\bj\b|vector)\b", low):
        scene = "vectors"
    elif "equilibrium" in hint or re.search(r"\b(equilibrium|held by a string|tension)\b", low):
        scene = "equilibrium"
    else:
        scene = "vertical"

    masses = _numbers_with_unit(clean, r"kg|kilograms?")
    speeds = _numbers_with_unit(clean, r"m\s*(?:s|/s)(?:\^?-?1)?|m/s")
    accelerations = _numbers_with_unit(clean, r"m\s*(?:s|/s)(?:\^?-?2)?|m/s(?:²|\^2)")
    distances = _numbers_with_unit(clean, r"m(?:etres?)?")
    angles = _numbers_with_unit(clean, r"°|degrees?")

    if scene == "collision":
        return _payload(
            scene, title, "Signed momentum, impulse and rebound",
            [
                _control("m1", "Mass P", masses[0] if masses else 4, 1, 30, 0.5, "kg"),
                _control("m2", "Mass Q", masses[1] if len(masses) > 1 else 7, 1, 30, 0.5, "kg"),
                _control("u1", "Velocity P", speeds[0] if speeds else 8, -25, 25, 0.5, "m/s"),
                _control("u2", "Velocity Q", speeds[1] if len(speeds) > 1 else 2, -25, 25, 0.5, "m/s"),
                _control("distance", "Initial separation", _near_value(clean, "apart|separation|distance", 12), 2, 40, 0.5, "m"),
                _control("restitution", "Restitution", _near_value(clean, "restitution", 0.6), 0, 1, 0.05, ""),
            ],
            join="join together" in low or "coalesce" in low,
        )
    if scene == "connected":
        return _payload(
            scene, title, "Connected motion, tension and friction",
            [
                _control("m1", "Mass on plane", masses[0] if masses else 6, 1, 30, 0.5, "kg"),
                _control("m2", "Hanging mass", masses[1] if len(masses) > 1 else 8, 1, 30, 0.5, "kg"),
                _control("angle", "Plane angle", angles[0] if angles else 30, 5, 60, 1, "°"),
                _control("mu", "Friction coefficient", _near_value(clean, "coefficient(?: of friction)?|mu", 0.2), 0, 0.8, 0.02, ""),
                _control("gravity", "Gravity", _near_value(clean, "gravity|g", 9.8), 1, 15, 0.1, "m/s²"),
            ],
        )
    if scene == "train":
        return _payload(
            scene, title, "Speed-time graph: gradient gives acceleration and area gives distance",
            [
                _control("mass", "Train mass", _near_value(clean, "mass", 90), 20, 250, 5, "t"),
                _control("initial_speed", "Initial speed", speeds[0] if speeds else 0, 0, 40, 0.5, "m/s"),
                _control("top_speed", "Maximum speed", max(speeds) if speeds else 20, 2, 70, 1, "m/s"),
                _control("accel_time", "Acceleration time", _near_value(clean, "accelerates?.{0,20}for|acceleration time", 10), 2, 40, 1, "s"),
                _control("cruise_time", "Cruise time", _near_value(clean, "constant speed.{0,20}for|cruise", 30), 2, 200, 2, "s"),
                _control("brake_time", "Braking time", _near_value(clean, "deceleration time|braking time", 20), 2, 80, 1, "s"),
            ],
        )
    if scene == "beam":
        forces = _numbers_with_unit(clean, r"N|newtons?")
        return _payload(
            scene, title, "Rigid-body equilibrium: forces and moments",
            [
                _control("length", "Beam length", distances[0] if distances else 6, 2, 20, 0.5, "m"),
                _control("weight", "Beam weight", forces[0] if forces else 90, 5, 400, 5, "N"),
                _control("support_x", "Left support position", distances[1] if len(distances) > 1 else 2, 0.2, 10, 0.1, "m"),
                _control("separation", "Support separation", distances[2] if len(distances) > 2 else 3, 0.5, 10, 0.1, "m"),
                _control("left_tension", "Left support force", forces[1] if len(forces) > 1 else 60, 0, 300, 5, "N"),
                _control("right_tension", "Right support force", forces[2] if len(forces) > 2 else 30, 0, 300, 5, "N"),
            ],
        )
    if scene == "friction":
        forces = _numbers_with_unit(clean, r"N|newtons?")
        return _payload(
            scene, title, "Resolved forces, reaction, friction and Newton's second law",
            [
                _control("mass", "Mass", masses[0] if masses else 5, 1, 80, 0.5, "kg"),
                _control("force", "Applied force", forces[0] if forces else 45, 0, 200, 1, "N"),
                _control("angle", "Pulling angle", angles[0] if angles else 25, 0, 60, 1, "°"),
                _control("mu", "Friction coefficient", _near_value(clean, "coefficient(?: of friction)?|mu", 0.3), 0, 0.8, 0.02, ""),
                _control("velocity", "Initial velocity", speeds[0] if speeds else 0, 0, 25, 0.5, "m/s"),
            ],
        )
    if scene == "vectors":
        numeric = [float(v) for v in re.findall(r"[-+]?\d+(?:\.\d+)?", clean)[:5]]
        numeric += [0] * (5 - len(numeric))
        return _payload(
            scene, title, "Two-dimensional constant-acceleration motion",
            [
                _control("ux", "Initial east velocity", numeric[0] or 4, -20, 20, 0.5, "m/s"),
                _control("uy", "Initial north velocity", numeric[1] or 3, -20, 20, 0.5, "m/s"),
                _control("ax", "East acceleration", numeric[2] or 1, -8, 8, 0.25, "m/s²"),
                _control("ay", "North acceleration", numeric[3] or 2, -8, 8, 0.25, "m/s²"),
                _control("time", "Observation time", numeric[4] or 5, 1, 15, 0.5, "s"),
            ],
        )
    if scene == "equilibrium":
        forces = _numbers_with_unit(clean, r"N|newtons?")
        return _payload(
            scene, title, "Vector equilibrium of a particle",
            [
                _control("weight", "Particle weight", forces[0] if forces else 8, 1, 40, 0.5, "N"),
                _control("angle", "String angle to vertical", angles[0] if angles else 45, 5, 80, 1, "°"),
                _control("force", "Perpendicular force", forces[1] if len(forces) > 1 else 5, 0, 40, 0.5, "N"),
                _control("tension", "String tension", forces[2] if len(forces) > 2 else 5, 0, 40, 0.5, "N"),
            ],
        )

    object_count = 2 if re.search(r"\b(two|2)\s+(?:masses|particles|objects|stones|balls)\b", low) else 1
    return _payload(
        "vertical", title, "Vertical motion with constant gravitational acceleration",
        [
            _control("mass1", "Mass 1", masses[0] if masses else 2, 0.5, 500, 0.5, "kg"),
            _control("mass2", "Mass 2", masses[1] if len(masses) > 1 else masses[0] if masses else 2, 0.5, 500, 0.5, "kg"),
            _control("height", "Initial height", _near_value(clean, "height|above (?:the )?ground", distances[0] if distances else 15), 0, 100, 1, "m"),
            _control("velocity", "Initial upward velocity", speeds[0] if speeds else 0, -40, 80, 1, "m/s"),
            _control("gravity", "Downward acceleration", accelerations[0] if accelerations else _near_value(clean, "gravity|g", 9.8), 1, 15, 0.1, "m/s²"),
        ],
        object_count=object_count,
    )


QUESTION_VISUALIZER_HTML = r"""
<section class="question-visualizer" aria-label="Interactive visual concept of the current mechanics question">
  <div class="qv-head">
    <div><b data-qv-title>Question concept</b><span data-qv-concept>Physical model</span></div>
    <span class="qv-status" data-qv-status>READY</span>
  </div>
  <div class="qv-stage">
    <canvas data-qv-canvas role="img" aria-label="Animated graphical representation of the current mechanics question"></canvas>
    <span class="qv-event" data-qv-event aria-hidden="true">IMPACT</span>
  </div>
  <div class="qv-controls" data-qv-controls></div>
  <div class="qv-actions">
    <button type="button" data-qv-start>▶ Animate concept</button>
    <button type="button" data-qv-reset>↺ Reset</button>
    <label><input type="checkbox" data-qv-sound checked> Event sound</label>
    <label><input type="checkbox" data-qv-music> Light music</label>
  </div>
  <div class="qv-readout" data-qv-readout aria-live="polite"></div>
</section>
"""


QUESTION_VISUALIZER_CSS = r"""
.question-visualizer{--qv-ink:#172554;--qv-muted:#64748b;--qv-a:#06b6d4;--qv-b:#ec4899;--qv-c:#7c3aed;--qv-warn:#f59e0b;color:var(--qv-ink);width:100%}.qv-head,.qv-actions{align-items:center;display:flex;flex-wrap:wrap;gap:10px;justify-content:space-between}.qv-head>div{display:flex;flex-direction:column}.qv-head span:not(.qv-status){color:var(--qv-muted);font-size:12px}.qv-status{background:linear-gradient(100deg,#6d28d9,#ec4899);border-radius:999px;color:white;font-size:11px;font-weight:800;padding:5px 10px}.qv-stage{background:linear-gradient(180deg,#e0f2fe,#f5f3ff 64%,#e2e8f0 65%,#cbd5e1);border:1px solid rgba(99,102,241,.2);border-radius:20px;margin-top:10px;overflow:hidden;position:relative}.qv-stage canvas{aspect-ratio:12/4.7;cursor:pointer;display:block;min-height:285px;width:100%}.qv-event{color:#b91c1c;font-size:clamp(32px,8vw,76px);font-weight:900;left:50%;opacity:0;pointer-events:none;position:absolute;top:32%;transform:translate(-50%,-50%) scale(.3)}.qv-event.is-active{animation:qv-pop .65s ease-out}@keyframes qv-pop{25%{opacity:1;transform:translate(-50%,-50%) scale(1.1)}100%{opacity:0;transform:translate(-50%,-70%) scale(1.45)}}.qv-controls{display:grid;gap:10px;grid-template-columns:repeat(3,minmax(0,1fr));margin-top:12px}.qv-control{background:rgba(255,255,255,.78);border:1px solid rgba(99,102,241,.15);border-radius:12px;padding:9px}.qv-control label{display:flex;font-size:12px;font-weight:750;justify-content:space-between}.qv-control output{color:#6d28d9}.qv-control input{accent-color:#7c3aed;width:100%}.qv-actions{justify-content:flex-start;margin-top:11px}.qv-actions button{border:1px solid #cbd5e1;border-radius:11px;cursor:pointer;font-weight:800;padding:9px 14px}.qv-actions button:first-child{background:linear-gradient(100deg,#0891b2,#2563eb);border:0;color:white}.qv-actions label{align-items:center;display:flex;font-size:12px;gap:5px;margin-left:auto}.qv-readout{background:rgba(255,255,255,.8);border-left:4px solid var(--qv-c);border-radius:10px;color:var(--qv-ink);font-size:13px;margin-top:10px;padding:9px 12px}@media(max-width:760px){.qv-controls{grid-template-columns:repeat(2,minmax(0,1fr))}.qv-stage canvas{min-height:235px}.qv-actions label{margin-left:0}}@media(max-width:460px){.qv-controls{grid-template-columns:1fr}}
"""


QUESTION_VISUALIZER_JS = r"""
let root=null,canvas=null,ctx=null,controlHost=null,statusNode=null,readout=null,eventNode=null;
let startButton=null,resetButton=null,soundToggle=null,musicToggle=null,resizeObserver=null;
let payload={},values={},phase="ready",frame=0,startStamp=0,audio=null,musicNodes=[],eventPlayed=false;
const reduced=window.matchMedia("(prefers-reduced-motion: reduce)").matches;
function readPayload(){try{payload=JSON.parse(props.value||"{}")}catch(error){payload={scene:"vertical",controls:[]}}if(!payload.controls)payload.controls=[]}
function css(name,fallback){const value=root?getComputedStyle(root).getPropertyValue(name).trim():"";return value||fallback}
function rebuildControls(){controlHost.replaceChildren();values={};payload.controls.forEach(item=>{values[item.key]=Number(item.value);const box=document.createElement("div");box.className="qv-control";const label=document.createElement("label");const name=document.createElement("span");const output=document.createElement("output");const input=document.createElement("input");name.textContent=item.label;output.textContent=format(item.value,item.unit);input.type="range";input.min=item.min;input.max=item.max;input.step=item.step;input.value=item.value;input.setAttribute("aria-label",item.label);input.addEventListener("input",()=>{values[item.key]=Number(input.value);output.textContent=format(input.value,item.unit);reset(false)});label.append(name,output);box.append(label,input);controlHost.append(box)})}
function format(value,unit){return `${Number(value).toLocaleString(undefined,{maximumFractionDigits:2})}${unit?" "+unit:""}`}
function resize(){if(!canvas||!ctx)return;const rect=canvas.getBoundingClientRect(),dpr=Math.min(devicePixelRatio||1,2);canvas.width=Math.max(1,Math.round(rect.width*dpr));canvas.height=Math.max(1,Math.round(rect.height*dpr));ctx.setTransform(dpr,0,0,dpr,0,0);draw(0)}
function base(){const w=canvas.clientWidth,h=canvas.clientHeight;ctx.clearRect(0,0,w,h);ctx.strokeStyle="rgba(51,65,85,.13)";ctx.lineWidth=1;for(let x=0;x<w;x+=44){ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,h);ctx.stroke()}}
function ground(y){const w=canvas.clientWidth;ctx.strokeStyle=css("--qv-ink","#172554");ctx.lineWidth=7;ctx.beginPath();ctx.moveTo(18,y);ctx.lineTo(w-18,y);ctx.stroke()}
function arrow(x,y,dx,dy,color,label){const length=Math.hypot(dx,dy)||1,ux=dx/length,uy=dy/length;ctx.strokeStyle=color;ctx.fillStyle=color;ctx.lineWidth=4;ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x+dx,y+dy);ctx.stroke();ctx.beginPath();ctx.moveTo(x+dx,y+dy);ctx.lineTo(x+dx-12*ux+7*uy,y+dy-12*uy-7*ux);ctx.lineTo(x+dx-12*ux-7*uy,y+dy-12*uy+7*ux);ctx.closePath();ctx.fill();ctx.font="700 12px Inter,Arial";ctx.fillText(label,x+dx+7,y+dy-5)}
function sphere(x,y,r,color,label){ctx.fillStyle=color;ctx.strokeStyle=css("--qv-ink","#172554");ctx.lineWidth=3;ctx.beginPath();ctx.arc(x,y,r,0,Math.PI*2);ctx.fill();ctx.stroke();ctx.fillStyle="white";ctx.font="800 13px Inter,Arial";ctx.textAlign="center";ctx.fillText(label,x,y+4)}
function flash(text){eventNode.textContent=text;eventNode.classList.remove("is-active");void eventNode.offsetWidth;eventNode.classList.add("is-active")}
function tone(frequency,duration,volume){if(!soundToggle.checked||!audio)return;const osc=audio.createOscillator(),gain=audio.createGain(),now=audio.currentTime;osc.frequency.value=frequency;gain.gain.setValueAtTime(volume,now);gain.gain.exponentialRampToValueAtTime(.0001,now+duration);osc.connect(gain).connect(audio.destination);osc.start(now);osc.stop(now+duration)}
function unlock(){if(!audio){const AudioCtor=window.AudioContext||window.webkitAudioContext;if(AudioCtor)audio=new AudioCtor()}if(audio&&audio.state==="suspended")audio.resume()}
function stopMusic(){musicNodes.forEach(node=>{try{node.stop()}catch(error){}try{node.disconnect()}catch(error){}});musicNodes=[]}
function startMusic(){stopMusic();if(!musicToggle.checked||!audio)return;[174.61,261.63].forEach((frequency,index)=>{const osc=audio.createOscillator(),gain=audio.createGain();osc.type=index?"sine":"triangle";osc.frequency.value=frequency;gain.gain.value=index?.006:.01;osc.connect(gain).connect(audio.destination);osc.start();musicNodes.push(osc,gain)})}
function drawCollision(p){const w=canvas.clientWidth,h=canvas.clientHeight,y=h*.75,m1=values.m1||4,m2=values.m2||7,r1=24+Math.cbrt(m1)*8,r2=24+Math.cbrt(m2)*8,hit=.57;ground(y+3);let x1,x2;if(p<=hit){const q=p/hit;x1=w*.14+(w*.5-(r1+r2)/2-w*.14)*q;x2=w*.86+(w*.5+(r1+r2)/2-w*.86)*q}else{const q=(p-hit)/(1-hit),join=Boolean(payload.join),e=join?0:(values.restitution||0),u1=values.u1||0,u2=values.u2||0,v1=join?(m1*u1+m2*u2)/(m1+m2):(m1*u1+m2*u2-m2*e*(u1-u2))/(m1+m2),v2=join?v1:v1+e*(u1-u2);x1=w*.5-(r1+r2)/2+v1*q*w*.018;x2=w*.5+(r1+r2)/2+v2*q*w*.018}sphere(x1,y-r1,r1,css("--qv-a","#06b6d4"),"P");sphere(x2,y-r2,r2,css("--qv-b","#ec4899"),"Q");if(p>hit&&!eventPlayed){eventPlayed=true;flash("IMPACT");tone(95,.32,.22)}const momentum=m1*(values.u1||0)+m2*(values.u2||0);readout.textContent=`Total signed momentum before impact: ${momentum.toFixed(2)} kg m/s · mass changes visual size.`}
function verticalTime(){const h=Math.max(0,values.height||0),u=values.velocity||0,g=Math.max(.1,values.gravity||9.8);return (u+Math.sqrt(u*u+2*g*h))/g}
function drawVertical(p){const w=canvas.clientWidth,h=canvas.clientHeight,gy=h*.82,total=verticalTime(),t=p*total,g=Math.max(.1,values.gravity||9.8),physical=Math.max(0,(values.height||0)+(values.velocity||0)*t-.5*g*t*t),peak=Math.max(1,(values.height||0)+Math.max(0,values.velocity||0)**2/(2*g)),ratio=physical/peak,count=Math.max(1,payload.object_count||1);ground(gy);for(let index=0;index<count;index+=1){const mass=values[index?"mass2":"mass1"]||values.mass1||2,r=20+Math.min(22,Math.cbrt(mass)*5),x=w*(count===1?.5:index?.62:.38),offset=index?Math.min(h*.08,p*.04*h):0,y=gy-ratio*h*.62+offset;sphere(x,y-r,r,index?css("--qv-b","#ec4899"):css("--qv-a","#06b6d4"),index?"M₂":"M₁");arrow(x,y-r*2-8,0,45,css("--qv-warn","#f59e0b"),"g")}if(p>.985&&!eventPlayed){eventPlayed=true;flash("GROUND");tone(72,.3,.18)}readout.textContent=`Time to ground: ${total.toFixed(2)} s · maximum height: ${peak.toFixed(2)} m · all masses share acceleration g when air resistance is ignored.`}
function drawTrain(p){const w=canvas.clientWidth,h=canvas.clientHeight,y=h*.78,ta=values.accel_time||10,tc=values.cruise_time||20,tb=values.brake_time||20,total=ta+tc+tb,t=p*total;let speed;if(t<ta)speed=(values.initial_speed||0)+((values.top_speed||20)-(values.initial_speed||0))*t/ta;else if(t<ta+tc)speed=values.top_speed||20;else speed=(values.top_speed||20)*Math.max(0,1-(t-ta-tc)/tb);ground(y);const x=w*(.08+.67*p),cars=Math.max(1,Math.min(4,Math.round((values.mass||90)/50))),cw=Math.min(64,w*.085);ctx.fillStyle=css("--qv-c","#7c3aed");for(let i=cars;i>0;i--)ctx.fillRect(x-i*(cw+7),y-55,cw,39);ctx.fillStyle=css("--qv-a","#06b6d4");ctx.fillRect(x,y-65,cw+15,49);ctx.fillStyle=css("--qv-ink","#172554");for(let i=0;i<=cars;i++){ctx.beginPath();ctx.arc(x+cw*.65-i*(cw+7),y-10,9,0,Math.PI*2);ctx.fill()}ctx.fillStyle=css("--qv-warn","#f59e0b");ctx.beginPath();ctx.arc(x+cw+17,y-43,5+speed/Math.max(1,values.top_speed||20)*7,0,Math.PI*2);ctx.fill();const avg=(values.initial_speed+values.top_speed)/2*ta+(values.top_speed||0)*tc+(values.top_speed||0)*tb/2;readout.textContent=`Current speed: ${speed.toFixed(2)} m/s · modelled distance: ${avg.toFixed(1)} m · phase: ${t<ta?"acceleration":t<ta+tc?"constant speed":"braking"}.`}
function drawBeam(p){const w=canvas.clientWidth,h=canvas.clientHeight,cx=w*.5,cy=h*.55,L=w*.72,weight=values.weight||90,left=values.left_tension||0,right=values.right_tension||0,net=left+right-weight,angle=Math.max(-.1,Math.min(.1,-net/Math.max(20,weight)*.08))*Math.sin(p*Math.PI);ctx.save();ctx.translate(cx,cy);ctx.rotate(angle);ctx.strokeStyle=css("--qv-ink","#172554");ctx.lineWidth=18;ctx.beginPath();ctx.moveTo(-L/2,0);ctx.lineTo(L/2,0);ctx.stroke();ctx.restore();const sx=-L/2+L*Math.min(.9,Math.max(.05,(values.support_x||2)/Math.max(1,values.length||6))),dx=sx+L*Math.min(.8,(values.separation||3)/Math.max(1,values.length||6));arrow(cx+sx,cy+55,0,-85,css("--qv-a","#06b6d4"),"T₁");arrow(cx+dx,cy+55,0,-65,css("--qv-b","#ec4899"),"T₂");arrow(cx,cy-15,0,95,css("--qv-warn","#f59e0b"),"W");const moment=(left*(values.support_x||0)+right*((values.support_x||0)+(values.separation||0))-weight*(values.length||0)/2);readout.textContent=`Vertical resultant: ${net.toFixed(1)} N · moment about A: ${moment.toFixed(1)} N m. Zero values mean equilibrium.`}
function drawFriction(p){const w=canvas.clientWidth,h=canvas.clientHeight,y=h*.78,m=values.mass||5,force=values.force||0,angle=(values.angle||0)*Math.PI/180,mu=values.mu||0,reaction=Math.max(0,m*9.8-force*Math.sin(angle)),friction=mu*reaction,a=(force*Math.cos(angle)-friction)/m,distance=Math.max(0,(values.velocity||0)*p*4+.5*a*(p*4)**2),x=w*.12+Math.min(w*.58,distance*w*.025);ground(y);const bw=80+Math.sqrt(m)*7;ctx.fillStyle=css("--qv-a","#06b6d4");ctx.fillRect(x,y-62,bw,48);ctx.fillStyle=css("--qv-ink","#172554");ctx.beginPath();ctx.arc(x+18,y-10,10,0,Math.PI*2);ctx.fill();ctx.beginPath();ctx.arc(x+bw-18,y-10,10,0,Math.PI*2);ctx.fill();arrow(x+bw,y-42,80*Math.cos(angle),-80*Math.sin(angle),css("--qv-b","#ec4899"),"P");arrow(x+10,y-30,-55,0,css("--qv-warn","#f59e0b"),"F");readout.textContent=`Reaction: ${reaction.toFixed(2)} N · limiting/kinetic friction: ${friction.toFixed(2)} N · horizontal acceleration: ${a.toFixed(3)} m/s².`}
function drawConnected(p){const w=canvas.clientWidth,h=canvas.clientHeight,angle=(values.angle||30)*Math.PI/180,origin={x:w*.12,y:h*.75},end={x:w*.7,y:h*.75-w*.58*Math.tan(angle)},pulley={x:end.x+18,y:end.y-10},m1=values.m1||6,m2=values.m2||8,g=values.gravity||9.8,mu=values.mu||0,a=g*(m2-m1*(Math.sin(angle)+mu*Math.cos(angle)))/(m1+m2),move=Math.max(-.14,Math.min(.14,a/8))*p*w;ctx.strokeStyle=css("--qv-ink","#172554");ctx.lineWidth=8;ctx.beginPath();ctx.moveTo(origin.x,origin.y);ctx.lineTo(end.x,end.y);ctx.stroke();ctx.beginPath();ctx.arc(pulley.x,pulley.y,17,0,Math.PI*2);ctx.stroke();const bx=origin.x+(end.x-origin.x)*.53+move*Math.cos(angle),by=origin.y+(end.y-origin.y)*.53-move*Math.sin(angle);ctx.fillStyle=css("--qv-a","#06b6d4");ctx.fillRect(bx-24,by-24,48,40);const hy=pulley.y+45+move;ctx.strokeStyle=css("--qv-ink","#172554");ctx.lineWidth=3;ctx.beginPath();ctx.moveTo(bx,by-25);ctx.lineTo(pulley.x,pulley.y);ctx.lineTo(pulley.x,hy);ctx.stroke();sphere(pulley.x,hy+22,22,css("--qv-b","#ec4899"),"B");readout.textContent=`Common acceleration: ${a.toFixed(3)} m/s² (${a>=0?"hanging mass downward":"block down the plane"}) · string keeps equal displacement magnitudes.`}
function drawVectors(p){const w=canvas.clientWidth,h=canvas.clientHeight,T=values.time||5,points=[];for(let i=0;i<=40;i++){const t=T*i/40,x=(values.ux||0)*t+.5*(values.ax||0)*t*t,y=(values.uy||0)*t+.5*(values.ay||0)*t*t;points.push({x,y})}const xs=points.map(q=>q.x),ys=points.map(q=>q.y),minX=Math.min(...xs),maxX=Math.max(...xs),minY=Math.min(...ys),maxY=Math.max(...ys),sx=(w*.72)/Math.max(1,maxX-minX),sy=(h*.58)/Math.max(1,maxY-minY),map=q=>({x:w*.14+(q.x-minX)*sx,y:h*.76-(q.y-minY)*sy});ctx.strokeStyle=css("--qv-c","#7c3aed");ctx.lineWidth=4;ctx.beginPath();points.forEach((q,i)=>{const m=map(q);if(i)ctx.lineTo(m.x,m.y);else ctx.moveTo(m.x,m.y)});ctx.stroke();const index=Math.min(40,Math.round(p*40)),pos=map(points[index]),t=T*index/40,vx=(values.ux||0)+(values.ax||0)*t,vy=(values.uy||0)+(values.ay||0)*t;sphere(pos.x,pos.y,16,css("--qv-a","#06b6d4"),"P");arrow(pos.x,pos.y,vx*5,-vy*5,css("--qv-b","#ec4899"),"v");readout.textContent=`At t=${t.toFixed(2)} s: velocity = (${vx.toFixed(2)} i + ${vy.toFixed(2)} j) m/s · speed ${Math.hypot(vx,vy).toFixed(2)} m/s.`}
function drawEquilibrium(p){const w=canvas.clientWidth,h=canvas.clientHeight,angle=(values.angle||45)*Math.PI/180,O={x:w*.45,y:h*.15},length=h*.42,idealForce=(values.weight||8)*Math.sin(angle),imbalance=(values.force||0)-idealForce,sway=Math.max(-.15,Math.min(.15,imbalance/20))*Math.sin(p*Math.PI*2)*(1-p),x=O.x+length*Math.sin(angle+sway),y=O.y+length*Math.cos(angle+sway);ctx.strokeStyle=css("--qv-ink","#172554");ctx.lineWidth=5;ctx.beginPath();ctx.moveTo(O.x,O.y);ctx.lineTo(x,y);ctx.stroke();sphere(x,y,22,css("--qv-a","#06b6d4"),"P");arrow(x,y,0,85,css("--qv-warn","#f59e0b"),"W");arrow(x,y,(O.x-x)*.45,(O.y-y)*.45,css("--qv-c","#7c3aed"),"T");arrow(x,y,65*Math.cos(angle),-65*Math.sin(angle),css("--qv-b","#ec4899"),"F");readout.textContent=`Force needed perpendicular to the string: ${idealForce.toFixed(2)} N · selected force imbalance: ${imbalance.toFixed(2)} N.`}
function draw(progress){if(!ctx)return;base();const scene=payload.scene||"vertical";if(scene==="collision")drawCollision(progress);else if(scene==="vertical")drawVertical(progress);else if(scene==="train")drawTrain(progress);else if(scene==="beam")drawBeam(progress);else if(scene==="friction")drawFriction(progress);else if(scene==="connected")drawConnected(progress);else if(scene==="vectors")drawVectors(progress);else drawEquilibrium(progress)}
function animate(now){const duration=reduced?1:5000,p=Math.min(1,(now-startStamp)/duration);draw(p);statusNode.textContent=p<1?"ANIMATING":"COMPLETE";if(p<1)frame=requestAnimationFrame(animate);else{phase="done";stopMusic()}}
function start(){if(phase==="running")return;unlock();reset(true);phase="running";eventPlayed=false;startMusic();startStamp=performance.now();statusNode.textContent="STARTED";if(payload.scene==="train"){flash("TOOT");tone(220,.6,.08)}frame=requestAnimationFrame(animate)}
function reset(quiet=true){cancelAnimationFrame(frame);stopMusic();phase="ready";eventPlayed=false;if(eventNode)eventNode.classList.remove("is-active");if(statusNode)statusNode.textContent="READY";draw(0);if(!quiet)readout.textContent+=" · Reset with the current exploration values."}
function bind(){root=element.querySelector(".question-visualizer");if(!root)return;canvas=root.querySelector("[data-qv-canvas]");ctx=canvas.getContext("2d");controlHost=root.querySelector("[data-qv-controls]");statusNode=root.querySelector("[data-qv-status]");readout=root.querySelector("[data-qv-readout]");eventNode=root.querySelector("[data-qv-event]");startButton=root.querySelector("[data-qv-start]");resetButton=root.querySelector("[data-qv-reset]");soundToggle=root.querySelector("[data-qv-sound]");musicToggle=root.querySelector("[data-qv-music]");readPayload();root.querySelector("[data-qv-title]").textContent=payload.title||"Question concept";root.querySelector("[data-qv-concept]").textContent=payload.concept||"Physical model";rebuildControls();if(!root.dataset.bound){startButton.addEventListener("click",start);resetButton.addEventListener("click",()=>reset(false));canvas.addEventListener("click",start);root.dataset.bound="true"}if(resizeObserver)resizeObserver.disconnect();resizeObserver=new ResizeObserver(resize);resizeObserver.observe(root);reset(true);requestAnimationFrame(resize)}
watch("value",bind);bind();
"""