-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptimized-obstacles.js
More file actions
598 lines (488 loc) · 20.8 KB
/
optimized-obstacles.js
File metadata and controls
598 lines (488 loc) · 20.8 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
// Optimized Obstacles Manager with Modern Performance Techniques
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { LANES, OBSTACLE_TYPES, SPAWN_CONFIG, SCORING, PHYSICS } from './constants.js';
import { ObjectPool, InstancedRenderingManager, FrustumCullingManager } from './performance-manager.js';
import { CollisionUtils, PositionTracker } from './collision-utils.js';
export class OptimizedObstacleManager {
constructor(scene, performanceMonitor) {
this.scene = scene;
this.performanceMonitor = performanceMonitor;
this.gameController = null;
// Modern performance systems
this.objectPools = new Map();
this.instancedRenderer = new InstancedRenderingManager(scene);
this.frustumCuller = new FrustumCullingManager();
// Obstacle management
this.obstacles = [];
this.activeInstances = new Map(); // Track instanced obstacles
this.lastObstacleType = '';
// Smart spawning system
this.SPAWN_HORIZON = 50;
this.DESPAWN_DISTANCE = 30;
this.MIN_OBSTACLE_SPACING = 4;
this.MAX_OBSTACLE_SPACING = 8;
this.playerPositionTracker = new PositionTracker();
// Asset loading
this.loader = new GLTFLoader();
this.loadedModels = new Map();
this.loadingPromises = new Map();
this.priorityModelsLoaded = false;
this.allModelsLoaded = false;
// Priority loading queues
this.priorityModels = ['pothole', 'constructionBarrier', 'cone'];
this.backgroundModels = ['rubble', 'trafficBarrier', 'floorHole'];
// Performance tracking
this.spawnCounter = 0;
this.poolEfficiency = 0;
this.renderingMode = 'hybrid'; // 'individual', 'instanced', or 'hybrid'
this.initializeOptimizedSystem();
}
async initializeOptimizedSystem() {
// Initializing optimized obstacle system
// Initialize object pools for each obstacle type
this.initializeObjectPools();
// Initialize instanced rendering for high-frequency obstacles
this.initializeInstancedRendering();
// Start progressive asset loading
await this.loadPriorityAssets();
this.loadBackgroundAssets(); // Load in background
// Optimized obstacle system ready
}
initializeObjectPools() {
for (const [type, config] of Object.entries(OBSTACLE_TYPES)) {
const pool = new ObjectPool(
() => this.createFallbackObstacle(type),
(mesh) => this.resetObstacle(mesh),
20, // Initial size
100 // Max size
);
this.objectPools.set(type, pool);
}
// Object pools initialized for obstacle types
}
initializeInstancedRendering() {
// Initialize instanced meshes for most common obstacles
const commonObstacles = ['pothole', 'cone', 'rubble'];
for (const type of commonObstacles) {
const config = OBSTACLE_TYPES[type];
const geometry = config.geometry();
const material = new THREE.MeshLambertMaterial({
color: config.color,
transparent: false,
fog: true
});
this.instancedRenderer.createInstancedMesh(geometry, material, type, 50);
}
// Instanced rendering initialized for common obstacles
}
async loadPriorityAssets() {
// Loading priority obstacle models
const loadPromises = this.priorityModels.map(type => this.loadModel(type));
await Promise.allSettled(loadPromises);
this.priorityModelsLoaded = true;
// Priority models loaded - enhanced visual quality activated
}
async loadBackgroundAssets() {
// Loading background obstacle models
const loadPromises = this.backgroundModels.map(type => this.loadModel(type));
await Promise.allSettled(loadPromises);
this.allModelsLoaded = true;
this.upgradeExistingObstacles();
// All obstacle models loaded - maximum visual quality achieved
}
async loadModel(type) {
if (this.loadedModels.has(type) || this.loadingPromises.has(type)) {
return this.loadingPromises.get(type);
}
const config = this.getModelConfig(type);
if (!config) return null;
const loadPromise = this.loader.loadAsync(config.path)
.then(gltf => {
this.loadedModels.set(type, gltf);
// GLB model loaded successfully
return gltf;
})
.catch(error => {
// Failed to load GLB model, using fallback
return null;
});
this.loadingPromises.set(type, loadPromise);
return loadPromise;
}
createOptimizedObstacle(type, position, lane) {
this.spawnCounter++;
// Decide rendering strategy based on frequency and performance
const useInstancing = this.shouldUseInstancing(type);
if (useInstancing) {
return this.createInstancedObstacle(type, position, lane);
} else {
return this.createPooledObstacle(type, position, lane);
}
}
shouldUseInstancing(type) {
// Use instancing for high-frequency obstacles in good performance conditions
const commonTypes = ['pothole', 'cone', 'rubble'];
const hasInstancedMesh = this.instancedRenderer.instancedMeshes.has(type);
const goodPerformance = this.performanceMonitor.getMetrics().fps > 45;
return commonTypes.includes(type) && hasInstancedMesh && goodPerformance;
}
createInstancedObstacle(type, position, lane) {
const rotation = new THREE.Euler(0, Math.random() * Math.PI, 0);
const scale = new THREE.Vector3(1, 1, 1);
const instanceInfo = this.instancedRenderer.addInstance(type, position, rotation, scale);
if (instanceInfo) {
const obstacle = {
type: type,
position: position.clone(),
lane: lane,
boundingBox: this.calculateBoundingBox(type, position),
collisionEnabled: true,
hasCollided: false,
isInstanced: true,
instanceInfo: instanceInfo,
id: `instanced_${type}_${this.spawnCounter}`
};
this.obstacles.push(obstacle);
this.activeInstances.set(obstacle.id, obstacle);
return obstacle;
}
// Fallback to pooled if instancing fails
return this.createPooledObstacle(type, position, lane);
}
createPooledObstacle(type, position, lane) {
const pool = this.objectPools.get(type);
const mesh = pool.acquire();
// Configure mesh
mesh.position.copy(position);
mesh.position.y = OBSTACLE_TYPES[type].yPos;
mesh.rotation.y = Math.random() * Math.PI;
mesh.visible = true;
mesh.userData = {
type: type,
lane: lane,
spawned: Date.now(),
isPooled: true
};
// Try to upgrade to GLB model if available
this.upgradeToGLBModel(mesh, type);
// Add to scene and tracking
this.scene.add(mesh);
this.frustumCuller.addCullableObject(mesh);
const obstacle = {
type: type,
position: position.clone(),
lane: lane,
mesh: mesh,
boundingBox: this.calculateBoundingBox(type, position),
collisionEnabled: true,
hasCollided: false,
isInstanced: false,
id: `pooled_${type}_${this.spawnCounter}`
};
this.obstacles.push(obstacle);
return obstacle;
}
upgradeToGLBModel(mesh, type) {
const gltf = this.loadedModels.get(type);
if (!gltf) return false;
try {
// Clone the GLB model
const glbScene = gltf.scene.clone();
const config = this.getModelConfig(type);
// Apply transformations
glbScene.scale.set(...config.scale);
glbScene.rotation.set(...config.rotation);
// Replace geometry and material
mesh.geometry.dispose();
if (mesh.material) mesh.material.dispose();
// Use first mesh from GLB
const firstMesh = glbScene.children.find(child => child.isMesh);
if (firstMesh) {
mesh.geometry = firstMesh.geometry;
mesh.material = firstMesh.material;
}
mesh.userData.isGLB = true;
mesh.userData.upgraded = Date.now();
return true;
} catch (error) {
// Failed to upgrade to GLB model
return false;
}
}
updateObstacles(gameSpeed, cameraZ, gameActive) {
if (!gameActive) return 0;
const playerPosition = this.gameController?.getPlayerPosition() || { z: cameraZ };
// Update frustum culling
this.frustumCuller.update();
let obstaclesPassedScore = 0;
const obstaclesToRemove = [];
// Update individual obstacles
for (let i = this.obstacles.length - 1; i >= 0; i--) {
const obstacle = this.obstacles[i];
// Move obstacle based on game speed
obstacle.position.z += gameSpeed;
if (obstacle.isInstanced) {
// Update instanced obstacle
this.instancedRenderer.updateInstance(
obstacle.type,
obstacle.instanceInfo,
obstacle.position,
new THREE.Euler(0, 0, 0),
new THREE.Vector3(1, 1, 1)
);
} else if (obstacle.mesh) {
// Update individual mesh
obstacle.mesh.position.z = obstacle.position.z;
}
// Update bounding box
obstacle.boundingBox.setFromCenterAndSize(
obstacle.position,
this.getBoundingBoxSize(obstacle.type)
);
// Check if obstacle should be removed
if (obstacle.position.z > cameraZ + this.DESPAWN_DISTANCE) {
obstaclesToRemove.push(i);
// Award score for passing obstacle
if (obstacle.position.z > playerPosition.z) {
obstaclesPassedScore += SCORING.OBSTACLE_PASSED;
}
}
}
// Remove old obstacles
for (const index of obstaclesToRemove) {
this.removeObstacle(index);
}
// Spawn new obstacles
this.spawnObstaclesAhead(playerPosition.z);
return obstaclesPassedScore;
}
removeObstacle(index) {
const obstacle = this.obstacles[index];
if (obstacle.isInstanced) {
// Remove from instanced rendering
this.instancedRenderer.removeInstance(obstacle.type, obstacle.instanceInfo);
this.activeInstances.delete(obstacle.id);
} else if (obstacle.mesh) {
// Return to pool
this.scene.remove(obstacle.mesh);
this.frustumCuller.removeCullableObject(obstacle.mesh);
const pool = this.objectPools.get(obstacle.type);
pool.release(obstacle.mesh);
}
this.obstacles.splice(index, 1);
}
spawnObstaclesAhead(playerZ) {
const spawnZ = playerZ - this.SPAWN_HORIZON;
const needsObstacle = this.obstacles.length === 0 ||
this.obstacles[this.obstacles.length - 1].position.z > spawnZ + this.MIN_OBSTACLE_SPACING;
if (!needsObstacle) return;
// Smart obstacle type selection
const availableTypes = Object.keys(OBSTACLE_TYPES);
let obstacleType = availableTypes[Math.floor(Math.random() * availableTypes.length)];
// Avoid repeating the same obstacle type
if (obstacleType === this.lastObstacleType && availableTypes.length > 1) {
do {
obstacleType = availableTypes[Math.floor(Math.random() * availableTypes.length)];
} while (obstacleType === this.lastObstacleType);
}
this.lastObstacleType = obstacleType;
let position, selectedLane;
if (obstacleType === 'electricLine') {
// Electric line spans across all lanes, position at center of road
selectedLane = LANES.CENTER; // Use center lane for reference
position = new THREE.Vector3(
0, // Center of road
0,
spawnZ
);
} else {
// Select lane (avoid spawning in player's current lane if possible)
const playerLane = this.gameController?.player?.lane || LANES.CENTER;
const availableLanes = [0, 1, 2].filter(lane => lane !== playerLane);
selectedLane = availableLanes.length > 0
? availableLanes[Math.floor(Math.random() * availableLanes.length)]
: Math.floor(Math.random() * LANES.COUNT);
position = new THREE.Vector3(
LANES.POSITIONS[selectedLane],
0,
spawnZ
);
}
this.createOptimizedObstacle(obstacleType, position, selectedLane);
}
checkCollisions(playerBox, waterSlideObjects = [], waterSlideActive = false) {
for (const obstacle of this.obstacles) {
if (!obstacle.collisionEnabled || obstacle.hasCollided) continue;
// Skip collision if in water slide safe zone
if (waterSlideActive && this.isInWaterSlideZone(obstacle.position, waterSlideObjects)) {
continue;
}
// Use high-speed collision detection for fast gameplay
let collisionDetected = false;
if (this.gameController?.getGameSpeed() > PHYSICS.HIGH_SPEED_THRESHOLD) {
collisionDetected = CollisionUtils.checkExpandedCollision(playerBox, obstacle.boundingBox, 1.2);
} else {
collisionDetected = playerBox.intersectsBox(obstacle.boundingBox);
}
if (collisionDetected) {
// Special handling for electric line obstacle
if (obstacle.type === 'electricLine') {
// Check if player is sliding or jumping high enough
const playerHeight = playerBox.max.y;
const wireHeight = 1.2; // Height of the electric wire
// Allow passing if player is sliding (low collision box) or jumping high enough
if (this.gameController && this.gameController.player) {
const player = this.gameController.player;
if (player.isSliding || playerHeight > wireHeight + 0.3) {
continue; // No collision, player can pass
}
}
}
obstacle.hasCollided = true;
return obstacle;
}
}
return null;
}
// Utility methods
createFallbackObstacle(type) {
const config = OBSTACLE_TYPES[type];
const geometry = config.geometry();
const material = new THREE.MeshLambertMaterial({
color: config.color,
transparent: false,
fog: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData = { type: type, isFallback: true };
return mesh;
}
resetObstacle(mesh) {
mesh.position.set(0, 0, 0);
mesh.rotation.set(0, 0, 0);
mesh.scale.set(1, 1, 1);
mesh.visible = false;
mesh.userData = {};
if (mesh.parent) {
mesh.parent.remove(mesh);
}
}
calculateBoundingBox(type, position) {
const size = this.getBoundingBoxSize(type);
const box = new THREE.Box3();
box.setFromCenterAndSize(position, size);
return box;
}
getBoundingBoxSize(type) {
const config = OBSTACLE_TYPES[type];
// Default sizes based on obstacle type
const sizeMap = {
pothole: new THREE.Vector3(1, 0.2, 1),
constructionBarrier: new THREE.Vector3(1.5, 1, 0.5),
cone: new THREE.Vector3(0.6, 0.8, 0.6),
rubble: new THREE.Vector3(0.8, 0.4, 0.8),
trafficBarrier: new THREE.Vector3(1.8, 0.8, 0.5),
floorHole: new THREE.Vector3(1.2, 0.1, 1.2),
electricLine: new THREE.Vector3(9, 2.5, 0.5) // Wide obstacle spanning across lanes
};
return sizeMap[type] || new THREE.Vector3(1, 1, 1);
}
getModelConfig(type) {
// Use our analyzed configurations with verified scale factors
const configs = {
'pothole': {
path: '/assets/models/obstacles/Floor Hole.glb',
scale: [0.833, 0.833, 0.833], // From analysis
rotation: [0, 0, 0]
},
'constructionBarrier': {
path: '/assets/models/obstacles/Plastic Barrier.glb',
scale: [0.898, 0.898, 0.898], // From analysis
rotation: [0, 0, 0]
},
'cone': {
path: '/assets/models/obstacles/Cone.glb',
scale: [0.886, 0.886, 0.886], // From analysis
rotation: [0, 0, 0]
},
'rubble': {
path: '/assets/models/obstacles/Cinder block.glb',
scale: [0.000002, 0.000002, 0.000002], // Extremely oversized model - use fallback
rotation: [0, Math.random() * Math.PI, 0],
useModelLoading: false // Skip this model, use fallback
}
};
return configs[type];
}
isInWaterSlideZone(position, waterSlideObjects) {
return waterSlideObjects.some(obj =>
position.distanceTo(obj.position) < 2.0
);
}
upgradeExistingObstacles() {
let upgradedCount = 0;
for (const obstacle of this.obstacles) {
if (!obstacle.isInstanced && obstacle.mesh && !obstacle.mesh.userData.isGLB) {
if (this.upgradeToGLBModel(obstacle.mesh, obstacle.type)) {
upgradedCount++;
}
}
}
// Upgraded existing obstacles to GLB models if available
}
// Performance and stats methods
getPerformanceStats() {
const poolStats = {};
for (const [type, pool] of this.objectPools.entries()) {
poolStats[type] = pool.getStats();
}
const instanceStats = this.instancedRenderer.getStats();
const cullingStats = this.frustumCuller.getStats();
return {
obstacles: {
total: this.obstacles.length,
instanced: this.activeInstances.size,
pooled: this.obstacles.length - this.activeInstances.size
},
pools: poolStats,
instances: instanceStats,
culling: cullingStats,
performance: {
spawnCount: this.spawnCounter,
renderingMode: this.renderingMode,
modelsLoaded: {
priority: this.priorityModelsLoaded,
all: this.allModelsLoaded
}
}
};
}
// Interface compatibility methods
setGameController(controller) {
this.gameController = controller;
this.frustumCuller = new FrustumCullingManager(controller.camera);
}
getObstacles() {
return this.obstacles;
}
startSpawning() {
// Optimized obstacle spawning started
}
reset() {
// Remove all obstacles
for (let i = this.obstacles.length - 1; i >= 0; i--) {
this.removeObstacle(i);
}
// Release all pooled objects
for (const pool of this.objectPools.values()) {
pool.releaseAll();
}
// Reset counters
this.spawnCounter = 0;
this.lastObstacleType = '';
// Optimized obstacle system reset
}
}