Repository navigation
Expand file tree
/
Copy pathproject-rts.cpp
More file actions
2178 lines (1801 loc) · 85.7 KB
/
Copy pathproject-rts.cpp
File metadata and controls
2178 lines (1801 loc) · 85.7 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
#include <iostream>
#include <string>
#include <algorithm>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <GL/glew.h>
#include <glfw3.h>
#include <common/shader.h>
#include <common/util.h>
#include <common/camera.h>
#include "common/texture.h"
#include <glm/gtc/type_ptr.hpp>
#include "Terrain.h"
#include "ShadowMap.h"
#include "SnowTrailMap.h"
#include "Building.h"
#include <vector>
#include <memory>
#include "Unit.h"
#include "Environment.h"
#include "Resource.h"
#include "SkinnedMesh.h"
#include "Pathfinder.h"
#include "NavigationGrid.h"
#include "Frustum.h"
#include "ParticleManager.h"
// ---------------------------------------------------------------
using namespace std;
using namespace glm;
// ---------------------------------------------------------------
#define W_WIDTH 1920 //1920
#define W_HEIGHT 1080 //1080
#define TITLE "RTS Project"
// ---------------------------------------------------------------
GLFWwindow* window = nullptr;
Camera* camera = nullptr;
GLuint shaderProgram = 0;
GLuint terrainShader = 0;
SnowTrailMap* snowTrailMap = nullptr;
GLuint snowTrailShader = 0;
ShadowMap* shadowMap = nullptr;
GLuint shadowShader = 0;
GLuint debugShader = 0;
GLuint quadVAO = 0, quadVBO = 0, quadEBO = 0;
GLuint dummyPointVAO = 0, dummyPointVBO = 0;
GLuint shadowMapTexUnit = 5;
bool showDepthMap = false;
GLuint shadowMapLoc_standard = 0;
GLuint lightSpaceMatrixLoc_standard = 0;
GLuint instancedShader = 0;
GLuint particleShaderProgram = 0;
std::vector<std::unique_ptr<IntParticleEmitter>> ParticleManager::active_emitters;
Drawable* ParticleManager::particle_quad = nullptr;
Frustum cameraFrustum;
Environment* environment = nullptr;
SkinnedMesh* myActor = nullptr;
//GLuint skinnedShader = 0;
GLuint texWorker = 0;
GLuint texWarrior = 0;
GLuint texMage = 0;
// Building Textures
GLuint texTownCenter = 0;
GLuint texBarracks = 0;
GLuint texArchery = 0;
// Nature Textures (pass these to Environment later)
GLuint texTree = 0;
GLuint texRock = 0;
GLuint fireTexture = 0;
GLuint whiteShader = 0;
NavigationGrid* navGrid = nullptr;
// Uniform locations (standard shader)
GLuint projectionMatrixLocation, viewMatrixLocation, modelMatrixLocation;
GLuint KaLocation, KdLocation, KsLocation, NsLocation;
GLuint LaLocation, LdLocation, LsLocation, lightDirectionLocation, lightPowerLocation;
// ---------------------------------------------------------------
// SELECTION & INPUT GLOBALS
// ---------------------------------------------------------------
enum class InputMode { UNIT_SELECT, RESOURCE_SELECT, ATTACK_SELECT};
InputMode currentMode = InputMode::UNIT_SELECT; // Default
// Left Click (Generic Dragging)
bool isDragging = false;
bool isRightDragging = false;
glm::vec3 dragStartWorld;
glm::vec3 dragEndWorld;
// Camera Mode State
bool unitCameraMode = false;
Unit* focusedUnit = nullptr;
// ---------------------------------------------------------------
struct Light {
vec4 La, Ld, Ls;
vec3 dir;
float power;
};
struct Material {
vec4 Ka, Kd, Ks;
float Ns;
};
const Material defaultMaterial{
vec4{0.1f,0.1f,0.1f,1},
vec4{1.0f,1.0f,1.0f,1.0f},
vec4{0.3f,0.3f,0.3f,1},
20.0f
};
Light light{
vec4{0.2f,0.2f,0.2f,1},
vec4{1,1,1,1},
vec4{1,1,1,1},
vec3(0,10,0),
1.0f
};
Terrain* terrain = nullptr;
std::vector<std::unique_ptr<Building>> buildings;
bool placingBuilding = false;
bool isPlacementValid = false;
BuildingType currentPlaceType = BuildingType::TOWN_CENTER;
std::unique_ptr<Building> previewBuilding = nullptr;
std::vector<std::unique_ptr<Unit>> units;
Resources playerResources;
// ---------------------------------------------------------------
void createContext()
{
// Standard shader
shaderProgram = loadShaders("StandardShading.vertexshader", "StandardShading.fragmentshader");
GLint isLinked = 0;
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &isLinked);
if (isLinked == GL_FALSE) {
GLint maxLength = 0;
glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<char> infoLog(maxLength);
glGetProgramInfoLog(shaderProgram, maxLength, &maxLength, &infoLog[0]);
std::cout << "CRITICAL SHADER ERROR: " << &infoLog[0] << std::endl;
return; // Stop execution here so you can read the error
}
projectionMatrixLocation = glGetUniformLocation(shaderProgram, "P");
viewMatrixLocation = glGetUniformLocation(shaderProgram, "V");
modelMatrixLocation = glGetUniformLocation(shaderProgram, "M");
KaLocation = glGetUniformLocation(shaderProgram, "mtl.Ka");
KdLocation = glGetUniformLocation(shaderProgram, "mtl.Kd");
KsLocation = glGetUniformLocation(shaderProgram, "mtl.Ks");
NsLocation = glGetUniformLocation(shaderProgram, "mtl.Ns");
LaLocation = glGetUniformLocation(shaderProgram, "light.La");
LdLocation = glGetUniformLocation(shaderProgram, "light.Ld");
LsLocation = glGetUniformLocation(shaderProgram, "light.Ls");
lightDirectionLocation = glGetUniformLocation(shaderProgram, "lightDirection_worldspace");
lightPowerLocation = glGetUniformLocation(shaderProgram, "light.power");
shadowMapLoc_standard = glGetUniformLocation(shaderProgram, "shadowMap");
lightSpaceMatrixLoc_standard = glGetUniformLocation(shaderProgram, "lightSpaceMatrix");
glUseProgram(shaderProgram);
glUniform1i(shadowMapLoc_standard, 5);
glUseProgram(0);
// Terrain shader
terrainShader = loadShaders("terrain.vertexshader", "terrain.fragmentshader");
terrain = new Terrain(512, 512, 1.05f);
// Create environment
environment = new Environment();
//create navigation grid
navGrid = new NavigationGrid(512, 512);
environment->initialize(terrain,navGrid, 512.0f, 1500);
environment->setTextures(texTree, texRock);
shadowShader = loadShaders("ShadowMap.vertexshader", "ShadowMap.fragmentshader");
shadowMap = new ShadowMap(4096, 4096);
snowTrailMap = new SnowTrailMap(2048, 2048);
snowTrailMap->clear(); // FULL SNOW at start
snowTrailShader = loadShaders("SnowTrail.vertexshader", "SnowTrail.fragmentshader");
debugShader = loadShaders("debugDepthShader.vertexshader", "debugDepthShader.fragmentshader");
whiteShader = loadShaders("White.vertexshader", "White.fragmentshader");
//skinnedShader = loadShaders("SkinnedShading.vertexshader", "SkinnedShading.fragmentshader");
instancedShader = loadShaders("SkinnedInstanced.vertexshader", "SkinnedInstanced.fragmentshader");
// Debug quad
float quadVertices[] = {
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 0.0f, 1.0f
};
unsigned int indices[] = { 0, 1, 2, 0, 2, 3 };
glGenVertexArrays(1, &quadVAO);
glGenBuffers(1, &quadVBO);
glGenBuffers(1, &quadEBO);
glBindVertexArray(quadVAO);
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, quadEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
glBindVertexArray(0);
// DUMMY VAO/VBO for snow trail points
glGenVertexArrays(1, &dummyPointVAO);
glGenBuffers(1, &dummyPointVBO);
glBindVertexArray(dummyPointVAO);
glBindBuffer(GL_ARRAY_BUFFER, dummyPointVBO);
float dummy = 0.0f;
glBufferData(GL_ARRAY_BUFFER, sizeof(float), &dummy, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 1, GL_FLOAT, GL_FALSE, sizeof(float), (void*)0);
glBindVertexArray(0);
// Starting content
vec3 myTownCenterPos = vec3(50.0f, 0.0f, 50.0f);
terrain->flattenArea(myTownCenterPos, 15.0f); // Flatten first
buildings.push_back(std::make_unique<Building>(BuildingType::TOWN_CENTER, myTownCenterPos,0));
buildings.back()->updateConstruction(10000.0f);
vec3 enemyTownCenterPos = vec3(460.0f, 0.0f, 460.0f);
terrain->flattenArea(enemyTownCenterPos, 15.0f); //Flatten first
buildings.push_back(std::make_unique<Building>(BuildingType::TOWN_CENTER, enemyTownCenterPos,1));
buildings.back()->updateConstruction(10000.0f);
vec3 enemyBarracksCenterPos = vec3(50.0f, 0.0f, 120.0f);
terrain->flattenArea(enemyBarracksCenterPos, 15.0f); //Flatten first
buildings.push_back(std::make_unique<Building>(BuildingType::BARRACKS, enemyBarracksCenterPos, 1));
buildings.back()->updateConstruction(10000.0f);
// ---------------------------------------------------------
// PERFORMANCE TEST: MASSIVE ARMY SPAWNER
// ---------------------------------------------------------
// Army 1: Player (Green/Team 0)
//int rows = 10;
//int cols = 10; // 10 * 10 = 100 Units
//float spacing = 2.5f;
//vec3 startPosPlayer(220.0f, 0.0f, 220.0f);
//for (int i = 0; i < rows; ++i) {
// for (int j = 0; j < cols; ++j) {
// float x = startPosPlayer.x + (j * spacing);
// float z = startPosPlayer.z + (i * spacing);
// // Mix up unit types for variety
// UnitType type;
// int r = (i + j) % 3;
// if (r == 0) type = UnitType::MELEE;
// else if (r == 1) type = UnitType::RANGED;
// else type = UnitType::WORKER;
// // Optional: Check grid to avoid spawning inside rocks
// if (navGrid && !navGrid->isBlocked((int)x, (int)z)) {
// units.push_back(std::make_unique<Unit>(type, vec3(x, 0.0f, z), 0));
// }
// }
//}
//// Army 2: Enemy (Red/Team 1)
//vec3 startPosEnemy(300.0f, 0.0f, 300.0f);
//for (int i = 0; i < rows; ++i) {
// for (int j = 0; j < cols; ++j) {
// float x = startPosEnemy.x + (j * spacing);
// float z = startPosEnemy.z + (i * spacing);
// UnitType type;
// int r = (i + j) % 3;
// if (r == 0) type = UnitType::MELEE;
// else if (r == 1) type = UnitType::RANGED;
// else type = UnitType::WORKER;
// if (navGrid && !navGrid->isBlocked((int)x, (int)z)) {
// units.push_back(std::make_unique<Unit>(type, vec3(x, 0.0f, z), 1));
// }
// }
//}
//std::cout << "--- PERFORMANCE TEST STARTED ---" << std::endl;
//std::cout << "Total Units Spawned: " << units.size() << std::endl;
// BAKE STATIC OBSTACLES (Trees/Rocks)
const std::vector<Obstacle>& envObstacles = environment->getObstacles();
for (const auto& obs : envObstacles) {
navGrid->updateArea(obs.position, obs.radius, true);
}
// BAKE BUILDINGS
for (const auto& b : buildings) {
float r = (b->getType() == BuildingType::TOWN_CENTER) ? 12.0f : 8.0f;
navGrid->updateArea(b->getPosition(), r, true);
}
// BAKE MAP BORDERS
// This ensures units never walk into the edge rocks or off the map
int mapSize = 512;
int borderThickness = 30; // Width of the rock border
// We loop through the grid pixels
for (int x = 0; x < mapSize; x++) {
for (int z = 0; z < mapSize; z++) {
// If we are close to ANY edge (Left, Right, Top, Bottom)
if (x < borderThickness || x >= mapSize - borderThickness ||
z < borderThickness || z >= mapSize - borderThickness) {
// Mark as BLOCKED manually
navGrid->updateArea(glm::vec3(x, 0, z), 0.5f, true);
}
}
}
//Particles
ParticleManager::init(new Drawable("models/sphere.obj"));
particleShaderProgram = loadShaders("ParticleShader.vertexshader", "ParticleShader.fragmentshader");
}
void checkGLError(const std::string& label) {
GLenum err;
while ((err = glGetError()) != GL_NO_ERROR) {
std::cout << "GL Error at " << label << ": " << std::hex << err << std::endl;
}
}
void uploadMaterial(const Material& m) {
glUniform4f(KaLocation, m.Ka.r, m.Ka.g, m.Ka.b, m.Ka.a);
glUniform4f(KdLocation, m.Kd.r, m.Kd.g, m.Kd.b, m.Kd.a);
glUniform4f(KsLocation, m.Ks.r, m.Ks.g, m.Ks.b, m.Ks.a);
glUniform1f(NsLocation, m.Ns);
}
void uploadLight(const Light& l) {
glUniform4f(LaLocation, l.La.r, l.La.g, l.La.b, l.La.a);
glUniform4f(LdLocation, l.Ld.r, l.Ld.g, l.Ld.b, l.Ld.a);
glUniform4f(LsLocation, l.Ls.r, l.Ls.g, l.Ls.b, l.Ls.a);
glUniform3f(lightDirectionLocation, l.dir.x, l.dir.y, l.dir.z);
glUniform1f(lightPowerLocation, l.power);
}
// Get world position under cursor
vec3 getWorldPosUnderCursor()
{
double mx, my;
glfwGetCursorPos(window, &mx, &my);
my = W_HEIGHT - my;
mat4 proj = camera->projectionMatrix;
mat4 view = camera->viewMatrix;
vec4 viewport(0, 0, W_WIDTH, W_HEIGHT);
vec3 nearPoint = unProject(vec3((float)mx, (float)my, 0.0f), view, proj, viewport);
vec3 farPoint = unProject(vec3((float)mx, (float)my, 1.0f), view, proj, viewport);
vec3 dir = normalize(farPoint - nearPoint);
if (abs(dir.y) < 0.0001f) return vec3(0.0f);
float t = -nearPoint.y / dir.y;
if (t < 0) return vec3(0.0f);
return nearPoint + dir * t;
}
// Helper: Convert World 3D to Screen 2D
vec2 worldToScreen(vec3 worldPos, mat4 view, mat4 proj) {
vec4 clip = proj * view * vec4(worldPos, 1.0f);
if (clip.w <= 0) return vec2(-1, -1); // Behind camera
vec3 ndc = vec3(clip) / clip.w;
float screenX = (ndc.x + 1.0f) * 0.5f * W_WIDTH;
float screenY = (1.0f - ndc.y) * 0.5f * W_HEIGHT; // Flip Y for OpenGL coords
return vec2(screenX, screenY);
}
// Logic: Handle ALL Mouse Input (Left & Right)
void handleInput() {
if (placingBuilding) return;
// -------------------------------------------------------
// 1. TOGGLE MODES
// -------------------------------------------------------
static bool lastR = false;
if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS && !lastR) {
currentMode = (currentMode == InputMode::RESOURCE_SELECT) ? InputMode::UNIT_SELECT : InputMode::RESOURCE_SELECT;
std::cout << ">>> MODE: " << (currentMode == InputMode::RESOURCE_SELECT ? "RESOURCE" : "UNIT") << " <<<" << std::endl;
}
lastR = glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS;
static bool lastB = false;
if (glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS && !lastB) {
currentMode = (currentMode == InputMode::ATTACK_SELECT) ? InputMode::UNIT_SELECT : InputMode::ATTACK_SELECT;
std::cout << ">>> MODE: " << (currentMode == InputMode::ATTACK_SELECT ? "ATTACK" : "UNIT") << " <<<" << std::endl;
}
lastB = glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS;
// -------------------------------------------------------
// 2. LEFT MOUSE: SELECTION & ACTION
// -------------------------------------------------------
static bool wasLeftPressed = false;
bool isLeftPressed = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
if (isLeftPressed && !wasLeftPressed) {
isDragging = true;
dragStartWorld = getWorldPosUnderCursor();
}
if (isDragging) dragEndWorld = getWorldPosUnderCursor();
if (!isLeftPressed && wasLeftPressed && isDragging) {
isDragging = false;
mat4 P = camera->projectionMatrix;
mat4 V = camera->viewMatrix;
vec2 startScreen = worldToScreen(dragStartWorld, V, P);
vec2 endScreen = worldToScreen(dragEndWorld, V, P);
float minX = std::min(startScreen.x, endScreen.x);
float maxX = std::max(startScreen.x, endScreen.x);
float minY = std::min(startScreen.y, endScreen.y);
float maxY = std::max(startScreen.y, endScreen.y);
bool isClick = (maxX - minX < 5 && maxY - minY < 5);
bool shiftHeld = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS;
// =========================================================
// MODE A: STANDARD UNIT SELECTION (Green Box)
// =========================================================
if (currentMode == InputMode::UNIT_SELECT) {
if (!shiftHeld) {
for (auto& u : units) u->setSelected(false);
focusedUnit = nullptr;
unitCameraMode = false;
}
if (isClick) {
float minDist = 5.0f;
Unit* closest = nullptr;
for (auto& u : units) {
float dist = distance(u->getPosition(), dragEndWorld);
if (dist < minDist) { minDist = dist; closest = u.get(); }
}
if (closest) closest->setSelected(true);
}
else {
for (auto& u : units) {
vec2 sPos = worldToScreen(u->getPosition(), V, P);
if (sPos.x >= minX && sPos.x <= maxX && sPos.y >= minY && sPos.y <= maxY) {
u->setSelected(true);
}
}
}
}
// =========================================================
// MODE B: RESOURCE TARGETING (Yellow Box)
// =========================================================
else if (currentMode == InputMode::RESOURCE_SELECT) {
std::vector<Unit*> workers;
for (auto& u : units) {
if (u->isSelected() && u->getType() == UnitType::WORKER) {
workers.push_back(u.get());
}
}
if (!workers.empty()) {
auto& allObs = environment->getObstacles();
// 1. Collect ALL selected resources first
std::vector<int> targetResources;
for (auto& obs : allObs) {
if (!obs.active) continue;
bool inBox = false;
if (isClick) {
// Click selection (Radius check)
if (glm::distance(obs.position, dragEndWorld) < obs.radius + 1.0f) inBox = true;
}
else {
// Box selection (Screen space check)
glm::vec2 sPos = worldToScreen(obs.position, V, P);
if (sPos.x >= minX && sPos.x <= maxX && sPos.y >= minY && sPos.y <= maxY) inBox = true;
}
if (inBox) {
obs.marked = true; // Visual feedback
targetResources.push_back(obs.id); // Add ID to list
}
}
// 2. Assign the list to workers (They will shuffle it internally)
if (!targetResources.empty()) {
for (auto* w : workers) {
w->assignGatherQueue(targetResources);
}
std::cout << "Assigned " << targetResources.size() << " resources to " << workers.size() << " workers." << std::endl;
}
}
// Auto-switch back to normal mode
currentMode = InputMode::UNIT_SELECT;
}
// =========================================================
// MODE C: ATTACK TARGETING (Red Box)
// =========================================================
else if (currentMode == InputMode::ATTACK_SELECT) {
std::vector<Unit*> myUnits;
for (auto& u : units) if (u->isSelected() && u->getTeam() == 0) myUnits.push_back(u.get());
if (!myUnits.empty()) {
vec3 clickPos = dragEndWorld;
bool commandIssued = false;
// ---------------------------------------------
// 1. Check for Enemy UNITS
// ---------------------------------------------
std::vector<Unit*> enemyTargets;
for (auto& u : units) {
if (u->getTeam() == 1) { // Is Enemy
bool targeted = false;
if (isClick) {
if (distance(u->getPosition(), clickPos) < 10.0f) targeted = true;
}
else {
vec2 sPos = worldToScreen(u->getPosition(), V, P);
if (sPos.x >= minX && sPos.x <= maxX && sPos.y >= minY && sPos.y <= maxY) targeted = true;
}
if (targeted) enemyTargets.push_back(u.get());
}
}
if (!enemyTargets.empty()) {
//std::cout << "Command: ATTACK UNITS (" << enemyTargets.size() << " enemies queued)" << std::endl;
commandIssued = true;
// SMART QUEUEING (Units)
for (auto* myUnit : myUnits) {
std::vector<Unit*> sortedTargets = enemyTargets;
std::sort(sortedTargets.begin(), sortedTargets.end(),
[myUnit](Unit* a, Unit* b) {
float distA = glm::distance(myUnit->getPosition(), a->getPosition());
float distB = glm::distance(myUnit->getPosition(), b->getPosition());
return distA < distB;
});
myUnit->assignAttackQueue(sortedTargets);
}
}
// ---------------------------------------------
// 2. Check for Enemy BUILDINGS (If no units clicked)
// ---------------------------------------------
if (!commandIssued && isClick) {
for (const auto& b : buildings) {
// Check if Enemy (Team 1)
if (b->getTeam() == 1) {
// Hitbox check (Radius approx 15-20)
float dist = glm::distance(clickPos, b->getPosition());
if (dist < 20.0f) {
std::cout << "Command: ATTACK BUILDING!" << std::endl;
commandIssued = true;
// Order all selected units to attack this building
for (auto* myUnit : myUnits) {
myUnit->assignAttackTask(b.get());
}
break; // Target found
}
}
}
}
if (!commandIssued) {
std::cout << "Attack command cancelled (No targets clicked)" << std::endl;
}
}
// Reset cursor to normal after command
currentMode = InputMode::UNIT_SELECT;
}
}
wasLeftPressed = isLeftPressed;
// -------------------------------------------------------
// 3. RIGHT MOUSE: MOVE (Always available as fallback)
// -------------------------------------------------------
static bool wasRightPressed = false;
bool isRightPressed = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS;
if (isRightPressed && !wasRightPressed) {
isRightDragging = true;
dragStartWorld = getWorldPosUnderCursor(); // Reuse global for start pos
}
// We use the same globals for drag start/end to simplify visuals,
// but logic handles them separately below.
if (isRightDragging) dragEndWorld = getWorldPosUnderCursor();
if (!isRightPressed && wasRightPressed && isRightDragging) {
isRightDragging = false;
vec3 clickPos = dragEndWorld;
// Collect My Selected Units
std::vector<Unit*> myUnits;
for (auto& u : units) if (u->isSelected() && u->getTeam() == 0) myUnits.push_back(u.get());
if (!myUnits.empty()) {
std::cout << "Command: Move (Shared Path + Formation)" << std::endl;
// 1. Calculate Group Center
vec3 groupCenter(0.0f);
for (auto* u : myUnits) groupCenter += u->getPosition();
groupCenter /= (float)myUnits.size();
// 2. Calculate ONE path from Center -> Mouse Click
std::vector<vec3> sharedPath = Pathfinder::findPath(groupCenter, clickPos, navGrid);
// 3. Assign path, but give each unit a unique END POINT
int count = myUnits.size();
float spacing = 3.0f;
for (int i = 0; i < count; i++) {
// Calculate Formation Offset (Spiral)
float radius = spacing * std::sqrt(i);
float angle = i * 2.4f;
vec3 offset(cos(angle) * radius, 0.0f, sin(angle) * radius);
// Copy the shared path
std::vector<vec3> myPersonalPath = sharedPath;
//Change the LAST point to be their unique spot
if (!myPersonalPath.empty()) {
myPersonalPath.back() = clickPos + offset;
}
else {
// If path was empty (very close), just push the single point
myPersonalPath.push_back(clickPos + offset);
}
myUnits[i]->clearTasks();
myUnits[i]->setPath(myPersonalPath);
}
// Visual cleanup
auto& allObs = environment->getObstacles();
for (auto& o : allObs) o.marked = false;
if (currentMode != InputMode::UNIT_SELECT) {
currentMode = InputMode::UNIT_SELECT;
}
}
}
wasRightPressed = isRightPressed;
// -------------------------------------------------------
// 4. CAMERA MODE TOGGLE ('C')
// -------------------------------------------------------
static bool lastC = false;
bool pressC = glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS;
if (pressC && !lastC) {
if (unitCameraMode) {
unitCameraMode = false;
}
else {
focusedUnit = nullptr;
for (auto& u : units) {
if (u->isSelected()) {
focusedUnit = u.get();
unitCameraMode = true;
break;
}
}
}
}
lastC = pressC;
static bool lastG = false;
bool keyG = glfwGetKey(window, GLFW_KEY_G) == GLFW_PRESS;
if (keyG && !lastG) {
for (auto& u : units) {
if (u->isSelected() && u->getType() == UnitType::MELEE) {
glm::vec3 pos = u->getPosition();
float radius = 12.0f;
// --- 1. PHYSICAL HOLE (Deform the actual 3D Mesh) ---
// --- 1. PHYSICAL HOLE (Deform the actual 3D Mesh) ---
terrain->createHole(pos, radius, 4.0f); // 4.0 units deep
// --- 3. GAMEPLAY & PARTICLES ---
navGrid->updateArea(pos, radius, true); // Block pathfinding
ParticleManager::addExplosion(pos); // Fire visuals
u->explode(); // Kill unit
}
}
}
lastG = keyG;
}
// Render: Draw the Drag Box (Green for Select, Yellow for Harvest)
void drawSelectionBox() {
if (!isDragging) return;
glDisable(GL_DEPTH_TEST);
glUseProgram(0);
mat4 P = camera->projectionMatrix;
mat4 V = camera->viewMatrix;
vec2 startScreen = worldToScreen(dragStartWorld, V, P);
vec2 endScreen = worldToScreen(dragEndWorld, V, P);
if (startScreen.x == -1 || endScreen.x == -1) return;
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, W_WIDTH, W_HEIGHT, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// COLOR BASED ON MODE
vec3 col;
if (currentMode == InputMode::UNIT_SELECT) col = vec3(0.0f, 1.0f, 0.0f); // Green
else if (currentMode == InputMode::RESOURCE_SELECT) col = vec3(1.0f, 1.0f, 0.0f); // Yellow
else col = vec3(1.0f, 0.0f, 0.0f); // Red (Attack)
// Outline
glColor4f(col.x, col.y, col.z, 1.0f);
glLineWidth(2.0f);
glBegin(GL_LINE_LOOP);
glVertex2f(startScreen.x, startScreen.y);
glVertex2f(endScreen.x, startScreen.y);
glVertex2f(endScreen.x, endScreen.y);
glVertex2f(startScreen.x, endScreen.y);
glEnd();
// Fill
glDisable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(col.x, col.y, col.z, 0.2f);
glBegin(GL_QUADS);
glVertex2f(startScreen.x, startScreen.y);
glVertex2f(endScreen.x, startScreen.y);
glVertex2f(endScreen.x, endScreen.y);
glVertex2f(startScreen.x, endScreen.y);
glEnd();
glDisable(GL_BLEND);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
}
// Render: Selection Rings under units
void drawSelectionRings(mat4 V, mat4 P) {
//glDisable(GL_DEPTH_TEST);
glUseProgram(0);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(&P[0][0]);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(&V[0][0]);
// ---------------------------------------------------------
// 1. Rings for SELECTED UNITS (Status Colors)
// ---------------------------------------------------------
for (const auto& u : units) {
if (u->isSelected()) {
vec3 pos = u->getPosition();
// Dynamic Color Logic
if (u->isGathering()) glColor3f(1.0f, 1.0f, 0.0f); // Yellow (Working)
else if (u->isAttacking() || u->isAttackingBuilding()) glColor3f(1.0f, 0.0f, 0.0f); // Red (Fighting)
else glColor3f(0.0f, 1.0f, 0.0f); // Green (Idle)
glLineWidth(2.0f);
glBegin(GL_LINE_LOOP);
float r = 2.5f;
for (int i = 0; i < 16; i++) {
float theta = 2.0f * 3.14159f * float(i) / 16.0f;
float x = r * cosf(theta);
float z = r * sinf(theta);
glVertex3f(pos.x + x, pos.y + 0.5f, pos.z + z);
}
glEnd();
}
}
// ---------------------------------------------------------
// 2. Rings for TARGETS (When in Attack Mode)
// ---------------------------------------------------------
if (currentMode == InputMode::ATTACK_SELECT) {
// A. Enemy Units
for (const auto& u : units) {
if (u->getTeam() == 1) { // Enemy
vec3 pos = u->getPosition();
glColor3f(1.0f, 0.0f, 0.0f); // Red Ring
glLineWidth(2.0f);
glBegin(GL_LINE_LOOP);
float r = 3.0f;
for (int i = 0; i < 16; i++) {
float theta = 2.0f * 3.14159f * float(i) / 16.0f;
float x = r * cosf(theta);
float z = r * sinf(theta);
glVertex3f(pos.x + x, pos.y + 0.5f, pos.z + z);
}
glEnd();
}
}
// B. Enemy Buildings (NEW)
for (const auto& b : buildings) {
if (b->getTeam() == 1) { // Enemy Building
vec3 pos = b->getPosition();
glColor3f(1.0f, 0.0f, 0.0f); // Red Ring
glLineWidth(3.0f); // Thicker for buildings
glBegin(GL_LINE_LOOP);
// Larger Radius for buildings (matches Town Center size roughly)
float r = 18.0f;
for (int i = 0; i < 32; i++) {
float theta = 2.0f * 3.14159f * float(i) / 32.0f;
float x = r * cosf(theta);
float z = r * sinf(theta);
glVertex3f(pos.x + x, pos.y + 1.0f, pos.z + z);
}
glEnd();
}
}
}
glEnable(GL_DEPTH_TEST);
}
// Render: Resource Rings (Yellow)
void drawResourceRings(mat4 V, mat4 P) {
glDisable(GL_DEPTH_TEST);
glUseProgram(0);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(&P[0][0]);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(&V[0][0]);
// Use the getter from Environment
const auto& obstacles = environment->getObstacles();
for (const auto& obs : obstacles) {
// Draw only if Active AND Marked
if (obs.active && obs.marked) {
// Yellow Color
glColor3f(1.0f, 1.0f, 0.0f);
glLineWidth(2.0f);
glBegin(GL_LINE_LOOP);
// Radius slightly larger than the object
float r = obs.radius + 1.5f;
for (int i = 0; i < 16; i++) {
float theta = 2.0f * 3.14159f * float(i) / 16.0f;
float x = r * cosf(theta);
float z = r * sinf(theta);
// Lift Y by 1.0f to ensure it sits on top of the grass
glVertex3f(obs.position.x + x, obs.position.y + 1.0f, obs.position.z + z);
}
glEnd();
}
}
glEnable(GL_DEPTH_TEST);
}
// Handle building placement
void updateBuildingPlacement()
{
static bool last1 = false, last2 = false, last3 = false;
bool key1 = glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS;
bool key2 = glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS;
bool key3 = glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS;
// -----------------------------------------------------------
// 1. DETERMINE RADIUS (Move this up so we can use it for checking)
// -----------------------------------------------------------
// We need to know the size BEFORE we click to check collisions.
float buildingRadius = 12.0f;
if (currentPlaceType == BuildingType::TOWN_CENTER) buildingRadius = 15.0f;
else if (currentPlaceType == BuildingType::BARRACKS) buildingRadius = 12.0f;
else if (currentPlaceType == BuildingType::SHOOTING_RANGE) buildingRadius = 10.0f;
// -----------------------------------------------------------
// 2. START PLACEMENT
// -----------------------------------------------------------
if (key1 && !last1) {
placingBuilding = true;
currentPlaceType = BuildingType::TOWN_CENTER;
vec3 pos = getWorldPosUnderCursor();
pos.y = 0.0f;
previewBuilding = std::make_unique<Building>(currentPlaceType, pos, 0);
}
if (key2 && !last2) {
placingBuilding = true;
currentPlaceType = BuildingType::BARRACKS;
vec3 pos = getWorldPosUnderCursor();
pos.y = 0.0f;
previewBuilding = std::make_unique<Building>(currentPlaceType, pos, 0);
}
if (key3 && !last3) {
placingBuilding = true;
currentPlaceType = BuildingType::SHOOTING_RANGE;
vec3 pos = getWorldPosUnderCursor();
pos.y = 0.0f;
previewBuilding = std::make_unique<Building>(currentPlaceType, pos, 0);
}
last1 = key1; last2 = key2; last3 = key3;
// -----------------------------------------------------------
// 3. CHECK VALIDITY & UPDATE PREVIEW
// -----------------------------------------------------------
// Default to false (safety)
isPlacementValid = false;
if (placingBuilding && previewBuilding) {
vec3 pos = getWorldPosUnderCursor();
pos.y = 0.0f;
previewBuilding->setPosition(pos);
// Calculate Radius (matches your building types)
float buildingRadius = 12.0f;
if (currentPlaceType == BuildingType::TOWN_CENTER) buildingRadius = 15.0f;
else if (currentPlaceType == BuildingType::BARRACKS) buildingRadius = 12.0f;
else if (currentPlaceType == BuildingType::SHOOTING_RANGE) buildingRadius = 10.0f;
// VALIDITY CHECK LOOP
// Assume valid until we hit a block
bool valid = true;
if (navGrid) {
int range = (int)buildingRadius;
for (int x = -range; x <= range; x += 2) {
for (int z = -range; z <= range; z += 2) {
// Circular check
if (glm::length(glm::vec2(x, z)) > buildingRadius) continue;
int gridX = (int)pos.x + x;
int gridZ = (int)pos.z + z;
// Check Bounds & Collisions
if (gridX < 0 || gridX >= 512 || gridZ < 0 || gridZ >= 512 ||