forked from IVRL/NoiseNCA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.js
More file actions
792 lines (652 loc) · 27.3 KB
/
demo.js
File metadata and controls
792 lines (652 loc) · 27.3 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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
import {NoiseNCA} from './noiseNCA.js'
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var html = document.documentElement;
var w = window.innerWidth || html.clientWidth;
var h = window.innerHeight || html.clientHeight;
return rect.top < h && rect.left < w && rect.bottom > 0 && rect.right > 0;
}
export function createDemo(divId) {
const root = document.getElementById(divId);
const $ = q => root.querySelector(q);
const $$ = q => root.querySelectorAll(q);
// const W = 256, H = 256;
const resolutions = [64, 96, 128, 192, 256];
var W = 128, H = 128;
var last_resolution_idx = 0;
let ca = null;
let experiment = 'ex3';
let paused = false;
let recording = false;
const canvas = $('#demo-canvas');
canvas.width = W * 6; //so we can render hexells
canvas.height = H * 6;
let gl = canvas.getContext("webgl2", {antialias: true, preserveDrawingBuffer: true});
if (!gl) {
console.log('your browser/OS/drivers do not support WebGL2');
console.log('Switching to WebGL1');
const gl = canvas.getContext("webgl2");
const ext1 = gl.getExtension('OES_texture_float');
if (!ext1) {
console.log("Sorry, your browser does not support OES_texture_float. Use a different browser");
// return;
}
} else {
console.log('webgl2 works!');
const ext2 = gl.getExtension('EXT_color_buffer_float');
if (!ext2) {
console.log("Sorry, your browser does not support EXT_color_buffer_float. Use a different browser");
// return;
}
}
gl.disable(gl.DITHER);
twgl.addExtensionsToContext(gl);
const maxZoom = 32.0;
const params = {
// modelSet: 'demo/models.json',
// modelSet: 'demo/test2.json',
// modelSet: 'demo/test_pos.json',
// modelSet: 'data/test3.json',
metadataJson: 'data/metadata.json',
metadata: null,
models: null,
model_type: "large",
brushSize: 16,
autoFill: true,
debug: false,
our_version: true,
zoom: 1.0,
alignment: 0,
rotationAngle: 0,
dt: 1.0,
dx: 1.0,
dy: 1.0,
epsilon: 1.0,
isotropic: true,
texture_name: "bubbly_0101",
viewChannel: -1.0, // -1 = RGB, -2 = grayscale, 0+ = hidden channel
// Alternate texture for blending
altTextureName: "bubbly_0101",
altTextureIdx: 0,
blendFactor: 0.0,
invertColors: false,
texture_img: null,
texture_idx: 0,
};
let metadata = null;
let gui = null;
let currentTexture = null;
let altCurrentTexture = null;
let selectingAltTexture = false;
let altModels = null; // Stores the alternate texture's model weights
let loadAltModelFn = null; // Will be set by initMetaData
const initTexture = "bubbly_0101";
var videoStream = canvas.captureStream(30);
var mediaRecorder = new MediaRecorder(videoStream);
var chunks = [];
mediaRecorder.ondataavailable = function (e) {
chunks.push(e.data);
}
mediaRecorder.onstop = function (e) {
var blob = new Blob(chunks, {'type': 'video/mp4'});
chunks = [];
var videoURL = URL.createObjectURL(blob);
var link = document.createElement("a");
link.download = params.texture_name;
link.href = videoURL;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
initMetaData();
async function initMetaData(load_meta_data = true) {
if (load_meta_data) {
const r = await fetch(params.metadataJson);
metadata = await r.json();
params.metadata = metadata;
} else {
metadata = params.metadata
}
let texture_names = metadata['texture_names'];
// let texture_images = metadata['texture_images'];
// Helper function to get texture image path (tries .jpg first, then .jpeg)
function getTextureImagePath(texture_name) {
// For blue_spiral, use .jpeg, otherwise try .jpg
if (texture_name === "blue_spiral") {
return "data/images/texture/" + texture_name + ".jpeg";
}
return "data/images/texture/" + texture_name + ".jpg";
}
async function setTextureModel(idx) {
params.texture_name = texture_names[idx];
params.texture_img = getTextureImagePath(texture_names[idx]);
params.modelSet = "data/models/" + texture_names[idx] + ".json"
params.texture_idx = idx;
$("#origtex").style.background = "url('" + params.texture_img + "')";
$("#origtex").style.backgroundSize = "100%100%";
let dtd = document.createElement('p')
dtd.innerHTML = "Texture Name: " + params.texture_name
// dtd.href = "https://www.robots.ox.ac.uk/~vgg/data/dtd/"
$("#texhinttext").innerHTML = '';
$("#texhinttext").appendChild(dtd);
// Add rotation-invariant indicator if applicable
console.log('setTextureModel called for:', params.texture_name);
console.log('rotationInvariantMap value:', rotationInvariantMap[params.texture_name]);
// Check if rotation-invariant (from pre-loaded map, or check directly if not found)
let isRotInv = rotationInvariantMap[params.texture_name];
if (isRotInv === undefined) {
// Fallback: check model directly if not in map
console.warn('Texture not in rotationInvariantMap, checking model directly...');
try {
const modelPath = "data/models/" + params.texture_name + ".json";
const r = await fetch(modelPath);
if (r.ok) {
const model = await r.json();
isRotInv = model.hasOwnProperty('rotation_invariant') ? model.rotation_invariant : false;
rotationInvariantMap[params.texture_name] = isRotInv; // Cache it
}
} catch (e) {
console.warn('Failed to check model:', e);
isRotInv = false;
}
}
if (isRotInv) {
console.log('✓ Adding rot-invariant text for:', params.texture_name);
let rotInvText = document.createElement('p')
rotInvText.innerHTML = "rot-invariant"
rotInvText.style.color = 'blue'
rotInvText.style.fontWeight = 'bold'
rotInvText.style.marginTop = '4px'
rotInvText.style.marginBottom = '0'
$("#texhinttext").appendChild(rotInvText)
} else {
console.log(' NOT rotation-invariant:', params.texture_name);
}
updateCA();
var video = document.getElementById('multiscale_video');
if (video) {
video.innerHTML = "";
var source = document.createElement('source');
source.setAttribute('src', "./videos/multiscale_videos/large_" + params.texture_name + "_low.mp4");
source.setAttribute('type', 'video/mp4');
video.appendChild(source);
video.load()
video.play();
}
}
async function setAltTextureModel(idx) {
params.altTextureName = texture_names[idx];
params.altTextureIdx = idx;
await loadAltModel(idx);
}
async function loadAltModel(idx) {
const altModelSet = "data/models/" + texture_names[idx] + ".json";
const r = await fetch(altModelSet);
altModels = await r.json();
if (ca) {
ca.setAltWeights(altModels);
}
}
// Make loadAltModel accessible from updateCA
loadAltModelFn = loadAltModel;
// Pre-load all model JSONs to check for rotation_invariant flags
const rotationInvariantMap = {};
const modelLoadPromises = texture_names.map(async (texture_name) => {
try {
const modelPath = "data/models/" + texture_name + ".json";
const r = await fetch(modelPath);
if (!r.ok) {
console.warn('Failed to fetch model for', texture_name, ':', r.status, r.statusText);
rotationInvariantMap[texture_name] = false;
return;
}
const model = await r.json();
// Check if rotation_invariant field exists (may be undefined for older models)
const isRotInv = model.hasOwnProperty('rotation_invariant') ? model.rotation_invariant : false;
rotationInvariantMap[texture_name] = isRotInv;
if (isRotInv) {
console.log('✓ Detected rotation-invariant model:', texture_name);
} else {
console.log(' Standard model (not rotation-invariant):', texture_name);
}
} catch (e) {
console.warn('Failed to load model for', texture_name, ':', e);
rotationInvariantMap[texture_name] = false;
}
});
await Promise.all(modelLoadPromises);
console.log('=== Rotation-invariant map (complete) ===');
console.log(rotationInvariantMap);
console.log('==========================================');
let len = texture_names.length;
console.log('Loading', len, 'textures from metadata');
for (let idx = 0; idx < len; idx++) {
let media_path = "";
let texture_name = "";
texture_name = texture_names[idx];
media_path = getTextureImagePath(texture_name);
if (texture_name === 'blue_spiral') {
console.log('Processing blue_spiral at index', idx, 'with path:', media_path);
}
const texture = document.createElement('div');
texture.style.background = "url('" + media_path + "')";
texture.style.backgroundSize = "100%100%";
// texture.style.backgroundSize = "100px100px";
texture.id = texture_name; //html5 support arbitrary id:s
texture.className = 'texture-square';
// Add error handling for image loading
const img = new Image();
img.onerror = () => {
console.warn('Failed to load texture image:', media_path);
};
img.src = media_path;
texture.onclick = () => {
// removeOverlayIcon();
console.log('Texture clicked, selectingAltTexture:', selectingAltTexture, 'idx:', idx);
console.log(' texture_name:', texture_name);
console.log(' rotationInvariantMap[' + texture_name + ']:', rotationInvariantMap[texture_name]);
console.log(' rotationInvariantMap keys:', Object.keys(rotationInvariantMap));
if (rotationInvariantMap[texture_name]) {
console.log(' → Rotation-invariant texture selected:', texture_name);
} else {
console.log(' → NOT rotation-invariant (or not in map):', texture_name);
}
if (selectingAltTexture) {
// Selecting alternate texture (green border)
console.log('Selecting alt texture');
if (altCurrentTexture) {
altCurrentTexture.style.borderColor = altCurrentTexture === currentTexture ? "rgb(245 140 44)" : "white";
}
altCurrentTexture = texture;
texture.style.borderColor = "rgb(76 175 80)"; // Green
setAltTextureModel(idx);
} else {
// Selecting primary texture (orange border)
if (currentTexture) {
currentTexture.style.borderColor = currentTexture === altCurrentTexture ? "rgb(76 175 80)" : "white";
}
currentTexture = texture;
texture.style.borderColor = "rgb(245 140 44)"; // Orange
if (!window.matchMedia('(min-width: 500px)').matches && navigator.userAgent.includes("Chrome")) {
texture.scrollIntoView({behavior: "smooth", block: "nearest", inline: "center"})
}
setTextureModel(idx);
}
};
let gridBox = $('#texture');
if (texture_name == initTexture) {
currentTexture = texture;
altCurrentTexture = texture; // Default alt texture to same as primary
texture.style.borderColor = "rgb(245 140 44)"; // Orange for primary (shown since blend=0)
gridBox.prepend(texture);
} else {
gridBox.insertBefore(texture, gridBox.lastElementChild);
}
}
setTextureModel(0);
//
// $$(".pattern-selector").forEach(sel => {
// sel.onscroll = () => {
// alret("scroll");
// removeOverlayIcon();
// sel.onscroll = null;
// }
// });
}
function removeOverlayIcon() {
$$(".overlayicon").forEach(sel2 => {
sel2.style.opacity = 0.0; //"rgba(255, 255, 255, 0.0)";
});
}
function createGUI(models) {
if (gui != null) {
gui.destroy();
}
gui = new dat.GUI();
if (!params.debug) {
dat.GUI.toggleHide();
}
const brush2idx = Object.fromEntries(models.model_names.map((s, i) => [s, i]));
params.modelname = models.model_names[params.model];
gui.add(params, 'brushSize').min(1).max(32).step(1);
gui.add(params, 'zoom').min(1).max(20);
}
function canvasToGrid(x, y) {
const [w, h] = ca.gridSize;
const gridX = x / canvas.clientWidth * w;
const gridY = y / canvas.clientHeight * h;
return [gridX, gridY];
}
function getMousePos(e) {
return canvasToGrid(e.offsetX, e.offsetY);
}
function createCA() {
ca = new NoiseNCA(gl, params.models, [W, H], gui, params.our_version);
ca.paint(0, 0, 10000, 0, [0.5, 0.5]);
ca.clearCircle(0, 0, 1000);
ca.alignment = params.alignment;
ca.rotationAngle = params.rotationAngle;
ca.blendFactor = params.blendFactor;
ca.invertColors = params.invertColors;
// Populate channel selector with hidden channels
populateChannelSelector();
}
function populateChannelSelector() {
const select = $('#channelSelect');
// Remove existing hidden channel options (keep RGB and grayscale)
while (select.options.length > 2) {
select.remove(2);
}
// Add hidden channel options (channels 3 to channelCount-1)
if (ca && ca.channelCount) {
const numHidden = ca.channelCount - 3; // subtract RGB channels
for (let i = 0; i < numHidden; i++) {
const option = document.createElement('option');
option.value = (3 + i).toString(); // channel index starts at 3
option.text = `Hidden ${i + 1}`;
select.add(option);
}
}
}
function getTouchPos(touch) {
const rect = canvas.getBoundingClientRect();
return canvasToGrid(touch.clientX - rect.left, touch.clientY - rect.top);
}
let prevPos = [0, 0]
function click(pos) {
const [x, y] = pos;
const [px, py] = prevPos;
let brushSize = params.brushSize * W / 128.0
ca.clearCircle(x, y, brushSize, null, params.zoom);
// ca.paint(x, y, params.brushSize, params.model, [x - px, y - py]);
prevPos = pos;
}
function updateEpsilon() {
let epsilon = parseFloat($('#epsilon').value);
let epsilon_ratio = (epsilon - $('#epsilon').min) / ($('#epsilon').max - $('#epsilon').min)
$('#epsilon').style.background = "linear-gradient(to right, indianred 0%, greenyellow " + (epsilon_ratio * 100) + "%, #fff " + (epsilon_ratio * 100) + "%, #fff 100%)";
params.epsilon = epsilon;
$('#epsilonLabel').innerHTML = params.epsilon.toFixed(3);
}
function updateDx() {
params.isotropic = $('#scaling_mode').checked;
let dx = parseFloat($('#dx').value);
let dx_ratio = (dx - $('#dx').min) / ($('#dx').max - $('#dx').min)
$('#dx').style.background = "linear-gradient(to right, indianred 0%, greenyellow " + (dx_ratio * 100) + "%, #fff " + (dx_ratio * 100) + "%, #fff 100%)";
if (params.isotropic) {
let dy = dx;
$('#dy').value = dy;
$('#dy').style.background = "linear-gradient(to right, indianred 0%, greenyellow " + (dx_ratio * 100) + "%, #fff " + (dx_ratio * 100) + "%, #fff 100%)";
params.dy = Math.pow(2.0, -dy);
$('#dyLabel').innerHTML = params.dy.toFixed(2);
}
params.dx = Math.pow(2.0, -dx);
$('#dxLabel').innerHTML = params.dx.toFixed(2);
updateDt();
}
function updateDy() {
params.isotropic = $('#scaling_mode').checked;
let dy = parseFloat($('#dy').value);
let dy_ratio = (dy - $('#dy').min) / ($('#dy').max - $('#dy').min)
$('#dy').style.background = "linear-gradient(to right, indianred 0%, greenyellow " + (dy_ratio * 100) + "%, #fff " + (dy_ratio * 100) + "%, #fff 100%)";
if (params.isotropic) {
let dx = dy;
$('#dx').value = dx;
$('#dx').style.background = "linear-gradient(to right, indianred 0%, greenyellow " + (dy_ratio * 100) + "%, #fff " + (dy_ratio * 100) + "%, #fff 100%)";
params.dx = Math.pow(2.0, -dx);
$('#dxLabel').innerHTML = params.dx.toFixed(2);
}
params.dy = Math.pow(2.0, -dy);
$('#dyLabel').innerHTML = params.dy.toFixed(2);
updateDt();
}
function updateDt() {
params.dt = parseFloat($('#dt').value);
params.dt = Math.min(params.dt, params.dx * params.dx, params.dy * params.dy);
$('#dt').value = params.dt;
$('#dtLabel').innerHTML = params.dt.toFixed(2);
$('#dt').style.background = "linear-gradient(to right, indianred 0%, greenyellow " + (params.dt * 100) + "%, #fff " + (params.dt * 100) + "%, #fff 100%)";
}
function updateUI() {
$$('#model-hints span').forEach(e => {
e.style.display = e.id.startsWith(experiment) ? "inline" : "none";
});
$('#play').style.display = paused ? "inline" : "none";
$('#pause').style.display = !paused ? "inline" : "none";
const speed = parseInt($('#speed').value);
$('#speedLabel').innerHTML = ['1/60 x', '1/30', '1/10 x', '1/2 x', '1x', '2x', '4x', '6x', '<b>max</b>'][speed + 4];
const resolution_idx = parseInt($('#resolution').value);
$('#resolutionLabel').innerHTML = ['64x64', '96x96', '128x128', '192x192', '256x256'][resolution_idx + 2];
W = resolutions[resolution_idx + 2]
H = resolutions[resolution_idx + 2]
canvas.width = W * 6;
canvas.height = H * 6;
if (resolution_idx != last_resolution_idx) {
createCA();
last_resolution_idx = resolution_idx;
}
// ca = new CA(gl, models, [W, H], gui, params.our_version);
// ca.paint(0, 0, 10000, params.model, [0.5, 0.5]);
params.rotationAngle = parseInt($('#rotation').value);
$('#rotationLabel').innerHTML = params.rotationAngle + "°";
$('#zoomOut').classList.toggle('disabled', params.zoom <= 1.0);
$('#zoomIn').classList.toggle('disabled', params.zoom >= maxZoom);
}
// function Screenshot(name) {
// const uri = canvas.toDataURL();
// var link = document.createElement("a");
// link.download = params.texture_name + "-dx" + params.dx + ".png";
// link.href = uri;
// document.body.appendChild(link);
// link.click();
// document.body.removeChild(link);
// // delete link;
// }
function initUI() {
$('#record').onclick = () => {
recording = !recording
$('#record_on').style.display = recording ? "inline" : "none";
$('#record_off').style.display = !recording ? "inline" : "none";
if (recording) {
mediaRecorder.start();
} else {
mediaRecorder.stop();
}
};
// $('#screenshot').onclick = () => {
// Screenshot();
// };
$('#play-pause').onclick = () => {
paused = !paused;
$('#play').style.display = paused ? "inline" : "none";
$('#pause').style.display = !paused ? "inline" : "none";
// updateUI();
};
$('#reset').onclick = () => {
ca.paint(0, 0, 10000, 0, [0.5, 0.5]);
ca.clearCircle(0, 0, 1000);
};
// $('#benchmark').onclick = () => {
// ca.benchmark();
// };
$$('#alignSelect input').forEach((sel, i) => {
sel.onchange = () => {
params.alignment = i
}
});
$$('#brushSelect input').forEach((sel, i) => {
sel.onchange = () => {
if (i == 0) {
params.brushSize = 4;
} else {
if (i == 1) {
params.brushSize = 8;
} else {
params.brushSize = 16;
}
}
}
});
$$('#gridSelect input').forEach(sel => {
sel.onchange = () => {
params.hexGrid = sel.id == 'gridHex';
}
});
$('#speed').onchange = updateUI;
$('#speed').oninput = updateUI;
$('#rotation').onchange = updateUI;
$('#rotation').oninput = updateUI;
$('#resolution').onchange = updateUI;
$('#resolution').oninput = updateUI;
$('#dt').onchange = updateDt;
$('#dt').oninput = updateDt;
$('#dx').onchange = updateDx;
$('#dx').oninput = updateDx;
$('#dy').onchange = updateDy;
$('#dy').oninput = updateDy;
$('#epsilon').onchange = updateEpsilon;
$('#epsilon').oninput = updateEpsilon;
$('#scaling_mode').onchange = updateDx;
$('#scaling_mode').oninput = updateDx;
// Blend factor slider
const updateBlendFactor = () => {
const val = parseFloat($('#blendFactor').value);
$('#blendFactorLabel').textContent = val.toFixed(2);
params.blendFactor = val;
if (ca) {
ca.blendFactor = val;
}
};
$('#blendFactor').onchange = updateBlendFactor;
$('#blendFactor').oninput = updateBlendFactor;
// Alt texture checkbox - toggles which texture is being selected
$('#altTexture').onchange = () => {
selectingAltTexture = $('#altTexture').checked;
console.log('Alt texture mode:', selectingAltTexture);
};
// Invert colors checkbox
$('#invertColors').onchange = () => {
params.invertColors = $('#invertColors').checked;
if (ca) {
ca.invertColors = params.invertColors;
}
};
// Channel view selector
$('#channelSelect').onchange = () => {
const val = $('#channelSelect').value;
if (val === 'rgb') {
params.viewChannel = -1.0;
} else if (val === 'grayscale') {
params.viewChannel = -2.0;
} else {
// Hidden channel: value is the channel index (3, 4, 5, ...)
params.viewChannel = parseFloat(val);
}
};
$('#zoomIn').onclick = () => {
if (params.zoom < maxZoom) {
params.zoom *= 2.0;
}
updateUI();
};
$('#zoomOut').onclick = () => {
if (params.zoom > 1.0) {
params.zoom /= 2.0;
}
updateUI();
};
canvas.onmousedown = e => {
e.preventDefault();
if (e.buttons == 1) {
click(getMousePos(e));
}
}
canvas.onmousemove = e => {
e.preventDefault();
if (e.buttons == 1) {
click(getMousePos(e));
}
}
canvas.addEventListener("touchstart", e => {
e.preventDefault();
click(getTouchPos(e.changedTouches[0]));
});
canvas.addEventListener("touchmove", e => {
e.preventDefault();
for (const t of e.touches) {
click(getTouchPos(t));
}
});
updateUI();
}
async function updateCA() {
// Fetch models from json file
const firstTime = ca == null;
const r = await fetch(params.modelSet);
const models = await r.json();
params.models = models;
createCA();
// Load alternate model (default to same as primary initially)
if (loadAltModelFn) {
await loadAltModelFn(params.altTextureIdx);
}
window.ca = ca;
if (firstTime) {
createGUI(models);
initUI();
updateUI();
updateDx();
updateDy();
updateEpsilon();
requestAnimationFrame(render);
}
}
// updateCA();
let lastDrawTime = 0;
let stepsPerFrame = 1;
let frameCount = 0;
let first = true;
function render(time) {
if (!isInViewport(canvas)) {
requestAnimationFrame(render);
return;
}
if (first) {
first = false;
requestAnimationFrame(render);
return;
}
ca.rotationAngle = params.rotationAngle;
ca.alignment = params.alignment;
ca.dt = params.dt;
ca.dx = params.dx;
ca.dy = params.dy;
ca.epsilon = params.epsilon;
// ca.hexGrid = params.hexGrid;
if (!paused) {
const speed = parseInt($("#speed").value);
if (speed <= 0) { // slow down by skipping steps
const skip = [1, 2, 10, 30, 60][-speed];
// alert(skip)
stepsPerFrame = (frameCount % skip) ? 0 : 1;
// alert(stepsPerFrame)
frameCount += 1;
} else if (speed > 0) { // speed up by making more steps per frame
const interval = time - lastDrawTime;
stepsPerFrame += interval < 20.0 ? 1 : -1;
stepsPerFrame = Math.max(1, stepsPerFrame);
stepsPerFrame = Math.min(stepsPerFrame, [1, 2, 4, 6, Infinity][speed])
// stepsPerFrame = 600;
}
for (let i = 0; i < stepsPerFrame; ++i) {
ca.step();
}
// $("#stepCount").innerText = ca.getStepCount();
// $("#ips").innerText = ca.fps();
}
lastDrawTime = time;
twgl.bindFramebufferInfo(gl);
ca.draw(params.zoom, params.viewChannel);
requestAnimationFrame(render);
}
}