-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cpp
More file actions
528 lines (439 loc) · 18.3 KB
/
Copy pathmain.cpp
File metadata and controls
528 lines (439 loc) · 18.3 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
extern "C" {
__declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
#include "graphics/Renderer.h"
#include "Constants.h"
//#include "mapbuilder/MapGrid.cpp"
#include "audio/AudioManager.h"
#include "glm/gtx/intersect.hpp"
#include "gamemaster/GameMaster.h"
#include "ecs/entity/EntityManager.h"
#include "Universe.h"
#include <chrono>
#include <functional>
//Noesis stuff, not all of this may be needed
#include <NsRender/RenderContext.h>
#include <NsCore/HighResTimer.h>
#include <NsGui/IntegrationAPI.h>
#include <NsGui/UserControl.h>
#include <NsGui/CheckBox.h>
#include <NsGui/TextBlock.h>
#include <NsGui/Button.h>
#include <NsGui/Grid.h>
#include <NsGui/IRenderer.h>
#include <NsGui/IView.h>
#include <NsGui/ResourceDictionary.h>
#include <NsApp/EntryPoint.h>
#include <NsApp/Launcher.h>
#include <NsApp/Display.h>
#include <NsApp/LocalXamlProvider.h>
#include <NsApp/LocalFontProvider.h>
#include <NsApp/ThemeProviders.h>
#include <NsGui/VisualTreeHelper.h>
#include <NsRender/GLFactory.h>
#include <NsRender/GLRenderDeviceApi.h>
// AI inlucde
#include "../headers/systems/AISystem.h"
// UI
#include "../headers/ui/UIController.h"
//NsMain is a lot like like main but Noesis-flavoured and evidently platform-agnostic
int NsMain(int argc, char** argv) {
NS_UNUSED(argc, argv);
//Timer for testing audio
int gunshotTimer = 0;
//Audio
AudioManager audioManager;
uint32_t gunA = audioManager.getSoundEffect("spellHit");
uint32_t gunB = audioManager.getSoundEffect("spellCast");
try {
if (!glfwInit()) {
throw std::runtime_error("Failed GLFW Init.");
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_VERSION_MINOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE);
GLFWwindow* window;
window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Window", 0, nullptr);
if (window == NULL) {
glfwTerminate();
throw std::runtime_error("Failed to create window.");
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
throw std::runtime_error("Failed to initialize GLAD.");
}
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
Renderer renderer = Renderer(window, WINDOW_WIDTH, WINDOW_HEIGHT);
//Texture loading
renderer.loadTexture("assets/textures/tree_texture.png", "tree_texture");
renderer.loadTexture("assets/textures/white.png", "white");
renderer.loadTexture("assets/textures/red_blue_texture.jpg", "red_blue_texture");
renderer.loadTexture("assets/textures/grass.jpg", "grass");
renderer.loadTexture("assets/textures/bush_texture.png", "bush_texture");
renderer.loadTexture("assets/textures/rock_texture.jpg", "rock_texture");
//Model loading
renderer.loadModel("assets/models/bushTree.fbx", "tree");
renderer.loadModel("assets/models/singleBigRock.fbx", "rock_big");
renderer.loadModel("assets/models/bush.fbx", "bush");
renderer.loadModel("assets/models/character.fbx", "character");
renderer.loadModel("assets/models/cursor.obj", "cursor");
renderer.loadModel("assets/models/enemy.fbx", "enemy");
//Shader loading
renderer.loadShaderProgram("shaders/basic.vert", "", "shaders/basic.frag", "basic");
renderer.loadShaderProgram("shaders/secondary.vert", "", "shaders/secondary.frag", "secondary");
//Background color
renderer.setBackgroundColor({ 0.1f, 0.075f, 0.1f, 1.0f });
//Initial camera position
glm::vec3 camRot{ 0.0f, 0.0f, 0.0f };
glm::vec3 camPos{ 5.0f, 5.0f, 10.0f };
//Ambient Light
renderer.setAmbientLight("basic", glm::vec3(0.15f, 0.15f, 0.15f));
//Light acting as sun
renderer.setLightState("basic", 2, 1, { 0.0f, 0.0f, 0.0f }, glm::vec3(-0.2f, 0.0f, -0.2f), { 1.0f, 1.0f, 1.0f }, 1.0f,
0, -1, -1);
//Game Objects Initalized and Components registered
EntityManager entityManager;
Universe universe = Universe({ 0, 0, 0 }, { 1.0f, 1.0f }, renderer, entityManager);
entityManager.registerComponentType<TransformComponent>();
entityManager.registerComponentType<StaticMeshComponent>();
entityManager.registerComponentType<AIComponent>();
entityManager.registerComponentType<HealthComponent>();
entityManager.registerComponentType<AttackComponent>();
entityManager.registerComponentType<MoveComponent>();
entityManager.registerComponentType<NameComponent>();
// Game master to handle gameplay
GameMaster* gm = new GameMaster(&entityManager, &audioManager);
// Transform Component initialized
TransformComponent trans;
trans.pos = { 15, 0 };
renderer.createMaterial("surfaceMaterial", glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), 0);
renderer.createMaterial("cursorMaterial", glm::vec3(0.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), 0);
// Static Mesh component for models, textures and offsets of entities
StaticMeshComponent stat;
stat.modelName = "cursor";
stat.textureName = "white";
stat.shaderName = "basic";
stat.materialName = "cursorMaterial";
stat.posOffset = { 0.0f, 0.0f, 0.5f };
// Cursor entity
Entity cursorEnt = entityManager.createEntity();
entityManager.addComponent<TransformComponent>(cursorEnt, trans);
entityManager.addComponent<StaticMeshComponent>(cursorEnt, stat);
stat.shaderName = "basic";
stat.materialName = "surfaceMaterial";
stat.posOffset = { 0.0f, 0.0f, 0.0f };
stat.modelName = "cube";
//World setup
for (int x = 0; x <= 10; x++) {
for (int y = 0; y <= 10; y++) {
Entity fresh = entityManager.createEntity();
trans.pos = { x, y };
stat.modelName = "cube";
stat.textureName = "grass";
stat.shaderName = "basic";
entityManager.addComponent<TransformComponent>(fresh, trans);
entityManager.addComponent<StaticMeshComponent>(fresh, stat);
}
}
//Initalize all components for entities
PlayerComponent playComp(0);
MoveComponent moveComp;
AttackComponent atkComp;
HealthComponent hpComp;
ObstacleComponent obComp;
AudioComponent audio;
NameComponent allyNameComp;
//Array containing all the entities names
std::string entityName[] = { "Player", "Player", "Rock", "Rock", "Rock", "Rock",
"Rock", "Rock", "Rock", "Rock", "Rock", "Rock", "Tree",
"Tree", "Tree", "Bush", "Bush", "Bush", "Bush", "Bush" };
//Array containing all the positions of the entities in same order as entityName
glm::ivec2 positions[] = { {0,3}, {2,1}, {1,4}, {2,4}, {3,4}, {5,4}, {1,6},
{3,7}, {3,8}, {6,7}, {6,2}, {9,5}, {1,8}, {8,8},
{9,2}, {0,4}, {3,2}, {4,9}, {6,3}, {9,7} };
//Array containing all the textures of the entities in same order as entityName
std::string tex[] = { "red_blue_texture", "red_blue_texture", "rock_texture", "rock_texture","rock_texture",
"rock_texture", "rock_texture", "rock_texture", "rock_texture","rock_texture",
"rock_texture", "rock_texture", "tree_texture", "tree_texture","tree_texture",
"bush_texture","bush_texture","bush_texture", "bush_texture", "bush_texture",
"bush_texture"};
//Array containing all the models of the entities in same order as entityName
std::string modelName[] = { "character","character","rock_big","rock_big","rock_big",
"rock_big","rock_big","rock_big","rock_big","rock_big",
"rock_big","rock_big", "tree","tree","tree","bush",
"bush", "bush", "bush", "bush" };
//Array with damage of the 2 players
int damage[] = { 3, 4 };
//Array with attack ranges of the 2 players
int atkRanges[] = { 3,2 };
//Array with the move ranges of the 2 players
int moveRanges[] = { 2,1 };
//Array holding all the health of the entities in same order as entityName
int health[] = { 5, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 1, 1, 1, 1, 1 };
//Array holding all the armor of the 2 players
int armor[] = { 1, 2 };
//stat.posOffset.z += 0f;
//Independent counting variable for player entities array specific variables
int playerCount = 0;
//Move component moved is intially false for all players
moveComp.moved = false;
//Ceates every entity with the arrays above in a for loop
for (int i = 0; i < 20; i++) {
Entity newEntity = entityManager.createEntity();
//Position of entity
trans.pos = positions[i];
//Model and texture of the entity
stat.modelName = modelName[i];
stat.textureName = tex[i];
//Health of the entity
hpComp.health = health[i];
hpComp.maxHealth = health[i];
//Adds all components that are the same for player and objects into the manager
entityManager.addComponent<TransformComponent>(newEntity, trans);
entityManager.addComponent<StaticMeshComponent>(newEntity, stat);
entityManager.addComponent<AudioComponent>(newEntity, audio);
//Adds player specific components
if (entityName[i] == "Player") {
stat.posOffset.z = 0.05f;
//Player damage component
atkComp.damage = damage[playerCount];
atkComp.range = atkRanges[playerCount];
//Player move range component
moveComp.moveRange = moveRanges[playerCount];
//Name of the player entity
allyNameComp.name = "Ally Wizard";
//Armor of the player entity
hpComp.armor = armor[playerCount];
//Adds player specific components to the entity into the manager
entityManager.addComponent<AttackComponent>(newEntity, atkComp);
entityManager.addComponent<MoveComponent>(newEntity, moveComp);
entityManager.addComponent<PlayerComponent>(newEntity, playComp);
entityManager.addComponent<NameComponent>(newEntity, allyNameComp);
//Increments player specific array count
playerCount++;
}
else {
//If not player its an obstacle so add obstacle component
entityManager.addComponent<ObstacleComponent>(newEntity, obComp);
}
//Adds hp + armour to the hpcomp if player and only hp if obstacle
entityManager.addComponent<HealthComponent>(newEntity, hpComp);
hpComp.armor = 0;
}
// AI setup
MessageBus bus;
AISystem aiSystem(entityManager, bus, *gm);
glm::vec2 aiPos[] = { {1,9}, {6,8}, {10,3} };
const int numOfEnemy = 3;
// Generate Enemy
for (int i = 0; i < numOfEnemy; i++) {
trans.pos = aiPos[i];
stat.modelName = "enemy";
stat.textureName = "red_blue_texture";
aiSystem.spawnEnemy(trans, stat);
}
UIController ui("everything.xaml", gm, entityManager);
auto nsguiView = ui.GetNsguiView();
static auto startTime = std::chrono::high_resolution_clock::now();
static float prevTime = 0;
int prevWidth = WINDOW_WIDTH;
int prevHeight = WINDOW_HEIGHT;
// Gets turn button from UI controller
auto turnBtn = ui.GetturnBtn();
//This is for finding out if LMB was released on this frame.
bool lmbDownPrevFrame = false;
while (!glfwWindowShouldClose(window)) {
auto currentTime = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count();
float deltaTime = time - prevTime;
nsguiView->Update(time); //this should happen early so that the time value is as exact as possible
//The correct way to update framebuffer size is with callbacks.
//However, callbacks are hard because we have multiple member objects that need
//to be changed when that happens, so I check it like this instead.
//This is probably something I should fix, but performance impact seems negligible, at least.
int cWidth, cHeight;
glfwGetFramebufferSize(window, &cWidth, &cHeight);
if ((cWidth != prevWidth || cHeight != prevHeight) && !(cWidth == 0 || cHeight == 0)) {
renderer.updateWindowSize(window, cWidth, cHeight);
nsguiView->SetSize(cWidth, cHeight);
prevWidth = cWidth;
prevHeight = cHeight;
}
renderer.setCameraPosition(camPos);
renderer.setCameraRotation(camRot);
universe.update(deltaTime);
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) {
camRot.x += 1.0f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) {
camRot.x -= 1.0f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
camRot.z -= 1.0f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
camRot.z += 1.0f * deltaTime;
}
glm::mat4 movementRotation = glm::rotate(glm::mat4(1.0f), camRot.z, { 0.0f, 0.0f, 1.0f });
movementRotation = glm::rotate(movementRotation, camRot.x, { 1.0f, 0.0f, 0.0f });
movementRotation = glm::rotate(movementRotation, camRot.y, { 0.0f, 1.0f, 0.0f });
//The camera points down by default, so the initial forward is -Z
glm::vec4 trueFwd = movementRotation * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f);
glm::vec4 trueRight = movementRotation * glm::vec4(1.0f, 0.0f, 0.0f, 0.0f);
glm::vec4 trueUp = movementRotation * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f);
// Camera controls when pressing a key on keyboard
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
camPos += glm::vec3(trueFwd.x, trueFwd.y, trueFwd.z) * 2.5f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
camPos += glm::vec3(trueFwd.x, trueFwd.y, trueFwd.z) * -2.5f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
camPos += glm::vec3(trueRight.x, trueRight.y, trueRight.z) * 2.5f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
camPos += glm::vec3(trueRight.x, trueRight.y, trueRight.z) * -2.5f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) {
camPos += glm::vec3(trueUp.x, trueUp.y, trueUp.z) * 2.5f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) {
camPos += glm::vec3(trueUp.x, trueUp.y, trueUp.z) * -2.5f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) {
camPos.z += 2.5f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) {
camPos.z += -2.5f * deltaTime;
}
//Audio Test
audioManager.setDevicePosition(camPos);
audioManager.setDeviceOrientation(trueFwd, trueUp);
if (!(cWidth <= 0 || cHeight <= 0)) {
//Mouse stuff, including sending to NSGUI
double x, y;
glfwGetCursorPos(window, &x, &y);
nsguiView->MouseMove(x, y);
Entity clicked;
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
//Find Grid Position of mouse
glm::mat4 cam = glm::translate(glm::mat4(1.0f), camPos);
cam = glm::rotate(cam, camRot.z, { 0.0f, 0.0f, 1.0f });
cam = glm::rotate(cam, camRot.x, { 1.0f, 0.0f, 0.0f });
glm::mat4 view = glm::inverse(cam);
glm::mat4 projection = glm::perspective(glm::radians(60.0f),
cWidth / (float)cHeight, 0.1f, 100.0f);
glm::vec3 farPlaneClickPos = glm::unProject(glm::vec3(x, cHeight - y, 1.0f),
view,
projection,
glm::vec4(0.0f, 0.0f, cWidth, cHeight));
auto v = normalize(farPlaneClickPos - camPos);
glm::vec3 posOnPlane{ 0, 0, 0 };
glm::vec3 planeOrig{ 0, 0, 0 };
glm::vec3 planeNorm{ 0, 0, 1 };
float res = 0;
glm::intersectRayPlane(camPos, v, planeOrig,
planeNorm, res);
posOnPlane = camPos + v * res;
int gridPositionX = std::round(posOnPlane.x);
int gridPositionY = std::round(posOnPlane.y);
//Set grid cursor position
entityManager.getComponent<TransformComponent>(cursorEnt).pos = { gridPositionX, gridPositionY };
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1) == GLFW_PRESS) {
if (!lmbDownPrevFrame) {
lmbDownPrevFrame = true;
nsguiView->MouseButtonDown(x, y, Noesis::MouseButton_Left);
Noesis::HitTestResult uiHitTest = Noesis::VisualTreeHelper::HitTest(
Noesis::VisualTreeHelper::GetRoot(turnBtn), Noesis::Point{ static_cast<float>(x), static_cast<float>(y) });
//If it hits UI don't click into game world
if (uiHitTest.visualHit == nullptr) {
//Select mode functionality and UI
if (gm->currentMode == select) {
gm->selectUnit(gridPositionX, gridPositionY);
if (gm->selected != NULL) {
ui.DisplayInfoPanel(gm->selected);
if (!gm->botSelected) {
if (entityManager.getComponent<MoveComponent>(gm->selected).moved) {
ui.SetMoveIcon(true);
}
else {
ui.SetMoveIcon(false);
}
}
else {
ui.HideMoveIcon();
}
}
}
//Move mode functionality and UI
else if (gm->currentMode == move) {
bool moved = gm->moveSelected(gridPositionX, gridPositionY);
if (moved) {
ui.SetMoveIcon(true);
ui.HighlightSelectMode();
gm->currentMode = select;
}
}
//Attack mode functionality and UI
else {
bool hit = gm->attackSelected(gridPositionX, gridPositionY);
if (hit) {
ui.SetMoveIcon(true);
ui.HighlightSelectMode();
gm->currentMode = select;
}
}
if (gm->selected == NULL) {
ui.HideInfoPanel();
}
}
}
}
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1) == GLFW_RELEASE) {
if (lmbDownPrevFrame) {
lmbDownPrevFrame = false;
nsguiView->MouseButtonUp(x, y, Noesis::MouseButton_Left);
}
}
}
prevTime = time;
//NSGUI rendering stuff
bool nsguiTreeDirty = nsguiView->GetRenderer()->UpdateRenderTree();
if (nsguiTreeDirty) {
//Rendering to offscreen buffer (I think) only needs to happen
//if something changed in the UI. If not, the previous one is kept and reused this frame.
nsguiView->GetRenderer()->RenderOffscreen();
}
//NS docs say the 3D scene should happen after RenderOffscreen() occurs.
//RenderOffscreen changes the GL state. Renderer.prepareForOperation() restores it to what the Renderer likes.
renderer.prepareForOperation();
renderer.renderFromQueue(true);
//Back to NSGUI. This needs to happen whether the UI actually changed or not
//because UI has to go on top of the scene in the otput framebuffer.
nsguiView->GetRenderer()->Render();
glfwSwapBuffers(window);
glfwPollEvents();
// AI test
aiSystem.update();
} //End of operation loop. Everything after this is cleanup.
//NSGUI stuff should be manually shut down before exiting the program.
//All Noesis::Ptr objects must be reset to free them because they are, in fact, pointers.
nsguiView.Reset();
//Most of the resetting happens in here.
ui.UIReset();
Noesis::GUI::Shutdown();
glfwTerminate();
return 0;
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}