shaders_deferred_render.c 16 KB

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