forked from KhronosGroup/Vulkan-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathengine.cpp
More file actions
870 lines (702 loc) · 28.5 KB
/
engine.cpp
File metadata and controls
870 lines (702 loc) · 28.5 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
#include "engine.h"
#include "scene_loading.h"
#include "mesh_component.h"
#include <chrono>
#include <algorithm>
#include <ranges>
#include <stdexcept>
#include <iostream>
#include <random>
// This implementation corresponds to the Engine_Architecture chapter in the tutorial:
// @see en/Building_a_Simple_Engine/Engine_Architecture/02_architectural_patterns.adoc
Engine::Engine()
: resourceManager(std::make_unique<ResourceManager>()) {
}
Engine::~Engine() {
Cleanup();
}
bool Engine::Initialize(const std::string& appName, int width, int height, bool enableValidationLayers) {
// Create platform
#if defined(PLATFORM_ANDROID)
// For Android, the platform is created with the android_app
// This will be handled in the android_main function
return false;
#else
platform = CreatePlatform();
if (!platform->Initialize(appName, width, height)) {
return false;
}
// Set resize callback
platform->SetResizeCallback([this](int width, int height) {
HandleResize(width, height);
});
// Set mouse callback
platform->SetMouseCallback([this](float x, float y, uint32_t buttons) {
handleMouseInput(x, y, buttons);
});
// Set keyboard callback
platform->SetKeyboardCallback([this](uint32_t key, bool pressed) {
handleKeyInput(key, pressed);
});
// Set char callback
platform->SetCharCallback([this](uint32_t c) {
if (imguiSystem) {
imguiSystem->HandleChar(c);
}
});
// Create renderer
renderer = std::make_unique<Renderer>(platform.get());
if (!renderer->Initialize(appName, enableValidationLayers)) {
return false;
}
try {
// Model loader via constructor; also wire into renderer
modelLoader = std::make_unique<ModelLoader>(renderer.get());
renderer->SetModelLoader(modelLoader.get());
// Audio system via constructor
audioSystem = std::make_unique<AudioSystem>(this, renderer.get());
// Physics system via constructor (GPU enabled)
physicsSystem = std::make_unique<PhysicsSystem>(renderer.get(), true);
// ImGui via constructor, then connect audio system
imguiSystem = std::make_unique<ImGuiSystem>(renderer.get(), width, height);
imguiSystem->SetAudioSystem(audioSystem.get());
} catch (const std::exception& e) {
std::cerr << "Subsystem initialization failed: " << e.what() << std::endl;
return false;
}
// Generate ball material properties once at load time
GenerateBallMaterial();
// Initialize physics scaling system
InitializePhysicsScaling();
initialized = true;
return true;
#endif
}
void Engine::Run() {
if (!initialized) {
throw std::runtime_error("Engine not initialized");
}
running = true;
// Main loop
while (running) {
// Process platform events
if (!platform->ProcessEvents()) {
running = false;
break;
}
// Calculate delta time
deltaTimeMs = CalculateDeltaTimeMs();
// Update frame counter and FPS
frameCount++;
fpsUpdateTimer += deltaTimeMs.count() * 0.001f;
// Update window title with FPS and frame time every second
if (fpsUpdateTimer >= 1.0f) {
uint64_t framesSinceLastUpdate = frameCount - lastFPSUpdateFrame;
double avgMs = 0.0;
if (framesSinceLastUpdate > 0 && fpsUpdateTimer > 0.0f) {
currentFPS = static_cast<float>(static_cast<double>(framesSinceLastUpdate) / static_cast<double>(fpsUpdateTimer));
avgMs = (fpsUpdateTimer / static_cast<double>(framesSinceLastUpdate)) * 1000.0;
} else {
// Avoid divide-by-zero; keep previous FPS and estimate avgMs from last delta
currentFPS = std::max(currentFPS, 1.0f);
avgMs = static_cast<double>(deltaTimeMs.count());
}
// Update window title with frame count, FPS, and frame time
std::string title = "Simple Engine - Frame: " + std::to_string(frameCount) +
" | FPS: " + std::to_string(static_cast<int>(currentFPS)) +
" | ms: " + std::to_string(static_cast<int>(avgMs));
platform->SetWindowTitle(title);
// Reset timer and frame counter for next update
fpsUpdateTimer = 0.0f;
lastFPSUpdateFrame = frameCount;
}
// Update
Update(deltaTimeMs);
// Render
Render();
}
}
void Engine::Cleanup() {
if (initialized) {
// Wait for the device to be idle before cleaning up
if (renderer) {
renderer->WaitIdle();
}
// Clear entities
entities.clear();
entityMap.clear();
// Clean up subsystems in reverse order of creation
imguiSystem.reset();
physicsSystem.reset();
audioSystem.reset();
modelLoader.reset();
renderer.reset();
platform.reset();
initialized = false;
}
}
Entity* Engine::CreateEntity(const std::string& name) {
// Always allow duplicate names; map stores a representative entity
// Create the entity
auto entity = std::make_unique<Entity>(name);
// Add to the vector and map
entities.push_back(std::move(entity));
Entity* rawPtr = entities.back().get();
// Update the map to point to the most recently created entity with this name
entityMap[name] = rawPtr;
return rawPtr;
}
Entity* Engine::GetEntity(const std::string& name) {
auto it = entityMap.find(name);
if (it != entityMap.end()) {
return it->second;
}
return nullptr;
}
bool Engine::RemoveEntity(Entity* entity) {
if (!entity) {
return false;
}
// Remember the name before erasing ownership
std::string name = entity->GetName();
// Find the entity in the vector
auto it = std::find_if(entities.begin(), entities.end(),
[entity](const std::unique_ptr<Entity>& e) {
return e.get() == entity;
});
if (it != entities.end()) {
// Remove from the vector (ownership)
entities.erase(it);
// Update the map: point to another entity with the same name if one exists
auto remainingIt = std::find_if(entities.begin(), entities.end(),
[&name](const std::unique_ptr<Entity>& e) {
return e->GetName() == name;
});
if (remainingIt != entities.end()) {
entityMap[name] = remainingIt->get();
} else {
entityMap.erase(name);
}
return true;
}
return false;
}
bool Engine::RemoveEntity(const std::string& name) {
Entity* entity = GetEntity(name);
if (entity) {
return RemoveEntity(entity);
}
return false;
}
void Engine::SetActiveCamera(CameraComponent* cameraComponent) {
activeCamera = cameraComponent;
}
const CameraComponent* Engine::GetActiveCamera() const {
return activeCamera;
}
const ResourceManager* Engine::GetResourceManager() const {
return resourceManager.get();
}
const Platform* Engine::GetPlatform() const {
return platform.get();
}
Renderer* Engine::GetRenderer() {
return renderer.get();
}
ModelLoader* Engine::GetModelLoader() {
return modelLoader.get();
}
const AudioSystem* Engine::GetAudioSystem() const {
return audioSystem.get();
}
PhysicsSystem* Engine::GetPhysicsSystem() {
return physicsSystem.get();
}
const ImGuiSystem* Engine::GetImGuiSystem() const {
return imguiSystem.get();
}
void Engine::handleMouseInput(float x, float y, uint32_t buttons) {
// Check if ImGui wants to capture mouse input first
bool imguiWantsMouse = imguiSystem && imguiSystem->WantCaptureMouse();
// Suppress right-click while loading
if (renderer && renderer->IsLoading()) {
buttons &= ~2u; // clear right button bit
}
if (!imguiWantsMouse) {
// Handle mouse click for ball throwing (right mouse button)
if (buttons & 2) { // Right mouse button (bit 1)
if (!cameraControl.mouseRightPressed) {
cameraControl.mouseRightPressed = true;
// Throw a ball on mouse click
ThrowBall(x, y);
}
} else {
cameraControl.mouseRightPressed = false;
}
// Handle camera rotation when left mouse button is pressed
if (buttons & 1) { // Left mouse button (bit 0)
if (!cameraControl.mouseLeftPressed) {
cameraControl.mouseLeftPressed = true;
cameraControl.firstMouse = true;
}
if (cameraControl.firstMouse) {
cameraControl.lastMouseX = x;
cameraControl.lastMouseY = y;
cameraControl.firstMouse = false;
}
float xOffset = x - cameraControl.lastMouseX;
float yOffset = cameraControl.lastMouseY - y; // Reversed since y-coordinates go from bottom to top
cameraControl.lastMouseX = x;
cameraControl.lastMouseY = y;
xOffset *= cameraControl.mouseSensitivity;
yOffset *= cameraControl.mouseSensitivity;
cameraControl.yaw += xOffset;
cameraControl.pitch += yOffset;
// Constrain pitch to avoid gimbal lock
if (cameraControl.pitch > 89.0f) cameraControl.pitch = 89.0f;
if (cameraControl.pitch < -89.0f) cameraControl.pitch = -89.0f;
} else {
cameraControl.mouseLeftPressed = false;
}
}
if (imguiSystem) {
imguiSystem->HandleMouse(x, y, buttons);
}
// Always perform hover detection (even when ImGui is active)
HandleMouseHover(x, y);
}
void Engine::handleKeyInput(uint32_t key, bool pressed) {
switch (key) {
case GLFW_KEY_W:
case GLFW_KEY_UP:
cameraControl.moveForward = pressed;
break;
case GLFW_KEY_S:
case GLFW_KEY_DOWN:
cameraControl.moveBackward = pressed;
break;
case GLFW_KEY_A:
case GLFW_KEY_LEFT:
cameraControl.moveLeft = pressed;
break;
case GLFW_KEY_D:
case GLFW_KEY_RIGHT:
cameraControl.moveRight = pressed;
break;
case GLFW_KEY_Q:
case GLFW_KEY_PAGE_UP:
cameraControl.moveUp = pressed;
break;
case GLFW_KEY_E:
case GLFW_KEY_PAGE_DOWN:
cameraControl.moveDown = pressed;
break;
default: break;
}
if (imguiSystem) {
imguiSystem->HandleKeyboard(key, pressed);
}
}
void Engine::Update(TimeDelta deltaTime) {
// Debug: Verify Update method is being called
static int updateCallCount = 0;
updateCallCount++;
// Process pending ball creations (outside rendering loop to avoid memory pool constraints)
ProcessPendingBalls();
if (activeCamera) {
glm::vec3 currentCameraPosition = activeCamera->GetPosition();
physicsSystem->SetCameraPosition(currentCameraPosition);
}
// Use real deltaTime for physics to maintain proper timing
physicsSystem->Update(deltaTime);
// Update audio system
audioSystem->Update(deltaTime);
// Update ImGui system
imguiSystem->NewFrame();
// Update camera controls
if (activeCamera) {
UpdateCameraControls(deltaTime);
}
// Update all entities (guard against null unique_ptrs)
for (auto& entity : entities) {
if (!entity) { continue; }
if (!entity->IsActive()) { continue; }
entity->Update(deltaTime);
}
}
void Engine::Render() {
// Ensure renderer is ready
if (!renderer || !renderer->IsInitialized()) {
return;
}
// Check if we have an active camera
if (!activeCamera) {
return;
}
// Render the scene (ImGui will be rendered within the render pass)
renderer->Render(entities, activeCamera, imguiSystem.get());
}
std::chrono::milliseconds Engine::CalculateDeltaTimeMs() {
// Get current time using a steady clock to avoid system time jumps
uint64_t currentTime = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()
).count()
);
// Initialize lastFrameTimeMs on first call
if (lastFrameTimeMs == 0) {
lastFrameTimeMs = currentTime;
return std::chrono::milliseconds(16); // ~16ms as a sane initial guess
}
// Calculate delta time in milliseconds
uint64_t delta = currentTime - lastFrameTimeMs;
// Update last frame time
lastFrameTimeMs = currentTime;
return std::chrono::milliseconds(static_cast<long long>(delta));
}
void Engine::HandleResize(int width, int height) const {
if (height <= 0 || width <= 0) {
return;
}
// Update the active camera's aspect ratio
if (activeCamera) {
activeCamera->SetAspectRatio(static_cast<float>(width) / static_cast<float>(height));
}
// Notify the renderer that the framebuffer has been resized
if (renderer) {
renderer->SetFramebufferResized();
}
// Notify ImGui system about the resize
if (imguiSystem) {
imguiSystem->HandleResize(static_cast<uint32_t>(width), static_cast<uint32_t>(height));
}
}
void Engine::UpdateCameraControls(TimeDelta deltaTime) const {
if (!activeCamera) return;
// Get a camera transform component
auto* cameraTransform = activeCamera->GetOwner()->GetComponent<TransformComponent>();
if (!cameraTransform) return;
// Check if camera tracking is enabled
if (imguiSystem && imguiSystem->IsCameraTrackingEnabled()) {
// Find the first active ball entity
auto ballEntityIt = std::ranges::find_if( entities, []( auto const & entity ){ return entity->IsActive() && ( entity->GetName().find( "Ball_" ) != std::string::npos ); } );
Entity* ballEntity = ballEntityIt != entities.end() ? ballEntityIt->get() : nullptr;
if (ballEntity) {
// Get ball's transform component
auto* ballTransform = ballEntity->GetComponent<TransformComponent>();
if (ballTransform) {
glm::vec3 ballPosition = ballTransform->GetPosition();
// Position camera at a fixed offset from the ball for good viewing
glm::vec3 cameraOffset = glm::vec3(2.0f, 1.5f, 2.0f); // Behind and above the ball
glm::vec3 cameraPosition = ballPosition + cameraOffset;
// Update camera position and target
cameraTransform->SetPosition(cameraPosition);
activeCamera->SetTarget(ballPosition);
return; // Skip manual controls when tracking
}
}
}
// Manual camera controls (only when tracking is disabled)
// Calculate movement speed
float velocity = cameraControl.cameraSpeed * deltaTime.count() * .001f;
// Calculate camera direction vectors based on yaw and pitch
glm::vec3 front;
front.x = cosf(glm::radians(cameraControl.yaw)) * cosf(glm::radians(cameraControl.pitch));
front.y = sinf(glm::radians(cameraControl.pitch));
front.z = sinf(glm::radians(cameraControl.yaw)) * cosf(glm::radians(cameraControl.pitch));
front = glm::normalize(front);
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 right = glm::normalize(glm::cross(front, up));
up = glm::normalize(glm::cross(right, front));
// Get the current camera position
glm::vec3 position = cameraTransform->GetPosition();
// Apply movement based on input
if (cameraControl.moveForward) {
position += front * velocity;
}
if (cameraControl.moveBackward) {
position -= front * velocity;
}
if (cameraControl.moveLeft) {
position -= right * velocity;
}
if (cameraControl.moveRight) {
position += right * velocity;
}
if (cameraControl.moveUp) {
position += up * velocity;
}
if (cameraControl.moveDown) {
position -= up * velocity;
}
// Update camera position
cameraTransform->SetPosition(position);
// Update camera target based on a direction
glm::vec3 target = position + front;
activeCamera->SetTarget(target);
}
void Engine::GenerateBallMaterial() {
// Generate 8 random material properties for PBR
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(0.0f, 1.0f);
// Generate bright, vibrant albedo colors for better visibility
std::uniform_real_distribution<float> brightDis(0.6f, 1.0f); // Ensure bright colors
ballMaterial.albedo = glm::vec3(brightDis(gen), brightDis(gen), brightDis(gen));
// Random metallic value (0.0 to 1.0)
ballMaterial.metallic = dis(gen);
// Random roughness value (0.0 to 1.0)
ballMaterial.roughness = dis(gen);
// Random ambient occlusion (typically 0.8 to 1.0 for good lighting)
ballMaterial.ao = 0.8f + dis(gen) * 0.2f;
// Random emissive color (usually subtle)
ballMaterial.emissive = glm::vec3(dis(gen) * 0.3f, dis(gen) * 0.3f, dis(gen) * 0.3f);
// Decent bounciness (0.6 to 0.9) so bounces are clearly visible
ballMaterial.bounciness = 0.6f + dis(gen) * 0.3f;
}
void Engine::InitializePhysicsScaling() {
// Based on issue analysis: balls reaching 120+ m/s and extreme positions like (-244, -360, -244)
// The previous 200.0f force scale was causing supersonic speeds and balls flying out of scene
// Need much more conservative scaling for realistic visual gameplay
// Use smaller game unit scale for more controlled physics
physicsScaling.gameUnitsToMeters = 0.1f; // 1 game unit = 0.1 meter (10cm) - smaller scale
// Much reduced force scaling to prevent extreme speeds
// With base forces 0.01f-0.05f, this gives final forces of 0.001f-0.005f
physicsScaling.forceScale = 1.0f; // Minimal force scaling for realistic movement
physicsScaling.physicsTimeScale = 1.0f; // Keep time scale normal
physicsScaling.gravityScale = 1.0f; // Keep gravity proportional to scale
// Apply scaled gravity to physics system
glm::vec3 realWorldGravity(0.0f, -9.81f, 0.0f);
glm::vec3 scaledGravity = ScaleGravityForPhysics(realWorldGravity);
physicsSystem->SetGravity(scaledGravity);
}
float Engine::ScaleForceForPhysics(float gameForce) const {
// Scale force based on the relationship between game units and real world
// and the force scaling factor to make physics feel right
return gameForce * physicsScaling.forceScale * physicsScaling.gameUnitsToMeters;
}
glm::vec3 Engine::ScaleGravityForPhysics(const glm::vec3& realWorldGravity) const {
// Scale gravity based on game unit scale and gravity scaling factor
// If 1 game unit = 1 meter, then gravity should remain -9.81
// If 1 game unit = 0.1 meter, then gravity should be -0.981
return realWorldGravity * physicsScaling.gravityScale * physicsScaling.gameUnitsToMeters;
}
float Engine::ScaleTimeForPhysics(float deltaTime) const {
// Scale time for physics simulation if needed
// This can be used to slow down or speed up physics relative to rendering
return deltaTime * physicsScaling.physicsTimeScale;
}
void Engine::ThrowBall(float mouseX, float mouseY) {
if (!activeCamera || !physicsSystem) {
return;
}
// Get window dimensions
int windowWidth, windowHeight;
platform->GetWindowSize(&windowWidth, &windowHeight);
// Convert mouse coordinates to normalized device coordinates (-1 to 1)
float ndcX = (2.0f * mouseX) / static_cast<float>(windowWidth) - 1.0f;
float ndcY = 1.0f - (2.0f * mouseY) / static_cast<float>(windowHeight);
// Get camera matrices
glm::mat4 viewMatrix = activeCamera->GetViewMatrix();
glm::mat4 projMatrix = activeCamera->GetProjectionMatrix();
// Calculate inverse matrices
glm::mat4 invView = glm::inverse(viewMatrix);
glm::mat4 invProj = glm::inverse(projMatrix);
// Convert NDC to world space for direction
glm::vec4 rayClip = glm::vec4(ndcX, ndcY, -1.0f, 1.0f);
glm::vec4 rayEye = invProj * rayClip;
rayEye = glm::vec4(rayEye.x, rayEye.y, -1.0f, 0.0f);
glm::vec4 rayWorld = invView * rayEye;
// Calculate screen center in world coordinates
// Screen center is at NDC (0, 0) which corresponds to the center of the view
glm::vec4 screenCenterClip = glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
glm::vec4 screenCenterEye = invProj * screenCenterClip;
screenCenterEye = glm::vec4(screenCenterEye.x, screenCenterEye.y, -1.0f, 0.0f);
glm::vec4 screenCenterWorld = invView * screenCenterEye;
glm::vec3 screenCenterDirection = glm::normalize(glm::vec3(screenCenterWorld));
// Calculate world position for screen center at a reasonable distance from camera
glm::vec3 cameraPosition = activeCamera->GetPosition();
glm::vec3 screenCenterWorldPos = cameraPosition + screenCenterDirection * 2.0f; // 2 units in front of camera
// Calculate throw direction from screen center toward mouse position
glm::vec3 throwDirection = glm::normalize(glm::vec3(rayWorld));
// Add upward component for realistic arc trajectory
throwDirection.y += 0.3f; // Add upward bias for throwing arc
throwDirection = glm::normalize(throwDirection); // Re-normalize after modification
// Generate ball properties now
static int ballCounter = 0;
std::string ballName = "Ball_" + std::to_string(ballCounter++);
std::random_device rd;
std::mt19937 gen(rd());
// Launch balls from screen center toward mouse cursor
glm::vec3 spawnPosition = screenCenterWorldPos;
// Add small random variation to avoid identical paths
std::uniform_real_distribution<float> posDis(-0.1f, 0.1f);
spawnPosition.x += posDis(gen);
spawnPosition.y += posDis(gen);
spawnPosition.z += posDis(gen);
std::uniform_real_distribution<float> spinDis(-10.0f, 10.0f);
std::uniform_real_distribution<float> forceDis(15.0f, 35.0f); // Stronger force range for proper throwing feel
// Store ball creation data for processing outside rendering loop
PendingBall pendingBall;
pendingBall.spawnPosition = spawnPosition;
pendingBall.throwDirection = throwDirection; // This is now the corrected direction toward geometry
pendingBall.throwForce = ScaleForceForPhysics(forceDis(gen)); // Apply physics scaling to force
pendingBall.randomSpin = glm::vec3(spinDis(gen), spinDis(gen), spinDis(gen));
pendingBall.ballName = ballName;
pendingBalls.push_back(pendingBall);
}
void Engine::ProcessPendingBalls() {
// Process all pending balls
for (const auto& pendingBall : pendingBalls) {
// Create ball entity
Entity* ballEntity = CreateEntity(pendingBall.ballName);
if (!ballEntity) {
std::cerr << "Failed to create ball entity: " << pendingBall.ballName << std::endl;
continue;
}
// Add transform component
auto* transform = ballEntity->AddComponent<TransformComponent>();
if (!transform) {
std::cerr << "Failed to add TransformComponent to ball: " << pendingBall.ballName << std::endl;
continue;
}
transform->SetPosition(pendingBall.spawnPosition);
transform->SetScale(glm::vec3(1.0f)); // Tennis ball size scale
// Add mesh component with sphere geometry
auto* mesh = ballEntity->AddComponent<MeshComponent>();
if (!mesh) {
std::cerr << "Failed to add MeshComponent to ball: " << pendingBall.ballName << std::endl;
continue;
}
// Create tennis ball-sized, bright red sphere
glm::vec3 brightRed(1.0f, 0.0f, 0.0f);
mesh->CreateSphere(0.0335f, brightRed, 32); // Tennis ball radius, bright color, high detail
mesh->SetTexturePath(renderer->SHARED_BRIGHT_RED_ID); // Use bright red texture for visibility
// Verify mesh geometry was created
const auto& vertices = mesh->GetVertices();
const auto& indices = mesh->GetIndices();
if (vertices.empty() || indices.empty()) {
std::cerr << "ERROR: CreateSphere failed to generate geometry!" << std::endl;
continue;
}
// Pre-allocate Vulkan resources for this entity (now outside rendering loop)
if (!renderer->preAllocateEntityResources(ballEntity)) {
std::cerr << "Failed to pre-allocate resources for ball: " << pendingBall.ballName << std::endl;
continue;
}
// Create rigid body with sphere collision shape
RigidBody* rigidBody = physicsSystem->CreateRigidBody(ballEntity, CollisionShape::Sphere, 1.0f);
if (rigidBody) {
// Set bounciness from material
rigidBody->SetRestitution(ballMaterial.bounciness);
// Apply throw force and spin
glm::vec3 throwImpulse = pendingBall.throwDirection * pendingBall.throwForce;
rigidBody->ApplyImpulse(throwImpulse, glm::vec3(0.0f));
rigidBody->SetAngularVelocity(pendingBall.randomSpin);
}
}
// Clear processed balls
pendingBalls.clear();
}
void Engine::HandleMouseHover(float mouseX, float mouseY) {
// Update current mouse position for any systems that might need it
currentMouseX = mouseX;
currentMouseY = mouseY;
}
#if defined(PLATFORM_ANDROID)
// Android-specific implementation
bool Engine::InitializeAndroid(android_app* app, const std::string& appName, bool enableValidationLayers) {
// Create platform
platform = CreatePlatform(app);
if (!platform->Initialize(appName, 0, 0)) {
return false;
}
// Set resize callback
platform->SetResizeCallback([this](int width, int height) {
HandleResize(width, height);
});
// Set mouse callback
platform->SetMouseCallback([this](float x, float y, uint32_t buttons) {
// Check if ImGui wants to capture mouse input first
bool imguiWantsMouse = imguiSystem && imguiSystem->WantCaptureMouse();
if (!imguiWantsMouse) {
// Handle mouse click for ball throwing (right mouse button)
if (buttons & 2) { // Right mouse button (bit 1)
if (!cameraControl.mouseRightPressed) {
cameraControl.mouseRightPressed = true;
// Throw a ball on mouse click
ThrowBall(x, y);
}
} else {
cameraControl.mouseRightPressed = false;
}
}
if (imguiSystem) {
imguiSystem->HandleMouse(x, y, buttons);
}
});
// Set keyboard callback
platform->SetKeyboardCallback([this](uint32_t key, bool pressed) {
if (imguiSystem) {
imguiSystem->HandleKeyboard(key, pressed);
}
});
// Set char callback
platform->SetCharCallback([this](uint32_t c) {
if (imguiSystem) {
imguiSystem->HandleChar(c);
}
});
// Create renderer
renderer = std::make_unique<Renderer>(platform.get());
if (!renderer->Initialize(appName, enableValidationLayers)) {
return false;
}
// Initialize model loader
if (!modelLoader->Initialize(renderer.get())) {
return false;
}
// Connect model loader to renderer for light extraction
renderer->SetModelLoader(modelLoader.get());
// Initialize audio system
if (!audioSystem->Initialize(this, renderer.get())) {
return false;
}
// Initialize physics system
physicsSystem->SetRenderer(renderer.get());
// Enable GPU acceleration for physics calculations to drastically speed up computations
physicsSystem->SetGPUAccelerationEnabled(true);
if (!physicsSystem->Initialize()) {
return false;
}
// Get window dimensions from platform
int width, height;
platform->GetWindowSize(&width, &height);
// Initialize ImGui system
if (!imguiSystem->Initialize(renderer.get(), width, height)) {
return false;
}
// Connect ImGui system to audio system for UI controls
imguiSystem->SetAudioSystem(audioSystem.get());
// Generate ball material properties once at load time
GenerateBallMaterial();
// Initialize physics scaling system
InitializePhysicsScaling();
initialized = true;
return true;
}
void Engine::RunAndroid() {
if (!initialized) {
throw std::runtime_error("Engine not initialized");
}
running = true;
// Main loop is handled by the platform
// We just need to update and render when the platform is ready
// Calculate delta time
deltaTimeMs = CalculateDeltaTimeMs();
// Update
Update(deltaTimeMs);
// Render
Render();
}
#endif