shaders_deferred_render.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*******************************************************************************************
  2. *
  3. * raylib [shaders] example - deferred rendering
  4. *
  5. * NOTE: This example requires raylib OpenGL 3.3 or OpenGL ES 3.0
  6. *
  7. * Example originally created with raylib 4.5, last time updated with raylib 4.5
  8. *
  9. * Example contributed by Justin Andreas Lacoste (@27justin) and reviewed by Ramon Santamaria (@raysan5)
  10. *
  11. * Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
  12. * BSD-like license that allows static linking with closed source software
  13. *
  14. * Copyright (c) 2023 Justin Andreas Lacoste (@27justin)
  15. *
  16. ********************************************************************************************/
  17. #include "raylib.h"
  18. #include "rlgl.h"
  19. #include "raymath.h"
  20. #define RLIGHTS_IMPLEMENTATION
  21. #include "rlights.h"
  22. #if defined(PLATFORM_DESKTOP)
  23. #define GLSL_VERSION 330
  24. #else // PLATFORM_ANDROID, PLATFORM_WEB
  25. #define GLSL_VERSION 100
  26. #endif
  27. #include <stdlib.h> // Required for: NULL
  28. #define MAX_CUBES 30
  29. typedef struct GBuffer {
  30. unsigned int framebuffer;
  31. unsigned int positionTexture;
  32. unsigned int normalTexture;
  33. unsigned int albedoSpecTexture;
  34. unsigned int depthRenderbuffer;
  35. } GBuffer;
  36. typedef enum {
  37. DEFERRED_POSITION,
  38. DEFERRED_NORMAL,
  39. DEFERRED_ALBEDO,
  40. DEFERRED_SHADING
  41. } DeferredMode;
  42. //------------------------------------------------------------------------------------
  43. // Program main entry point
  44. //------------------------------------------------------------------------------------
  45. int main(void)
  46. {
  47. // Initialization
  48. // -------------------------------------------------------------------------------------
  49. const int screenWidth = 800;
  50. const int screenHeight = 450;
  51. InitWindow(screenWidth, screenHeight, "raylib [shaders] example - deferred render");
  52. Camera camera = { 0 };
  53. camera.position = (Vector3){ 5.0f, 4.0f, 5.0f }; // Camera position
  54. camera.target = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera looking at point
  55. camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
  56. camera.fovy = 60.0f; // Camera field-of-view Y
  57. camera.projection = CAMERA_PERSPECTIVE; // Camera projection type
  58. // Load plane model from a generated mesh
  59. Model model = LoadModelFromMesh(GenMeshPlane(10.0f, 10.0f, 3, 3));
  60. Model cube = LoadModelFromMesh(GenMeshCube(2.0f, 2.0f, 2.0f));
  61. // Load geometry buffer (G-buffer) shader and deferred shader
  62. Shader gbufferShader = LoadShader("resources/shaders/glsl330/gbuffer.vs",
  63. "resources/shaders/glsl330/gbuffer.fs");
  64. Shader deferredShader = LoadShader("resources/shaders/glsl330/deferred_shading.vs",
  65. "resources/shaders/glsl330/deferred_shading.fs");
  66. deferredShader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(deferredShader, "viewPosition");
  67. // Initialize the G-buffer
  68. GBuffer gBuffer = { 0 };
  69. gBuffer.framebuffer = rlLoadFramebuffer(screenWidth, screenHeight);
  70. if (!gBuffer.framebuffer)
  71. {
  72. TraceLog(LOG_WARNING, "Failed to create framebuffer");
  73. exit(1);
  74. }
  75. rlEnableFramebuffer(gBuffer.framebuffer);
  76. // Since we are storing position and normal data in these textures,
  77. // we need to use a floating point format.
  78. gBuffer.positionTexture = rlLoadTexture(NULL, screenWidth, screenHeight, RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32, 1);
  79. gBuffer.normalTexture = rlLoadTexture(NULL, screenWidth, screenHeight, RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32, 1);
  80. // Albedo (diffuse color) and specular strength can be combined into one texture.
  81. // The color in RGB, and the specular strength in the alpha channel.
  82. gBuffer.albedoSpecTexture = rlLoadTexture(NULL, screenWidth, screenHeight, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1);
  83. // Activate the draw buffers for our framebuffer
  84. rlActiveDrawBuffers(3);
  85. // Now we attach our textures to the framebuffer.
  86. rlFramebufferAttach(gBuffer.framebuffer, gBuffer.positionTexture, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_TEXTURE2D, 0);
  87. rlFramebufferAttach(gBuffer.framebuffer, gBuffer.normalTexture, RL_ATTACHMENT_COLOR_CHANNEL1, RL_ATTACHMENT_TEXTURE2D, 0);
  88. rlFramebufferAttach(gBuffer.framebuffer, gBuffer.albedoSpecTexture, RL_ATTACHMENT_COLOR_CHANNEL2, RL_ATTACHMENT_TEXTURE2D, 0);
  89. // Finally we attach the depth buffer.
  90. gBuffer.depthRenderbuffer = rlLoadTextureDepth(screenWidth, screenHeight, true);
  91. rlFramebufferAttach(gBuffer.framebuffer, gBuffer.depthRenderbuffer, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_RENDERBUFFER, 0);
  92. // Make sure our framebuffer is complete.
  93. // NOTE: rlFramebufferComplete() automatically unbinds the framebuffer, so we don't have
  94. // to rlDisableFramebuffer() here.
  95. if (!rlFramebufferComplete(gBuffer.framebuffer))
  96. {
  97. TraceLog(LOG_WARNING, "Framebuffer is not complete");
  98. exit(1);
  99. }
  100. // Now we initialize the sampler2D uniform's in the deferred shader.
  101. // We do this by setting the uniform's value to the color channel slot we earlier
  102. // bound our textures to.
  103. rlEnableShader(deferredShader.id);
  104. rlSetUniformSampler(rlGetLocationUniform(deferredShader.id, "gPosition"), 0);
  105. rlSetUniformSampler(rlGetLocationUniform(deferredShader.id, "gNormal"), 1);
  106. rlSetUniformSampler(rlGetLocationUniform(deferredShader.id, "gAlbedoSpec"), 2);
  107. rlDisableShader();
  108. // Assign out lighting shader to model
  109. model.materials[0].shader = gbufferShader;
  110. cube.materials[0].shader = gbufferShader;
  111. // Create lights
  112. //--------------------------------------------------------------------------------------
  113. Light lights[MAX_LIGHTS] = { 0 };
  114. lights[0] = CreateLight(LIGHT_POINT, (Vector3){ -2, 1, -2 }, Vector3Zero(), YELLOW, deferredShader);
  115. lights[1] = CreateLight(LIGHT_POINT, (Vector3){ 2, 1, 2 }, Vector3Zero(), RED, deferredShader);
  116. lights[2] = CreateLight(LIGHT_POINT, (Vector3){ -2, 1, 2 }, Vector3Zero(), GREEN, deferredShader);
  117. lights[3] = CreateLight(LIGHT_POINT, (Vector3){ 2, 1, -2 }, Vector3Zero(), BLUE, deferredShader);
  118. const float CUBE_SCALE = 0.25;
  119. Vector3 cubePositions[MAX_CUBES] = { 0 };
  120. float cubeRotations[MAX_CUBES] = { 0 };
  121. for (int i = 0; i < MAX_CUBES; i++)
  122. {
  123. cubePositions[i] = (Vector3){
  124. .x = (float)(rand()%10) - 5,
  125. .y = (float)(rand()%5),
  126. .z = (float)(rand()%10) - 5,
  127. };
  128. cubeRotations[i] = (float)(rand()%360);
  129. }
  130. DeferredMode mode = DEFERRED_SHADING;
  131. rlEnableDepthTest();
  132. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  133. //---------------------------------------------------------------------------------------
  134. // Main game loop
  135. while (!WindowShouldClose())
  136. {
  137. // Update
  138. //----------------------------------------------------------------------------------
  139. UpdateCamera(&camera, CAMERA_ORBITAL);
  140. // Update the shader with the camera view vector (points towards { 0.0f, 0.0f, 0.0f })
  141. float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z };
  142. SetShaderValue(deferredShader, deferredShader.locs[SHADER_LOC_VECTOR_VIEW], cameraPos, SHADER_UNIFORM_VEC3);
  143. // Check key inputs to enable/disable lights
  144. if (IsKeyPressed(KEY_Y)) { lights[0].enabled = !lights[0].enabled; }
  145. if (IsKeyPressed(KEY_R)) { lights[1].enabled = !lights[1].enabled; }
  146. if (IsKeyPressed(KEY_G)) { lights[2].enabled = !lights[2].enabled; }
  147. if (IsKeyPressed(KEY_B)) { lights[3].enabled = !lights[3].enabled; }
  148. // Check key inputs to switch between G-buffer textures
  149. if (IsKeyPressed(KEY_ONE)) mode = DEFERRED_POSITION;
  150. if (IsKeyPressed(KEY_TWO)) mode = DEFERRED_NORMAL;
  151. if (IsKeyPressed(KEY_THREE)) mode = DEFERRED_ALBEDO;
  152. if (IsKeyPressed(KEY_FOUR)) mode = DEFERRED_SHADING;
  153. // Update light values (actually, only enable/disable them)
  154. for (int i = 0; i < MAX_LIGHTS; i++) UpdateLightValues(deferredShader, lights[i]);
  155. //----------------------------------------------------------------------------------
  156. // Draw
  157. // ---------------------------------------------------------------------------------
  158. BeginDrawing();
  159. ClearBackground(RAYWHITE);
  160. // Draw to the geometry buffer by first activating it
  161. rlEnableFramebuffer(gBuffer.framebuffer);
  162. rlClearScreenBuffers(); // Clear color and depth buffer
  163. rlDisableColorBlend();
  164. BeginMode3D(camera);
  165. // NOTE: We have to use rlEnableShader here. `BeginShaderMode` or thus `rlSetShader`
  166. // will not work, as they won't immediately load the shader program.
  167. rlEnableShader(gbufferShader.id);
  168. // When drawing a model here, make sure that the material's shaders
  169. // are set to the gbuffer shader!
  170. DrawModel(model, Vector3Zero(), 1.0f, WHITE);
  171. DrawModel(cube, (Vector3) { 0.0, 1.0f, 0.0 }, 1.0f, WHITE);
  172. for (int i = 0; i < MAX_CUBES; i++)
  173. {
  174. Vector3 position = cubePositions[i];
  175. DrawModelEx(cube, position, (Vector3) { 1, 1, 1 }, cubeRotations[i], (Vector3) { CUBE_SCALE, CUBE_SCALE, CUBE_SCALE }, WHITE);
  176. }
  177. rlDisableShader();
  178. EndMode3D();
  179. rlEnableColorBlend();
  180. // Go back to the default framebuffer (0) and draw our deferred shading.
  181. rlDisableFramebuffer();
  182. rlClearScreenBuffers(); // Clear color & depth buffer
  183. switch (mode)
  184. {
  185. case DEFERRED_SHADING:
  186. {
  187. BeginMode3D(camera);
  188. rlDisableColorBlend();
  189. rlEnableShader(deferredShader.id);
  190. // Activate our g-buffer textures
  191. // These will now be bound to the sampler2D uniforms `gPosition`, `gNormal`,
  192. // and `gAlbedoSpec`
  193. rlActiveTextureSlot(0);
  194. rlEnableTexture(gBuffer.positionTexture);
  195. rlActiveTextureSlot(1);
  196. rlEnableTexture(gBuffer.normalTexture);
  197. rlActiveTextureSlot(2);
  198. rlEnableTexture(gBuffer.albedoSpecTexture);
  199. // Finally, we draw a fullscreen quad to our default framebuffer
  200. // This will now be shaded using our deferred shader
  201. rlLoadDrawQuad();
  202. rlDisableShader();
  203. rlEnableColorBlend();
  204. EndMode3D();
  205. // As a last step, we now copy over the depth buffer from our g-buffer to the default framebuffer.
  206. rlEnableFramebuffer(gBuffer.framebuffer); //glBindFramebuffer(GL_READ_FRAMEBUFFER, gBuffer.framebuffer);
  207. rlEnableFramebuffer(0); //glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  208. rlBlitFramebuffer(0, 0, screenWidth, screenHeight, 0, 0, screenWidth, screenHeight, 0x00000100); // GL_DEPTH_BUFFER_BIT
  209. rlDisableFramebuffer();
  210. // Since our shader is now done and disabled, we can draw our lights in default
  211. // forward rendering
  212. BeginMode3D(camera);
  213. rlEnableShader(rlGetShaderIdDefault());
  214. for(int i = 0; i < MAX_LIGHTS; i++)
  215. {
  216. if (lights[i].enabled) DrawSphereEx(lights[i].position, 0.2f, 8, 8, lights[i].color);
  217. else DrawSphereWires(lights[i].position, 0.2f, 8, 8, ColorAlpha(lights[i].color, 0.3f));
  218. }
  219. rlDisableShader();
  220. EndMode3D();
  221. DrawText("FINAL RESULT", 10, screenHeight - 30, 20, DARKGREEN);
  222. } break;
  223. case DEFERRED_POSITION:
  224. {
  225. DrawTextureRec((Texture2D){
  226. .id = gBuffer.positionTexture,
  227. .width = screenWidth,
  228. .height = screenHeight,
  229. }, (Rectangle) { 0, 0, screenWidth, -screenHeight }, Vector2Zero(), RAYWHITE);
  230. DrawText("POSITION TEXTURE", 10, screenHeight - 30, 20, DARKGREEN);
  231. } break;
  232. case DEFERRED_NORMAL:
  233. {
  234. DrawTextureRec((Texture2D){
  235. .id = gBuffer.normalTexture,
  236. .width = screenWidth,
  237. .height = screenHeight,
  238. }, (Rectangle) { 0, 0, screenWidth, -screenHeight }, Vector2Zero(), RAYWHITE);
  239. DrawText("NORMAL TEXTURE", 10, screenHeight - 30, 20, DARKGREEN);
  240. } break;
  241. case DEFERRED_ALBEDO:
  242. {
  243. DrawTextureRec((Texture2D){
  244. .id = gBuffer.albedoSpecTexture,
  245. .width = screenWidth,
  246. .height = screenHeight,
  247. }, (Rectangle) { 0, 0, screenWidth, -screenHeight }, Vector2Zero(), RAYWHITE);
  248. DrawText("ALBEDO TEXTURE", 10, screenHeight - 30, 20, DARKGREEN);
  249. } break;
  250. }
  251. DrawText("Toggle lights keys: [Y][R][G][B]", 10, 40, 20, DARKGRAY);
  252. DrawText("Switch G-buffer textures: [1][2][3][4]", 10, 70, 20, DARKGRAY);
  253. DrawFPS(10, 10);
  254. EndDrawing();
  255. // -----------------------------------------------------------------------------
  256. }
  257. // De-Initialization
  258. //--------------------------------------------------------------------------------------
  259. UnloadModel(model); // Unload the models
  260. UnloadModel(cube);
  261. UnloadShader(deferredShader); // Unload shaders
  262. UnloadShader(gbufferShader);
  263. // Unload geometry buffer and all attached textures
  264. rlUnloadFramebuffer(gBuffer.framebuffer);
  265. rlUnloadTexture(gBuffer.positionTexture);
  266. rlUnloadTexture(gBuffer.normalTexture);
  267. rlUnloadTexture(gBuffer.albedoSpecTexture);
  268. rlUnloadTexture(gBuffer.depthRenderbuffer);
  269. CloseWindow(); // Close window and OpenGL context
  270. //--------------------------------------------------------------------------------------
  271. return 0;
  272. }