-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimulation.html
More file actions
573 lines (520 loc) · 22.4 KB
/
Copy pathsimulation.html
File metadata and controls
573 lines (520 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Physics Simulation Tuner</title>
<style>
* { box-sizing: border-box; }
body {
font-family: system-ui, sans-serif;
margin: 0;
padding: 0;
background: #1a1a1a;
color: #fff;
height: 100vh;
display: flex;
flex-direction: column;
}
#tray {
width: 100%;
flex: 1;
background: #000;
min-height: 0;
}
#controls {
padding: 0.75rem 1rem;
background: #222;
flex-shrink: 0;
}
.control-row {
display: flex;
align-items: center;
margin-bottom: 0.4rem;
gap: 0.5rem;
}
.control-row label {
width: 110px;
flex-shrink: 0;
font-size: 0.8rem;
}
.help-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
border-radius: 50%;
background: #555;
color: #ccc;
font-size: 10px;
cursor: help;
flex-shrink: 0;
position: relative;
}
.help-icon:hover { background: #777; }
.help-icon:hover::after {
content: attr(data-tip);
position: absolute;
bottom: 100%;
left: 0;
background: #000;
color: #fff;
padding: 0.4rem 0.6rem;
border-radius: 4px;
font-size: 0.75rem;
white-space: nowrap;
max-width: min(400px, 90vw);
z-index: 100;
margin-bottom: 4px;
box-shadow: 0 2px 8px rgba(0,0,0,0.5);
}
.control-row input[type="range"] {
flex: 1;
min-width: 80px;
}
.control-row .value {
width: 55px;
text-align: right;
font-family: monospace;
font-size: 0.8rem;
padding: 0.15rem 0.25rem;
border: 1px solid #444;
border-radius: 3px;
background: #333;
color: #fff;
}
h3 {
margin: 0.8rem 0 0.4rem;
padding-bottom: 0.2rem;
border-bottom: 1px solid #444;
font-size: 0.85rem;
color: #aaa;
}
h3:first-child { margin-top: 0; }
.actions {
display: flex;
gap: 0.5rem;
margin-bottom: 0.8rem;
flex-wrap: wrap;
align-items: center;
}
button, select {
padding: 0.4rem 0.8rem;
border: none;
border-radius: 4px;
font: inherit;
font-size: 0.9rem;
cursor: pointer;
background: #444;
color: #fff;
}
button:hover { background: #555; }
button:disabled { opacity: 0.5; cursor: not-allowed; }
button.primary { background: #2563eb; }
button.primary:hover { background: #3b82f6; }
select { background: #333; }
.sweep-controls {
display: flex;
gap: 0.5rem;
align-items: center;
flex-wrap: wrap;
padding: 0.5rem;
background: #333;
border-radius: 4px;
margin-bottom: 0.8rem;
font-size: 0.85rem;
}
.sweep-controls input[type="text"] {
width: 50px;
padding: 0.2rem 0.3rem;
border: 1px solid #555;
border-radius: 3px;
background: #222;
color: #fff;
font-family: monospace;
font-size: 0.85rem;
}
.columns {
display: flex;
gap: 2rem;
}
.column { flex: 1; }
@media (max-width: 700px) {
.columns { flex-direction: column; gap: 0; }
}
</style>
</head>
<body>
<div id="tray"></div>
<div id="controls">
<div class="actions">
<select id="die-select">
<option value="4">d4</option>
<option value="6" selected>d6</option>
<option value="8">d8</option>
<option value="10">d10</option>
<option value="12">d12</option>
<option value="20">d20</option>
<option value="all">all</option>
</select>
<select id="dice-count">
<option value="1">×1</option>
<option value="4">×4</option>
<option value="9">×9</option>
</select>
<button id="roll-btn" class="primary">roll</button>
<button id="stop-btn" style="background:#dc2626;" disabled>stop</button>
<button id="reset-btn">Reset Defaults</button>
<label style="font-size:0.85rem">
<input type="checkbox" id="slowmo"> Slowmo
</label>
</div>
<div class="sweep-controls">
<span>Sweep:</span>
<select id="sweep-param"><option value="">— parameter —</option></select>
<span>from</span>
<input type="text" id="sweep-min" value="">
<span>to</span>
<input type="text" id="sweep-max" value="">
<span>increment</span>
<input type="text" id="sweep-increment" value="">
<button id="sweep-btn">Run</button>
</div>
<div class="columns">
<div class="column">
<h3>Setup</h3>
<div class="control-row">
<label>aspect</label>
<select id="aspect-mode">
<option value="auto" selected>Auto</option>
<option value="landscape">Landscape</option>
<option value="portrait">Portrait</option>
<option value="square">Square</option>
</select>
</div>
<div id="setup-settings"></div>
<h3>Throw</h3>
<div class="control-row">
<label>type</label>
<select id="throw-type">
<option value="full" selected>Full</option>
<option value="gentle">Gentle</option>
</select>
</div>
<div id="throw-settings"></div>
<h3>Air Resistance</h3>
<div id="air-resistance-settings"></div>
</div>
<div class="column">
<h3>Tray Interactions</h3>
<div id="tray-settings"></div>
<h3>Dice Collisions</h3>
<div id="dice-collision-settings"></div>
</div>
</div>
</div>
<script src="dist/dice-roller.js"></script>
<script>
const SETTINGS = {
gravity: { min: -80, default: -50, max: -10, group: 'setup', tray: 'gravity', tip: 'Downward acceleration. Higher magnitude = faster settling.' },
solverIterations: { min: 3, default: 10, max: 50, step: 1, group: 'setup', tray: 'solverIterations', tip: 'Collision resolution passes per frame. More = accurate but slower.' },
sleepSpeedLimit: { min: 0.01, default: 0.25, max: 1, group: 'setup', dice: 'sleepSpeedLimit', tip: 'Velocity below which die is considered stationary.' },
sleepTimeLimit: { min: 0.01, default: 0.05, max: 2, group: 'setup', dice: 'sleepTimeLimit', tip: 'How long die must be slow before sleeping.' },
velocity: { min: 0.2, default: 1, max: 3, group: 'throw', throw: 'velocityMultiplier', tip: 'Throw speed multiplier. 0.5 = half speed, 2 = double speed.' },
linearDamping: { min: 0, default: 0.5, max: 1, group: 'air', dice: 'linearDamping', tip: 'Air resistance for movement. 0 = slides forever, 1 = stops mid-air.' },
angularDamping: { min: 0, default: 0.9, max: 1, group: 'air', dice: 'angularDamping', tip: 'Air resistance for rotation. 0 = spins forever, 1 = stops instantly.' },
floorFriction: { min: 0, default: 0.6, max: 5, group: 'tray', tray: 'floorFriction', tip: 'Floor grip. 0 = ice, high = velcro.' },
floorRestitution: { min: 0, default: 0.1, max: 1, group: 'tray', tray: 'floorRestitution', tip: 'Floor bounciness. 0 = thud, 1 = super ball.' },
wallFriction: { min: 0, default: 0.2, max: 5, group: 'tray', tray: 'wallFriction', tip: 'Wall grip. Affects whether dice slide or catch.' },
wallRestitution: { min: 0, default: 0.8, max: 1, group: 'tray', tray: 'wallRestitution', tip: 'Wall bounciness. Higher keeps dice moving inward.' },
mass: { min: 0.01, default: 10, max: 100, group: 'dice', dice: 'mass', tip: 'Resistance to acceleration in collisions. Heavier dice push lighter ones.' },
diceRestitution: { min: 0, default: 0.8, max: 1, group: 'dice', tray: 'diceRestitution', tip: 'Bounciness when dice hit each other.' },
diceFriction: { min: 0, default: 0.2, max: 5, group: 'dice', tray: 'diceFriction', tip: 'Grip between dice. Affects stacking behaviour.' },
};
const sliders = {};
const valueDisplays = {};
function buildControls() {
const containers = {
setup: document.getElementById('setup-settings'),
throw: document.getElementById('throw-settings'),
air: document.getElementById('air-resistance-settings'),
tray: document.getElementById('tray-settings'),
dice: document.getElementById('dice-collision-settings'),
};
const sweepSelect = document.getElementById('sweep-param');
for (const [name, cfg] of Object.entries(SETTINGS)) {
const container = containers[cfg.group];
const row = document.createElement('div');
row.className = 'control-row';
const label = document.createElement('label');
label.textContent = name;
const help = document.createElement('span');
help.className = 'help-icon';
help.textContent = '?';
help.dataset.tip = cfg.tip;
const slider = document.createElement('input');
slider.type = 'range';
slider.min = cfg.min;
slider.max = cfg.max;
slider.step = cfg.step || (cfg.max - cfg.min) / 100;
slider.value = cfg.default;
const textInput = document.createElement('input');
textInput.type = 'text';
textInput.className = 'value';
textInput.value = formatValue(cfg.default);
slider.addEventListener('input', () => {
textInput.value = formatValue(parseFloat(slider.value));
});
textInput.addEventListener('change', () => {
const v = parseFloat(textInput.value);
if (!isNaN(v)) {
slider.value = v;
textInput.value = formatValue(v);
}
});
row.append(label, help, slider, textInput);
container.appendChild(row);
sliders[name] = slider;
valueDisplays[name] = textInput;
const opt = document.createElement('option');
opt.value = name;
opt.textContent = name;
sweepSelect.appendChild(opt);
}
}
function formatValue(v) {
if (Math.abs(v) >= 10) return v.toFixed(1);
if (Math.abs(v) >= 1) return v.toFixed(2);
return v.toPrecision(2);
}
function getTrayConfig() {
const cfg = { ...DiceRoller.DEFAULT_TRAY_CONFIG };
for (const [name, def] of Object.entries(SETTINGS)) {
if (def.tray) cfg[def.tray] = parseFloat(sliders[name].value);
}
return cfg;
}
function getDiceConfig() {
const cfg = { ...DiceRoller.DEFAULT_DICE_CONFIG };
for (const [name, def] of Object.entries(SETTINGS)) {
if (def.dice) cfg[def.dice] = parseFloat(sliders[name].value);
}
return cfg;
}
function resetToDefaults() {
for (const [name, cfg] of Object.entries(SETTINGS)) {
sliders[name].value = cfg.default;
valueDisplays[name].value = formatValue(cfg.default);
}
document.getElementById('aspect-mode').value = 'auto';
document.getElementById('throw-type').value = 'full';
}
// Die creators
const dieCreators = {
4: DiceRoller.createD4,
6: DiceRoller.createD6,
8: DiceRoller.createD8,
10: DiceRoller.createD10,
12: DiceRoller.createD12,
20: DiceRoller.createD20,
};
let currentStage = null;
let currentSimulation = null;
let rolling = false;
let aborted = false;
async function runRoll() {
if (rolling) return;
rolling = true;
const trayEl = document.getElementById('tray');
const throwType = document.getElementById('throw-type').value;
const velocity = parseFloat(sliders.velocity.value);
const slowmo = document.getElementById('slowmo').checked;
// clean up previous...
if (currentStage) {
DiceRoller.removeDice(currentStage.physicsTray, currentStage);
currentStage.renderer.dispose();
trayEl.innerHTML = '';
}
// ...then create new tray with current settings
const trayConfig = getTrayConfig();
const diceConfig = getDiceConfig();
const containerAspect = trayEl.clientWidth / trayEl.clientHeight;
const aspectMode = document.getElementById('aspect-mode').value;
let trayAspect;
if (aspectMode === 'landscape') {
trayAspect = 16 / 9;
} else if (aspectMode === 'portrait') {
trayAspect = 9 / 16;
} else if (aspectMode === 'square') {
trayAspect = 1;
} else {
trayAspect = containerAspect;
}
// camera shows the full container, tray fits within it
const dieType = document.getElementById('die-select').value;
const multiplier = parseInt(document.getElementById('dice-count').value);
const baseCount = dieType === 'all' ? 6 : 1;
const totalDice = baseCount * multiplier;
const trayScale = totalDice <= 6 ? 10 : totalDice <= 24 ? 14 : 18;
const containerDims = DiceRoller.getTrayDimensions(containerAspect, trayScale);
// constrain tray to selected aspect while fitting in container
let trayHalfWidth, trayHalfDepth;
if (trayAspect > containerAspect) {
// tray is wider than container - fit to width
trayHalfWidth = containerDims.halfWidth;
trayHalfDepth = trayHalfWidth / trayAspect;
} else {
// tray is taller than container - fit to height
trayHalfDepth = containerDims.halfDepth;
trayHalfWidth = trayHalfDepth * trayAspect;
}
// set camera to show full container area
const physicsTray = DiceRoller.createTray(trayHalfWidth, trayHalfDepth, trayConfig);
currentStage = DiceRoller.createStage(trayEl, physicsTray);
DiceRoller.resizeCamera(currentStage, containerDims.halfWidth, containerDims.halfDepth);
physicsTray.frameDelay = slowmo ? 5 : 1;
// add tray outline
const THREE = DiceRoller.THREE;
const outlineGeometry = new THREE.BufferGeometry();
const vertices = new Float32Array([
-trayHalfWidth, 0.01, -trayHalfDepth,
trayHalfWidth, 0.01, -trayHalfDepth,
trayHalfWidth, 0.01, trayHalfDepth,
-trayHalfWidth, 0.01, trayHalfDepth,
-trayHalfWidth, 0.01, -trayHalfDepth,
]);
outlineGeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
const outlineMaterial = new THREE.LineBasicMaterial({ color: 0x666666 });
const outlineLine = new THREE.Line(outlineGeometry, outlineMaterial);
currentStage.scene.add(outlineLine);
// create the dice
const dieTypes = [];
const types = dieType === 'all' ? [4, 6, 8, 10, 12, 20] : [parseInt(dieType)];
for (let i = 0; i < multiplier; i++) {
for (const type of types) {
dieTypes.push(type);
}
}
const dice = [];
for (let i = 0; i < dieTypes.length; i++) {
const wrapper = await dieCreators[dieTypes[i]]();
const die = wrapper.dice[0];
const body = die.physics.body;
body.mass = diceConfig.mass;
body.linearDamping = diceConfig.linearDamping;
body.angularDamping = diceConfig.angularDamping;
body.sleepSpeedLimit = diceConfig.sleepSpeedLimit;
body.sleepTimeLimit = diceConfig.sleepTimeLimit;
body.updateMassProperties();
dice.push(die);
}
const allPhysics = dice.map(d => d.physics);
DiceRoller.packDice(allPhysics);
// add dice to tray
for (const die of dice) {
physicsTray.world.addBody(die.physics.body);
physicsTray.dice.push(die);
currentStage.scene.add(die.mesh);
}
// position and throw using library code
const whichSide = Math.random() < 0.5;
DiceRoller.offsetToEdge(allPhysics, physicsTray, whichSide);
const throwOptions = { velocityMultiplier: velocity };
for (let i = 0; i < allPhysics.length; i++) {
if (throwType === 'gentle') {
DiceRoller.applyGentleThrow(
allPhysics[i],
physicsTray,
whichSide,
throwOptions,
);
} else {
DiceRoller.applyFullThrow(
allPhysics[i],
physicsTray,
whichSide,
i / Math.max(1, allPhysics.length - 1),
allPhysics.length,
throwOptions,
);
}
DiceRoller.syncDie(dice[i]);
}
// simulate
currentSimulation = DiceRoller.simulateThrow(physicsTray, allPhysics, {
rerollCocked: false,
onStep: async () => {
dice.forEach(d => DiceRoller.syncDie(d));
await new Promise(r => requestAnimationFrame(r));
}
});
await currentSimulation.result;
currentSimulation = null;
rolling = false;
}
async function runEndlessly() {
document.getElementById('roll-btn').disabled = true;
document.getElementById('stop-btn').disabled = false;
aborted = false;
while (!aborted) {
await runRoll();
if (aborted) break;
await new Promise(r => setTimeout(r, 1000));
}
document.getElementById('roll-btn').disabled = false;
document.getElementById('stop-btn').disabled = true;
}
async function runSweep() {
const param = document.getElementById('sweep-param').value;
if (!param) return;
const from = parseFloat(document.getElementById('sweep-min').value);
const to = parseFloat(document.getElementById('sweep-max').value);
const step = Math.abs(parseFloat(document.getElementById('sweep-increment').value));
if (isNaN(from) || isNaN(to) || isNaN(step) || step === 0) {
alert('Invalid sweep parameters');
return;
}
document.getElementById('roll-btn').disabled = true;
document.getElementById('stop-btn').disabled = false;
document.getElementById('sweep-btn').disabled = true;
aborted = false;
const direction = to >= from ? 1 : -1;
const values = [];
if (direction > 0) {
for (let v = from; v <= to + step / 2; v += step) values.push(Math.min(v, to));
} else {
for (let v = from; v >= to - step / 2; v -= step) values.push(Math.max(v, to));
}
for (const value of values) {
if (aborted) break;
sliders[param].value = value;
valueDisplays[param].value = formatValue(value);
await runRoll();
}
document.getElementById('roll-btn').disabled = false;
document.getElementById('stop-btn').disabled = true;
document.getElementById('sweep-btn').disabled = false;
}
document.getElementById('sweep-param').addEventListener('change', (e) => {
const p = e.target.value;
if (p && SETTINGS[p]) {
const cfg = SETTINGS[p];
document.getElementById('sweep-min').value = cfg.min;
document.getElementById('sweep-max').value = cfg.max;
const range = cfg.max - cfg.min;
const increment = cfg.step || range / 10;
document.getElementById('sweep-increment').value = increment;
}
});
buildControls();
document.getElementById('roll-btn').addEventListener('click', runEndlessly);
document.getElementById('stop-btn').addEventListener('click', () => {
aborted = true;
if (currentSimulation) currentSimulation.cancel();
});
document.getElementById('reset-btn').addEventListener('click', resetToDefaults);
document.getElementById('sweep-btn').addEventListener('click', runSweep);
</script>
</body>
</html>