models_skybox.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*******************************************************************************************
  2. *
  3. * raylib [models] example - Skybox loading and drawing
  4. *
  5. * This example has been created using raylib 3.5 (www.raylib.com)
  6. * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
  7. *
  8. * Copyright (c) 2017-2020 Ramon Santamaria (@raysan5)
  9. *
  10. ********************************************************************************************/
  11. #include "raylib.h"
  12. #include "rlgl.h"
  13. #include "raymath.h" // Required for: MatrixPerspective(), MatrixLookAt()
  14. #if defined(PLATFORM_DESKTOP)
  15. #define GLSL_VERSION 330
  16. #else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB
  17. #define GLSL_VERSION 100
  18. #endif
  19. // Generate cubemap (6 faces) from equirectangular (panorama) texture
  20. static TextureCubemap GenTextureCubemap(Shader shader, Texture2D panorama, int size, int format);
  21. int main(void)
  22. {
  23. // Initialization
  24. //--------------------------------------------------------------------------------------
  25. const int screenWidth = 800;
  26. const int screenHeight = 450;
  27. InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox loading and drawing");
  28. // Define the camera to look into our 3d world
  29. Camera camera = { { 1.0f, 1.0f, 1.0f }, { 4.0f, 1.0f, 4.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 };
  30. // Load skybox model
  31. Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
  32. Model skybox = LoadModelFromMesh(cube);
  33. bool useHDR = true;
  34. // Load skybox shader and set required locations
  35. // NOTE: Some locations are automatically set at shader loading
  36. skybox.materials[0].shader = LoadShader(TextFormat("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION),
  37. TextFormat("resources/shaders/glsl%i/skybox.fs", GLSL_VERSION));
  38. SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "environmentMap"), (int[1]){ MATERIAL_MAP_CUBEMAP }, SHADER_UNIFORM_INT);
  39. SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "doGamma"), (int[1]) { useHDR ? 1 : 0 }, SHADER_UNIFORM_INT);
  40. SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "vflipped"), (int[1]){ useHDR ? 1 : 0 }, SHADER_UNIFORM_INT);
  41. // Load cubemap shader and setup required shader locations
  42. Shader shdrCubemap = LoadShader(TextFormat("resources/shaders/glsl%i/cubemap.vs", GLSL_VERSION),
  43. TextFormat("resources/shaders/glsl%i/cubemap.fs", GLSL_VERSION));
  44. SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT);
  45. char skyboxFileName[256] = { 0 };
  46. Texture2D panorama;
  47. if (useHDR)
  48. {
  49. TextCopy(skyboxFileName, "resources/dresden_square_2k.hdr");
  50. // Load HDR panorama (sphere) texture
  51. panorama = LoadTexture(skyboxFileName);
  52. // Generate cubemap (texture with 6 quads-cube-mapping) from panorama HDR texture
  53. // NOTE 1: New texture is generated rendering to texture, shader calculates the sphere->cube coordinates mapping
  54. // NOTE 2: It seems on some Android devices WebGL, fbo does not properly support a FLOAT-based attachment,
  55. // despite texture can be successfully created.. so using PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 instead of PIXELFORMAT_UNCOMPRESSED_R32G32B32A32
  56. skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
  57. //UnloadTexture(panorama); // Texture not required anymore, cubemap already generated
  58. }
  59. else
  60. {
  61. Image img = LoadImage("resources/skybox.png");
  62. skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = LoadTextureCubemap(img, CUBEMAP_LAYOUT_AUTO_DETECT); // CUBEMAP_LAYOUT_PANORAMA
  63. UnloadImage(img);
  64. }
  65. SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set a first person camera mode
  66. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  67. //--------------------------------------------------------------------------------------
  68. // Main game loop
  69. while (!WindowShouldClose()) // Detect window close button or ESC key
  70. {
  71. // Update
  72. //----------------------------------------------------------------------------------
  73. UpdateCamera(&camera); // Update camera
  74. // Load new cubemap texture on drag&drop
  75. if (IsFileDropped())
  76. {
  77. int count = 0;
  78. char **droppedFiles = GetDroppedFiles(&count);
  79. if (count == 1) // Only support one file dropped
  80. {
  81. if (IsFileExtension(droppedFiles[0], ".png;.jpg;.hdr;.bmp;.tga"))
  82. {
  83. // Unload current cubemap texture and load new one
  84. UnloadTexture(skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture);
  85. if (useHDR)
  86. {
  87. Texture2D panorama = LoadTexture(droppedFiles[0]);
  88. // Generate cubemap from panorama texture
  89. skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
  90. UnloadTexture(panorama);
  91. }
  92. else
  93. {
  94. Image img = LoadImage(droppedFiles[0]);
  95. skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = LoadTextureCubemap(img, CUBEMAP_LAYOUT_AUTO_DETECT);
  96. UnloadImage(img);
  97. }
  98. TextCopy(skyboxFileName, droppedFiles[0]);
  99. }
  100. }
  101. ClearDroppedFiles(); // Clear internal buffers
  102. }
  103. //----------------------------------------------------------------------------------
  104. // Draw
  105. //----------------------------------------------------------------------------------
  106. BeginDrawing();
  107. ClearBackground(RAYWHITE);
  108. BeginMode3D(camera);
  109. // We are inside the cube, we need to disable backface culling!
  110. rlDisableBackfaceCulling();
  111. rlDisableDepthMask();
  112. DrawModel(skybox, (Vector3){0, 0, 0}, 1.0f, WHITE);
  113. rlEnableBackfaceCulling();
  114. rlEnableDepthMask();
  115. DrawGrid(10, 1.0f);
  116. EndMode3D();
  117. //DrawTextureEx(panorama, (Vector2){ 0, 0 }, 0.0f, 0.5f, WHITE);
  118. if (useHDR) DrawText(TextFormat("Panorama image from hdrihaven.com: %s", GetFileName(skyboxFileName)), 10, GetScreenHeight() - 20, 10, BLACK);
  119. else DrawText(TextFormat(": %s", GetFileName(skyboxFileName)), 10, GetScreenHeight() - 20, 10, BLACK);
  120. DrawFPS(10, 10);
  121. EndDrawing();
  122. //----------------------------------------------------------------------------------
  123. }
  124. // De-Initialization
  125. //--------------------------------------------------------------------------------------
  126. UnloadShader(skybox.materials[0].shader);
  127. UnloadTexture(skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture);
  128. UnloadModel(skybox); // Unload skybox model
  129. CloseWindow(); // Close window and OpenGL context
  130. //--------------------------------------------------------------------------------------
  131. return 0;
  132. }
  133. // Generate cubemap texture from HDR texture
  134. static TextureCubemap GenTextureCubemap(Shader shader, Texture2D panorama, int size, int format)
  135. {
  136. TextureCubemap cubemap = { 0 };
  137. rlDisableBackfaceCulling(); // Disable backface culling to render inside the cube
  138. // STEP 1: Setup framebuffer
  139. //------------------------------------------------------------------------------------------
  140. unsigned int rbo = rlLoadTextureDepth(size, size, true);
  141. cubemap.id = rlLoadTextureCubemap(0, size, format);
  142. unsigned int fbo = rlLoadFramebuffer(size, size);
  143. rlFramebufferAttach(fbo, rbo, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_RENDERBUFFER, 0);
  144. rlFramebufferAttach(fbo, cubemap.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_CUBEMAP_POSITIVE_X, 0);
  145. // Check if framebuffer is complete with attachments (valid)
  146. if (rlFramebufferComplete(fbo)) TraceLog(LOG_INFO, "FBO: [ID %i] Framebuffer object created successfully", fbo);
  147. //------------------------------------------------------------------------------------------
  148. // STEP 2: Draw to framebuffer
  149. //------------------------------------------------------------------------------------------
  150. // NOTE: Shader is used to convert HDR equirectangular environment map to cubemap equivalent (6 faces)
  151. rlEnableShader(shader.id);
  152. // Define projection matrix and send it to shader
  153. Matrix matFboProjection = MatrixPerspective(90.0*DEG2RAD, 1.0, RL_CULL_DISTANCE_NEAR, RL_CULL_DISTANCE_FAR);
  154. rlSetUniformMatrix(shader.locs[SHADER_LOC_MATRIX_PROJECTION], matFboProjection);
  155. // Define view matrix for every side of the cubemap
  156. Matrix fboViews[6] = {
  157. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }),
  158. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ -1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }),
  159. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }),
  160. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }),
  161. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }),
  162. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f })
  163. };
  164. rlViewport(0, 0, size, size); // Set viewport to current fbo dimensions
  165. // Activate and enable texture for drawing to cubemap faces
  166. rlActiveTextureSlot(0);
  167. rlEnableTexture(panorama.id);
  168. for (int i = 0; i < 6; i++)
  169. {
  170. // Set the view matrix for the current cube face
  171. rlSetUniformMatrix(shader.locs[SHADER_LOC_MATRIX_VIEW], fboViews[i]);
  172. // Select the current cubemap face attachment for the fbo
  173. // WARNING: This function by default enables->attach->disables fbo!!!
  174. rlFramebufferAttach(fbo, cubemap.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_CUBEMAP_POSITIVE_X + i, 0);
  175. rlEnableFramebuffer(fbo);
  176. // Load and draw a cube, it uses the current enabled texture
  177. rlClearScreenBuffers();
  178. rlLoadDrawCube();
  179. // ALTERNATIVE: Try to use internal batch system to draw the cube instead of rlLoadDrawCube
  180. // for some reason this method does not work, maybe due to cube triangles definition? normals pointing out?
  181. // TODO: Investigate this issue...
  182. //rlSetTexture(panorama.id); // WARNING: It must be called after enabling current framebuffer if using internal batch system!
  183. //rlClearScreenBuffers();
  184. //DrawCubeV(Vector3Zero(), Vector3One(), WHITE);
  185. //rlDrawRenderBatchActive();
  186. }
  187. //------------------------------------------------------------------------------------------
  188. // STEP 3: Unload framebuffer and reset state
  189. //------------------------------------------------------------------------------------------
  190. rlDisableShader(); // Unbind shader
  191. rlDisableTexture(); // Unbind texture
  192. rlDisableFramebuffer(); // Unbind framebuffer
  193. rlUnloadFramebuffer(fbo); // Unload framebuffer (and automatically attached depth texture/renderbuffer)
  194. // Reset viewport dimensions to default
  195. rlViewport(0, 0, rlGetFramebufferWidth(), rlGetFramebufferHeight());
  196. rlEnableBackfaceCulling();
  197. //------------------------------------------------------------------------------------------
  198. cubemap.width = size;
  199. cubemap.height = size;
  200. cubemap.mipmaps = 1;
  201. cubemap.format = format;
  202. return cubemap;
  203. }