forked from Hamza-Anver/Gridfinity-Generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
707 lines (597 loc) · 19.1 KB
/
main.js
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
import { spawnOpenSCAD } from './openscad-runner.js'
//import { buildFeatureCheckboxes } from './features.js';
const renderButton = document.getElementById('render');
const killButton = document.getElementById('kill');
const metaElement = document.getElementById('header-message');
const linkContainerElement = document.getElementById('download-link');
const stlViewerElement = document.getElementById("viewer");
const logsElement = document.getElementById("logs");
const featuresContainer = document.getElementById("features");
const flipModeButton = document.getElementById("flip-mode");
const colorPicker = document.getElementById("colorpicker");
const resetDefaults = document.getElementById("reset_default");
const settingsButton = document.getElementById("viewer-settings");
const settingsMenu = document.getElementById("settings-menu");
const pageTitle = document.getElementById("page-title");
const renderInfoButton = document.getElementById('render-info');
const renderInfo = document.getElementById('render-info-menu');
const bgColor = document.getElementById("bg-color");
const stlColor = document.getElementById("stl-color");
const gridLines = document.getElementById("gridlines");
const queryParams = new URLSearchParams(location.search);
// Does not exist but a pain to change
const autorotateCheckbox = document.getElementById('autorotate');
const autorotateButton = document.getElementById('autorotate')
import {config} from './config.js';
const {model_params_default, model_params_description, model_params_possible} = await processOpenSCADFromZip(config.zip_archive);
// Not an elegant approach but it should work
// Will probably regret later if I work on it
// Seems to be a theme now
const model_parameter_mappings = {
Normal: "normal",
Reduced: "reduced",
None: "none",
"No Label": "disabled",
Left: "left",
Right: "right",
Center: "center",
"Left Chamber": "leftchamber",
"Right Chamber": "rightchamber",
"Center Chamber": "centerchamber",
};
const model_path = config.zip_archive.replace(".zip","/") + config.model_filename;
function paramSetDefaults() {
for (var param in model_params_default) {
const defaultValue = model_params_default[param];
var propElt = document.getElementById(param);
if (propElt.type == "boolean") {
propElt.checked = defaultValue;
} else if (propElt.type == "select-one") {
propElt.value = defaultValue[0];
} else {
propElt.value = defaultValue;
}
}
}
(async () => {
if ('serviceWorker' in navigator) {
for (const reg of await navigator.serviceWorker.getRegistrations()) {
try {
reg.unregister()
} catch (e) {
console.error(e, e.stackTrace);
}
}
}
})();
function getFormProp(prop) {
const propElt = document.getElementById(prop);
if (propElt.type == "checkbox") {
return propElt.checked;
}
else if (propElt.type === "number") {
return Number(propElt.value);
}
else if (propElt.type === "select-one") {
return String(propElt.value);
}
else {
const mappedString = model_parameter_mappings[propElt.value];
return String(mappedString); // force to string after mapping
}
}
const settings_defaults = {
bgColor: "#ebebeb",
stlColor: "#737373",
gridLines: false,
};
function settingsDefault() {
bgColor.value=settings_defaults["bgColor"];
stlColor.value=settings_defaults["stlColor"];
gridLines.checked = settings_defaults["gridLines"];
};
settingsDefault();
var settingsVis = false;
function SettingsMenuToggle(){
if(settingsVis){
settingsMenu.classList.add('hide');
settingsButton.classList.add('btn-ghost');
}else{
settingsMenu.classList.remove('hide');
settingsButton.classList.remove('btn-ghost');
}
settingsVis= !(settingsVis);
};
settingsButton.onclick = () => {
if(renderinfoVis){
renderInfoToggle();
}
SettingsMenuToggle();
};
var renderinfoVis = false;
function renderInfoToggle(){
if(renderinfoVis){
renderInfo.classList.add('hide');
renderInfoButton.classList.add('btn-ghost');
}else{
renderInfo.classList.remove('hide');
renderInfoButton.classList.remove('btn-ghost');
}
renderinfoVis= !(renderinfoVis);
};
renderInfoButton.onclick = () => {
if(settingsVis){
SettingsMenuToggle();
}
renderInfoToggle();
};
stlColor.onchange = () => {
stlViewer.set_color(model_id, stlColor.value)
};
gridLines.onchange = () => {
stlViewer.set_grid(gridLines.checked);
};
bgColor.onchange = () => {
stlViewer.set_bg_color(bgColor.value);
};
var cameraStartState = {
"position": {
"x": 91.44090197259156,
"y": 73.79826512044899,
"z": 72.62376999581453
},
"up": {
"x": 0,
"y": 1,
"z": 0
},
"target": {
"x": 0,
"y": 0,
"z": 0
}
};
const featureCheckboxes = {};
var persistCameraState = false;
var stlViewer;
var stlFile;
var model_id;
function buildStlViewer() {
const stlViewer = new StlViewer(stlViewerElement);
stlViewer.model_loaded_callback = id => {
model_id = id;
stlViewer.set_grid(gridLines.checked);
stlViewer.set_bg_color(bgColor.value);
stlViewer.set_color(id, stlColor.value);
stlViewer.set_camera_state(cameraStartState);
stlViewer.set_auto_zoom(true);
stlViewer.set_auto_resize(true);
};
return stlViewer;
}
function viewStlFile() {
try { stlViewer.remove_model(1); } catch (e) { }
stlViewer.add_model({ id: 1, local_file: stlFile, rotationx: -1.5708 });
}
function addDownloadLink(container, blob, fileName) {
container.innerText = "Download";
container.href = URL.createObjectURL(blob);
container.download = fileName;
container.classList.remove("btn-ghost");
return container;
}
function formatMillis(n) {
if (n < 1000) {
return `${Math.floor(n / 1000)}s`;
}
return `${Math.floor(n / 100) / 10}s`;
}
let lastJob;
killButton.onclick = () => {
if (lastJob) {
lastJob.kill();
lastJob = null;
}
};
autorotateButton.onclick = () => {
autorotate= !(autorotate);
if(autorotate){
autorotateButton.classList.remove('btn-ghost');
}else{
autorotateButton.classList.add('btn-ghost');
}
stlViewer.set_auto_rotate(autorotate);
};
function setAutoRotate(value) {
autorotateCheckbox.checked = value;
stlViewer.set_auto_rotate(value);
}
function isViewerFocused() {
return stlViewerElement.classList.contains('focused');
}
function setExecuting(v) {
killButton.disabled = !v;
}
var lastProcessedOutputsTimestamp;
function processMergedOutputs(mergedOutputs, timestamp) {
if (lastProcessedOutputsTimestamp != null && timestamp < lastProcessedOutputsTimestamp) {
// We have slow (render) and fast (syntax check) runs running concurrently.
// The results of slow runs might be out of date now.
return;
}
lastProcessedOutputsTimestamp = timestamp;
let unmatchedLines = [];
let allLines = [];
const markers = [];
let warningCount = 0, errorCount = 0;
const addError = (error, file, line) => {
}
for (const { stderr, stdout, error } of mergedOutputs) {
allLines.push(stderr ?? stdout ?? `EXCEPTION: ${error}`);
if (stderr) {
if (stderr.startsWith('ERROR:')) errorCount++;
if (stderr.startsWith('WARNING:')) warningCount++;
let m = /^ERROR: Parser error in file "([^"]+)", line (\d+): (.*)$/.exec(stderr)
if (m) {
continue;
}
m = /^ERROR: Parser error: (.*?) in file ([^",]+), line (\d+)$/.exec(stderr)
if (m) {
continue;
}
m = /^WARNING: (.*?),? in file ([^,]+), line (\d+)\.?/.exec(stderr);
if (m) {
continue;
}
}
unmatchedLines.push(stderr ?? stdout ?? `EXCEPTION: ${error}`);
}
if (errorCount || warningCount) unmatchedLines = [`${errorCount} errors, ${warningCount} warnings!`, '', ...unmatchedLines];
logsElement.innerText = allLines.join("\n")
}
var sourceFileName;
function turnIntoDelayableExecution(delay, createJob) {
var pendingId;
var runningJobKillSignal;
const doExecute = async () => {
if (runningJobKillSignal) {
runningJobKillSignal();
runningJobKillSignal = null;
}
const { kill, completion } = createJob();
runningJobKillSignal = kill;
try {
await completion;
} finally {
runningJobKillSignal = null;
}
}
return async ({ now }) => {
if (pendingId) {
clearTimeout(pendingId);
pendingId = null;
}
if (now) {
doExecute();
} else {
pendingId = setTimeout(doExecute, delay);
}
};
}
var renderDelay = 1000;
const render = turnIntoDelayableExecution(renderDelay, () => {
const source = 'include <' + model_path + '>';
const model_dir = model_path.split(/[\\/]/)[0];
const timestamp = Date.now();
metaElement.innerHTML = '- Rendering <span class="loader-dots"></span>';
pageTitle.innerText = 'Rendering...';
metaElement.title = null;
renderButton.disabled = true;
setExecuting(true);
var arglist = [
"input.scad",
"-o", config.output_filename,
...Object.keys(featureCheckboxes).filter(f => featureCheckboxes[f].checked).map(f => `--enable=${f}`),
];
// add model parameters to openscad arglist according to its type
for (var prop in model_params_default) {
let var_type = typeof(model_params_default[prop]);
if (var_type == "string") {
arglist.push("-D", prop + '="' + getFormProp(prop) + '"');
} else if (["number", "boolean"].includes(var_type)) {
arglist.push("-D", prop + "=" + getFormProp(prop));
} else if ( Array.isArray(model_params_possible[prop]) ) {
arglist.push("-D", prop + '="' + getFormProp(prop) + '"');
} else {
console.log("Failed to handle property:" + prop);
}
}
// console.log(arglist);
const job = spawnOpenSCAD({
inputs: [['input.scad', source]],
args: arglist,
outputPaths: [config.output_filename],
zipArchives: [model_dir], // just a list of zip files (no longer an object)
});
return {
kill: () => job.kill(),
completion: (async () => {
try {
const result = await job;
// console.log(result);
processMergedOutputs(result.mergedOutputs, timestamp);
if (result.error) {
throw result.error;
}
metaElement.innerText = ' - Rendered in ' + formatMillis(result.elapsedMillis);
pageTitle.innerText= 'OpenSCAD Web Customizer'
const [output] = result.outputs;
if (!output) throw 'No output from runner!'
const [filePath, content] = output;
const filePathFragments = filePath.split('/');
const fileName = filePathFragments[filePathFragments.length - 1];
// TODO: have the runner accept and return files.
const blob = new Blob([content], { type: "application/octet-stream" });
stlFile = new File([blob], fileName);
viewStlFile(stlFile);
linkContainerElement.innerHTML = '';
addDownloadLink(linkContainerElement, blob, fileName);
} catch (e) {
console.error(e, e.stack);
metaElement.innerText = '<failed>';
metaElement.title = e.toString();
} finally {
setExecuting(false);
renderButton.disabled = false;
}
})()
}
});
renderButton.onclick = () => render({ now: true });
var autorotate = true;
function getState() {
const features = Object.keys(featureCheckboxes).filter(f => featureCheckboxes[f].checked);
return {
source: {
name: sourceFileName,
content: 'include <' + model_path + '>',
},
autorotate: autorotateCheckbox.checked,
features,
viewerFocused: isViewerFocused(),
camera: persistCameraState ? stlViewer.get_camera_state() : null,
};
}
function normalizeSource(src) {
return src.replaceAll(/\/\*.*?\*\/|\/\/.*?$/gm, '')
.replaceAll(/([,.({])\s+/gm, '$1')
.replaceAll(/\s+([,.({])/gm, '$1')
.replaceAll(/\s+/gm, ' ')
.trim()
}
function normalizeStateForCompilation(state) {
return {
...state,
source: {
...state.source,
content: normalizeSource(state.source.content)
},
}
}
const defaultState = {
source: {
name: 'input.stl',
content: 'include <' + model_path + '>',
},
maximumMegabytes: 1024,
viewerFocused: false,
features: ['fast-csg', 'fast-csg-trust-corefinement', 'fast-csg-remesh', 'fast-csg-exact-callbacks', 'lazy-union'],
};
function setState(state) {
sourceFileName = state.source.name || 'input.scad';
if (state.camera && persistCameraState) {
stlViewer.set_camera_state(state.camera);
}
let features = new Set();
if (state.features) {
features = new Set(state.features);
Object.keys(featureCheckboxes).forEach(f => featureCheckboxes[f].checked = features.has(f));
}
setAutoRotate(state.autorotate ?? true)
}
var previousNormalizedState;
function onStateChanged({ allowRun }) {
const newState = getState();
featuresContainer.style.display = 'none';
const normalizedState = normalizeStateForCompilation(newState);
if (JSON.stringify(previousNormalizedState) != JSON.stringify(normalizedState)) {
previousNormalizedState = normalizedState;
if (allowRun) {
render({ now: false });
}
}
}
function pollCameraChanges() {
if (!persistCameraState) {
return;
}
let lastCam;
setInterval(function () {
const ser = JSON.stringify(stlViewer.get_camera_state());
if (ser != lastCam) {
lastCam = ser;
onStateChanged({ allowRun: false });
}
}, 1000); // TODO only if active tab
}
async function fetchModelZip(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.arrayBuffer(); // Returns the binary data for further processing
}
async function extractOpenSCADFile(arrayBuffer) {
const zip = await JSZip.loadAsync(arrayBuffer);
// Assuming there's only one OpenSCAD file or its name is known
const scadFile = zip.file("model.scad")
if (!scadFile) {
throw new Error("OpenSCAD file not found in the ZIP archive.");
}
return scadFile.async("string") ; // Extract file as a string
}
function parseOpenSCADConfVariables(content) {
const model_parameters_raw = content.split("[Hidden]")[0];
// Split the input text into lines
const lines = model_parameters_raw.split("\n");
// Initialize the two objects to hold the parameters
const model_params_default = {};
const model_params_description = {};
const model_params_possible = {};
// Use a regex to match the parameter and value lines
const booleanPattern = /^(\w+)\s*=\s*(true|false);/;
const numberPattern = /(\w+)\s*=\s*(\d*(?:\.\d*)?);(?:.*\/\/\s*\[(.+)\])?/;
const menuPattern = /(\w+)\s*=\s*"(.*)";.*\/\/\[(.*)\]/;
// Iterate through the lines to extract parameters and their descriptions
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Check if the line is a comment (description)
if (line.startsWith("//")) {
const description = line.replace("//", "").trim(); // Remove '//' and trim spaces
var {match_bool, match_num, match} = {};
// Look ahead to see if the next line contains a parameter definition
const nextLine = lines[i + 1] ? lines[i + 1].trim() : "";
let paramName;
let paramValue;
let paramPossible;
// Check for boolean variables
if ( match = nextLine.match(booleanPattern)) {
paramName = match[1];
paramValue = ( (match[2]) === "true" );
}
// Check for number variables with optional range info
else if (match = nextLine.match(numberPattern)) {
const rangeInfo = match[3] ? match[3].split(':').map(Number) : null; // Parse the range if available
paramName = match[1];
paramValue = parseFloat(match[2]);
if (rangeInfo) {
paramPossible = [parseFloat(rangeInfo[0]), parseFloat(rangeInfo[1]), parseFloat(rangeInfo[2])];
}
}
// Check for menu select variables
else if (match = nextLine.match(menuPattern)) {
//const options = match[3].split(',').map(opt => opt.trim()); // Parse options
paramName = match[1];
paramValue = match[2];
paramPossible = match[3].split(',').map(opt => opt.trim()); // Parse options
}
else { console.log("match failed") ;}
// Add the parameter and its value to the _defaults object
model_params_default[paramName] = paramValue;
// Add the parameter and its description to the description object
model_params_description[paramName] = description;
// Add the parameter and its description to the description object
model_params_possible[paramName] = paramPossible;
// Skip the next line since we already processed it
i++;
}
}
//console.log( model_params_default);
return { model_params_default, model_params_description, model_params_possible };
}
async function processOpenSCADFromZip(url) {
try {
const arrayBuffer = await fetchModelZip(url);
const openSCADContent = await extractOpenSCADFile(arrayBuffer);
const parameters = parseOpenSCADConfVariables(openSCADContent);
return parameters;
} catch (error) {
console.error("Error processing OpenSCAD file:", error);
}
}
async function createInputNodes() {
const container = document.getElementById("param-container"); // Assuming there's a container div in index.html
Object.keys(model_params_default).forEach(param => {
const value = model_params_default[param];
const description = model_params_description[param];
const possible_value = model_params_possible[param];
// Create a div to hold the input node
const div = document.createElement("div");
div.classList.add("cell", "param-item-moi");
// Create the label element
const label = document.createElement("label");
label.setAttribute("for", param);
const tooltip = document.createElement("span");
tooltip.setAttribute("aria-label", description);
tooltip.classList.add("cooltipz--down", "cooltipz--large");
tooltip.textContent = "ⓘ";
label.appendChild(tooltip);
label.appendChild(document.createTextNode(`${param}: `));
console.log(param);
// Create the input element based on the type of value
let input;
if (typeof value === "boolean") {
// Boolean: create checkbox input
input = document.createElement("input");
input.id = param;
input.classList.add("checkmark", "form-control");
input.type = "checkbox";
input.checked = value; // Set the checkbox based on the boolean value
// Float/Number: create number input
} else if (typeof value === "number") {
input = document.createElement("input");
input.id = param;
input.type = "number";
input.min = possible_value[0];
input.step = possible_value[1];
input.max = possible_value[2];
input.classList.add("form-control");
input.value = value; // Set the value of the input to the number
// Array: create list input
} else if (Array.isArray(possible_value)) {
input = document.createElement("select");
input.id = param;
input.classList.add("form-control");
possible_value.forEach(function(item) {
var option = document.createElement("option");
option.value = item;
option.textContent = item;
input.appendChild(option);
});
}
// Append label and input to the div
div.appendChild(label);
div.appendChild(input);
// Append the div to the container
container.appendChild(div);
});
}
try {
createInputNodes();
stlViewer = buildStlViewer();
stlViewerElement.ondblclick = () => {
setAutoRotate(!autorotateCheckbox.checked);
onStateChanged({ allowRun: false });
};
stlViewerElement.onclick = () => {
if(settingsVis){ SettingsMenuToggle();};
if(renderinfoVis){ renderInfoToggle();};
}
const initialState = defaultState;
setState(initialState);
// await buildFeatureCheckboxes(featuresContainer, featureCheckboxes, () => {
// onStateChanged({ allowRun: true });
// });
setState(initialState);
autorotateCheckbox.onchange = () => {
stlViewer.set_auto_rotate(autorotateCheckbox.checked);
onStateChanged({ allowRun: false });
};
resetDefaults.onclick = () => {
paramSetDefaults();
}
pollCameraChanges();
onStateChanged({ allowRun: true });
} catch (e) {
console.error(e);
}