shaders_shadowmap_rendering.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*******************************************************************************************
  2. *
  3. * raylib [shaders] example - shadowmap rendering
  4. *
  5. * Example complexity rating: [★★★★] 4/4
  6. *
  7. * Example originally created with raylib 5.0, last time updated with raylib 5.0
  8. *
  9. * Example contributed by TheManTheMythTheGameDev (@TheManTheMythTheGameDev) 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-2025 TheManTheMythTheGameDev (@TheManTheMythTheGameDev)
  15. *
  16. ********************************************************************************************/
  17. #include "raylib.h"
  18. #include "raymath.h"
  19. #include "rlgl.h"
  20. #if defined(PLATFORM_DESKTOP)
  21. #define GLSL_VERSION 330
  22. #else // PLATFORM_ANDROID, PLATFORM_WEB
  23. #define GLSL_VERSION 100
  24. #endif
  25. #define SHADOWMAP_RESOLUTION 1024
  26. static RenderTexture2D LoadShadowmapRenderTexture(int width, int height);
  27. static void UnloadShadowmapRenderTexture(RenderTexture2D target);
  28. static void DrawScene(Model cube, Model robot);
  29. //------------------------------------------------------------------------------------
  30. // Program main entry point
  31. //------------------------------------------------------------------------------------
  32. int main(void)
  33. {
  34. // Initialization
  35. //--------------------------------------------------------------------------------------
  36. const int screenWidth = 800;
  37. const int screenHeight = 450;
  38. // Shadows are a HUGE topic, and this example shows an extremely simple implementation of the shadowmapping algorithm,
  39. // which is the industry standard for shadows. This algorithm can be extended in a ridiculous number of ways to improve
  40. // realism and also adapt it for different scenes. This is pretty much the simplest possible implementation
  41. SetConfigFlags(FLAG_MSAA_4X_HINT);
  42. InitWindow(screenWidth, screenHeight, "raylib [shaders] example - shadowmap rendering");
  43. Camera3D camera = (Camera3D){ 0 };
  44. camera.position = (Vector3){ 10.0f, 10.0f, 10.0f };
  45. camera.target = Vector3Zero();
  46. camera.projection = CAMERA_PERSPECTIVE;
  47. camera.up = (Vector3){ 0.0f, 1.0f, 0.0f };
  48. camera.fovy = 45.0f;
  49. Shader shadowShader = LoadShader(TextFormat("resources/shaders/glsl%i/shadowmap.vs", GLSL_VERSION),
  50. TextFormat("resources/shaders/glsl%i/shadowmap.fs", GLSL_VERSION));
  51. shadowShader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shadowShader, "viewPos");
  52. Vector3 lightDir = Vector3Normalize((Vector3){ 0.35f, -1.0f, -0.35f });
  53. Color lightColor = WHITE;
  54. Vector4 lightColorNormalized = ColorNormalize(lightColor);
  55. int lightDirLoc = GetShaderLocation(shadowShader, "lightDir");
  56. int lightColLoc = GetShaderLocation(shadowShader, "lightColor");
  57. SetShaderValue(shadowShader, lightDirLoc, &lightDir, SHADER_UNIFORM_VEC3);
  58. SetShaderValue(shadowShader, lightColLoc, &lightColorNormalized, SHADER_UNIFORM_VEC4);
  59. int ambientLoc = GetShaderLocation(shadowShader, "ambient");
  60. float ambient[4] = {0.1f, 0.1f, 0.1f, 1.0f};
  61. SetShaderValue(shadowShader, ambientLoc, ambient, SHADER_UNIFORM_VEC4);
  62. int lightVPLoc = GetShaderLocation(shadowShader, "lightVP");
  63. int shadowMapLoc = GetShaderLocation(shadowShader, "shadowMap");
  64. int shadowMapResolution = SHADOWMAP_RESOLUTION;
  65. SetShaderValue(shadowShader, GetShaderLocation(shadowShader, "shadowMapResolution"), &shadowMapResolution, SHADER_UNIFORM_INT);
  66. Model cube = LoadModelFromMesh(GenMeshCube(1.0f, 1.0f, 1.0f));
  67. cube.materials[0].shader = shadowShader;
  68. Model robot = LoadModel("resources/models/robot.glb");
  69. for (int i = 0; i < robot.materialCount; i++) robot.materials[i].shader = shadowShader;
  70. int animCount = 0;
  71. ModelAnimation *robotAnimations = LoadModelAnimations("resources/models/robot.glb", &animCount);
  72. RenderTexture2D shadowMap = LoadShadowmapRenderTexture(SHADOWMAP_RESOLUTION, SHADOWMAP_RESOLUTION);
  73. // For the shadowmapping algorithm, we will be rendering everything from the light's point of view
  74. Camera3D lightCamera = { 0 };
  75. lightCamera.position = Vector3Scale(lightDir, -15.0f);
  76. lightCamera.target = Vector3Zero();
  77. lightCamera.projection = CAMERA_ORTHOGRAPHIC; // Use an orthographic projection for directional lights
  78. lightCamera.up = (Vector3){ 0.0f, 1.0f, 0.0f };
  79. lightCamera.fovy = 20.0f;
  80. int frameCounter = 0;
  81. // Store the light matrices
  82. Matrix lightView = { 0 };
  83. Matrix lightProj = { 0 };
  84. Matrix lightViewProj = { 0 };
  85. int textureActiveSlot = 10; // Can be anything 0 to 15, but 0 will probably be taken up
  86. SetTargetFPS(60);
  87. //--------------------------------------------------------------------------------------
  88. // Main game loop
  89. while (!WindowShouldClose()) // Detect window close button or ESC key
  90. {
  91. // Update
  92. //----------------------------------------------------------------------------------
  93. float deltaTime = GetFrameTime();
  94. Vector3 cameraPos = camera.position;
  95. SetShaderValue(shadowShader, shadowShader.locs[SHADER_LOC_VECTOR_VIEW], &cameraPos, SHADER_UNIFORM_VEC3);
  96. UpdateCamera(&camera, CAMERA_ORBITAL);
  97. frameCounter++;
  98. frameCounter %= (robotAnimations[0].frameCount);
  99. UpdateModelAnimation(robot, robotAnimations[0], frameCounter);
  100. // Move light with arrow keys
  101. const float cameraSpeed = 0.05f;
  102. if (IsKeyDown(KEY_LEFT))
  103. {
  104. if (lightDir.x < 0.6f) lightDir.x += cameraSpeed*60.0f*deltaTime;
  105. }
  106. if (IsKeyDown(KEY_RIGHT))
  107. {
  108. if (lightDir.x > -0.6f) lightDir.x -= cameraSpeed*60.0f*deltaTime;
  109. }
  110. if (IsKeyDown(KEY_UP))
  111. {
  112. if (lightDir.z < 0.6f) lightDir.z += cameraSpeed*60.0f*deltaTime;
  113. }
  114. if (IsKeyDown(KEY_DOWN))
  115. {
  116. if (lightDir.z > -0.6f) lightDir.z -= cameraSpeed*60.0f*deltaTime;
  117. }
  118. lightDir = Vector3Normalize(lightDir);
  119. lightCamera.position = Vector3Scale(lightDir, -15.0f);
  120. SetShaderValue(shadowShader, lightDirLoc, &lightDir, SHADER_UNIFORM_VEC3);
  121. //----------------------------------------------------------------------------------
  122. // Draw
  123. //----------------------------------------------------------------------------------
  124. // PASS 01: Render all objects into the shadowmap render texture
  125. // We record all the objects' depths (as rendered from the light source's point of view) in a buffer
  126. // Anything that is "visible" to the light is in light, anything that isn't is in shadow
  127. // We can later use the depth buffer when rendering everything from the player's point of view
  128. // to determine whether a given point is "visible" to the light
  129. BeginTextureMode(shadowMap);
  130. ClearBackground(WHITE);
  131. BeginMode3D(lightCamera);
  132. lightView = rlGetMatrixModelview();
  133. lightProj = rlGetMatrixProjection();
  134. DrawScene(cube, robot);
  135. EndMode3D();
  136. EndTextureMode();
  137. lightViewProj = MatrixMultiply(lightView, lightProj);
  138. // PASS 02: Draw the scene into main framebuffer, using the generated shadowmap
  139. BeginDrawing();
  140. ClearBackground(RAYWHITE);
  141. SetShaderValueMatrix(shadowShader, lightVPLoc, lightViewProj);
  142. rlEnableShader(shadowShader.id);
  143. rlActiveTextureSlot(textureActiveSlot);
  144. rlEnableTexture(shadowMap.depth.id);
  145. rlSetUniform(shadowMapLoc, &textureActiveSlot, SHADER_UNIFORM_INT, 1);
  146. BeginMode3D(camera);
  147. DrawScene(cube, robot); // Draw the same exact things as we drew in the shadowmap!
  148. EndMode3D();
  149. DrawText("Use the arrow keys to rotate the light!", 10, 10, 30, RED);
  150. DrawText("Shadows in raylib using the shadowmapping algorithm!", screenWidth - 280, screenHeight - 20, 10, GRAY);
  151. EndDrawing();
  152. if (IsKeyPressed(KEY_F)) TakeScreenshot("shaders_shadowmap.png");
  153. //----------------------------------------------------------------------------------
  154. }
  155. // De-Initialization
  156. //--------------------------------------------------------------------------------------
  157. UnloadShader(shadowShader);
  158. UnloadModel(cube);
  159. UnloadModel(robot);
  160. UnloadModelAnimations(robotAnimations, animCount);
  161. UnloadShadowmapRenderTexture(shadowMap);
  162. CloseWindow(); // Close window and OpenGL context
  163. //--------------------------------------------------------------------------------------
  164. return 0;
  165. }
  166. // Load render texture for shadowmap projection
  167. // NOTE: Load framebuffer with only a texture depth attachment,
  168. // no color attachment required for shadowmap
  169. static RenderTexture2D LoadShadowmapRenderTexture(int width, int height)
  170. {
  171. RenderTexture2D target = { 0 };
  172. target.id = rlLoadFramebuffer(); // Load an empty framebuffer
  173. target.texture.width = width;
  174. target.texture.height = height;
  175. if (target.id > 0)
  176. {
  177. rlEnableFramebuffer(target.id);
  178. // Create depth texture
  179. // NOTE: No need a color texture attachment for the shadowmap
  180. target.depth.id = rlLoadTextureDepth(width, height, false);
  181. target.depth.width = width;
  182. target.depth.height = height;
  183. target.depth.format = 19; // DEPTH_COMPONENT_24BIT?
  184. target.depth.mipmaps = 1;
  185. // Attach depth texture to FBO
  186. rlFramebufferAttach(target.id, target.depth.id, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_TEXTURE2D, 0);
  187. // Check if fbo is complete with attachments (valid)
  188. if (rlFramebufferComplete(target.id)) TRACELOG(LOG_INFO, "FBO: [ID %i] Framebuffer object created successfully", target.id);
  189. rlDisableFramebuffer();
  190. }
  191. else TRACELOG(LOG_WARNING, "FBO: Framebuffer object can not be created");
  192. return target;
  193. }
  194. // Unload shadowmap render texture from GPU memory (VRAM)
  195. static void UnloadShadowmapRenderTexture(RenderTexture2D target)
  196. {
  197. if (target.id > 0)
  198. {
  199. // NOTE: Depth texture/renderbuffer is automatically
  200. // queried and deleted before deleting framebuffer
  201. rlUnloadFramebuffer(target.id);
  202. }
  203. }
  204. // Draw full scene projecting shadows
  205. // NOTE: Required to be called several time to generate shadowmap
  206. static void DrawScene(Model cube, Model robot)
  207. {
  208. DrawModelEx(cube, Vector3Zero(), (Vector3) { 0.0f, 1.0f, 0.0f }, 0.0f, (Vector3) { 10.0f, 1.0f, 10.0f }, BLUE);
  209. DrawModelEx(cube, (Vector3) { 1.5f, 1.0f, -1.5f }, (Vector3) { 0.0f, 1.0f, 0.0f }, 0.0f, Vector3One(), WHITE);
  210. DrawModelEx(robot, (Vector3) { 0.0f, 0.5f, 0.0f }, (Vector3) { 0.0f, 1.0f, 0.0f }, 0.0f, (Vector3) { 1.0f, 1.0f, 1.0f }, RED);
  211. }