-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathportal.html
More file actions
1657 lines (1405 loc) · 63.4 KB
/
portal.html
File metadata and controls
1657 lines (1405 loc) · 63.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
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>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#87CEEB">
<meta name="application-name" content="IdleGames">
<script src="assets/js/pwa.js" defer></script>
<title>Portal World</title>
<style>
:root {
color-scheme: dark light;
--bg: #87CEEB;
--text: #1e293b;
--panel-bg: rgba(255, 255, 255, 0.85);
--panel-border: rgba(0, 0, 0, 0.1);
font-family: "Inter", "Segoe UI", system-ui, sans-serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
height: 100vh;
overflow: hidden;
background: var(--bg);
color: var(--text);
}
#gameContainer {
position: relative;
width: 100%;
height: 100%;
}
#viewport {
width: 100%;
height: 100%;
display: block;
}
#hud {
position: absolute;
top: 10px;
left: 10px;
padding: 12px 16px;
background: var(--panel-bg);
border: 1px solid var(--panel-border);
border-radius: 12px;
backdrop-filter: blur(10px);
font-size: 13px;
line-height: 1.6;
z-index: 10;
pointer-events: none;
max-width: 280px;
}
#hud h3 {
margin: 0 0 8px 0;
font-size: 15px;
font-weight: 600;
}
#hud kbd {
display: inline-block;
padding: 2px 6px;
background: rgba(0, 0, 0, 0.08);
border-radius: 4px;
font-family: monospace;
font-size: 12px;
}
#crosshair {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 8px;
height: 8px;
border: 2px solid rgba(255, 255, 255, 0.7);
border-radius: 50%;
pointer-events: none;
z-index: 5;
mix-blend-mode: difference;
}
#loadingOverlay {
position: absolute;
inset: 0;
background: linear-gradient(135deg, #87CEEB 0%, #98D8C8 100%);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 100;
transition: opacity 0.5s ease-out;
}
#loadingOverlay.hidden {
opacity: 0;
pointer-events: none;
}
#loadingOverlay h1 {
font-size: 32px;
margin: 0 0 20px 0;
color: #2d5a4a;
}
#loadingOverlay p {
font-size: 16px;
color: #3d6a5a;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid rgba(45, 90, 74, 0.2);
border-top-color: #2d5a4a;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 20px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
#clickToStart {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.4);
display: flex;
align-items: center;
justify-content: center;
z-index: 50;
cursor: pointer;
}
#clickToStart.hidden {
display: none;
}
#clickToStart span {
background: white;
padding: 20px 40px;
border-radius: 12px;
font-size: 18px;
font-weight: 600;
color: #2d5a4a;
}
</style>
</head>
<body>
<div id="gameContainer">
<canvas id="viewport"></canvas>
<div id="crosshair"></div>
<div id="hud">
<h3>🌀 Portal World</h3>
<div><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> Move</div>
<div><kbd>Double-tap</kbd> Sprint</div>
<div><kbd>Space</kbd> Jump</div>
<div><kbd>Mouse</kbd> Look around</div>
<div style="margin-top: 8px; opacity: 0.7; font-size: 12px;">
Walk through portals to reach higher levels!
</div>
</div>
<div id="loadingOverlay">
<div class="spinner"></div>
<h1>Portal World</h1>
<p>Loading assets...</p>
</div>
<div id="clickToStart">
<span>Click to Play</span>
</div>
</div>
<script type="module">
// ═══════════════════════════════════════════════════════════════════════════
// THREE.JS IMPORT WITH FALLBACK
// ═══════════════════════════════════════════════════════════════════════════
const CDN_THREE_BASE = 'https://cdn.jsdelivr.net/npm/three@0.184.0';
async function importWithFallback(primary, fallback) {
try {
return await import(primary);
} catch (error) {
console.warn(`Failed to load ${primary}; attempting CDN fallback.`, error);
if (!fallback) throw error;
try {
return await import(fallback);
} catch (fallbackError) {
console.error(`Fallback import for ${primary} also failed.`, fallbackError);
throw fallbackError;
}
}
}
const THREE = await importWithFallback(
'./assets/vendor/three/three.module.js',
`${CDN_THREE_BASE}/build/three.module.js`
);
// ═══════════════════════════════════════════════════════════════════════════
// CFFR COORDINATE SYSTEM CONSTANTS
// Frame of Reference: +X = East, +Y = North, +Z = Up (like Second Life)
// ═══════════════════════════════════════════════════════════════════════════
const CFFR = {
EAST: new THREE.Vector3(1, 0, 0), // +X
NORTH: new THREE.Vector3(0, 1, 0), // +Y
UP: new THREE.Vector3(0, 0, 1), // +Z
WEST: new THREE.Vector3(-1, 0, 0),
SOUTH: new THREE.Vector3(0, -1, 0),
DOWN: new THREE.Vector3(0, 0, -1),
};
// World dimensions in meters
const WORLD = {
SIZE_X: 100, // East-West extent
SIZE_Y: 100, // North-South extent
SIZE_Z: 100, // Vertical extent (Up-Down)
CENTER: new THREE.Vector3(50, 50, 0),
};
// Player measurements (5'9" = 1.7526m)
const PLAYER = {
HEIGHT: 1.7526,
EYE_HEIGHT: 1.62, // Eyes slightly below top of head
RADIUS: 0.3, // Collision radius
WALK_SPEED: 1.4, // m/s (average walking speed)
SPRINT_SPEED: 5.5, // m/s (jogging speed)
JUMP_VELOCITY: 5.0, // m/s initial upward velocity
GRAVITY: 9.81, // m/s²
SHOULDER_OFFSET: 0.35, // Camera offset to the right
CAMERA_BACK: 2.5, // Camera distance behind player
CAMERA_UP: 0.3, // Camera height above eye level
};
// Terrain level heights
const TERRAIN_LEVELS = [
{ z: 0, name: 'Ground Level' },
{ z: 8, name: 'First Plateau' },
{ z: 18, name: 'Second Plateau' },
{ z: 30, name: 'Summit' },
];
// ═══════════════════════════════════════════════════════════════════════════
// UTILITY FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════
// Convert CFFR coordinates to Three.js coordinates
// Three.js uses: +X right, +Y up, +Z toward camera
// CFFR uses: +X East, +Y North, +Z Up
// Mapping: CFFR.X -> Three.X, CFFR.Y -> Three.Z (negated), CFFR.Z -> Three.Y
function cffrToThree(x, y, z) {
return new THREE.Vector3(x, z, -y);
}
function cffrVecToThree(vec) {
return new THREE.Vector3(vec.x, vec.z, -vec.y);
}
function threeVecToCffr(vec) {
return new THREE.Vector3(vec.x, -vec.z, vec.y);
}
function randomRange(min, max) {
return Math.random() * (max - min) + min;
}
function lerp(a, b, t) {
return a + (b - a) * t;
}
// ═══════════════════════════════════════════════════════════════════════════
// SCENE SETUP
// ═══════════════════════════════════════════════════════════════════════════
const canvas = document.getElementById('viewport');
const scene = new THREE.Scene();
// Sky color
scene.background = new THREE.Color(0x87CEEB);
scene.fog = new THREE.Fog(0x87CEEB, 50, 150);
// Camera (will be positioned by player controller)
const camera = new THREE.PerspectiveCamera(
70,
window.innerWidth / window.innerHeight,
0.1,
500
);
// Renderer
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: 'high-performance'
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
// ═══════════════════════════════════════════════════════════════════════════
// LIGHTING (Sunlit Daytime)
// ═══════════════════════════════════════════════════════════════════════════
const ambientLight = new THREE.AmbientLight(0x9DC8E8, 0.5);
scene.add(ambientLight);
const sunLight = new THREE.DirectionalLight(0xFFFAE6, 1.8);
sunLight.position.copy(cffrToThree(80, 60, 100));
sunLight.castShadow = true;
sunLight.shadow.mapSize.width = 2048;
sunLight.shadow.mapSize.height = 2048;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 200;
sunLight.shadow.camera.left = -80;
sunLight.shadow.camera.right = 80;
sunLight.shadow.camera.top = 80;
sunLight.shadow.camera.bottom = -80;
sunLight.shadow.bias = -0.0005;
scene.add(sunLight);
scene.add(sunLight.target);
sunLight.target.position.copy(cffrToThree(50, 50, 0));
// Hemisphere light for natural sky/ground color blending
const hemiLight = new THREE.HemisphereLight(0x87CEEB, 0x556B2F, 0.4);
scene.add(hemiLight);
// ═══════════════════════════════════════════════════════════════════════════
// MATERIALS
// ═══════════════════════════════════════════════════════════════════════════
const materials = {
grass: new THREE.MeshLambertMaterial({ color: 0x4CAF50 }),
grassDark: new THREE.MeshLambertMaterial({ color: 0x388E3C }),
cliff: new THREE.MeshLambertMaterial({ color: 0x8B7355 }),
cliffDark: new THREE.MeshLambertMaterial({ color: 0x6B5344 }),
rock: new THREE.MeshLambertMaterial({ color: 0x808080 }),
rockDark: new THREE.MeshLambertMaterial({ color: 0x606060 }),
stone: new THREE.MeshLambertMaterial({ color: 0x9E9E9E }),
stoneDark: new THREE.MeshLambertMaterial({ color: 0x757575 }),
portalFrame: new THREE.MeshLambertMaterial({ color: 0x5D4E37 }),
portalGlow: new THREE.MeshBasicMaterial({
color: 0x00FFFF,
transparent: true,
opacity: 0.6,
side: THREE.DoubleSide
}),
portalPlaceholder: new THREE.MeshBasicMaterial({
color: 0x4488FF,
transparent: true,
opacity: 0.4,
side: THREE.DoubleSide
}),
player: new THREE.MeshLambertMaterial({ color: 0xE07B39 }),
playerShirt: new THREE.MeshLambertMaterial({ color: 0x3498DB }),
playerPants: new THREE.MeshLambertMaterial({ color: 0x2C3E50 }),
};
// ═══════════════════════════════════════════════════════════════════════════
// PORTAL DEFINITIONS
// ═══════════════════════════════════════════════════════════════════════════
// Portal definitions: [fromLevel, toLevel, fromPos, fromRot, toPos, toRot]
const PORTAL_DEFS = [
// Ground to First Plateau
// Ground portals positioned away from cliff bases, reachable from player start (50, 45)
{ from: { level: 0, x: 50, y: 15, rot: 0 },
to: { level: 1, x: 30, y: 30, rot: Math.PI } },
// Ground to First Plateau (alternate) - near the other plateau
{ from: { level: 0, x: 75, y: 85, rot: -Math.PI * 0.5 },
to: { level: 1, x: 70, y: 65, rot: Math.PI * 0.5 } },
// First Plateau to Second (from first plateau shape 0 to second plateau shape 0)
{ from: { level: 1, x: 38, y: 38, rot: Math.PI * 0.25 },
to: { level: 2, x: 55, y: 40, rot: -Math.PI * 0.75 } },
// First Plateau to Second (alternate - from first plateau shape 1 to second plateau shape 1)
{ from: { level: 1, x: 62, y: 58, rot: -Math.PI * 0.75 },
to: { level: 2, x: 35, y: 65, rot: Math.PI * 0.25 } },
// Second to Summit (from second plateau shape 0 to summit)
{ from: { level: 2, x: 50, y: 35, rot: Math.PI * 0.5 },
to: { level: 3, x: 50, y: 52, rot: -Math.PI * 0.5 } },
];
// ═══════════════════════════════════════════════════════════════════════════
// TERRAIN GENERATION
// ═══════════════════════════════════════════════════════════════════════════
const terrainGroup = new THREE.Group();
scene.add(terrainGroup);
// Ground collision data (for physics)
const groundSegments = [];
// Cliff collision data - stores ellipse boundaries for each level
const cliffColliders = [];
function createTerrainLevel(levelIndex) {
const level = TERRAIN_LEVELS[levelIndex];
const nextLevel = TERRAIN_LEVELS[levelIndex + 1];
const group = new THREE.Group();
// Define platform shapes for each level
let platformShapes = [];
if (levelIndex === 0) {
// Ground level - large base
platformShapes = [
{ cx: 50, cy: 50, rx: 45, ry: 45, type: 'ellipse' }
];
} else if (levelIndex === 1) {
// First plateau - medium platforms
platformShapes = [
{ cx: 30, cy: 30, rx: 18, ry: 15, type: 'ellipse' },
{ cx: 70, cy: 65, rx: 20, ry: 18, type: 'ellipse' },
];
} else if (levelIndex === 2) {
// Second plateau - smaller platforms
platformShapes = [
{ cx: 55, cy: 40, rx: 14, ry: 12, type: 'ellipse' },
{ cx: 35, cy: 70, rx: 12, ry: 10, type: 'ellipse' },
];
} else if (levelIndex === 3) {
// Summit - small platform
platformShapes = [
{ cx: 50, cy: 55, rx: 10, ry: 8, type: 'ellipse' },
];
}
platformShapes.forEach((shape, shapeIndex) => {
const segments = 16 + levelIndex * 4;
const noiseValues = [];
for (let i = 0; i < segments; i++) {
noiseValues.push(0.9 + Math.random() * 0.2);
}
// Create grass top surface (low-poly)
const topGeo = createLowPolyEllipse(shape.rx, shape.ry, segments, noiseValues);
const topMesh = new THREE.Mesh(topGeo, levelIndex % 2 === 0 ? materials.grass : materials.grassDark);
topMesh.position.copy(cffrToThree(shape.cx, shape.cy, level.z));
topMesh.rotation.x = -Math.PI / 2;
topMesh.receiveShadow = true;
topMesh.castShadow = false;
group.add(topMesh);
// Store ground segment for collision
groundSegments.push({
type: 'ellipse',
cx: shape.cx,
cy: shape.cy,
rx: shape.rx,
ry: shape.ry,
z: level.z,
levelIndex
});
// Store cliff collider for horizontal collision detection
if (levelIndex > 0) {
cliffColliders.push({
cx: shape.cx,
cy: shape.cy,
rx: shape.rx + 0.5, // Slightly larger for collision
ry: shape.ry + 0.5,
baseZ: 0,
topZ: level.z,
levelIndex
});
}
// Create cliff sides extending all the way to ground level
const cliffHeight = levelIndex === 0 ? 3 : level.z;
createCliffSides(group, shape, level.z, cliffHeight, levelIndex, segments, noiseValues);
// Add grass edge overhang
createGrassOverhang(group, shape, level.z, levelIndex, segments, noiseValues);
// Add decorative rocks
addRocks(group, shape, level.z, levelIndex);
});
return group;
}
function createLowPolyEllipse(rx, ry, segments, noiseValues) {
const shape = new THREE.Shape();
for (let i = 0; i <= segments; i++) {
const angle = (i / segments) * Math.PI * 2;
// Use modulo to wrap around noise values for the last vertex
const noise = noiseValues[i % segments];
const x = Math.cos(angle) * rx * noise;
const y = Math.sin(angle) * ry * noise;
if (i === 0) shape.moveTo(x, y);
else shape.lineTo(x, y);
}
return new THREE.ShapeGeometry(shape);
}
function createCliffSides(group, shape, topZ, height, levelIndex, segments, noiseValues) {
const positions = [];
const indices = [];
// Pre-calculate bottom outsets
const bottomOutsets = [];
for (let i = 0; i < segments; i++) {
bottomOutsets.push(0.5 + Math.random() * 0.5);
}
// Generate cliff vertices
for (let i = 0; i <= segments; i++) {
const angle = (i / segments) * Math.PI * 2;
const idx = i % segments;
const noise = noiseValues[idx];
const bottomOutset = bottomOutsets[idx];
// Top edge (slightly inward for overhang effect)
const topInset = 0.3;
const topX = shape.cx + Math.cos(angle) * (shape.rx - topInset) * noise;
const topY = shape.cy + Math.sin(angle) * (shape.ry - topInset) * noise;
const topPos = cffrToThree(topX, topY, topZ);
positions.push(topPos.x, topPos.y, topPos.z);
// Bottom edge (outward for rugged cliff)
const bottomX = shape.cx + Math.cos(angle) * (shape.rx + bottomOutset);
const bottomY = shape.cy + Math.sin(angle) * (shape.ry + bottomOutset);
const bottomPos = cffrToThree(bottomX, bottomY, topZ - height);
positions.push(bottomPos.x, bottomPos.y, bottomPos.z);
}
// Create faces
for (let i = 0; i < segments; i++) {
const topLeft = i * 2;
const bottomLeft = i * 2 + 1;
const topRight = (i + 1) * 2;
const bottomRight = (i + 1) * 2 + 1;
indices.push(topLeft, bottomLeft, topRight);
indices.push(bottomLeft, bottomRight, topRight);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
const cliffMesh = new THREE.Mesh(
geometry,
levelIndex % 2 === 0 ? materials.cliff : materials.cliffDark
);
cliffMesh.castShadow = true;
cliffMesh.receiveShadow = true;
group.add(cliffMesh);
}
function createGrassOverhang(group, shape, topZ, levelIndex, segments, noiseValues) {
const overhangWidth = 0.8;
const overhangDrop = 0.15;
for (let i = 0; i < segments; i++) {
const angle1 = (i / segments) * Math.PI * 2;
const angle2 = ((i + 1) / segments) * Math.PI * 2;
// Random grass tufts along edge
if (Math.random() > 0.3) {
const midAngle = (angle1 + angle2) / 2;
// Interpolate noise
const n1 = noiseValues[i];
const n2 = noiseValues[(i + 1) % segments];
const noise = (n1 + n2) / 2;
const edgeX = shape.cx + Math.cos(midAngle) * shape.rx * noise;
const edgeY = shape.cy + Math.sin(midAngle) * shape.ry * noise;
// Create grass tuft geometry
const tuftGeo = new THREE.ConeGeometry(0.3 + Math.random() * 0.3, 0.5 + Math.random() * 0.3, 4);
const tuft = new THREE.Mesh(tuftGeo, materials.grass);
const pos = cffrToThree(edgeX, edgeY, topZ - 0.1);
tuft.position.copy(pos);
tuft.rotation.x = Math.PI; // Point down
tuft.rotation.z = Math.random() * 0.3 - 0.15;
tuft.castShadow = true;
group.add(tuft);
}
}
}
function addRocks(group, shape, topZ, levelIndex) {
const rockCount = 5 + Math.floor(Math.random() * 8);
for (let i = 0; i < rockCount; i++) {
// Position rock randomly within platform
const angle = Math.random() * Math.PI * 2;
const dist = Math.random() * 0.7; // Keep within 70% of edge
const x = shape.cx + Math.cos(angle) * shape.rx * dist;
const y = shape.cy + Math.sin(angle) * shape.ry * dist;
// Check distance to any portal on this level
let tooClose = false;
for (const def of PORTAL_DEFS) {
// Check 'from' portal
if (def.from.level === levelIndex) {
const dx = x - def.from.x;
const dy = y - def.from.y;
if (dx*dx + dy*dy < 16) { // 4m radius
tooClose = true;
break;
}
}
// Check 'to' portal
if (def.to.level === levelIndex) {
const dx = x - def.to.x;
const dy = y - def.to.y;
if (dx*dx + dy*dy < 16) { // 4m radius
tooClose = true;
break;
}
}
}
if (tooClose) continue;
// Random rock size
const size = 0.3 + Math.random() * 0.8;
// Create low-poly rock (irregular icosahedron)
const rockGeo = new THREE.IcosahedronGeometry(size, 0);
// Distort vertices for more natural look
distortGeometry(rockGeo, size * 0.3);
const rock = new THREE.Mesh(
rockGeo,
Math.random() > 0.5 ? materials.rock : materials.rockDark
);
const pos = cffrToThree(x, y, topZ + size * 0.3);
rock.position.copy(pos);
rock.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
rock.castShadow = true;
rock.receiveShadow = true;
group.add(rock);
}
}
// Create all terrain levels
TERRAIN_LEVELS.forEach((level, index) => {
const levelGroup = createTerrainLevel(index);
terrainGroup.add(levelGroup);
});
// ═══════════════════════════════════════════════════════════════════════════
// PORTAL SYSTEM
// ═══════════════════════════════════════════════════════════════════════════
const portals = [];
const portalRenderTargets = new Map();
// Helper to distort geometry while keeping it watertight
function distortGeometry(geometry, amount) {
const posAttribute = geometry.getAttribute('position');
const vertexMap = new Map();
const precision = 1000; // Round to 3 decimal places for matching
// 1. Identify unique vertices and generate offsets
for (let i = 0; i < posAttribute.count; i++) {
const x = posAttribute.getX(i);
const y = posAttribute.getY(i);
const z = posAttribute.getZ(i);
// Create a key based on position
const key = `${Math.round(x * precision)},${Math.round(y * precision)},${Math.round(z * precision)}`;
if (!vertexMap.has(key)) {
vertexMap.set(key, {
x: (Math.random() - 0.5) * amount,
y: (Math.random() - 0.5) * amount,
z: (Math.random() - 0.5) * amount
});
}
}
// 2. Apply offsets
for (let i = 0; i < posAttribute.count; i++) {
const x = posAttribute.getX(i);
const y = posAttribute.getY(i);
const z = posAttribute.getZ(i);
const key = `${Math.round(x * precision)},${Math.round(y * precision)},${Math.round(z * precision)}`;
const offset = vertexMap.get(key);
posAttribute.setX(i, x + offset.x);
posAttribute.setY(i, y + offset.y);
posAttribute.setZ(i, z + offset.z);
}
posAttribute.needsUpdate = true;
geometry.computeVertexNormals();
return geometry;
}
class Portal {
constructor(id, position, rotation, destination) {
this.id = id;
this.position = position.clone(); // CFFR coordinates
this.rotation = rotation; // Rotation around Z axis (yaw)
this.destination = destination; // Reference to destination portal
this.destinationId = null; // For linking later
this.group = new THREE.Group();
this.portalPlane = null;
this.isNearest = false;
this.placeholderTime = 0;
this.createMesh();
}
createMesh() {
const frameWidth = 2.5;
const frameHeight = 3.0;
const frameDepth = 0.4;
const stoneSize = 0.5;
// Create stone frame pieces
const createStone = (w, h, d) => {
const geo = new THREE.BoxGeometry(w, h, d);
// Distort for low-poly look using watertight helper
distortGeometry(geo, 0.05);
return geo;
};
// Left pillar
const leftPillar = new THREE.Mesh(
createStone(stoneSize, frameHeight, frameDepth),
materials.stone
);
leftPillar.position.set(-frameWidth / 2, frameHeight / 2, 0);
leftPillar.castShadow = true;
leftPillar.receiveShadow = true;
this.group.add(leftPillar);
// Right pillar
const rightPillar = new THREE.Mesh(
createStone(stoneSize, frameHeight, frameDepth),
materials.stone
);
rightPillar.position.set(frameWidth / 2, frameHeight / 2, 0);
rightPillar.castShadow = true;
rightPillar.receiveShadow = true;
this.group.add(rightPillar);
// Top lintel
const lintel = new THREE.Mesh(
createStone(frameWidth + stoneSize, stoneSize * 0.8, frameDepth),
materials.stoneDark
);
lintel.position.set(0, frameHeight + stoneSize * 0.3, 0);
lintel.castShadow = true;
lintel.receiveShadow = true;
this.group.add(lintel);
// Add decorative cap stones
const capLeft = new THREE.Mesh(
createStone(stoneSize * 0.7, stoneSize * 0.5, stoneSize * 0.7),
materials.stone
);
capLeft.position.set(-frameWidth / 2, frameHeight + stoneSize * 0.7, 0);
capLeft.castShadow = true;
this.group.add(capLeft);
const capRight = new THREE.Mesh(
createStone(stoneSize * 0.7, stoneSize * 0.5, stoneSize * 0.7),
materials.stone
);
capRight.position.set(frameWidth / 2, frameHeight + stoneSize * 0.7, 0);
capRight.castShadow = true;
this.group.add(capRight);
// Portal surface (the actual portal)
const portalGeo = new THREE.PlaneGeometry(frameWidth - stoneSize * 0.5, frameHeight - 0.2);
this.portalPlane = new THREE.Mesh(portalGeo, materials.portalPlaceholder.clone());
this.portalPlane.position.set(0, frameHeight / 2, 0.05);
this.portalPlane.receiveShadow = false; // Ensure portal view is not darkened by shadows
this.portalPlane.castShadow = false;
this.group.add(this.portalPlane);
// Position the group in world space
const threePos = cffrToThree(this.position.x, this.position.y, this.position.z);
this.group.position.copy(threePos);
this.group.rotation.y = -this.rotation; // Negative because of coordinate flip
scene.add(this.group);
}
updatePlaceholder(time) {
if (!this.isNearest && this.portalPlane) {
// Animated placeholder effect
const pulse = 0.3 + Math.sin(time * 2 + this.id) * 0.15;
this.portalPlane.material.opacity = pulse;
this.portalPlane.material.side = THREE.FrontSide; // Invisible from back
// Swirling color effect
const hue = (time * 0.1 + this.id * 0.2) % 1;
this.portalPlane.material.color.setHSL(hue, 0.7, 0.5);
}
}
setAsNearest(isNearest, renderTarget) {
this.isNearest = isNearest;
if (isNearest && renderTarget) {
// Use shader for screen-space portal effect
// The key is to sample the render target at screen-space coordinates
// so the view through the portal matches exactly what would be seen
this.portalPlane.material = new THREE.ShaderMaterial({
uniforms: {
map: { value: renderTarget.texture },
resolution: { value: new THREE.Vector2(window.innerWidth, window.innerHeight) }
},
vertexShader: `
varying vec4 vClipPos;
void main() {
vClipPos = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
gl_Position = vClipPos;
}
`,
fragmentShader: `
uniform sampler2D map;
uniform vec2 resolution;
varying vec4 vClipPos;
// Linear to sRGB conversion
vec4 linearToSRGB(vec4 color) {
return vec4(pow(color.rgb, vec3(1.0 / 2.2)), color.a);
}
void main() {
// Convert clip space to screen UV
vec2 screenUV = (vClipPos.xy / vClipPos.w) * 0.5 + 0.5;
// Sample the render target (contains linear color values)
vec4 color = texture2D(map, screenUV);
// Convert to sRGB for display
gl_FragColor = linearToSRGB(color);
}
`,
side: THREE.FrontSide,
toneMapped: false
});
} else {
// Use placeholder material
this.portalPlane.material = materials.portalPlaceholder.clone();
this.portalPlane.material.side = THREE.FrontSide; // Invisible from back
}
}
getWorldPosition() {
const pos = new THREE.Vector3();
this.group.getWorldPosition(pos);
return pos;
}
getWorldDirection() {
const dir = new THREE.Vector3(0, 0, 1);
this.group.localToWorld(dir);
dir.sub(this.getWorldPosition()).normalize();
return dir;
}
// Get the front position (where player exits) in CFFR coordinates
getExitPosition() {
// Exit just in front of portal plane, at ground level
// Need to match the Three.js portal facing direction
// Portal group has rotation.y = -this.rotation
// Local +Z in Three.js becomes world direction after this rotation
// Three.js +Z (0,0,1) rotated by -this.rotation around Y:
// x = sin(-this.rotation) = -sin(this.rotation)
// z = cos(-this.rotation) = cos(this.rotation)
// Converting to CFFR (cffr.x = three.x, cffr.y = -three.z):
// cffr.x = -sin(this.rotation)
// cffr.y = -cos(this.rotation)
const exitDist = 0.3; // Just past the portal plane to avoid re-triggering
const exitX = this.position.x - Math.sin(this.rotation) * exitDist;
const exitY = this.position.y - Math.cos(this.rotation) * exitDist;
const exitZ = this.position.z; // Ground level (same as portal base)
return new THREE.Vector3(exitX, exitY, exitZ);
}
}
// Create portals linking levels
function createPortals() {
let portalId = 0;
PORTAL_DEFS.forEach(def => {
const fromZ = TERRAIN_LEVELS[def.from.level].z;
const toZ = TERRAIN_LEVELS[def.to.level].z;
const portalA = new Portal(
portalId++,
new THREE.Vector3(def.from.x, def.from.y, fromZ),
def.from.rot,
null
);
portalA.destinationId = portalId;
const portalB = new Portal(
portalId++,
new THREE.Vector3(def.to.x, def.to.y, toZ),
def.to.rot,
null
);
portalB.destinationId = portalId - 2;
portalA.destination = portalB;
portalB.destination = portalA;
portals.push(portalA);
portals.push(portalB);
// Create render target for this portal pair
const rt = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
});
portalRenderTargets.set(portalA.id, rt);
const rt2 = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
});
portalRenderTargets.set(portalB.id, rt2);
});
}
createPortals();
// ═══════════════════════════════════════════════════════════════════════════
// PLAYER CHARACTER
// ═══════════════════════════════════════════════════════════════════════════
class PlayerCharacter {
constructor() {
// Position in CFFR coordinates
this.position = new THREE.Vector3(50, 45, 0.01);
this.velocity = new THREE.Vector3(0, 0, 0);
this.yaw = 0; // Rotation around Z (looking direction)
this.pitch = 0; // Looking up/down
this.isGrounded = true;
this.isSprinting = false;
// Double-tap detection
this.lastKeyTimes = { w: 0, a: 0, s: 0, d: 0 };
this.doubleTapThreshold = 300; // ms
// Portal teleport cooldown
this.teleportCooldown = 0;
// Input state
this.keys = { w: false, a: false, s: false, d: false, space: false };
// Create visual mesh
this.mesh = this.createMesh();
scene.add(this.mesh);
}
createMesh() {
const group = new THREE.Group();
// Body (torso)
const torsoHeight = PLAYER.HEIGHT * 0.35;
const torsoGeo = new THREE.BoxGeometry(0.4, torsoHeight, 0.25);
const torso = new THREE.Mesh(torsoGeo, materials.playerShirt);
torso.position.y = PLAYER.HEIGHT * 0.55;
torso.castShadow = true;
group.add(torso);
// Head
const headSize = PLAYER.HEIGHT * 0.15;
const headGeo = new THREE.BoxGeometry(headSize, headSize * 1.1, headSize * 0.9);
const head = new THREE.Mesh(headGeo, materials.player);
head.position.y = PLAYER.HEIGHT * 0.85;
head.castShadow = true;
group.add(head);
// Legs
const legHeight = PLAYER.HEIGHT * 0.45;
const legGeo = new THREE.BoxGeometry(0.15, legHeight, 0.18);
const leftLeg = new THREE.Mesh(legGeo, materials.playerPants);
leftLeg.position.set(-0.1, legHeight / 2, 0);
leftLeg.castShadow = true;
group.add(leftLeg);
const rightLeg = new THREE.Mesh(legGeo, materials.playerPants);
rightLeg.position.set(0.1, legHeight / 2, 0);