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 | /*
BSD Zero Clause License
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
window.addEventListener('load', () => {
'use strict';
// Convert hex string colour to RGB array (0.0 to 1.0).
function hexColorToRgb(hexCol) {
return [
parseInt(hexCol.substring(1, 3), 16) / 255,
parseInt(hexCol.substring(3, 5), 16) / 255,
parseInt(hexCol.substring(5, 7), 16) / 255,
]
}
//--------------
// Canvas Setup
//--------------
const canvas = document.getElementById('roseEngineCanvas');
const displayContext = canvas.getContext('webgl2');
if (displayContext == null) {
alert("WebGL2 unsupported?");
return;
}
const hiddenCanvas = document.getElementById('hiddenCanvas');
const hiddenGraphicsContext = hiddenCanvas.getContext('2d');
function resize(force) {
const w = canvas.clientWidth;
const h = canvas.clientHeight;
if (!force && canvas.width == w && canvas.height == h) {
return;
}
// Render circuits at double size for anti-aliasing.
const side = Math.min(w, h) * 2;
hiddenCanvas.width = side;
hiddenCanvas.height = side;
circuits.forEach(c => c.dirty = true);
canvas.width = w;
canvas.height = h;
const gl = displayContext;
gl.viewport(0, 0, w, h);
gl.bindTexture(gl.TEXTURE_2D, depthTexture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,
w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S,
gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T,
gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER,
gl.LINEAR);
requestRender();
}
//--------
// Curves
//--------
const curves = {
"sin(θ)": angle => Math.sin(angle),
"sin(θ)^3": angle => Math.sin(angle) ** 3,
};
//----------
// Controls
//----------
function addOneControl(fromElement, toObject, name) {
toObject[name] = fromElement;
// Update value display on input
const valDisplay = fromElement.parentNode.parentNode
.getElementsByClassName('range-value-display')[0];
if (fromElement.type == 'range' && valDisplay) {
fromElement.addEventListener('input', () => {
valDisplay.innerHTML = fromElement.value;
});
}
}
// Add DOMObjects of controls under 'fromElement' into 'toObject'
function addControls(fromElement, toObject) {
const group = fromElement.dataset?.ctrlGroup;
const name = fromElement.dataset?.ctrl;
const arr = fromElement.dataset?.ctrlArray;
if (group) {
if (!toObject[group]) {
toObject[group] = { element: fromElement };
}
Array.from(fromElement.children).forEach(
element => addControls(element, toObject[group]));
} else if (name) {
addOneControl(fromElement, toObject, name);
} else if (arr) {
const destArr = toObject[arr] = [];
Array.from(fromElement.children).forEach(element => {
if (element.tagName === 'DIV') {
const obj = { element };
destArr.push(obj);
addControls(element, obj);
}
});
} else {
// Recurse down through selected tags.
switch (fromElement.tagName) {
case 'DIV':
case 'LABEL':
case 'SPAN':
Array.from(fromElement.children).forEach(
element => addControls(element, toObject));
break;
}
}
}
const controls = {};
addControls(document.getElementById('roseEngineCtrls'), controls);
function getRenderSettings(controls) {
return {
quality: controls.quality.valueAsNumber,
surfaceColour: controls.surfaceColour.value,
light: {
x: controls.light.x.valueAsNumber,
y: controls.light.y.valueAsNumber,
z: controls.light.z.valueAsNumber,
}
}
}
// Populate curve shape selection lists.
controls.circuits.forEach(ctrl => {
const select = ctrl.curveName;
Object.keys(curves).forEach(cName => {
select.add(new Option(cName, cName));
});
});
controls.quality.addEventListener('change', () => {
circuits.forEach(c => c.dirty = true);
requestRender(8);
});
controls.surfaceColour.addEventListener('change',
() => requestRender(1));
Object.values(controls.light).forEach(
ctrl => ctrl.addEventListener('input', () => requestRender(1)));
//-------------
// WebGL Setup
//-------------
const vertexSource = `
attribute vec4 aVertexPosition;
varying highp vec2 vTextureCoord;
uniform highp vec2 uScale;
void main() {
gl_Position = vec4(aVertexPosition.xy * uScale, 0.0, 1.0);
vTextureCoord = aVertexPosition.xy / 2.0 + 0.5;
}
`;
const fragmentSource = {
copy: `
varying highp vec2 vTextureCoord;
uniform sampler2D uSampler;
void main() {
gl_FragColor = texture2D(uSampler, vTextureCoord);
}
`,
light: `
varying highp vec2 vTextureCoord;
uniform sampler2D uSampler;
uniform highp vec3 uLightPos;
uniform mediump vec3 uColor;
uniform highp vec2 uPixelSize;
uniform highp float uDepthScale;
highp vec3 pos(highp vec2 offset) {
highp vec2 readFrom = vec2(vTextureCoord +
offset * uPixelSize);
return vec3(readFrom,
texture2D(uSampler, readFrom) * uDepthScale);
}
void main() {
// positions
highp vec3 mid = pos(vec2(0,0));
highp vec3 up = pos(vec2(0, -1));
highp vec3 down = pos(vec2(0, 1));
highp vec3 left = pos(vec2(-1, 0));
highp vec3 right = pos(vec2(1, 0));
highp vec3 normal = cross(right - left, down - up);
highp vec3 lightDir = mid - uLightPos;
mediump vec3 col = dot(lightDir, normal) /
length(normal) / length(lightDir) * uColor;
gl_FragColor = vec4(col, 1.0);
}
`,
};
function loadShader(ctx, type, source) {
const shader = ctx.createShader(type);
ctx.shaderSource(shader, source);
ctx.compileShader(shader);
if (!ctx.getShaderParameter(shader, ctx.COMPILE_STATUS)) {
console.log("Shader compiler failed: " +
ctx.getShaderInfoLog(shader));
ctx.deleteShader(shader);
return null;
}
return shader;
}
function initShaderProgram(ctx, vsSource, fsSource) {
const vertexShader = loadShader(ctx, ctx.VERTEX_SHADER,
vsSource);
const fragmentShader = loadShader(ctx, ctx.FRAGMENT_SHADER,
fsSource);
const shaderProgram = ctx.createProgram();
ctx.attachShader(shaderProgram, vertexShader);
ctx.attachShader(shaderProgram, fragmentShader);
ctx.linkProgram(shaderProgram);
if (!ctx.getProgramParameter(shaderProgram, ctx.LINK_STATUS)) {
console.log("Shader link fail: " +
ctx.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
function initBuffers(ctx) {
const positionBuffer = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, positionBuffer);
const positions = new Float32Array([
-1.0, 1.0,
1.0, 1.0,
-1.0, -1.0,
1.0, -1.0,
]);
ctx.bufferData(ctx.ARRAY_BUFFER, positions, ctx.STATIC_DRAW);
return { position: positionBuffer };
}
const depthTexture = displayContext.createTexture();
const frameBuffer = displayContext.createFramebuffer();
const copyShaderInfo = function(ctx) {
const program = initShaderProgram(ctx, vertexSource,
fragmentSource.copy);
const vertexPosition = ctx.getAttribLocation(program,
'aVertexPosition');
const uSampler = ctx.getUniformLocation(program, 'uSampler');
const uScale = ctx.getUniformLocation(program, 'uScale');
return {
program,
attribLocations: { vertexPosition },
uniformLocations: { uSampler, uScale },
};
}(displayContext);
const lightShaderInfo = function(ctx) {
const program = initShaderProgram(ctx, vertexSource,
fragmentSource.light);
const vertexPosition = ctx.getAttribLocation(program,
'aVertexPosition');
const uniformLocations = {};
[
'uSampler',
'uLightPos',
'uColor',
'uPixelSize',
'uDepthScale',
'uScale',
].forEach(u =>
uniformLocations[u] = ctx.getUniformLocation(program, u));
return {
program,
attribLocations: { vertexPosition },
uniformLocations,
};
}(displayContext);
const glBuffers = initBuffers(displayContext);
//--------
// Circuit
//--------
class Circuit {
constructor(workCtx, displayCtx, control) {
this.workCtx = workCtx;
this.displayCtx = displayCtx;
this.texture = displayCtx.createTexture();
this.control = control;
this.element = control.element;
this.element.circuitObj = this;
this.updateParams();
this.dirty = true;
const cb = () => {
this.updateParams();
this.dirty = true;
requestRender();
};
[
control.repeat,
control.travel,
control.radius,
control.offset,
control.curveName,
].forEach(c => c.addEventListener('input', cb));
control.btns.up.addEventListener('click', () => {
const target = this.element.previousElementSibling;
if (target) {
target.before(this.element);
target.circuitObj?.updateControlState();
}
this.updateControlState();
});
control.btns.down.addEventListener('click', () => {
const target = this.element.nextElementSibling;
if (target) {
target.after(this.element);
target.circuitObj?.updateControlState();
}
this.updateControlState();
});
control.btns.remove.addEventListener('click', () => {
const prev = this.element.previousElementSibling;
const next = this.element.nextElementSibling;
if (prev != null || next != null) {
this.destroy();
prev?.circuitObj?.updateControlState();
next?.circuitObj?.updateControlState();
requestRender();
} else {
this.updateControlState();
}
});
control.btns.add.addEventListener('click', () => {
const newNode = this.element.cloneNode(true);
this.element.after(newNode);
const ctrls = {element: newNode};
addControls(newNode, ctrls);
ctrls.curveName.selectedIndex =
this.control.curveName.selectedIndex;
const newObj = new Circuit(workCtx, displayCtx, ctrls);
circuits.push(newObj);
this.updateControlState();
});
this.updateControlState();
}
updateParams() {
const c = this.control;
this.params = {
repeat: c.repeat.valueAsNumber,
travel: c.travel.valueAsNumber,
radius: c.radius.valueAsNumber,
offset: c.offset.valueAsNumber,
cutWidth: 0.03,
cutDepth: 1.0,
curveName: c.curveName.value,
};
}
destroy() {
this.element.circuitObj = null;
const index = circuits.findIndex(e => e == this);
circuits.splice(index, 1);
this.element.remove();
if (this.texture) {
this.displayCtx.deleteTexture(this.texture);
this.texture = null;
}
}
updateControlState() {
const control = this.control;
const element = this.element;
if (element.parentElement.childElementCount < 2) {
control.btns.up.disabled = true;
control.btns.down.disabled = true;
control.btns.remove.disabled = true;
} else {
control.btns.remove.disabled = false;
control.btns.up.disabled =
element.previousElementSibling === null;
control.btns.down.disabled =
element.nextElementSibling === null;
}
}
updateTexture(quality) {
if (!this.dirty) {
return;
}
const ctx = this.workCtx;
const gl = this.displayCtx;
const canvas = ctx.canvas;
const side = Math.min(canvas.width, canvas.height);
const unit = side / 2;
const repeat = this.params.repeat;
const travel = this.params.travel * unit / 2000;
const radius = this.params.radius * unit / 1000;
const offset = this.params.offset * Math.PI * 2;
const cutWidth = this.params.cutWidth * unit;
const cutDepth = this.params.cutDepth;
const travelFunction = curves[this.params.curveName];
ctx.save();
ctx.clearRect(0, 0, side, side);
ctx.fillStyle = "black";
ctx.fillRect(0, 0, side, side);
// Create gradient representing the depth of a
// cross-section of the cut.
const grad = ctx.createLinearGradient(0, 0, cutWidth, 0);
grad.addColorStop(0, 'black');
const c = Math.floor(cutDepth * 255);
grad.addColorStop(0.5, `RGB(${c},${c},${c})`);
grad.addColorStop(1, 'black');
ctx.strokeStyle = grad;
// Use lighten so we always represent the deepest point cut.
ctx.globalCompositeOperation = 'lighten';
ctx.translate(side / 2, side / 2);
ctx.lineWidth = 1;
// Use less segments for inner circuits.
const segments = quality * Math.PI * (radius + cutWidth);
// Stamp out a load of 1px long cross-sections to
// approximate the cut.
const segmentAngle = Math.PI * 2 / segments;
for (let i = segments; i-- > 0;) {
ctx.save();
const angle = segmentAngle * i;
ctx.rotate(angle);
const q = (angle * repeat + offset) % (Math.PI * 2);
ctx.translate(radius + travel * travelFunction(q), 0);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(cutWidth, 0);
ctx.stroke();
ctx.restore();
}
ctx.restore();
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE,
canvas
);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S,
gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T,
gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER,
gl.LINEAR);
this.dirty = false;
}
};
const circuits = controls.circuits.map(c =>
new Circuit(hiddenGraphicsContext, displayContext, c)
);
//-----------
// Rendering
//-----------
function glRender(renderSettings) {
const gl = displayContext;
circuits.forEach(c => c.updateTexture(renderSettings.quality));
// Render to target texture.
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, depthTexture);
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D, depthTexture, 0);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.BLEND);
gl.blendEquation(gl.MAX);
gl.useProgram(copyShaderInfo.program);
const numComponents = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffers.position);
gl.vertexAttribPointer(
copyShaderInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
copyShaderInfo.attribLocations.vertexPosition);
gl.activeTexture(gl.TEXTURE0);
// Use scale to place design in centre, with correct aspect ratio.
gl.uniform2f(copyShaderInfo.uniformLocations.uScale,
hiddenCanvas.width / canvas.width / 2,
hiddenCanvas.height / canvas.height / 2);
circuits.forEach(c => {
gl.bindTexture(gl.TEXTURE_2D, c.texture);
gl.uniform1i(copyShaderInfo.uniformLocations.uSampler, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
});
// Switch back to rendering onto canvas.
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.useProgram(lightShaderInfo.program);
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffers.position);
gl.vertexAttribPointer(
lightShaderInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
lightShaderInfo.attribLocations.vertexPosition);
const lightPos = [
renderSettings.light.x,
1 - renderSettings.light.y,
-renderSettings.light.z,
];
gl.activeTexture(gl.TEXTURE1);
gl.uniform1i(lightShaderInfo.uniformLocations.uSampler, 1);
gl.uniform3fv(lightShaderInfo.uniformLocations.uLightPos,
lightPos);
gl.uniform3fv(lightShaderInfo.uniformLocations.uColor,
hexColorToRgb(renderSettings.surfaceColour));
gl.uniform2f(lightShaderInfo.uniformLocations.uPixelSize,
1.0 / hiddenCanvas.width, 1.0 / hiddenCanvas.width);
gl.uniform1f(lightShaderInfo.uniformLocations.uDepthScale,
6.0 / hiddenCanvas.width);
gl.uniform2f(lightShaderInfo.uniformLocations.uScale, 1.0, 1.0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
let renderDelay = 0;
function requestRender(delayFrames = 4)
{
renderDelay = delayFrames || 1;
}
function frame() {
resize();
if (renderDelay && !--renderDelay) {
glRender(getRenderSettings(controls));
}
window.requestAnimationFrame(frame);
}
resize(true);
requestRender(1);
frame();
});
|