-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp.txt
More file actions
2425 lines (2036 loc) · 100 KB
/
temp.txt
File metadata and controls
2425 lines (2036 loc) · 100 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
/*
---------------------------------------------------------------------------------
| Includes |
---------------------------------------------------------------------------------
*/
#pragma once
#include "Math.h"
#include "techstorm/common.h"
#include "techstorm/core/utils/Button.h" // TODO : Can this be moved to common.h?
// Game Engine Includes
#include "techstorm/Game.h"
#include "techstorm/globalobj/Block.h"
#include "techstorm/core/obj/Gameobject.h"
#include "techstorm/core/gamescreen/MenuCamera.h"
#include "techstorm/player/Player.h"
#include "techstorm/core/rendering/Light.h"
#include "techstorm/core/threading/ThreadGroups.h"
#include "techstorm/core/ui/UIElement.h"
#include "techstorm/core/ui/UIMan.h"
#include "techstorm/ui/UIFadingMsg.h"
#include "techstorm/core/audio/FxMan.h"
#include "techstorm/globalobj/Objects.h"
#include "techstorm/console/Console.h"
#include "techstorm/core/ui/UIMenu.h"
#include "techstorm/ui/MainMenu.h"
#include "techstorm/ui/PlayerHUD.h"
#include "techstorm/economy/SystemEconomy.h"
#include "techstorm/discord/DiscordAPI.h"
#include <time.h>
#include <vector> // needed for game object list
#include <raylib.h>
#include <lua.hpp>
#include <sol/sol.hpp>
//config
#include <toml++/toml.hpp>
#include <tinyxml2.h>
#define NUM_MODELS 9 // Parametric 3d shapes to generate
namespace TechStormRivalry {
static void mainThread() {
// Lets the program know if the game should use HDR as the skybox
bool useHDR = true;
// Initialie the condition for the breathing sound.
bool isBreathing = false;
// Viewsway
float swayAmount = 0.0003f; // how much should the view sway be affected.
float swaySpeed = 0.02f; // how fast should camera sway
float swayTimer = 0.0f; // Dont mess with this. it will fuck up the swaying.
/*
* Near death affect.
* Important :
* THESE ARE REQUIRED FOR THE ARCH ALGORITHM TO WORK!
* See Math.h for the Arch algorithm explanation and uses.
*
* Note:
* Use a graphing calculator to visualize the algorithm
*/
float nearDeathTimer = 0.0f; // The X axis
float amplitude = 255; // How high the Parabola goes
float frequency = 5; // How often the arches are
float steepness = 2.4f; // How steep the curve is, NOTE : If it is an odd number, it will not show as it only works for even times.
float offset = 1; // Offset of the arches from x = 0
const float scaleFactor = 25; // Scaling factor, how much the parabolas is scaled
float nearDeathIntensity = 0.0f; // The Y Axis of the algorithm
// Health bar fuckery
float healthBarPositionX = 0.0f;
float healthBarPositionY = 0.0f;
int healthBarOffsetX = 0;
int healthBarOffsetY = 500;
// represents the raycasting from the player to the world.
Ray ray;
// Create game & load it into memory.
Game* game = new Game();
// Start the game and do any needed setup
game->init();
DiscordAPI* disc = new DiscordAPI();
disc->initAPI();
TechStorm::Logman::Log("Main menu ready");
Console::ConsoleUI* console = new Console::ConsoleUI();
MainMenu::MainMenu* menu = new MainMenu::MainMenu(game);
menu->awakeMenu();
menu->drawMenu(console);
console = new Console::ConsoleUI();
game->pushRogueElement(console);
// Assign already setup PBR shader to model.materials[0], used by models.meshes[0]
// Create a default block model with a length, width, and height of the value of BLOCK_SIZE.
// This creates a cube mesh with a length, width, and height of BLOCK_SIZE and then converts it
// to a model, loading it into memory.
Model DefaultBlockModel = LoadModelFromMesh(
GenMeshCube(BLOCK_SIZE, BLOCK_SIZE,
BLOCK_SIZE)); // this is the default model used in blocksd.
// todo : change all use instances of DefaultBlockModel to use the global default model.
SetDefaultModel(DefaultBlockModel);
// Construct the block object
Block* block = new Block(Vector3Zero(), WHITE, game->pbrShader, LoadModelFromMesh(GenMeshCylinder(BLOCK_SIZE, BLOCK_SIZE, 100)));
// Finally push it off to the object manager
game->pushObject(block);
// Create the player model
// NOTE: This model is TEMPORARY! It will be deleted after a proper model is made. Refers to the
// size of the player model. Same process as the default block model creation.
const int Playersize = 3;
Model PlayerModel = LoadModelFromMesh(GenMeshCube(Playersize, Playersize, Playersize));
// Construct the player object
Player::Player* player = new Player::Player(Vector3{ 0.0f, 2.0f, 4.0f }, PlayerModel, CAMERA_FIRST_PERSON);
// Finally push it off to the object manager
game->pushObject(player);
// Skybox geometry generation step
Mesh skyboxMesh = GenMeshCube(1.0f, 1.0f, 1.0f);
// Skybox model loading step
Model skybox = LoadModelFromMesh(skyboxMesh);
// Load skybox shader and set required locations step
// NOTE: Some locations are automatically set at shader loading
skybox.materials[0].shader = LoadShader("resources/skybox.vs", "resources/skybox.fs");
// since the compiler complains about the references of such, these three vars are for the
// skybox shaders. They will be deleted after.
static int skyboxEnvironmentMap = MATERIAL_MAP_CUBEMAP;
// Both variables are equal to 1 if useHDR is true, otherwise 0
static int skyboxUsesGamma = { useHDR ? 1 : 0 };
static int skyboxIsVFlipped = { useHDR ? 1 : 0 };
// Load the environment map
SetShaderValue(
skybox.materials[0].shader,
GetShaderLocation(skybox.materials[0].shader, "environmentMap"), &skyboxEnvironmentMap,
SHADER_UNIFORM_INT);
// Should the shader use gamma correction
SetShaderValue(skybox.materials[0].shader,
GetShaderLocation(skybox.materials[0].shader, "doGamma"), &skyboxUsesGamma,
SHADER_UNIFORM_INT);
// Is the skybox flipped vertically
SetShaderValue(skybox.materials[0].shader,
GetShaderLocation(skybox.materials[0].shader, "vflipped"), &skyboxIsVFlipped,
SHADER_UNIFORM_INT);
// Load cubemap shader and setup required shader locations
Shader shdrCubemap =
LoadShader("resources/cubemap.vs", "resources/cubemap.fs");
// set shdrCubemap's equirectangular map.
const static int equimap = 0;
SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), &equimap, SHADER_UNIFORM_INT);
// Note: The filename is hardcoded here and also has a limit of 256 characters! I will be
// dissapointed if you somehow dont know what that variable does...
char skyboxFileName[256] = { 0 };
// This is the panoramic texture, It is used IF useHDR is true
Texture2D panorama = { 0 };
if (useHDR)
{
TextCopy(skyboxFileName, "resources/milkyWay.hdr");
// Load HDR panorama (sphere) texture
panorama = LoadTexture(skyboxFileName);
//skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = GenTextureCubemap(
// shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
}
else
{
// it isnt going to be used. so it can fuck off.
UnloadTexture(panorama);
// Load non HDR panorama (cube) texture
Image img = LoadImage("resources/textures/space.png");
// Set it's cubemap texture.
skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = LoadTextureCubemap(
img, CUBEMAP_LAYOUT_AUTO_DETECT); // CUBEMAP_LAYOUT_PANORAMA
// unload img as we dont need it anymore.
UnloadImage(img);
}
TechStorm::Light sun = TechStorm::CreateLight(TechStorm::LIGHT_POINT, TechStorm::uVec3f{ 1.0f, 0.0f, 1.0f }, Vector3One(), WHITE, 4.0f, game->pbrShader);
// The texture for the near death affect initialization
Texture2D nearDeathTex = { 0 };
// The image for the near death affect initialization
Image nearDeathAffect = { 0 };
// The color for the near death affect initialization
TechStorm::uColor nearDeathColor = TechStorm::uColor();
healthBarPositionX = game->winWidth + healthBarOffsetX;
healthBarPositionY = game->winHeight + healthBarOffsetY;
DisableCursor();
PlayerHUD* hud = new PlayerHUD(game);
Economy::MarketProduct tester = Economy::MarketProduct();
tester.baseValue = 5;
tester.supply = 100;
Economy::Merchant* merchant = new Economy::Merchant();
merchant->m_market[0] = tester;
merchant->m_priceUptick = 0.25f;
Faction::CharacterFaction fa = Faction::CharacterFaction();
Faction::CharacterFaction fb = Faction::CharacterFaction();
merchant->m_owner = &fb;
fa.meetFaction(fb);
fb.meetFaction(fa);
SetTargetFPS(60);
while (!WindowShouldClose())
{
int scroll = GetMouseWheelMove();
disc->update();
// Camera PRO usage example (EXPERIMENTAL)
// This new camera function allows custom movement/rotation values to be directly provided
// as input parameters, with this approach, rcamera module is internally independent of raylib inputs
UpdateCameraPro(player->cameraComponent->getSelfCameraPointer(),
Vector3{
(IsKeyDown(player->controller->forward) || IsKeyDown(KEY_UP)) * player->controller->speed - // Move forward-backward
(IsKeyDown(player->controller->backward) || IsKeyDown(KEY_DOWN)) * player->controller->speed,
(IsKeyDown(player->controller->right) || IsKeyDown(KEY_RIGHT)) * player->controller->speed - // Move right-left
(IsKeyDown(player->controller->left) || IsKeyDown(KEY_LEFT)) * player->controller->speed,
(IsKeyDown(player->controller->jump)) * player->controller->speed - // Move up-down
(IsKeyDown(player->controller->crouch)) * player->controller->speed
},
Vector3{
GetMouseDelta().x * player->controller->mouseSensitivity, // Rotation: yaw
GetMouseDelta().y * player->controller->mouseSensitivity, // Rotation: pitch
player->controller->CalculateCameraTilt() // Rotation: roll
},
GetMouseWheelMove() * 2.0f); // Move to target (zoom)
// NOTE : This is a very basic implementation of placing an object into the world. This is
// temporary and should be fleshed out.
if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
{
Vector3 placepos = player->cameraComponent->getTarget();
}
if (IsKeyPressed(KEY_ESCAPE))
{
// Todo, move the menuCamera to be created on game startup and then hidden. it gets
// shown on if statement validation
bool exitMenu = false;
bool manualExit = false;
MenuCamera* men_pause = new MenuCamera();
TechStorm::ButtonR* save = new TechStorm::ButtonR("Save", 100, 100);
TechStorm::ButtonR* Options = new TechStorm::ButtonR("Options", 100, 200);
TechStorm::ButtonR* exitButton = new TechStorm::ButtonR("Exit to Windows", 100, 300);
EnableCursor();
while (!exitMenu)
{
game->updateUI();
BeginDrawing();
game->drawUI(DRAW_FINAL);
save->draw();
save->updateObjects();
Options->draw();
Options->updateObjects();
exitButton->draw();
exitButton->updateObjects();
if (exitButton->IsClicked())
{
manualExit = true;
}
if (Options->IsClicked())
{
bool closeOptions = false;
while (!closeOptions)
{
// TODO : Add options
if (IsKeyDown(KEY_ESCAPE))
{
closeOptions = true;
}
}
}
EndDrawing();
if (IsKeyPressed(KEY_ESCAPE) && exitMenu == false)
{
exitMenu = true;
}
else if (IsKeyPressed(KEY_ESCAPE) && exitMenu == true)
{
break;
}
if (manualExit)
{
exitMenu = true;
}
}
// cleanup UnloadTexture(tex);
delete men_pause;
delete save;
delete exitButton;
if (manualExit)
{
TechStorm::Logman::customLog(LOG_INFO, "Exiting Game", NULL);
exit(0);
}
}
if (IsKeyPressed(KEY_E)) {
}
if (IsKeyDown(KEY_Y)) {
player->damage(15);
}
if (IsKeyPressed(KEY_B)) {
merchant->buy(0, 5, fa);
TechStorm::Logman::Log(TextFormat("Supply %i, Demand %i, buy price %f, sell %f, base %i", merchant->m_market[0].supply, merchant->m_market[0].demand, merchant->m_market[0].buyPrice, merchant->m_market[0].sellPrice, merchant->m_market[0].baseValue));
}
if (IsKeyPressed(KEY_K)) {
Economy::MarketPurchase purchase = merchant->sell(0, 500, fa);
//player->m_balance += purchase.value;
TechStorm::Logman::Log(TextFormat("Supply %i, Demand %i, buy price %f, sell %f, base %i", merchant->m_market[0].supply, merchant->m_market[0].demand, merchant->m_market[0].buyPrice, merchant->m_market[0].sellPrice, merchant->m_market[0].baseValue));
}
// The player's looking direction is the target of the camera. This is the direction the
// player is looking TODO : Check relevancy.
ray.position = player->cameraComponent->getPosition();
ray.direction = player->cameraComponent->getTarget();
// Sway timer is equal to swayTimer + frame delta time
swayTimer += GetFrameTime();
// sway the camera according to the sway algorithm.
player->cameraComponent->setTarget(Vector3{ player->cameraComponent->getTarget().x + sin(swayTimer * swaySpeed) * swayAmount, player->cameraComponent->getTarget().y, player->cameraComponent->getTarget().z + cos(swayTimer * swaySpeed) * swayAmount });
/*
* if (player->health <= 15) {
// equal to nearDeathTimer + frame delta time
//nearDeathTimer += GetFrameTime();
if (nearDeathIntensity >= 255) {
nearDeathIntensity -= nearDeathIntensity / 2;
}
else if ((nearDeathIntensity > 0) && (nearDeathIntensity < 255)) {
nearDeathIntensity += nearDeathIntensity / 2;
}
Image img = LoadImageFromTexture(game->renderer->getRenderTexture().texture);
nearDeathColor = Color{ 255, 0, 0, (unsigned char)nearDeathIntensity };
ImageColorTint(&img, nearDeathColor);
Color* pixels = LoadImageColors(img);
UpdateTexture(game->renderer->getRenderTexture().texture, pixels); // Update texture with new image data
UnloadImageColors(pixels); // Unload pixels data from RAM
UpdateTexture(game->renderer->getRenderTexture().texture, pixels);
}
*/
// Stashes input events for later
PollInputEvents(); // helps for some reason?
sun.position = player->cameraComponent->getTarget();
TechStorm::UpdateLight(game->pbrShader, sun);
game->updateObjects();
game->startTexturingStep(player->cameraComponent->getSelfCameraPointer());
game->updateUI();
game->drawUI(DRAW_CLIPPABLE);
//DrawTextureRec(nearDeathTex, Rectangle{ 0, 0, (float)(game->renderer->fboDimensions.x), (float)(-game->renderer->fboDimensions.y) }, TechStorm::uVec2i{ 0, 0 }, WHITE);
game->startRenderingStep(player->cameraComponent->getSelfCamera());
SetShaderValue(game->pbrShader, game->textureTilingLoc, &block->blockTextureTiling, SHADER_UNIFORM_VEC2);
Vector4 carEmissiveColor = ColorNormalize(block->model.materials[0].maps[MATERIAL_MAP_EMISSION].color);
SetShaderValue(game->pbrShader, game->emissiveColorLoc, &carEmissiveColor, SHADER_UNIFORM_VEC4);
// How bright should the object emit it's emission color.
float emissiveIntensity = 0.1f;
SetShaderValue(game->pbrShader, game->emissiveIntensityLoc, &emissiveIntensity, SHADER_UNIFORM_FLOAT);
game->renderObjects();
game->endRenderingStep();
game->endTexturingStep();
game->startDrawingstep();
game->drawUI(DRAW_FINAL);
game->endDrawingStep();
}
UnloadModel(DefaultBlockModel);
// Unload textures
UnloadTexture(nearDeathTex);
// Unload images
UnloadImage(nearDeathAffect);
// Delete temporary files.
using namespace std;
{
remove("PerlinTest.png");
remove("HMap.png");
}
game->assets->unloadAssets();
game->endGame();
delete game;
delete block;
//delete man;
delete player;
}
}
int main()
{
try
{
// Run the game
std::thread t(std::move(TechStormRivalry::mainThread));
//scriptManager->startScriptMan(true);
t.join();
}
catch (const std::exception& e)
{
TechStorm::Logman::Log(e.what());
}
return 0;
}
/***********************************************************************************
*
* rPBR - Physically based rendering viewer for raylib
*
* FEATURES:
* - Load OBJ models and texture images in real-time by drag and drop.
* - Use right mouse button to rotate lighting.
* - Use middle mouse button to rotate and pan camera.
* - Use interface to adjust material, textures, render and effects settings (space bar - display/hide interface).
* - Press F1-F11 to switch between different render modes.
* - Press F12 or use Screenshot button to capture a screenshot and save it as PNG file.
*
* Use the following line to compile:
*
* gcc -o $(NAME_PART).exe $(FILE_NAME) -s icon\rpbr_icon -I$(CURRENT_DIRECTORY)\external\raylib\src -L$(CURRENT_DIRECTORY)\external\raylib\release\win32
* -L$(CURRENT_DIRECTORY)\external\raylib\src\external\glfw3\lib\win32 -L$(CURRENT_DIRECTORY)\external\raylib\src\external\openal_soft\lib\win32\ -lraylib
* -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition
*
* LICENSE: zlib/libpng
*
* rPBR is licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software:
*
* Copyright (c) 2017-2020 Victor Fisac
*
* This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
***********************************************************************************/
#pragma warning(disable : 4996)
//----------------------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------------------
#include <math.h> // Required for: powf()
#include <raylib.h>
#include "raymath.h" // Required for matrix, vectors and other math functions
#include "glad/glad.h" // Required for OpenGL API
#define RAYGUI_IMPLEMENTATION
#include <raygui.h>
//----------------------------------------------------------------------------------
// Defines
//----------------------------------------------------------------------------------
#define MAX_LIGHTS 4 // Max lights supported by shader
#define MAX_MIPMAP_LEVELS 5 // Max number of prefilter texture mipmaps
#define PATH_PBR_VS "resources/shaders/pbr.vs" // Path to physically based rendering vertex shader
#define PATH_PBR_FS "resources/shaders/pbr.fs" // Path to physically based rendering fragment shader
#define PATH_CUBE_VS "resources/shaders/cubemap.vs" // Path to equirectangular to cubemap vertex shader
#define PATH_CUBE_FS "resources/shaders/cubemap.fs" // Path to equirectangular to cubemap fragment shader
#define PATH_SKYBOX_VS "resources/shaders/skybox.vs" // Path to skybox vertex shader
#define PATH_SKYBOX_FS "resources/shaders/skybox.fs" // Path to skybox vertex shader
#define PATH_IRRADIANCE_FS "resources/shaders/irradiance.fs" // Path to irradiance (GI) calculation fragment shader
#define PATH_PREFILTER_FS "resources/shaders/prefilter.fs" // Path to reflection prefilter calculation fragment shader
#define PATH_BRDF_VS "resources/shaders/brdf.vs" // Path to bidirectional reflectance distribution function vertex shader
#define PATH_BRDF_FS "resources/shaders/brdf.fs" // Path to bidirectional reflectance distribution function fragment shader
//----------------------------------------------------------------------------------
// Structs and enums
//----------------------------------------------------------------------------------
typedef enum {
LIGHT_DIRECTIONAL,
LIGHT_POINT
} LightType;
typedef struct {
bool enabled;
LightType type;
Vector3 position;
Vector3 target;
Color color;
int enabledLoc;
int typeLoc;
int posLoc;
int targetLoc;
int colorLoc;
} Light;
typedef struct Environment {
Shader pbrShader;
Shader skyShader;
unsigned int cubemapId;
unsigned int irradianceId;
unsigned int prefilterId;
unsigned int brdfId;
int modelMatrixLoc;
int pbrViewLoc;
int skyViewLoc;
int skyResolutionLoc;
} Environment;
typedef struct PropertyPBR {
Texture2D bitmap;
bool useBitmap;
Color color;
int bitmapLoc;
int useBitmapLoc;
int colorLoc;
} PropertyPBR;
typedef struct MaterialPBR {
PropertyPBR albedo;
PropertyPBR normals;
PropertyPBR metalness;
PropertyPBR roughness;
PropertyPBR ao;
PropertyPBR emission;
PropertyPBR height;
Environment env;
} MaterialPBR;
typedef enum TypePBR {
PBR_ALBEDO,
PBR_NORMALS,
PBR_METALNESS,
PBR_ROUGHNESS,
PBR_AO,
PBR_EMISSION,
PBR_HEIGHT
} TypePBR;
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
static int lightsCount = 0; // Current amount of created lights
//----------------------------------------------------------------------------------
// Functions Declaration
//----------------------------------------------------------------------------------
MaterialPBR SetupMaterialPBR(Environment env, Color albedo, int metalness, int roughness); // Set up PBR environment shader constant values
void SetMaterialTexturePBR(MaterialPBR* mat, TypePBR type, Texture2D texture); // Set texture to PBR material
void UnsetMaterialTexturePBR(MaterialPBR* mat, TypePBR type); // Unset texture to PBR material and unload it from GPU
Light CreateLight(int type, Vector3 pos, Vector3 targ, Color color, Environment env); // Defines a light and get locations from environment PBR shader
Environment LoadEnvironment(const char* filename, int cubemapSize, int irradianceSize, int prefilterSize, int brdfSize); // Load an environment cubemap, irradiance, prefilter and PBR scene
int GetLightsCount(void); // Get the current amount of created lights
void UpdateLightValues(Environment env, Light light); // Send to environment PBR shader light values
void UpdateEnvironmentValues(Environment env, Camera camera, Vector2 res); // Send to environment PBR shader camera view and resolution values
void DrawModelPBR(Model model, MaterialPBR mat, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale); // Draw a model using physically based rendering
void DrawSkybox(Environment environment, Camera camera); // Draw a cube skybox using environment cube map
void RenderCube(void); // Renders a 1x1 3D cube in NDC
void RenderQuad(void); // Renders a 1x1 XY quad in NDC
void UnloadMaterialPBR(MaterialPBR mat); // Unload material PBR textures
void UnloadEnvironment(Environment env); // Unload environment loaded shaders and dynamic textures
//----------------------------------------------------------------------------------
// Functions Definition
//----------------------------------------------------------------------------------
// Set up PBR environment shader constant values
MaterialPBR SetupMaterialPBR(Environment env, Color albedo, int metalness, int roughness)
{
MaterialPBR mat;
// Set up material properties color
mat.albedo.color = albedo;
mat.normals.color = Color{ 128, 128, 255, 255 };
mat.metalness.color = Color{ static_cast<unsigned char>(metalness), 0, 0, 0 };
mat.roughness.color = Color{ static_cast<unsigned char>(roughness), 0, 0, 0 };
mat.ao.color = Color{ 255, 255, 255, 255 };
mat.emission.color = Color{ 0, 0, 0, 0 };
mat.height.color = Color{ 0, 0, 0, 0 };
// Set up material properties use texture state
mat.albedo.useBitmap = false;
mat.normals.useBitmap = false;
mat.metalness.useBitmap = false;
mat.roughness.useBitmap = false;
mat.ao.useBitmap = false;
mat.emission.useBitmap = false;
mat.height.useBitmap = false;
// Set up material properties textures
mat.albedo.bitmap = Texture2D{ 0 };
mat.normals.bitmap = Texture2D{ 0 };
mat.metalness.bitmap = Texture2D{ 0 };
mat.roughness.bitmap = Texture2D{ 0 };
mat.ao.bitmap = Texture2D{ 0 };
mat.emission.bitmap = Texture2D{ 0 };
mat.height.bitmap = Texture2D{ 0 };
// Set up material environment
mat.env = env;
// Set up PBR shader material locations
mat.albedo.bitmapLoc = GetShaderLocation(mat.env.pbrShader, "albedo.sampler");
mat.normals.bitmapLoc = GetShaderLocation(mat.env.pbrShader, "normals.sampler");
mat.metalness.bitmapLoc = GetShaderLocation(mat.env.pbrShader, "metalness.sampler");
mat.roughness.bitmapLoc = GetShaderLocation(mat.env.pbrShader, "roughness.sampler");
mat.ao.bitmapLoc = GetShaderLocation(mat.env.pbrShader, "ao.sampler");
mat.emission.bitmapLoc = GetShaderLocation(mat.env.pbrShader, "emission.sampler");
mat.height.bitmapLoc = GetShaderLocation(mat.env.pbrShader, "height.sampler");
mat.albedo.useBitmapLoc = GetShaderLocation(mat.env.pbrShader, "albedo.useSampler");
mat.normals.useBitmapLoc = GetShaderLocation(mat.env.pbrShader, "normals.useSampler");
mat.metalness.useBitmapLoc = GetShaderLocation(mat.env.pbrShader, "metalness.useSampler");
mat.roughness.useBitmapLoc = GetShaderLocation(mat.env.pbrShader, "roughness.useSampler");
mat.ao.useBitmapLoc = GetShaderLocation(mat.env.pbrShader, "ao.useSampler");
mat.emission.useBitmapLoc = GetShaderLocation(mat.env.pbrShader, "emission.useSampler");
mat.height.useBitmapLoc = GetShaderLocation(mat.env.pbrShader, "height.useSampler");
mat.albedo.colorLoc = GetShaderLocation(mat.env.pbrShader, "albedo.color");
mat.normals.colorLoc = GetShaderLocation(mat.env.pbrShader, "normals.color");
mat.metalness.colorLoc = GetShaderLocation(mat.env.pbrShader, "metalness.color");
mat.roughness.colorLoc = GetShaderLocation(mat.env.pbrShader, "roughness.color");
mat.ao.colorLoc = GetShaderLocation(mat.env.pbrShader, "ao.color");
mat.emission.colorLoc = GetShaderLocation(mat.env.pbrShader, "emission.color");
mat.height.colorLoc = GetShaderLocation(mat.env.pbrShader, "height.color");
// Set up PBR shader material texture units
int a = 3;
int b = 4;
int c = 5;
int d = 6;
int e = 7;
int f = 8;
int g = 9;
SetShaderValue(mat.env.pbrShader, mat.albedo.bitmapLoc, &a, SHADER_UNIFORM_INT);
SetShaderValue(mat.env.pbrShader, mat.normals.bitmapLoc, &b, SHADER_UNIFORM_INT);
SetShaderValue(mat.env.pbrShader, mat.metalness.bitmapLoc, &c, SHADER_UNIFORM_INT);
SetShaderValue(mat.env.pbrShader, mat.roughness.bitmapLoc, &d, SHADER_UNIFORM_INT);
SetShaderValue(mat.env.pbrShader, mat.ao.bitmapLoc, &e, SHADER_UNIFORM_INT);
SetShaderValue(mat.env.pbrShader, mat.emission.bitmapLoc, &f, SHADER_UNIFORM_INT);
SetShaderValue(mat.env.pbrShader, mat.height.bitmapLoc, &g, SHADER_UNIFORM_INT);
return mat;
}
// Set texture to PBR material
void SetMaterialTexturePBR(MaterialPBR* mat, TypePBR type, Texture2D texture)
{
switch (type)
{
case PBR_ALBEDO:
{
mat->albedo.bitmap = texture;
mat->albedo.useBitmap = true;
} break;
case PBR_NORMALS:
{
mat->normals.bitmap = texture;
mat->normals.useBitmap = true;
} break;
case PBR_METALNESS:
{
mat->metalness.bitmap = texture;
mat->metalness.useBitmap = true;
} break;
case PBR_ROUGHNESS:
{
mat->roughness.bitmap = texture;
mat->roughness.useBitmap = true;
} break;
case PBR_AO:
{
mat->ao.bitmap = texture;
mat->ao.useBitmap = true;
} break;
case PBR_EMISSION:
{
mat->emission.bitmap = texture;
mat->emission.useBitmap = true;
} break;
case PBR_HEIGHT:
{
mat->height.bitmap = texture;
mat->height.useBitmap = true;
} break;
default: break;
}
}
// Unset texture to PBR material and unload it from GPU
void UnsetMaterialTexturePBR(MaterialPBR* mat, TypePBR type)
{
switch (type)
{
case PBR_ALBEDO:
{
if (mat->albedo.useBitmap)
{
mat->albedo.useBitmap = false;
UnloadTexture(mat->albedo.bitmap);
mat->albedo.bitmap = Texture2D{ 0 };
}
} break;
case PBR_NORMALS:
{
if (mat->normals.useBitmap)
{
mat->normals.useBitmap = false;
UnloadTexture(mat->normals.bitmap);
mat->normals.bitmap = Texture2D{ 0 };
}
} break;
case PBR_METALNESS:
{
if (mat->metalness.useBitmap)
{
mat->metalness.useBitmap = false;
UnloadTexture(mat->metalness.bitmap);
mat->metalness.bitmap = Texture2D{ 0 };
}
} break;
case PBR_ROUGHNESS:
{
if (mat->roughness.useBitmap)
{
mat->roughness.useBitmap = false;
UnloadTexture(mat->roughness.bitmap);
mat->roughness.bitmap = Texture2D{ 0 };
}
} break;
case PBR_AO:
{
if (mat->ao.useBitmap)
{
mat->ao.useBitmap = false;
UnloadTexture(mat->ao.bitmap);
mat->ao.bitmap = Texture2D{ 0 };
}
} break;
case PBR_EMISSION:
{
if (mat->emission.useBitmap)
{
mat->emission.useBitmap = false;
UnloadTexture(mat->emission.bitmap);
mat->emission.bitmap = Texture2D{ 0 };
}
} break;
case PBR_HEIGHT:
{
if (mat->height.useBitmap)
{
mat->height.useBitmap = false;
UnloadTexture(mat->height.bitmap);
mat->height.bitmap = Texture2D{ 0 };
}
} break;
default: break;
}
}
// Defines a light and get locations from environment shader
Light CreateLight(int type, Vector3 pos, Vector3 targ, Color color, Environment env)
{
Light light = { 0 };
if (lightsCount < MAX_LIGHTS)
{
light.enabled = true;
light.type = (LightType)type;
light.position = pos;
light.target = targ;
light.color = color;
char enabledName[32] = "lights[x].enabled\0";
char typeName[32] = "lights[x].type\0";
char posName[32] = "lights[x].position\0";
char targetName[32] = "lights[x].target\0";
char colorName[32] = "lights[x].color\0";
enabledName[7] = '0' + lightsCount;
typeName[7] = '0' + lightsCount;
posName[7] = '0' + lightsCount;
targetName[7] = '0' + lightsCount;
colorName[7] = '0' + lightsCount;
light.enabledLoc = GetShaderLocation(env.pbrShader, enabledName);
light.typeLoc = GetShaderLocation(env.pbrShader, typeName);
light.posLoc = GetShaderLocation(env.pbrShader, posName);
light.targetLoc = GetShaderLocation(env.pbrShader, targetName);
light.colorLoc = GetShaderLocation(env.pbrShader, colorName);
UpdateLightValues(env, light);
lightsCount++;
}
return light;
}
// Load an environment cubemap, irradiance, prefilter and PBR scene
Environment LoadEnvironment(const char* filename, int cubemapSize, int irradianceSize, int prefilterSize, int brdfSize)
{
Environment env = { 0 };
// Load environment required shaders
env.pbrShader = LoadShader(PATH_PBR_VS, PATH_PBR_FS);
Shader cubeShader = LoadShader(PATH_CUBE_VS, PATH_CUBE_FS);
Shader irradianceShader = LoadShader(PATH_SKYBOX_VS, PATH_IRRADIANCE_FS);
Shader prefilterShader = LoadShader(PATH_SKYBOX_VS, PATH_PREFILTER_FS);
Shader brdfShader = LoadShader(PATH_BRDF_VS, PATH_BRDF_FS);
env.skyShader = LoadShader(PATH_SKYBOX_VS, PATH_SKYBOX_FS);
// Get cubemap shader locations
int cubeProjectionLoc = GetShaderLocation(cubeShader, "projection");
int cubeViewLoc = GetShaderLocation(cubeShader, "view");
// Get skybox shader locations
int skyProjectionLoc = GetShaderLocation(env.skyShader, "projection");
env.skyViewLoc = GetShaderLocation(env.skyShader, "view");
env.skyResolutionLoc = GetShaderLocation(env.skyShader, "resolution");
// Get irradiance shader locations
int irradianceProjectionLoc = GetShaderLocation(irradianceShader, "projection");
int irradianceViewLoc = GetShaderLocation(irradianceShader, "view");
// Get prefilter shader locations
int prefilterProjectionLoc = GetShaderLocation(prefilterShader, "projection");
int prefilterViewLoc = GetShaderLocation(prefilterShader, "view");
int prefilterRoughnessLoc = GetShaderLocation(prefilterShader, "roughness");
// Set up environment shader texture units
int imap = 0;
int pfmap = 1;
int brdfmap = 2;
SetShaderValue(env.pbrShader, GetShaderLocation(env.pbrShader, "irradianceMap"), &imap, SHADER_UNIFORM_INT);
SetShaderValue(env.pbrShader, GetShaderLocation(env.pbrShader, "prefilterMap"), &pfmap, SHADER_UNIFORM_INT);
SetShaderValue(env.pbrShader, GetShaderLocation(env.pbrShader, "brdfLUT"), &brdfmap, SHADER_UNIFORM_INT);
// Set up cubemap shader constant values
SetShaderValue(cubeShader, GetShaderLocation(cubeShader, "equirectangularMap"), NULL, SHADER_UNIFORM_INT);
// Set up irradiance shader constant values
SetShaderValue(irradianceShader, GetShaderLocation(irradianceShader, "environmentMap"), NULL, SHADER_UNIFORM_INT);
// Set up prefilter shader constant values
SetShaderValue(prefilterShader, GetShaderLocation(prefilterShader, "environmentMap"), NULL, SHADER_UNIFORM_INT);
// Set up skybox shader constant values
SetShaderValue(env.skyShader, GetShaderLocation(env.skyShader, "environmentMap"), NULL, SHADER_UNIFORM_INT);
// Set up depth face culling and cube map seamless
//glDepthFunc(GL_LEQUAL);
//glDisable(GL_CULL_FACE);
//glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
//glLineWidth(2);
// Load HDR environment texture
Texture2D skyTex = LoadTexture(filename);
// Set up framebuffer for skybox
unsigned int captureFBO, captureRBO;
//glGenFramebuffers(1, &captureFBO);
//glGenRenderbuffers(1, &captureRBO);
//glBindFramebuffer(GL_FRAMEBUFFER, captureFBO);
//glBindRenderbuffer(GL_RENDERBUFFER, captureRBO);
//glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, cubemapSize, cubemapSize);
//glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, captureRBO);
// Set up cubemap to render and attach to framebuffer
// NOTE: faces are stored with 16 bit floating point values
//glGenTextures(1, &env.cubemapId);
//glBindTexture(GL_TEXTURE_CUBE_MAP, env.cubemapId);
//for (unsigned int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, cubemapSize, cubemapSize, 0, GL_RGB, GL_FLOAT, NULL);
//glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
//glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
///glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
//glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
////glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Create projection (transposed) and different views for each face
Matrix captureProjection = MatrixPerspective(90.0f, 1.0f, 0.01, 1000.0);
MatrixTranspose(captureProjection);
Matrix captureViews[6] = {
MatrixLookAt(Vector3 { 0.0f, 0.0f, 0.0f },Vector3 { 1.0f, 0.0f, 0.0f }, Vector3 { 0.0f, -1.0f, 0.0f }),
MatrixLookAt(Vector3 { 0.0f, 0.0f, 0.0f }, Vector3 { -1.0f, 0.0f, 0.0f }, Vector3 { 0.0f, -1.0f, 0.0f }),
MatrixLookAt(Vector3 { 0.0f, 0.0f, 0.0f }, Vector3 { 0.0f, 1.0f, 0.0f }, Vector3 { 0.0f, 0.0f, 1.0f }),
MatrixLookAt(Vector3 { 0.0f, 0.0f, 0.0f }, Vector3 { 0.0f, -1.0f, 0.0f }, Vector3 { 0.0f, 0.0f, -1.0f }),
MatrixLookAt(Vector3 { 0.0f, 0.0f, 0.0f }, Vector3 { 0.0f, 0.0f, 1.0f }, Vector3 { 0.0f, -1.0f, 0.0f }),
MatrixLookAt(Vector3 { 0.0f, 0.0f, 0.0f }, Vector3 { 0.0f, 0.0f, -1.0f }, Vector3 { 0.0f, -1.0f, 0.0f })
};
// Convert HDR equirectangular environment map to cubemap equivalent
//glUseProgram(cubeShader.id);
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, skyTex.id);
SetShaderValueMatrix(cubeShader, cubeProjectionLoc, captureProjection);
// Note: don't forget to configure the viewport to the capture dimensions
//glViewport(0, 0, cubemapSize, cubemapSize);
//glBindFramebuffer(GL_FRAMEBUFFER, captureFBO);
for (unsigned int i = 0; i < 6; i++)
{
SetShaderValueMatrix(cubeShader, cubeViewLoc, captureViews[i]);
//glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, env.cubemapId, 0);
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
RenderCube();
}