-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
1992 lines (1715 loc) · 57 KB
/
script.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
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
import * as THREE from "three";
import { AsciiEffect } from "three-ascii-effect";
import Stats from "three-stats";
import { DRACOLoader } from "three-draco-loader";
import { GLTFLoader } from "three-gltf-loader";
import { CSS3DRenderer, CSS3DObject } from "three-css-3d-renderer";
// ------------------------------------
// ------------- elements -------------
// ------------------------------------
const CURSOR_ACTION_SELECTOR = "#cursor-action";
const JUMBOTRON_DESCRIPTION_LINK_SELECTOR = "#jumbotron .description a";
const SCROLL_DOWN_INDICATOR_SELECTOR = "#jumbotron .scroll-down";
const SELECTED_WORK_BUTTONS_SELECTOR = "#selected-work .slide .button";
const FOOTER_LOGO_SELECTOR = "#footer .footer-logo";
const FOOTER_EMAIL_LINKS_SELECTOR = "#footer .email";
const FOOTER_SOCIAL_LINKS_SELECTOR = "#footer .social-media";
const html = document.documentElement;
const cursor = document.getElementById("cursor");
const cursorAction = document.querySelector(CURSOR_ACTION_SELECTOR);
const loadingScreen = document.getElementById("loading-screen");
const loadingScreenPercentageValue = loadingScreen.querySelector(".value");
const loadingScreenMobileStartButton = loadingScreen.querySelector(
".mobile-start-button"
);
const jumbotron = document.getElementById("jumbotron");
const jumbotronDescriptionLink = document.querySelector(
JUMBOTRON_DESCRIPTION_LINK_SELECTOR
);
const asciiLogoContainer = document.getElementById("ascii-logo");
const asciiLogoMobileOverlay =
asciiLogoContainer.querySelector(".mobile-overlay");
const scrollDownIndicator = document.querySelector(
SCROLL_DOWN_INDICATOR_SELECTOR
);
const selectedWork = document.getElementById("selected-work");
const selectedWorkSlides = selectedWork.querySelectorAll(".slide");
const laptopContainer = document.getElementById("laptop");
const laptopScreen = document.getElementById("laptop-screen");
const laptopScreenContainer = document.getElementById("screen-content");
let updatedScreenContent;
let infoPopup;
let infoPopupText;
const footer = document.getElementById("footer");
const footerBackground = footer.querySelector(".background");
const footerCarouselTrack = footer.querySelector(".carousel-track");
const footerLogo = document.querySelector(FOOTER_LOGO_SELECTOR);
const footerEmailLinks = document.querySelectorAll(FOOTER_EMAIL_LINKS_SELECTOR);
const footerSocialLinks = document.querySelectorAll(
FOOTER_SOCIAL_LINKS_SELECTOR
);
const scrollableContentSections = {
jumbotron: document.querySelector("#scrollable-content .jumbotron"),
selectedWork: document.querySelector("#scrollable-content .selected-work"),
footer: document.querySelector("#scrollable-content .footer"),
};
// ------------------------------------
// ----------- global vars ------------
// ------------------------------------
const asciiLogoScene = {
// geometryFile
// container
// mesh
// scene
// renderer (with effect)
// camera
// controls
};
const laptopScene = {
// geometryFile
// container
// mesh
// -- base
// -- lid
// -- screen
// scene
// renderer
// camera
// raycaster
// controls
};
const laptopScreenScene = {
// container
// mesh
// scene
// renderer
};
let statsScene;
const currentLoadingPercentages = {
ascii: 0,
laptop: 0,
fonts: 0,
images: 0,
};
let displayedTotalLoadingPercentage = 0;
const mousePosition = {
x: window.innerWidth / 2,
y: window.innerHeight / 2,
action: null,
clicked: false,
hoveredLink: undefined,
hoveredProject: undefined,
hasMoved: false,
};
let hasScrolledPastJumbotronThreshold = false;
let infoPopupWaitStatus;
let infoPopupHiddenAfterStarted = false;
let laptopMeshHoverCount = 0;
let laptopMeshHovering = false;
let scrollPosition = 0;
// ------------------------------------
// ------------ constants -------------
// ------------------------------------
const IS_CHROME = navigator.userAgent.toLowerCase().includes("chrome");
const IS_FIREFOX = navigator.userAgent.toLowerCase().includes("firefox");
const IS_TOUCH_DEVICE = navigator.maxTouchPoints > 0;
const ASCII_LOGO_FILE = "./models/logo.glb";
const LAPTOP_FILE = "./models/laptop.glb";
const DRACO_DECODER_URL =
"https://www.gstatic.com/draco/versioned/decoders/1.5.6/";
const ASCII_LOGO_FILE_SIZE_BYTES = 203996;
const LAPTOP_FILE_SIZE_BYTES = 70344;
const LOADING_WEIGHTS = {
// need to add up to 1
ascii: 0.25,
laptop: 0.25,
fonts: 0.25,
images: 0.25,
};
const START_TIME = Date.now();
const ASCII_LOGO_ROTATION_SCALAR = 0.2;
const ASCII_AUTO_ROTATION_SPEED = 0.0005;
const ASCII_AUTO_ROTATION_MAX_DIST = 0.4;
const ASCII_LOGO_INIT = {
rotation: { x: Math.PI / 2, y: 0, z: 0 },
};
const ASCII_LOGO_SCENE_CAMERA_Z_POS = 10;
const LAPTOP_INIT = {
position: { x: 0, y: -100, z: 0 },
rotation: { x: Math.PI / 20, y: 0, z: 0 },
scale: { x: 50, y: 50, z: 50 },
};
const LAPTOP_ROTATION_SCALARS = { x: 0.025, y: 0.05 };
const LAPTOP_LID_ROTATION_X = { close: Math.PI / 2, open: 0 };
const LAPTOP_SCENE_CAMERA_INIT_Z_POSITION = 750;
const SLIDE_PIXELATION_THRESHOLD = 0.5;
const BACKGROUND_DOT_SIZE = {
height: 10,
width: 6,
};
const INFO_POPUP_WAIT_TIME_SECONDS = 10;
const INFO_POPUP_MAX_HOVER_COUNT = 3;
const PIXELATION_MIN = 0;
const PIXELATION_MAX = 40;
const MOBILE_BREAKPOINT_MAX_WIDTH = 768;
const SlideLocation = {
LEFT: "LEFT",
CENTER: "CENTER",
RIGHT: "RIGHT",
};
const Projects = {
CINESPACE: "CINESPACE",
SIRIUS_XM: "SIRIUS_XM",
SPOTLIGHT: "SPOTLIGHT",
};
const ProjectUrls = {
[Projects.CINESPACE]: "https://cinespace.com",
[Projects.SIRIUS_XM]: "https://podcastreport2022.siriusxmmedia.com",
[Projects.SPOTLIGHT]: "https://spotlight.com",
};
const ProjectImages = {
[Projects.CINESPACE]: "images/cinespace.jpg",
[Projects.SIRIUS_XM]: "images/sirius-xm.jpg",
[Projects.SPOTLIGHT]: "images/spotlight.jpg",
};
const MouseActions = {
COPY_EMAIL: "copy email",
OPEN_LINK: "open link",
SCROLL_DOWN: "scroll down",
SCROLL_TO_TOP: "scroll to top",
VIEW_SITE: "view site",
};
const SceneType = {
ASCII_LOGO: "ASCII_LOGO",
LAPTOP: "LAPTOP",
};
const EMAIL_ADDRESS = "[email protected]";
const Links = {
LINKEDIN: "LINKEDIN",
GITHUB: "GITHUB",
SIGMA_COMPUTING: "SIGMA_COMPUTING",
WORKING_NOT_WORKING: "WORKING_NOT_WORKING",
};
const LinkDestinations = {
[Links.GITHUB]: "https://github.com/BiermanM",
[Links.LINKEDIN]: "https://linkedin.com/in/biermanm",
[Links.SIGMA_COMPUTING]: "https://sigmacomputing.com",
[Links.WORKING_NOT_WORKING]: "https://workingnotworking.com/108158-matthew",
};
// ------------------------------------
// --- device orientation controls ----
// ------------------------------------
// modified from old three.js code:
// https://github.com/mrdoob/three.js/blob/e62b253081438c030d6af1ee3c3346a89124f277/examples/jsm/controls/DeviceOrientationControls.js
const _zee = new THREE.Vector3(0, 0, 1);
const _euler = new THREE.Euler();
const _q0 = new THREE.Quaternion();
const _q1 = new THREE.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); // - PI/2 around the x-axis
const _changeEvent = { type: "change" };
const _rotationOrder = "YXZ";
class DeviceOrientationControls extends THREE.EventDispatcher {
constructor(object, sceneType) {
super();
this.sceneType = sceneType;
if (window.isSecureContext === false) {
console.error(
"THREE.DeviceOrientationControls: DeviceOrientationEvent is only available in secure contexts (https)"
);
}
const scope = this;
const EPS = 0.000001;
const lastQuaternion = new THREE.Quaternion();
this.object = object;
this.object.rotation.reorder(_rotationOrder);
this.enabled = true;
this.deviceOrientation = {};
this.screenOrientation = 0;
const onDeviceOrientationChangeEvent = function (event) {
scope.deviceOrientation = event;
};
const onScreenOrientationChangeEvent = function () {
// update this to use screen.orientation
// https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation
scope.screenOrientation = window.orientation || 0;
};
const setObjectQuaternion = function (object, alpha, beta, gamma, orient) {
_euler.set(beta, alpha, -gamma, _rotationOrder);
object.quaternion.setFromEuler(_euler);
object.quaternion.multiply(_q1);
object.quaternion.multiply(_q0.setFromAxisAngle(_zee, -orient));
if (scope.sceneType === SceneType.ASCII_LOGO) {
object.rotation.x += ASCII_LOGO_INIT.rotation.x;
object.rotation.y += ASCII_LOGO_INIT.rotation.y;
object.rotation.z += ASCII_LOGO_INIT.rotation.z;
} else if (scope.sceneType === SceneType.LAPTOP) {
object.rotation.x += LAPTOP_INIT.rotation.x;
object.rotation.y += LAPTOP_INIT.rotation.y;
object.rotation.z += LAPTOP_INIT.rotation.z;
}
};
this.connect = function () {
onScreenOrientationChangeEvent();
if (
window.DeviceOrientationEvent !== undefined &&
typeof window.DeviceOrientationEvent.requestPermission === "function"
) {
window.DeviceOrientationEvent.requestPermission()
.then(function (response) {
if (response == "granted") {
window.addEventListener(
"orientationchange",
onScreenOrientationChangeEvent
);
window.addEventListener(
"deviceorientation",
onDeviceOrientationChangeEvent
);
}
})
.catch(function (error) {
console.error(
"THREE.DeviceOrientationControls: Unable to use DeviceOrientation API:",
error
);
});
} else {
window.addEventListener(
"orientationchange",
onScreenOrientationChangeEvent
);
window.addEventListener(
"deviceorientation",
onDeviceOrientationChangeEvent
);
}
scope.enabled = true;
};
this.disconnect = function () {};
this.update = function () {
if (scope.enabled === false) {
return;
}
const isLaptop = scope.sceneType === SceneType.LAPTOP;
const isAsciiLogo = scope.sceneType === SceneType.ASCII_LOGO;
const device = scope.deviceOrientation;
const a = device.alpha || 0;
const b = device.beta || 0;
const g = device.gamma || 0;
const o = scope.screenOrientation || 0;
const aMagnitude = a > 180 ? a - 360 : a;
const bMagnitude = b - 90;
let SCALAR = 1;
if (isAsciiLogo) {
SCALAR = 0.6;
} else if (isLaptop) {
SCALAR = 0.4;
}
const aScaled = aMagnitude * (isAsciiLogo ? SCALAR : 1);
const bScaled = bMagnitude * SCALAR;
const gScaled = g * (isAsciiLogo ? SCALAR : 1);
const aWithDirection = aScaled < 0 ? 360 + aScaled : aScaled;
const bWithDirection = 90 + bScaled;
if (device) {
setObjectQuaternion(
scope.object,
THREE.MathUtils.degToRad(aWithDirection),
THREE.MathUtils.degToRad(bWithDirection),
THREE.MathUtils.degToRad(gScaled),
THREE.MathUtils.degToRad(o)
);
if (8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
lastQuaternion.copy(scope.object.quaternion);
scope.dispatchEvent(_changeEvent);
}
}
};
this.dispose = function () {
scope.disconnect();
};
this.connect();
}
}
// ------------------------------------
// ------------ math utils ------------
// ------------------------------------
const getValueInRangeFromPercentage = (percentage, [start, end]) =>
percentage * (end - start) + start;
const getPercentageInRangeFromValue = (value, [start, end]) =>
(value - start) / (end - start);
const clampWithinRange = (value, [start, end]) =>
Math.max(start, Math.min(value, end));
const roundToDecimalPlace = (value, numPlaces) =>
Math.round((value + Number.EPSILON) * Math.pow(10, numPlaces)) /
Math.pow(10, numPlaces);
// start: inclusive, end: exclusive
const range = (end, start = 0) =>
[...Array(end).keys()].filter((num) => num >= start);
const wait = (seconds) =>
new Promise((resolve) => setTimeout(resolve, seconds * 1000));
// ------------------------------------
// ---------- styling utils -----------
// ------------------------------------
const getWindowSize = () => ({
height: window.innerHeight,
width: window.innerWidth,
});
const getElementSize = (element) => ({
width: element.offsetWidth,
height: element.offsetHeight,
});
const applyStyles = (element, styles) => {
Object.entries(styles).forEach(([property, value]) => {
element.style[property] = value;
});
};
const parseTransformAttributeValue = (element) => {
const value = element.style.transform;
const functions = value.split(" ");
return Object.fromEntries(
functions
.map((fxn) => {
if (!fxn) {
return undefined;
}
const functionName = fxn.split("(")[0];
const functionValue = parseFloat(fxn.split("(")[1].split("px")[0]);
return isNaN(functionValue) ? undefined : [functionName, functionValue];
})
.filter((formattedFxn) => !!formattedFxn)
);
};
const isInMobileBreakpoint = () =>
getWindowSize().width <= MOBILE_BREAKPOINT_MAX_WIDTH;
// ------------------------------------
// ---------- three.js utils ----------
// ------------------------------------
const createPointLight = (intensity, x, y, z) => {
const pointLight = new THREE.PointLight(0xffffff, intensity, 0, 0);
pointLight.position.set(x, y, z);
return pointLight;
};
const createCamera = (z, container) => {
const { height, width } = getElementSize(container);
const camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);
camera.position.set(0, 0, z);
return camera;
};
const createScene = (background) => {
const scene = new THREE.Scene();
if (background) {
scene.background = background;
}
return scene;
};
const createRenderer = (container, alpha) => {
const { height, width } = getElementSize(container);
const highDpr = window.devicePixelRatio > 1;
const renderer = new THREE.WebGLRenderer({
alpha,
antialias: !highDpr,
powerPreference: "high-performance",
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(width, height);
return renderer;
};
const createCss3dRenderer = () => {
const { height, width } = getWindowSize();
const renderer = new CSS3DRenderer();
renderer.setSize(width, height);
applyStyles(renderer.domElement, { position: "absolute", top: 0 });
return renderer;
};
const createRendererWithAsciiShader = (
container,
charSet,
resolution,
invert,
textColor,
backgroundColor
) => {
const { height, width } = getElementSize(container);
const renderer = createRenderer(container);
const effect = new AsciiEffect(renderer, charSet, { resolution, invert });
effect.setSize(width, height);
applyStyles(effect.domElement, { backgroundColor, color: textColor });
return effect;
};
const createRaycaster = () => new THREE.Raycaster();
const addCss3dToObject = (container, obj) => {
const containerClone = container.cloneNode(true);
container.remove();
const css3dObject = new CSS3DObject(containerClone);
obj.css3dObject = css3dObject;
obj.add(css3dObject);
// make an invisible plane for the DOM element to chop
// clip a WebGL geometry with it.
obj.material = new THREE.MeshPhongMaterial({
opacity: 0.15,
color: new THREE.Color(0x111111),
blending: THREE.NoBlending,
});
const { max, min } = obj.geometry.boundingBox;
obj.geometry = new THREE.BoxGeometry(
max.x - min.x,
max.y - min.y,
max.z - min.z + 0.2
);
};
const connectRendererToDom = (scene) => {
scene.container.appendChild(scene.renderer.domElement);
};
const renderScene = (scene, cameraFromOtherScene) => {
scene.renderer.render(scene.scene, cameraFromOtherScene || scene.camera);
scene.controls?.update();
};
const renderStats = () => {
statsScene.update();
};
const updateRendererAndCameraSize = (scene, cameraFromOtherScene) => {
const camera = cameraFromOtherScene || scene.camera;
const { height, width } = getElementSize(scene.container);
camera.aspect = width / height;
camera.updateProjectionMatrix();
scene.renderer.setSize(width, height);
};
// ------------------------------------
// --------- positioning utils --------
// ------------------------------------
const getJumbotronScolledPercentage = () => {
const jumbotronPlaceholderHeight = getElementSize(
scrollableContentSections.jumbotron
).height;
return clampWithinRange(scrollPosition / jumbotronPlaceholderHeight, [0, 1]);
};
const getSelectedWorkSlideCount = () =>
Math.round(
getElementSize(scrollableContentSections.selectedWork).height /
getElementSize(selectedWork).height
);
const getScrolledPercentageWithinCurrentSlide = (slideIndex) => {
const slideCount = getSelectedWorkSlideCount();
const sectionStartPos = scrollableContentSections.selectedWork.offsetTop;
const startPos =
sectionStartPos +
getElementSize(scrollableContentSections.selectedWork).height *
(slideIndex / slideCount);
const endPos =
sectionStartPos +
getElementSize(scrollableContentSections.selectedWork).height *
((slideIndex + 1) / slideCount);
const scrolledPercentage = getPercentageInRangeFromValue(scrollPosition, [
startPos,
endPos,
]);
return scrolledPercentage >= 0 && scrolledPercentage <= 1
? scrolledPercentage
: undefined;
};
const getCurrentSlide = () => {
const slideCount = getSelectedWorkSlideCount();
const slidesPercentageScrolled = range(slideCount).map((index) =>
getScrolledPercentageWithinCurrentSlide(index)
);
const index = slidesPercentageScrolled.findIndex(
(percentageScrolled) => percentageScrolled !== undefined
);
const percentage = slidesPercentageScrolled[index];
return { index, percentage };
};
const getCurrentHoverableProject = () => {
const currentSlide = getCurrentSlide();
let currentProject;
if (
currentSlide.index === 1 ||
(currentSlide.index === 2 &&
currentSlide.percentage <= SLIDE_PIXELATION_THRESHOLD)
) {
currentProject = Projects.CINESPACE;
} else if (
(currentSlide.index === 3 &&
currentSlide.percentage > SLIDE_PIXELATION_THRESHOLD) ||
(currentSlide.index === 4 &&
currentSlide.percentage <= SLIDE_PIXELATION_THRESHOLD)
) {
currentProject = Projects.SPOTLIGHT;
} else if (
(currentSlide.index === 5 &&
currentSlide.percentage > SLIDE_PIXELATION_THRESHOLD) ||
(currentSlide.index === 6 &&
currentSlide.percentage <= SLIDE_PIXELATION_THRESHOLD)
) {
currentProject = Projects.SIRIUS_XM;
}
return currentProject;
};
const isLoadingComplete = () => displayedTotalLoadingPercentage === 100;
// only render after loading screen if scrolled 50% through jumbotron
const shouldRenderAsciiLogoScene = () =>
isLoadingComplete() && getJumbotronScolledPercentage() < 0.5;
// only render after loading screen if 50% scrolled through jumbotron or past jumbotron
const shouldRenderLaptopScene = () =>
isLoadingComplete() && getJumbotronScolledPercentage() > 0.5;
const smoothScrollToSlide = (slideIndex) => {
const slidesStartPos = scrollableContentSections.selectedWork.offsetTop;
const slideHeight = getWindowSize().height;
const scrollPos =
slideIndex === -1 ? 0 : slidesStartPos + slideHeight * slideIndex;
window.scrollTo({ left: 0, top: scrollPos, behavior: "smooth" });
};
// ------------------------------------
// ---------- main functions ----------
// ------------------------------------
const initPage = () => {
if (history.scrollRestoration) {
history.scrollRestoration = "manual";
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
};
}
applyStyles(html, { scrollBehavior: "smooth" });
if (IS_TOUCH_DEVICE) {
document.body.classList.add("is-touch-device");
}
if (IS_CHROME) {
document.body.classList.add("is-chrome");
}
if (IS_FIREFOX) {
document.body.classList.add("is-firefox");
}
};
const initImageLoaders = () => {
const imageUrls = Object.values(ProjectImages);
imageUrls.forEach((url) => {
const img = new Image();
img.onload = function () {
currentLoadingPercentages.images += 1 / imageUrls.length;
};
img.src = url;
});
};
const load3DModels = async () => {
const gltfLoader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath(DRACO_DECODER_URL);
gltfLoader.setDRACOLoader(dracoLoader);
asciiLogoScene.geometryFile = await gltfLoader.loadAsync(
ASCII_LOGO_FILE,
(progress) => {
currentLoadingPercentages.ascii =
progress.loaded / ASCII_LOGO_FILE_SIZE_BYTES;
}
);
laptopScene.geometryFile = await gltfLoader.loadAsync(
LAPTOP_FILE,
(progress) => {
currentLoadingPercentages.laptop =
progress.loaded / LAPTOP_FILE_SIZE_BYTES;
}
);
};
const createAsciiLogoMesh = (geometryFile) => {
const mesh = geometryFile.scene;
mesh.position.set(0, 0, 0);
mesh.rotation.set(0, 0, 0);
mesh.scale.set(1, 1, 1);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
};
const setLaptopMeshMaterials = (mesh) => {
if (mesh.name === "Cube008_2") {
mesh.material.side = THREE.FrontSide;
} else if (mesh.name === "keyboard") {
mesh.material = new THREE.MeshPhongMaterial({
color: 0x1a1a1a,
emissive: 0x000000,
specular: 0x111111,
shininess: 100,
side: THREE.FrontSide,
});
}
(mesh.children || []).forEach((child) => setLaptopMeshMaterials(child));
};
const createLaptopMesh = (geometryFile) => {
const base = geometryFile.scene;
setLaptopMeshMaterials(base);
const lid = base.children[0];
const screen = lid.children[0].children[2];
base.position.set(
LAPTOP_INIT.position.x,
LAPTOP_INIT.position.y,
LAPTOP_INIT.position.z
);
base.rotation.set(
LAPTOP_INIT.rotation.x,
LAPTOP_INIT.rotation.y,
LAPTOP_INIT.rotation.z
);
base.scale.set(LAPTOP_INIT.scale.x, LAPTOP_INIT.scale.y, LAPTOP_INIT.scale.z);
base.castShadow = true;
base.receiveShadow = true;
return { base, lid, screen };
};
const initAllScenes = () => {
const { height: vh, width: vw } = getWindowSize();
const screenPixelArea = vw * vh;
// ascii logo scene
const asciiShaderResolution =
0.18 - 0.00000005 * Math.max(screenPixelArea - 1500000, 0);
asciiLogoScene.container = asciiLogoContainer;
asciiLogoScene.mesh = createAsciiLogoMesh(asciiLogoScene.geometryFile);
asciiLogoScene.scene = createScene(new THREE.Color(0, 0, 0));
asciiLogoScene.renderer = createRendererWithAsciiShader(
asciiLogoScene.container,
".:-+*=%@#&",
asciiShaderResolution,
true,
"var(--black)",
"var(--white)"
);
asciiLogoScene.camera = createCamera(
ASCII_LOGO_SCENE_CAMERA_Z_POS,
asciiLogoScene.container
);
asciiLogoScene.scene.add(createPointLight(3, 0, 0, 500), asciiLogoScene.mesh);
connectRendererToDom(asciiLogoScene);
// laptop scene
laptopScene.container = laptopContainer;
laptopScene.mesh = createLaptopMesh(laptopScene.geometryFile);
addCss3dToObject(laptopScreenContainer, laptopScene.mesh.screen);
laptopScene.scene = createScene();
laptopScene.renderer = createRenderer(laptopScene.container, true);
laptopScene.camera = createCamera(
LAPTOP_SCENE_CAMERA_INIT_Z_POSITION,
laptopScene.container
);
laptopScene.raycaster = createRaycaster();
laptopScene.scene.add(
createPointLight(3.5, 0, 700, 750),
createPointLight(0.05, -300, 100, 100),
laptopScene.mesh.base
);
connectRendererToDom(laptopScene);
// laptop screen scene
laptopScreenScene.container = laptopScreen;
laptopScreenScene.mesh = laptopScene.mesh.screen.css3dObject;
laptopScreenScene.scene = createScene();
laptopScreenScene.renderer = createCss3dRenderer();
laptopScreenScene.scene.add(laptopScreenScene.mesh);
connectRendererToDom(laptopScreenScene);
// stats scene
const searchParams = new URLSearchParams(window.location.search);
const isDebug = searchParams.get("debug") === "true";
if (isDebug) {
statsScene = new Stats();
document.body.appendChild(statsScene.dom);
}
};
const renderLoop = () => {
const newScrollPosition = window.scrollY;
const hasScrolled = scrollPosition !== newScrollPosition;
const hasScrolledOrMovedCursorOrIsTouchDevice =
(IS_TOUCH_DEVICE && asciiLogoScene.controls) ||
hasScrolled ||
mousePosition.hasMoved;
if (hasScrolledOrMovedCursorOrIsTouchDevice) {
if (hasScrolled) {
scrollPosition = newScrollPosition;
onScroll();
}
if (shouldRenderLaptopScene()) {
renderScene(laptopScene);
renderScene(laptopScreenScene, laptopScene.camera);
if (IS_TOUCH_DEVICE) {
syncLaptopScreen();
}
}
if (shouldRenderAsciiLogoScene()) {
renderScene(asciiLogoScene);
updateAsciiLogoRotation();
}
}
if (statsScene) {
renderStats();
}
mousePosition.hasMoved = false;
requestAnimationFrame(renderLoop);
};
const setMousePosition = (mouseOrTouchEvent, isTouch) => {
const { height: vh, width: vw } = getWindowSize();
const { x, y } = mousePosition;
let eventClientX;
if (mouseOrTouchEvent && isTouch) {
eventClientX = mouseOrTouchEvent.changedTouches[0].clientX;
} else if (mouseOrTouchEvent && !isTouch) {
eventClientX = mouseOrTouchEvent.clientX;
}
let eventClientY;
if (mouseOrTouchEvent && isTouch) {
eventClientY = mouseOrTouchEvent.changedTouches[0].clientY;
} else if (mouseOrTouchEvent && !isTouch) {
eventClientY = mouseOrTouchEvent.clientY;
}
mousePosition.x = eventClientX || Math.min(x, vw);
mousePosition.y = eventClientY || Math.min(y, vh);
mousePosition.hasMoved = true;
setCursorSizeAndPosition();
};
const updateMouseAction = (action, hoveredProject, hoveredLink) => {
const { action: prevMouseAction } = mousePosition;
mousePosition.action = action || null;
mousePosition.hoveredProject = hoveredProject;
mousePosition.hoveredLink = hoveredLink;
if (action && !prevMouseAction) {
if (action === MouseActions.VIEW_SITE && hoveredProject) {
cursorAction.innerHTML = `${action}<a href="${
ProjectUrls[mousePosition.hoveredProject]
}" target="_blank"></a>`;
} else if (action !== MouseActions.VIEW_SITE) {
cursorAction.innerText = action;
}
} else if (!action) {
cursorAction.innerText = "";
}
};
const setCursorSizeAndPosition = () => {
const { action, clicked, x, y } = mousePosition;
const CURSOR_SIZE = 16;
const CURSOR_ACTION_SIZE = 56;
applyStyles(cursor, {
translate: `${x - CURSOR_SIZE / 2}px ${y - CURSOR_SIZE / 2}px 0`,
scale: clicked ? 0.75 : 1,
});
applyStyles(cursorAction, {
translate: `${x - CURSOR_ACTION_SIZE / 2}px ${
y - CURSOR_ACTION_SIZE / 2
}px 0`,
scale: action ? (clicked ? 0.9 : 1) : 0,
});
};
// rotate 3D model based on mouse position
const updateAsciiLogoRotation = () => {
const percentageScrolled = getJumbotronScolledPercentage();
const { x: initX, y: initY, z: initZ } = ASCII_LOGO_INIT.rotation;
if (!shouldRenderAsciiLogoScene()) {
return;
}
// if controls for scene exist, it's using those to control the mesh rotation
if (asciiLogoScene.controls) {
return;
}
// if touch device but controls not connected, auto rotate
if (IS_TOUCH_DEVICE) {
const timer = Date.now() - START_TIME;
asciiLogoScene.mesh.rotation.set(
initX +
Math.sin(timer * ASCII_AUTO_ROTATION_SPEED) *
ASCII_AUTO_ROTATION_MAX_DIST,
initY,
initZ +
Math.cos(timer * ASCII_AUTO_ROTATION_SPEED) *
ASCII_AUTO_ROTATION_MAX_DIST
);
return;
}
const { height: vh, width: vw } = getWindowSize();
const dampen =
1 - getPercentageInRangeFromValue(percentageScrolled, [0, 0.5]);
asciiLogoScene.mesh.rotation.set(
initX +
(Math.PI * (mousePosition.y / vh) * 2 - Math.PI) *
ASCII_LOGO_ROTATION_SCALAR *
dampen,
initY,
initZ +
(Math.PI * (mousePosition.x / vw) * 2 - Math.PI) *
ASCII_LOGO_ROTATION_SCALAR *
dampen *
-1
);
};
// rotate 3D model based on mouse position
const updateLaptopRotation = () => {
if (!shouldRenderLaptopScene()) {