Repository navigation
Expand file tree
/
Copy pathupdate.js
More file actions
529 lines (453 loc) · 19.9 KB
/
Copy pathupdate.js
File metadata and controls
529 lines (453 loc) · 19.9 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
/*
* Copyright 2026 Mark Longo
*/
import * as THREE from 'three';
import {
scene, controls, disposeOwnedResources, textureManager,
emitParticle, createPickupFloatingText, createPickupParticleBurst,
flashScreen, FLASH_PICKUP_HEALTH, FLASH_PICKUP_XP,
updatePickupEffects, updateExplosionFlashes, releaseDynamicLight
} from './render.js';
import { monsters, doors, MonsterState } from './gameState.js';
import {
velocity, CAPSULE_RADIUS, MONSTER_CAPSULE_RADIUS,
gatherNearbyTriangles, gatherNearbyBoxes, closestPointTrianglePoint
} from './collision.js';
import {
levelObjects, activePickups, activeProjectiles, activeTeleporters,
PROJECTILE_TYPES, PLAYER_GUNS, unlockedWeapons, spellCounts,
setCurrentGunIndex, getCurrentGunMesh, generateAndLoadNewLevel,
MD2_ANIMATIONS, healPlayer, addPlayerXp,
updatePlayerHud, playPickupSound, playSound,
triggerSpellExplosion, triggerMonsterSpellExplosion, checkPlayerAttackHit,
updateWeaponMesh, playerWeaponCurrentAnim, playerWeaponAnimTimer,
setPlayerWeaponAnimTimer, setPlayerWeaponCurrentAnim,
isWeaponAttacking, setIsWeaponAttacking,
hasWeaponHitThisSwing, setHasWeaponHitThisSwing, playerWeaponActiveInfluences
} from './logic.js';
let teleporterTransitionCooldown = 0.0;
const TELEPORTER_ANIMATION_RANGE_SQ = 2500.0 * 2500.0;
// Player Movement State
export let isFlyMode = false;
export let isGrounded = false;
export let jumpRequested = false;
export function setIsGrounded(val) {
isGrounded = val;
}
export function setJumpRequested(val) {
jumpRequested = val;
}
export function toggleFlyMode(forceState) {
if (typeof forceState === 'boolean') {
isFlyMode = forceState;
} else {
isFlyMode = !isFlyMode;
}
velocity.set(0, 0, 0);
updateModeDisplay();
}
export function updateModeDisplay() {
const modeElem = document.getElementById('mode-display');
if (modeElem) {
modeElem.textContent = isFlyMode ? 'FLY MODE' : 'FPS (WALK)';
modeElem.style.color = isFlyMode ? '#00ffff' : '#00ff88';
}
}
export const direction = new THREE.Vector3();
export const cameraQuaternion = new THREE.Quaternion();
export const worldDir = new THREE.Vector3();
export let footstepTimer = 0.0;
export function setFootstepTimer(val) {
footstepTimer = val;
}
// Tick Updates
const PICKUP_DISTANCE = 70.0;
const PICKUP_DISTANCE_SQ = PICKUP_DISTANCE * PICKUP_DISTANCE;
export function updateTeleporters(delta, playerPos) {
if (teleporterTransitionCooldown > 0) {
teleporterTransitionCooldown -= delta;
}
for (const tp of activeTeleporters) {
if (!tp || !tp.group) continue;
const dx = playerPos.x - tp.position.x;
const dz = playerPos.z - tp.position.z;
const distSq = dx * dx + dz * dz;
// Far-away portals are invisible through fog: skip animation and particles entirely.
if (distSq > TELEPORTER_ANIMATION_RANGE_SQ) continue;
tp.timer += delta;
// 1. Swirling Animation on Rings & Beam
if (tp.beamMesh) {
tp.beamMesh.rotation.y += delta * 1.5;
tp.beamMesh.material.opacity = 0.25 + Math.sin(tp.timer * 4.0) * 0.15;
}
if (tp.coreMesh) {
tp.coreMesh.rotation.y -= delta * 2.5;
tp.coreMesh.material.opacity = 0.5 + Math.cos(tp.timer * 6.0) * 0.2;
}
if (tp.rings) {
for (let r = 0; r < tp.rings.length; r++) {
const ring = tp.rings[r];
const dir = (r % 2 === 0) ? 1 : -1;
ring.rotation.z += delta * (2.0 + r * 0.8) * dir;
ring.position.y = 15 + r * 45 + Math.sin(tp.timer * 3.0 + r) * 12.0;
ring.scale.setScalar(1.0 + Math.sin(tp.timer * 2.0 + r) * 0.15);
}
}
// 2. Ascending Spiral Particles
if (Math.random() < 0.8) {
for (let k = 0; k < 3; k++) {
const angle = tp.timer * 8.0 + (k * Math.PI * 2 / 3);
const radius = 30 + Math.sin(tp.timer * 5.0 + k) * 10;
const px = tp.position.x + Math.cos(angle) * radius;
const pz = tp.position.z + Math.sin(angle) * radius;
const py = tp.position.y + Math.random() * 20;
emitParticle(
px, py, pz,
-Math.sin(angle) * 40,
120 + Math.random() * 80,
Math.cos(angle) * 40,
(k % 2 === 0) ? 0x38bdf8 : 0xc084fc,
10,
0.8
);
}
}
// 3. Player Proximity & Level Transition Trigger
if (distSq <= 75.0 * 75.0 && teleporterTransitionCooldown <= 0) {
teleporterTransitionCooldown = 3.0;
playSound('spell3.wav', 0.9);
flashScreen(FLASH_PICKUP_XP, 0.8, 350);
createPickupFloatingText('LEVEL COMPLETE! TELEPORTING...', playerPos, '#38bdf8');
generateAndLoadNewLevel(textureManager, true);
}
}
}
export function updatePickups(delta, playerPos) {
updatePickupEffects(delta);
for (let i = activePickups.length - 1; i >= 0; i--) {
const pickup = activePickups[i];
if (!pickup || !pickup.mesh) continue;
if (pickup.state === 'ACTIVE') {
const distSq = playerPos.distanceToSquared(pickup.position);
if (distSq <= PICKUP_DISTANCE_SQ) {
pickup.state = 'FLOATING';
pickup.floatTimer = 0.0;
const nameClean = (pickup.name || '').toUpperCase().trim();
const def = pickup.def;
const isHealth = def && def.type === 'health';
let popupLabel = def ? def.label : `+${pickup.name}`;
let colorHex = isHealth ? 0x22c55e : 0xeab308;
let colorCss = isHealth ? '#4ade80' : '#facc15';
// Check spell scrolls / spellbook first
let spellScrollName = null;
// Weapon names such as LIGHTNINGSWORD contain spell names, so they must never match as scrolls.
const isWeaponName = PLAYER_GUNS.some(g => spellCounts[g] === undefined && g.toUpperCase() === nameClean);
const scrollName = isWeaponName ? '' : nameClean;
if (scrollName.includes('SPELLBOOK')) {
spellCounts['MAGIC MISSILE'] += 5;
spellCounts['FIREBALL'] += 5;
spellCounts['LIGHTNING'] += 5;
spellCounts['HEALING'] += 5;
popupLabel = '+5 ALL SPELLS';
colorHex = 0xa855f7;
colorCss = '#c084fc';
updatePlayerHud();
} else if (scrollName.includes('SCROLL-MAGICMISSLE') || scrollName.includes('MAGICMISSLE') || scrollName === 'MAGIC MISSILE') {
spellScrollName = 'MAGIC MISSILE';
colorHex = 0x38bdf8;
colorCss = '#38bdf8';
} else if (scrollName.includes('SCROLL-FIREBALL') || scrollName.includes('FIREBALL')) {
spellScrollName = 'FIREBALL';
colorHex = 0xff5500;
colorCss = '#ff7700';
} else if (scrollName.includes('SCROLL-LIGHTNING') || scrollName.includes('LIGHTNING')) {
spellScrollName = 'LIGHTNING';
colorHex = 0x00ffff;
colorCss = '#00ffff';
} else if (scrollName.includes('SCROLL-HEALING') || scrollName.includes('HEALING')) {
spellScrollName = 'HEALING';
colorHex = 0x22c55e;
colorCss = '#4ade80';
}
if (spellScrollName) {
const prevCount = spellCounts[spellScrollName] || 0;
spellCounts[spellScrollName] = prevCount + 5;
popupLabel = `+5 ${spellScrollName}`;
updatePlayerHud();
} else if (!nameClean.includes('SPELLBOOK')) {
// Check physical weapon pickups (excluding spell slots)
let unlockedWeapon = null;
for (const gun of PLAYER_GUNS) {
if (spellCounts[gun] !== undefined) continue;
const gunUpper = gun.toUpperCase();
if (gunUpper === nameClean) {
unlockedWeapon = gun;
break;
}
if (nameClean && (nameClean.includes(gunUpper) || gunUpper.includes(nameClean))) {
if (!unlockedWeapon || gun.length > unlockedWeapon.length) {
unlockedWeapon = gun;
}
}
}
if (!unlockedWeapon && def && def.type === 'weapon') {
unlockedWeapon = pickup.name;
}
if (unlockedWeapon) {
const wasUnlocked = unlockedWeapons.has(unlockedWeapon);
unlockedWeapons.add(unlockedWeapon);
popupLabel = `+${unlockedWeapon}`;
colorHex = 0x38bdf8;
colorCss = '#38bdf8';
// Only switch to weapon if it's the first time the slot is activated
if (!wasUnlocked) {
const newIndex = PLAYER_GUNS.indexOf(unlockedWeapon);
if (newIndex !== -1) {
setCurrentGunIndex(newIndex);
updateWeaponMesh();
}
}
} else if (isHealth) {
healPlayer(def.amount);
} else if (def && def.amount) {
addPlayerXp(def.amount);
}
}
playPickupSound(isHealth);
if (window.triggerGamepadVibration) {
window.triggerGamepadVibration(60, 0.35, 0.1);
}
createPickupFloatingText(popupLabel, pickup.position, colorCss);
createPickupParticleBurst(pickup.position, colorHex);
flashScreen(isHealth ? FLASH_PICKUP_HEALTH : FLASH_PICKUP_XP, 0.5, 150);
}
} else if (pickup.state === 'FLOATING') {
pickup.floatTimer += delta;
const floatDuration = 0.7;
const progress = pickup.floatTimer / floatDuration;
pickup.mesh.position.y = pickup.originalY + (progress * progress) * 350.0;
pickup.mesh.rotation.y += delta * 12.0;
pickup.mesh.scale.setScalar(pickup.baseScale * Math.max(0, 1 - progress));
if (progress >= 1.0) {
scene.remove(pickup.mesh);
disposeOwnedResources(pickup.mesh);
const objIdx = levelObjects.findIndex(o => o.mesh === pickup.mesh);
if (objIdx !== -1) {
levelObjects.splice(objIdx, 1);
}
activePickups.splice(i, 1);
}
}
}
}
export function updateDoors(delta) {
const RISE_SPEED = 200.0;
for (let i = 0; i < doors.length; i++) {
const door = doors[i];
if (!door.isOpening || door.isOpen) continue;
let dy = RISE_SPEED * delta;
if (door.currentUp + dy >= door.maxUp) {
dy = door.maxUp - door.currentUp;
door.currentUp = door.maxUp;
door.isOpening = false;
door.isOpen = true;
} else {
door.currentUp += dy;
}
if (dy > 0) {
door.mesh.position.y += dy;
if (door.levelObj) {
door.levelObj.position.y += dy;
}
if (door.triangles) {
for (let t = 0; t < door.triangles.length; t++) {
const tri = door.triangles[t];
tri.a.y += dy;
tri.b.y += dy;
tri.c.y += dy;
tri.minY += dy;
tri.maxY += dy;
}
door.bounds.minY += dy;
door.bounds.maxY += dy;
}
}
}
}
const _projNext = new THREE.Vector3();
const _projStep = new THREE.Vector3();
const _projSample = new THREE.Vector3();
const _projClosest = new THREE.Vector3();
export function removeProjectile(index) {
const proj = activeProjectiles[index];
scene.remove(proj.group);
releaseDynamicLight(proj.lightSlot);
activeProjectiles.splice(index, 1);
}
export function projectileHitsEnvironmentAt(p, radius) {
const radiusSq = radius * radius;
const tris = gatherNearbyTriangles(p.x - radius, p.x + radius, p.y - radius, p.y + radius, p.z - radius, p.z + radius);
for (let t = 0; t < tris.length; t++) {
const tri = tris[t];
closestPointTrianglePoint(tri.a, tri.b, tri.c, p, _projClosest);
if (p.distanceToSquared(_projClosest) <= radiusSq) return true;
}
const boxes = gatherNearbyBoxes(p.x - radius, p.x + radius, p.y - radius, p.y + radius, p.z - radius, p.z + radius);
for (let b = 0; b < boxes.length; b++) {
if (boxes[b].distanceToPoint(p) <= radius) return true;
}
return false;
}
export function monsterProjectileHitsAt(p, radius) {
if (controls) {
const playerPos = controls.getObject().position;
const reach = radius + CAPSULE_RADIUS;
if (p.distanceToSquared(playerPos) <= reach * reach) {
return true;
}
}
return projectileHitsEnvironmentAt(p, radius);
}
export function projectileHitsAt(p, radius) {
const monsterReach = radius + MONSTER_CAPSULE_RADIUS;
const monsterReachSq = monsterReach * monsterReach;
for (let m = 0; m < monsters.length; m++) {
const monster = monsters[m];
if (monster.state === MonsterState.DEATH || monster.health <= 0) continue;
if (p.distanceToSquared(monster.position) <= monsterReachSq) return true;
}
return projectileHitsEnvironmentAt(p, radius);
}
export function updateProjectiles(delta) {
updateExplosionFlashes(delta);
for (let i = activeProjectiles.length - 1; i >= 0; i--) {
const proj = activeProjectiles[i];
proj.lifeTimer += delta;
if (proj.lifeTimer >= proj.maxLife) {
if (proj.owner === 'monster') {
triggerMonsterSpellExplosion(proj.position, proj.type, proj.damage, proj.aoeRadius, proj.colorHex);
} else {
triggerSpellExplosion(proj.position, proj.type, proj.damage, proj.aoeRadius, proj.colorHex);
}
removeProjectile(i);
continue;
}
if (proj.owner === 'monster' && proj.type === 'MAGIC MISSILE' && controls) {
const playerPos = controls.getObject().position;
const targetPos = _projSample.copy(playerPos);
targetPos.y += 20;
const toPlayer = _projClosest.subVectors(targetPos, proj.position).normalize();
proj.velocity.lerp(toPlayer.multiplyScalar(PROJECTILE_TYPES['MAGIC MISSILE'].speed * 0.88), delta * 2.5);
}
proj.velocity.y += proj.gravity * delta;
_projStep.copy(proj.velocity).multiplyScalar(delta);
_projNext.copy(proj.position).add(_projStep);
const segments = Math.min(8, Math.max(1, Math.ceil(_projStep.length() / proj.radius)));
let hasExploded = false;
for (let s = 1; s <= segments; s++) {
_projSample.copy(proj.position).addScaledVector(_projStep, s / segments);
const isHit = (proj.owner === 'monster') ? monsterProjectileHitsAt(_projSample, proj.radius) : projectileHitsAt(_projSample, proj.radius);
if (isHit) {
hasExploded = true;
_projNext.copy(_projSample);
if (proj.owner === 'monster') {
triggerMonsterSpellExplosion(_projNext, proj.type, proj.damage, proj.aoeRadius, proj.colorHex);
} else {
triggerSpellExplosion(_projNext, proj.type, proj.damage, proj.aoeRadius, proj.colorHex);
}
break;
}
}
if (hasExploded) {
removeProjectile(i);
continue;
}
proj.position.copy(_projNext);
proj.group.position.copy(proj.position);
if (proj.lightSlot) proj.lightSlot.light.position.copy(proj.position);
if (Math.random() < 0.7) {
for (let k = 0; k < 4; k++) {
emitParticle(
proj.position.x + (Math.random() - 0.5) * 10,
proj.position.y + 10 + (Math.random() - 0.5) * 10,
proj.position.z + (Math.random() - 0.5) * 10,
(Math.random() - 0.5) * 120,
50 + (Math.random() - 0.5) * 120,
(Math.random() - 0.5) * 120,
proj.colorHex, 8, 0.5);
}
}
}
}
export function updatePlayerWeaponAnimation(delta, inputs) {
const currentGunMesh = getCurrentGunMesh();
if (!currentGunMesh) return;
const geometry = currentGunMesh.geometry;
if (!geometry || !geometry.morphAttributes || !geometry.morphAttributes.position) return;
const influences = currentGunMesh.morphTargetInfluences;
if (!influences) return;
const { moveForward, moveBackward, moveLeft, moveRight } = inputs || {};
let targetAnim = MD2_ANIMATIONS.STAND;
if (isWeaponAttacking) {
targetAnim = MD2_ANIMATIONS.ATTACK;
} else if (!isGrounded && !isFlyMode) {
targetAnim = MD2_ANIMATIONS.JUMP;
} else if (moveForward || moveBackward || moveLeft || moveRight) {
targetAnim = MD2_ANIMATIONS.RUN;
} else {
targetAnim = MD2_ANIMATIONS.STAND;
}
if (playerWeaponCurrentAnim !== targetAnim) {
setPlayerWeaponCurrentAnim(targetAnim);
setPlayerWeaponAnimTimer(0.0);
}
setPlayerWeaponAnimTimer(playerWeaponAnimTimer + delta);
const anim = playerWeaponCurrentAnim;
const totalFrames = anim.end - anim.start + 1;
const totalDuration = totalFrames / anim.fps;
if (isWeaponAttacking && playerWeaponCurrentAnim === MD2_ANIMATIONS.ATTACK) {
if (!hasWeaponHitThisSwing && playerWeaponAnimTimer >= totalDuration * 0.5) {
setHasWeaponHitThisSwing(true);
checkPlayerAttackHit();
}
}
if (!anim.loop && playerWeaponAnimTimer >= totalDuration) {
if (isWeaponAttacking) {
setIsWeaponAttacking(false);
setHasWeaponHitThisSwing(false);
setPlayerWeaponCurrentAnim((moveForward || moveBackward || moveLeft || moveRight)
? MD2_ANIMATIONS.RUN
: MD2_ANIMATIONS.STAND);
setPlayerWeaponAnimTimer(0.0);
}
}
const curAnim = playerWeaponCurrentAnim;
const curTotalFrames = curAnim.end - curAnim.start + 1;
const progress = playerWeaponAnimTimer * curAnim.fps;
let frameA, frameB, alpha;
if (curAnim.loop) {
const frameIdx = progress % curTotalFrames;
frameA = curAnim.start + Math.floor(frameIdx);
frameB = curAnim.start + ((Math.floor(frameIdx) + 1) % curTotalFrames);
alpha = frameIdx - Math.floor(frameIdx);
} else {
const frameIdx = Math.min(progress, curTotalFrames - 1);
frameA = curAnim.start + Math.floor(frameIdx);
frameB = curAnim.start + Math.min(Math.floor(frameIdx) + 1, curTotalFrames - 1);
alpha = frameIdx - Math.floor(frameIdx);
}
for (const idx of playerWeaponActiveInfluences) {
if (idx >= 0 && idx < influences.length) {
influences[idx] = 0;
}
}
playerWeaponActiveInfluences.clear();
if (frameA >= 0 && frameA < influences.length) {
influences[frameA] = (1 - alpha);
playerWeaponActiveInfluences.add(frameA);
}
if (frameB >= 0 && frameB < influences.length && alpha > 0.001) {
influences[frameB] = (influences[frameB] || 0) + alpha;
playerWeaponActiveInfluences.add(frameB);
}
}