You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

251 lines
9.9 KiB

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