-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webgl2.html
2099 lines (1834 loc) · 87.7 KB
/
webgl2.html
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<meta charset="utf-8">
<!--
https://jakedowns.github.io/starpages/webgl2.html
TODO:
- bitonic sort
// finish back merging "video texture" / three.js bindings
// finish triple-buffering
- lerping between colors using an intermediary accumulator texture which we display
// backed by our current Original, and Target textures
-->
<html>
<head>
<script>
window.capturerSpeedReduction = 0.5;
</script>
<title>Pixel Mixer</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://jakedowns.github.io/starpages/res/CCapture.all.min.js"></script>
<link href="https://unpkg.com/tailwindcss@^2.0.2/dist/tailwind.min.css" rel="stylesheet">
<script type="module">
import { GUI } from './import/threejs/examples/jsm/libs/lil-gui.module.min.js';
const panel = new GUI( );
panel.add( settings, 'res', 1, 6, 1 ).name( 'Res' ).onFinishChange( compile );
panel.add( settings, 'bounds', 1, 10, 1 ).name( 'Bounds' ).onFinishChange( compile );
panel.add( settings, 'material', [ 'depth', 'normal' ] ).name( 'Material' ).onChange( setMaterial );
panel.add( settings, 'wireframe' ).name( 'Wireframe' ).onChange( setMaterial );
panel.add( settings, 'autoRotate' ).name( 'Auto Rotate' );
panel.add( settings, 'vertexCount' ).name( 'Vertex count' ).listen().disable();
</script>
<script>
// stat.js
(function(){
var script=document.createElement('script');script.onload=function(){
var stats=new Stats();
document.body.appendChild(stats.dom);
stats.dom.style.position = 'absolute';
stats.dom.style.bottom = '0px';
stats.dom.style.top = 'auto';
requestAnimationFrame(function loop(){stats.update();requestAnimationFrame(loop)});};script.src='https://mrdoob.github.io/stats.js/build/stats.min.js';document.head.appendChild(script);})()
</script>
<style>
html, body { margin: 0; padding: 0; overflow: hidden; background-color: #000; }
canvas#canvas {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
width: 100vw;
min-Width: 100vw;
max-width: 100vw;
height: 100vh;
min-height: 100vh;
max-height: 100vh;
/* filter: blur(100px); */
opacity: 1;
transition: filter 0.5s ease-in-out, opacity 0.5s ease-in-out;
will-change: filter;
}
canvas.unblur { filter: blur(0px); opacity: 1; }
canvas.undarken { opacity: 0.8; }
.drop-here-text {
pointer-events: none;
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 4000;
font-size: 43px;
font-weight: bold;
text-align: center;
color: white;
font-family: sans-serif;
text-shadow: 4px 4px 5px black, 5px 5px 5px blue;
-webkit-text-strokes: 1px black;
top: 50%;
transform: translateY(-50%);
transition: all 1s ease-in-out;
}
.drop-here-text.fadeout {
opacity: 0;
pointer-events: none;
}
.drop-here-text span {
display: block;
font-size: 25px;
}
.drop-here-text.fadeout span {
pointer-events: none;
}
.drop-here-text .hint {
font-size: 15px;
}
.intro-card {
top: 50%;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
z-index: 1000;
display: block;
width: 100%;
max-width: 100vw;
padding: 20px;
box-sizing: border-box;
opacity: 1;
}
.intro-card.fade-out {
opacity: 0;
pointer-events: none;
}
.intro-card iframe {
height: auto;
width: 100%;
min-width: 100px;
max-width: 100%;
}
p {
color: white;
font-size: 12px;
font-family: serif;
}
h1 {
font-family: sans-serif;
}
.intro-underlay {
background-color: rgba(.1,0,.1,.8);
backdrop-filter: blur(10px);
position: absolute;
z-index: 999;
top: 0; left: 0; right: 0; bottom: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.intro-underlay.fade-out {
opacity: 0;
pointer-events: none;
}
.hide-intro-button {
text-align: center;
width: auto;
margin: 0 auto;
position: relative;
display: block;
border-radius: 100px;
border: 2px solid black;
padding: 10px 20px;
box-sizing: border-box;
font-size: 20px;
color: white;
cursor: pointer;
transition: all 1s ease-in-out;
background-color: #663dff;
font-family: sans-serif;
text-shadow: 1px 1px 3px rgba(0,0,0,0.8);
background-size: 200% auto;
background-image: linear-gradient(90deg, #cc4499, #aa00ff, #663dff, #aa00ff, #cc4499);
transition: all 1s ease-in-out;
/* Apply the animation */
animation: gradient-animation 2s linear infinite;
}
/* here we use a rounded rectangle + a linear gradient to emulate gloss via psuedo element */
.hide-intro-button .btn-inner::after {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
border-radius: 100px;
background-color: rgba(255,255,255,0.1);
z-index: 1;
backdrop-filter: blur(50px);
}
.hide-intro-button:hover {
}
.hide-intro-button .btn-text {
position: relative;
font-size: 18px;
z-index: 2;
color: white;
text-shadow: 1px 1px 10px rgba(255,255,255,1); /* 1px 1px 1px rgba(0,0,0,0.8), */
cursor: pointer;
}
/*
1. we reflect the gradient over the Y axis
2. we animate the gradient over time from left to right infinitely
3. [#cc4499, #aa00ff, #663dff, #aa00ff, #cc4499]
4. we use a linear gradient to emulate gloss
5. we stretch it to 2x the width of the button
*/
@keyframes gradient-animation {
0% { background-position: 0% 50%; }
99.99% { background-position: -200% 50%; }
100% { background-position: 0% 50%; }
}
#controls {
position: absolute;
right: 0;
top: 0;
width: 100px;
height: 100%;
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: stretch;
}
video {
position: absolute;
left: 0;
opacity: 0.1;
transition: all 1s ease-in-out;
bottom: 100px;
width: 100px;
}
video:hover {
opacity: 1;
width: 300px;
}
#record-video-button {
position: absolute;
bottom: 10px;
right: 10px;
width: 100px;
z-index: 1000;
}
/* final z-indexes */
.intro-card { z-index: 1002; position: absolute; }
.intro-underlay { z-index: 1001; }
#controls { z-index: 1000; }
video { z-index: 1000; }
canvas { z-index: 999; }
.view-source-link {
position: absolute;
top: 0;
right: 0;
z-index: 9999;
font-size: 10px;
font-family: sans-serif;
color: white;
text-decoration: none;
padding: 5px;
background-color: black;
opacity: 0.5;
transition: all 1s ease-in-out;
&:hover {
opacity: 1;
}
}
</style>
</head>
<body>
<!-- todo: gif support -->
<!-- view source on github -->
<a href="https://github.com/jakedowns/starpages/blob/main/webgl2.html"
class="view-source-link" target="_blank">view source on GitHub</a>
<!-- buy me a coffee; ko-fi link -->
<a href="https://ko-fi.com/jakedowns" target="_blank" style="position: absolute; top: 0; left: 0; z-index: 1003; font-size: 10px; font-family: sans-serif; color: white; text-decoration: none; padding: 5px; background-color: black; opacity: 0.5;">☕🥰 Buy me a coffee</a>
<div id="controls">
<input type="file" accept="image/*,video/*,image/svg+xml" id="fileupload" />
<progress id="progress" value="0" max="100"></progress>
<button onclick="window.startCapture()" style="background:white; color:black;">record video</button>
</div>
<div class="intro-card transition-opacity fade-out">
<h1>Pixel Mixer Demo</h1>
<p>v24.01.01.01 - Major Release 001</p>
<p>Shout out to acerola on youtube for his original "I tried sorting pixels" video which inspired me to dig back into this</p>
<p>Drop images and video on this webpage to have them mixed and blended in unique ways</p>
<p>⚠️ Flashing Light Warning ⚠️ <br/>this app produces rapidly flashing light patterns. I'm working on a "safe" comfort mode - but for now, do not use it if you are photo-sensitive. 🙇🏻♂️🙏🏻</p>
<!-- <iframe width="560" height="315" src="https://www.youtube.com/embed/NGA-Sc-2XTg?si=YxW01ggV4KRXI-U4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> -->
<button class="hide-intro-button">
<span class="btn-inner">
<span class="btn-text" onclick="window.hideWelcome()">Click to Continue ➡️</span>
</span>
</button>
</div>
<div class="intro-underlay fade-out" onclick="window.hideWelcome()"></div>
<div class="drop-here-text">pixel mixer<span>drop an image here<br/>or<br/>tap here to select an image <span class="hint">(local only, doesn't get uploaded anywhere)</span></span></div>
<canvas id="canvas" classname="undarken"></canvas>
<script>
window.pixelWidth = window.innerWidth;
window.pixelHeight = window.innerHeight;
window.canvas;
window.uReflectionY = 0.5; // 0.5 = no reflection, 0 = full reflection, 1 = no reflection
window.reverseSort = true;
window.capturer = null;
window.capturing = false;
window.targetRecordingFPS = 29.97; //120;
window.targetRecordingDurationSeconds = 30;
Object.defineProperty(window, 'maxFrames', {
get: function() { return this.targetRecordingFPS * 10; }
});
// define fixedTime
// a wall time we can hold to pause the shader
Object.defineProperty(window, 'fixedTime', {
get() {
return window.targetVideoPlaybackRate >= 0.1 ? null : this._fixedTime;
},
set(value) {
this._fixedTime = value;
}
});
window.videoIsPlaying = false;
// used to distinguish element's playback state from our virtual playback state(sub-0.1x playback rate)
window.videoIsVirtuallyPlaying = false;
// window.recordingStartedAt = 0;
window.subframePlaybackCurrentFrame = 0;
window.currentVideoTime = null;
window.baseTexture = null;
// this is one of the base textures for the screen, it's part of a double-buffering ping-pong scheme
// where we swap reading/writing to baseTexture or accumulationTexture
// so, we need a NEW texture that's meant specifically the mandlebulb
window.mandlebulbTexture = null;
window.shaderTimeIsPaused = false;
window.theVideoplayerElement = null;
let _targetVideoPlaybackRate = 0.01;
let _targetVideoPlaybackRateClamped = 0.1;
Object.defineProperty(window, 'targetVideoPlaybackRate', {
get: function() {
return _targetVideoPlaybackRate;
},
set: function(value) {
_targetVideoPlaybackRate = value;
_targetVideoPlaybackRateClamped = parseFloat(Math.min(Math.max(value, 0.1), 1.0).toFixed(1));
if (window.theVideoplayerElement) {
window.theVideoplayerElement.playbackRate = _targetVideoPlaybackRateClamped;
}else{
console.warn('no video element to set playback rate on')
}
}
});
// was: fsSource
/*
// bare bones debug
// make sure we set, otherwise safari won't work
// fsSource = `
// precision mediump float;
// void main() {
// gl_FragColor = vec4(1.0,0.0,0.0,1.0);
// }
// `
*/
//window.fragmentShaderSource = null;
window.selectedImageTexture;
window.shaderMaterial;
window.onBaseTextureRefresh = function(){
// 1. reset Offset texture
// 2. clone base -> target (refresh)
// 3. clone base -> accumulator (refresh)
// 4. clone base -> lerped (refresh)?
}
// window.switchToImageTexture
// may have changed pixel resolution
// TODO: maybe make sure we set three to just fill/crop whatever we're trying to display to fit our existing pixel resolution
window.reinitTexturesOnNewInput = function(){
// 1. reset Offset texture
// 2. clone base -> target (refresh)
// 3. clone base -> accumulator (refresh)
// 4. clone base -> lerped (refresh)?
}
let handling_slow_motion_advance = false;
function maybeAdvanceVideoOneFrame() {
if(!window.targetVideoPlaybackRate >= 0.1){
handling_slow_motion_advance = false;
return;
}
if(handling_slow_motion_advance){
return;
}
//theVideoplayerElement.pause();
handling_slow_motion_advance = false;
let frameDuration = 1 / window.targetRecordingFPS; //framerate;
let desiredSpeed = window.targetVideoPlaybackRate;// 0.05; // Replace with your desired speed
let playDuration = frameDuration / desiredSpeed;
let do_advance_virtual_frame_this_literal_frame = window.subframePlaybackCurrentFrame % Math.floor(1 / desiredSpeed) == 0;
if(!do_advance_virtual_frame_this_literal_frame){
return;
}
subframePlaybackCurrentFrame++;
// currentTime is also not precise enough for sub-frame playback
// we will hit play then pause in a short manner
// the min time beyond the point where a "play was cancelled by pause" is ??ms ?
//theVideoplayerElement.currentTime += frameDuration;
window.playSlowMotion = function() {
// console.warn("onPlaySlowMotion",{
// frameDuration,
// targetFPS: window.targetRecordingFPS,
// desiredSpeed,
// playDuration,
// });
setTimeout(() => {
handling_slow_motion_advance = true;
theVideoplayerElement.play();
}, 32);
// onseek we call BACK to this function to pause and continue slow motion
}
theVideoplayerElement.addEventListener('seeked', () => {
if (handling_slow_motion_advance) {
playSlowMotion();
}
});
// theVideoplayerElement.addEventListener('pause', () => {
// if (handling_slow_motion_advance && theVideoplayerElement.currentTime < theVideoplayerElement.duration) {
// theVideoplayerElement.currentTime += frameDuration;
// }
// });
}
document.addEventListener('wheel', (e) => {
vec2MouseWheelRaw.set(
vec2MouseWheelRaw.x + e.deltaX * 0.1,
vec2MouseWheelRaw.y + e.deltaY * 0.1
);
});
window.setupThree = async function(){
const pasteFromClipboardPrompt = document.getElementById("pasteFromClipboardPrompt");
function showPasteFromClipboardPrompt(){
pasteFromClipboardPrompt.classList.add("show");
setTimeout(()=>{
pasteFromClipboardPrompt.classList.remove("show");
},5000);
}
function hidePasteFromClipboardPrompt(){
pasteFromClipboardPrompt.classList.remove("show");
}
let didShowClipboardPrompt = false;
let currentClipboardBagValueHash = null;
let previousClipboardBagValueHash = null;
// let clipboardCheckInterval = setInterval(async()=>{
// if(didShowClipboardPrompt){
// // check if clipboard has changed
// let currentClipboardBagValueHash = null;
// try{
// const items = await navigator.clipboard.read();
// let hash_string = '';
// for (const item of items) {
// let types_concat = item.types.join('');
// hash_string += types_concat;
// hash_string += item.size ?? 0;
// hash_string += item.lastModified ?? 0;
// }
// console.warn({hash_string})
// currentClipboardBagValueHash = hash_string;
// }catch(e){
// console.error(e);
// }
// if(currentClipboardBagValueHash != previousClipboardBagValueHash){
// didShowClipboardPrompt = false;
// }
// }
// if(didShowClipboardPrompt){
// return;
// }
// didShowClipboardPrompt = true;
// try{
// const text = await navigator.clipboard.readText();
// if(text){
// showPasteFromClipboardPrompt();
// }else{
// hidePasteFromClipboardPrompt();
// console.warn('nothing in clipboard')
// }
// }catch(e){
// console.error(e);
// }
// },1000);
/* adds paste support for Clipboard ImageBlob -> Three.js Texture */
window.doPasteFromClipboard = async function(){
try{
const items = await navigator.clipboard.read();
console.warn('items',items)
for (const item of items) {
if (item.types.includes('image/png')) {
const blob = await item.getType('image/png');
const url = URL.createObjectURL(blob);
if(window?.baseTexture?.image){
return;
}
window.baseTexture.image.onload = function() {
URL.revokeObjectURL(url);
window.baseTexture.needsUpdate = true;
};
window.baseTexture.image.src = url;
break;
}
// or if ti's a base64 image in a text string, pass _that_ to image.src
if (item.types.includes('text/plain')) {
const text = await item.getType('text/plain');
if(window?.baseTexture?.image){
return;
}
window.baseTexture.image.onload = function() {
URL.revokeObjectURL(url);
window.baseTexture.needsUpdate = true;
};
window.baseTexture.image.src = text;
break;
}
}
}catch(e){
console.error(e);
}
}
document.addEventListener("keydown",(e)=>{
if(e.key == "v" && (e.ctrlKey || e.metaKey)){
try{
window.doPasteFromClipboard();
}catch(e){
console.error(e);
}
}
},false);
document.getElementById("fileupload").addEventListener("change", (e) => {
hideIntroText();
handleFileInput(e);
});
canvas = document.getElementById("canvas");
const renderer = new THREE.WebGLRenderer({canvas});
canvas.width = pixelWidth;
canvas.height = pixelHeight;
// Scale up the canvas using CSS
canvas.style.width = '100vw';
canvas.style.height = '100vh';
canvas.style.imageRendering = 'pixelated'; // This ensures nearest neighbor scaling in browsers that support it
//canvas.style.imageRendering = 'crisp-edges'; // This ensures nearest neighbor scaling in browsers that support it
//object-fit: contain;
canvas.style.objectFit = 'contain';
// Orthographic camera setup
const frustumSize = 1;
const aspect = pixelWidth / pixelHeight; //canvas.clientWidth / canvas.clientHeight;
const camera = new THREE.OrthographicCamera(
frustumSize * aspect / -2,
frustumSize * aspect / 2,
frustumSize / 2,
frustumSize / -2,
1,
1000
);
camera.position.z = 2;
const scene = new THREE.Scene();
// Full-screen plane geometry
const planeGeometry = new THREE.PlaneGeometry(2 * aspect, 2);
window.textureLoader = new THREE.TextureLoader();
let rand_int_1_thru_17 = Math.floor(Math.random() * 17) + 1;
//let url = `./res/bg_${rand_int_1_thru_17}.png`;
//let url = "./res/download (3).png";
let url = "./res/inspiration/Bsodwindows10.png";
window.baseTexture = textureLoader.load(url);
window.mandlebulbTexture = textureLoader.load(url);
// define our textures / buffers
// 1. our starting values (provided by user image or video, etc)
window.originalPixelDataTexture = new THREE.DataTexture(
new Uint8Array(4 * fixedPixelsX * fixedPixelsY),
fixedPixelsX,
fixedPixelsY,
THREE.RGBAFormat,
THREE.UnsignedByteType
);
// 2. our target values
window.targetPixelDataTexture = new THREE.DataTexture(
new Uint8Array(4 * fixedPixelsX * fixedPixelsY),
fixedPixelsX,
fixedPixelsY,
THREE.RGBAFormat,
THREE.UnsignedByteType
);
// 3. our "accumulator" texture, which we use to lerp between the original and target textures
// this is our output buffer for now, but we may add additional buffers later
window.lerpedColorTexture = new THREE.DataTexture(
new Uint8Array(4 * fixedPixelsX * fixedPixelsY),
fixedPixelsX,
fixedPixelsY,
THREE.RGBAFormat,
THREE.UnsignedByteType
);
// 4. our "offset" buffer where we accumulate / calculate our offsets
window.offsetTexture = new THREE.DataTexture(
new Uint8Array(4 * fixedPixelsX * fixedPixelsY),
fixedPixelsX,
fixedPixelsY,
THREE.RGBAFormat,
THREE.UnsignedByteType
);
window.currentFrameTextureRT = new THREE.WebGLRenderTarget(pixelWidth, pixelHeight);
window.accumulationTextureRT = new THREE.WebGLRenderTarget(pixelWidth, pixelHeight);
window.accumulationTextureRT.texture.magFilter = THREE.NearestFilter;
window.accumulationTextureRT.texture.minFilter = THREE.NearestFilter;
window.accumulationTextureRT.needsUpdate = true;
// Assuming you have a texture loaded into a variable named 'texture'
window.baseTexture.wrapS = THREE.MirroredRepeatWrapping; // For horizontal mirroring
window.baseTexture.wrapT = THREE.MirroredRepeatWrapping; // For vertical mirroring
// do the same for mandlebulbTexture
window.mandlebulbTexture.wrapS = THREE.MirroredRepeatWrapping; // For horizontal mirroring
window.mandlebulbTexture.wrapT = THREE.MirroredRepeatWrapping; // For vertical mirroring
window.image_height = baseTexture.height;
// Set how many times the texture should repeat
baseTexture.repeat.set(2, 2); // Adjust as needed
mandlebulbTexture.repeat.set(2, 2); // Adjust as needed
/* Match ShaderToy uniforms for compatibility */
// Custom Shader
window.mouseRaw = new THREE.Vector4();
window.mouseLerping = new THREE.Vector4();
window.iMouseWheel = new THREE.Vector4();
// window.mandleBulbMaterial = new THREE.ShaderMaterial({
// uniforms: {
// iChannel0: { value: window.mandlebulbTexture },
// iResolution: { value: new THREE.Vector3(pixelWidth, pixelHeight, 1.0) },
// iMouse: { value: window.mouseLerping },
// iMouseRaw: { value: window.mouseRaw },
// iMouseWheel: { value: window.iMouseWheel },
// iTime: { value: 1.0 },
// },
// vertexShader: `void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
// fragmentShader: window.fragmentShaderSource,
// transparent: true, // Enable transparency
// });
window.shaderMaterial = new THREE.ShaderMaterial({
uniforms: {
iTime: { value: 1.0 },
iChannel0: { value: mandlebulbTexture },
iResolution: { value: new THREE.Vector3(window.innerWidth, window.innerHeight, 1.0) },
iMouse: { value: window.mouseLerping },
iMouseRaw: { value: window.mouseRaw },
iMouseWheel: { value: window.iMouseWheel }
},
vertexShader: `
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: window.fragmentShaderSource,
transparent: true, // Enable transparency
});
// do a SECOND material
// tied to combineTexturesShaderSource
window.shaderAccumulationMaterial = new THREE.ShaderMaterial({
uniforms: {
iChannel0: { value: window.mandlebulbTexture },
iChannel1: { value: window.accumulationTextureRT.texture },
iResolution: { value: new THREE.Vector3(window.innerWidth, window.innerHeight, 1.0) },
iMouse: { value: window.mouseLerping },
iMouseRaw: { value: window.mouseRaw },
iMouseWheel: { value: window.iMouseWheel },
iTime: { value: 1.0 },
},
vertexShader: `
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: combineTexturesShaderSource,
transparent: true, // Enable transparency
});
window.backPlane = new THREE.Mesh(planeGeometry, window.shaderMaterial);
scene.add(backPlane);
// Creating and adding the plane to the scene
window.plane = new THREE.Mesh(planeGeometry, window.shaderAccumulationMaterial);
scene.add(plane);
function resizeRendererToDisplaySize(renderer) {
canvas = renderer.domElement;
let width = window.innerWidth * window.PIXEL_RATIO;
let height = window.innerHeight * window.PIXEL_RATIO;
// force to even dimensions for ffmpeg compatibility
width = 2 * Math.floor(width / 2);
height = 2 * Math.floor(height / 2);
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
canvas.width = width;
canvas.height = height;
renderer.setSize(width, height, false);
}
return needResize;
}
window.mouseX = window.mouseY = 0;
document.addEventListener('mousemove', (e)=>{
window.mouseX = e.clientX;
window.mouseY = e.clientY;
});
window.vec2MouseWheelRaw = new THREE.Vector2();
window.vec2MouseWheelLerped = new THREE.Vector2();
function updateMouseUniform() {
// Normalize coordinates (0 to 1)
let normalizedX = window.mouseX / pixelWidth; //window.innerWidth;
let normalizedY = window.mouseY / pixelHeight; //window.innerHeight;
// Adjust for aspect ratio
const aspect = window.innerWidth / window.innerHeight;
if (aspect > 1) {
// Wider than tall
normalizedX = (normalizedX - 0.5) * aspect + 0.5;
} else {
// Taller than wide
normalizedY = (normalizedY - 0.5) / aspect + 0.5;
}
// offset to center of "quad"
normalizedX = normalizedX * 2 - 1;
normalizedY = normalizedY * 2 - 1;
// Set the shader uniform
// Implement ShaderToy compatibility:
// Shows how to use the mouse input (only left button supported):
// mouse.xy = mouse position during last button down
// abs(mouse.zw) = mouse position during last button click
// sign(mouse.z) = button is down
// sign(mouse.w) = button is clicked
let dist = Math.sqrt(normalizedX * normalizedX + normalizedY * normalizedY);
let magnitude = Math.min(dist, 1.0);
window.mouseRaw.set(
window.mouseX,
window.innerHeight - window.mouseY,
window.leftMouseDown ? 1 : -1,
0
);
window.mouseLerping.lerp(window.mouseRaw, .005 * magnitude);
shaderMaterial.uniforms.iMouseRaw.value.set(
window.mouseRaw.x,
window.mouseRaw.y,
window.mouseRaw.z,
0
);
shaderMaterial.uniforms.iMouse.value.set(
window.mouseLerping.x,
window.mouseLerping.y,
window.leftMouseDown ? 1 : -1,
0
);
vec2MouseWheelLerped.lerp(vec2MouseWheelRaw, .08);
// Set the shader uniform for the mouse wheel
// it's a vec4, first two are lerped, second two are raw
shaderMaterial.uniforms.iMouseWheel.value.set(
vec2MouseWheelLerped.x,
vec2MouseWheelLerped.y,
vec2MouseWheelRaw.x,
vec2MouseWheelRaw.y
);
// update our other shader
shaderAccumulationMaterial.uniforms.iMouseRaw.value.set(
window.mouseRaw.x,
window.mouseRaw.y,
window.mouseRaw.z,
0
);
shaderAccumulationMaterial.uniforms.iMouse.value.set(
window.mouseLerping.x,
window.mouseLerping.y,
window.leftMouseDown ? 1 : -1,
0
);
shaderAccumulationMaterial.uniforms.iMouseWheel.value.set(
vec2MouseWheelLerped.x,
vec2MouseWheelLerped.y,
vec2MouseWheelRaw.x,
vec2MouseWheelRaw.y
);
}
// Global variable to store the last played video
let lastPlayedVideo = null;
window.onVideoPause = function(){
window.fixedTime = shaderMaterial.uniforms.iTime.value;
if(!window.capturing && !handling_slow_motion_advance){
window.videoIsPlaying = false;
}
}
window.onVideoResume = function(){
window.fixedTime = null;
if(!window.capturing && !handling_slow_motion_advance){
window.videoIsPlaying = true;
}
}
window.createVideoElement = function(){
let video = document.createElement('video');
video.setAttribute('id', 'video');
video.crossOrigin = 'anonymous';
video.loop = true;
// Add an event listener for when the video ends
video.onended = pickOne;
video.onpause = onVideoPause;
video.onplay = onVideoResume;
//video.muted = true;
// min of the html attribute is 0.1,
// if we want to go lower, we need to simulate with pause and manual frame-stepping
// see: window.targetVideoPlaybackRate
video.playbackRate = 0.1;
video.pictureInPictureEnabled = true;
video.addEventListener('enterpictureinpicture', (event) => {
console.warn('enterpictureinpicture',event)
});
video.addEventListener('leavepictureinpicture', (event) => {
console.warn('leavepictureinpicture',event)
});
// video.addEventListener('loadedmetadata', (event) => {
// console.warn('loadedmetadata',event)
// });
document.body.appendChild(video);
window.theVideoplayerElement = video;
}
window.theVideoplayerElement = document.getElementById("video");
if(!window.theVideoplayerElement){
createVideoElement();
}
window.setVideoAsChannel = function(videoURL){
try{
//console.warn('setVideoAsChannel',videoURL)
let video = window.theVideoplayerElement;
video.src = videoURL;
video.autoplay = false; // true;
video.controls = true;
video.buffer = true;
video.play();
let needs_on_can_play_update = true;
video.oncanplay = function() {
if(needs_on_can_play_update){
needs_on_can_play_update = false;
window.videoTexture = new THREE.VideoTexture(video);
window.videoTexture.minFilter = THREE.LinearFilter;
window.videoTexture.magFilter = THREE.LinearFilter;
window.videoTexture.format = THREE.RGBFormat;
window.videoTexture.crossOrigin = 'anonymous';
window.videoTexture.needsUpdate = true;
setTimeout(()=>{
window.videoIsPlaying = true;
window.videoIsVirtuallyPlaying = true;
},1);
}
}
}catch(e){
console.error(e);
}
}
window.progressElement = document.getElementById("progress");
window.animate = function(time) {
if (resizeRendererToDisplaySize(renderer)) {
canvas = renderer.domElement;
console.warn('resizing');
camera.aspect = canvas.width / canvas.height;
camera.updateProjectionMatrix();
}
let _time = window.fixedTime ? window.fixedTime : time * 0.001;
// Use a custom shader material that combines the textures
window.shaderMaterial.uniforms.iChannel0.value = window.mandlebulbTexture.texture;
window.shaderAccumulationMaterial.uniforms.iChannel0.value
//= window.currentFrameTextureRT.texture;
= window.mandlebulbTexture.texture;
window.shaderAccumulationMaterial.uniforms.iChannel1.value
= accumulationTextureRT.texture;
window.shaderAccumulationMaterial.uniforms.iTime.value = _time;
shaderMaterial.uniforms.iTime.value = _time;
shaderMaterial.uniforms.iChannel0.value = accumulationTextureRT.texture;
shaderMaterial.uniforms.iResolution.value.set(pixelWidth, pixelHeight, 1.0);
window.accumulationTextureRT.needsUpdate = true;
// Update uniforms
updateMouseUniform();
// // Render the scene into the currentFrameTextureRT
// renderer.setRenderTarget(window.currentFrameTextureRT);
// renderer.render(scene, camera);
// // Use the rendered texture as input for the next pass
// shaderMaterial.uniforms.iChannel0.value = window.currentFrameTextureRT.texture;
// Render the accumulation pass to the screen
renderer.setRenderTarget(null);
renderer.render(scene, camera);
// Swap the textures
// let temp = window.currentFrameTextureRT;
// window.currentFrameTextureRT = window.accumulationTextureRT;
// window.accumulationTextureRT = temp;
// sub-frame playback
maybeAdvanceVideoOneFrame();
if(window.capturing){
// update recording progress
if (progressElement) {
// Calculate progress based on targetRecordingDurationSeconds
progressElement.value = (window.subframePlaybackCurrentFrame / maxFrames) * 100;
}
window.capturer.capture(canvas);
if(window.subframePlaybackCurrentFrame >= maxFrames){
window.stopCapture();
}else{
// emulate being called requestAnimationFrame with a DOMHighResTimeStamp
setTimeout(() => {
window.animate(time + window.currentFrameDelta);
}, 0);
}
}else{
// next frame
requestAnimationFrame(animate);
}
}
resizeRendererToDisplaySize(renderer);
// first frame...
requestAnimationFrame(animate);
// make sure we don't pick the same one back to back
// also make sure we auto switch to the next one after the end of the video
function pickOne(){