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.

266 line
12 KiB

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