shaders_basic_pbr.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*******************************************************************************************
  2. *
  3. * raylib [shaders] example - Basic PBR
  4. *
  5. * Example originally created with raylib 5.0, last time updated with raylib 5.1-dev
  6. *
  7. * Example contributed by Afan OLOVCIC (@_DevDad) 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. * Copyright (c) 2023-2024 Afan OLOVCIC (@_DevDad)
  13. *
  14. * Model: "Old Rusty Car" (https://skfb.ly/LxRy) by Renafox,
  15. * licensed under Creative Commons Attribution-NonCommercial
  16. * (http://creativecommons.org/licenses/by-nc/4.0/)
  17. *
  18. ********************************************************************************************/
  19. #include "raylib.h"
  20. #if defined(PLATFORM_WEB)
  21. #include <emscripten/emscripten.h>
  22. #endif
  23. #if defined(PLATFORM_DESKTOP)
  24. #define GLSL_VERSION 330
  25. #else // PLATFORM_ANDROID, PLATFORM_WEB
  26. #define GLSL_VERSION 120
  27. #endif
  28. #include <stdlib.h> // Required for: NULL
  29. #define MAX_LIGHTS 4 // Max dynamic lights supported by shader
  30. //----------------------------------------------------------------------------------
  31. // Types and Structures Definition
  32. //----------------------------------------------------------------------------------
  33. // Light type
  34. typedef enum {
  35. LIGHT_DIRECTIONAL = 0,
  36. LIGHT_POINT,
  37. LIGHT_SPOT
  38. } LightType;
  39. // Light data
  40. typedef struct {
  41. int type;
  42. int enabled;
  43. Vector3 position;
  44. Vector3 target;
  45. float color[4];
  46. float intensity;
  47. // Shader light parameters locations
  48. int typeLoc;
  49. int enabledLoc;
  50. int positionLoc;
  51. int targetLoc;
  52. int colorLoc;
  53. int intensityLoc;
  54. } Light;
  55. //----------------------------------------------------------------------------------
  56. // Global Variables Definition
  57. //----------------------------------------------------------------------------------
  58. static int lightCount = 0; // Current number of dynamic lights that have been created
  59. //----------------------------------------------------------------------------------
  60. // Module specific Functions Declaration
  61. //----------------------------------------------------------------------------------
  62. // Create a light and get shader locations
  63. static Light CreateLight(int type, Vector3 position, Vector3 target, Color color, float intensity, Shader shader);
  64. // Update light properties on shader
  65. // NOTE: Light shader locations should be available
  66. static void UpdateLight(Shader shader, Light light);
  67. //----------------------------------------------------------------------------------
  68. // Main Entry Point
  69. //----------------------------------------------------------------------------------
  70. int main()
  71. {
  72. // Initialization
  73. //--------------------------------------------------------------------------------------
  74. const int screenWidth = 800;
  75. const int screenHeight = 450;
  76. SetConfigFlags(FLAG_MSAA_4X_HINT);
  77. InitWindow(screenWidth, screenHeight, "raylib [shaders] example - basic pbr");
  78. // Define the camera to look into our 3d world
  79. Camera camera = { 0 };
  80. camera.position = (Vector3){ 2.0f, 2.0f, 6.0f }; // Camera position
  81. camera.target = (Vector3){ 0.0f, 0.5f, 0.0f }; // Camera looking at point
  82. camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
  83. camera.fovy = 45.0f; // Camera field-of-view Y
  84. camera.projection = CAMERA_PERSPECTIVE; // Camera projection type
  85. // Load PBR shader and setup all required locations
  86. Shader shader = LoadShader(TextFormat("resources/shaders/glsl%i/pbr.vs", GLSL_VERSION),
  87. TextFormat("resources/shaders/glsl%i/pbr.fs", GLSL_VERSION));
  88. shader.locs[SHADER_LOC_MAP_ALBEDO] = GetShaderLocation(shader, "albedoMap");
  89. // WARNING: Metalness, roughness, and ambient occlusion are all packed into a MRA texture
  90. // They are passed as to the SHADER_LOC_MAP_METALNESS location for convenience,
  91. // shader already takes care of it accordingly
  92. shader.locs[SHADER_LOC_MAP_METALNESS] = GetShaderLocation(shader, "mraMap");
  93. shader.locs[SHADER_LOC_MAP_NORMAL] = GetShaderLocation(shader, "normalMap");
  94. // WARNING: Similar to the MRA map, the emissive map packs different information
  95. // into a single texture: it stores height and emission data
  96. // It is binded to SHADER_LOC_MAP_EMISSION location an properly processed on shader
  97. shader.locs[SHADER_LOC_MAP_EMISSION] = GetShaderLocation(shader, "emissiveMap");
  98. shader.locs[SHADER_LOC_COLOR_DIFFUSE] = GetShaderLocation(shader, "albedoColor");
  99. // Setup additional required shader locations, including lights data
  100. shader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
  101. int lightCountLoc = GetShaderLocation(shader, "numOfLights");
  102. int maxLightCount = MAX_LIGHTS;
  103. SetShaderValue(shader, lightCountLoc, &maxLightCount, SHADER_UNIFORM_INT);
  104. // Setup ambient color and intensity parameters
  105. float ambientIntensity = 0.02f;
  106. Color ambientColor = (Color){ 26, 32, 135, 255 };
  107. Vector3 ambientColorNormalized = (Vector3){ ambientColor.r/255.0f, ambientColor.g/255.0f, ambientColor.b/255.0f };
  108. SetShaderValue(shader, GetShaderLocation(shader, "ambientColor"), &ambientColorNormalized, SHADER_UNIFORM_VEC3);
  109. SetShaderValue(shader, GetShaderLocation(shader, "ambient"), &ambientIntensity, SHADER_UNIFORM_FLOAT);
  110. // Get location for shader parameters that can be modified in real time
  111. int emissiveIntensityLoc = GetShaderLocation(shader, "emissivePower");
  112. int emissiveColorLoc = GetShaderLocation(shader, "emissiveColor");
  113. int textureTilingLoc = GetShaderLocation(shader, "tiling");
  114. // Load old car model using PBR maps and shader
  115. // WARNING: We know this model consists of a single model.meshes[0] and
  116. // that model.materials[0] is by default assigned to that mesh
  117. // There could be more complex models consisting of multiple meshes and
  118. // multiple materials defined for those meshes... but always 1 mesh = 1 material
  119. Model car = LoadModel("resources/models/old_car_new.glb");
  120. // Assign already setup PBR shader to model.materials[0], used by models.meshes[0]
  121. car.materials[0].shader = shader;
  122. // Setup materials[0].maps default parameters
  123. car.materials[0].maps[MATERIAL_MAP_ALBEDO].color = WHITE;
  124. car.materials[0].maps[MATERIAL_MAP_METALNESS].value = 0.0f;
  125. car.materials[0].maps[MATERIAL_MAP_ROUGHNESS].value = 0.0f;
  126. car.materials[0].maps[MATERIAL_MAP_OCCLUSION].value = 1.0f;
  127. car.materials[0].maps[MATERIAL_MAP_EMISSION].color = (Color){ 255, 162, 0, 255 };
  128. // Setup materials[0].maps default textures
  129. car.materials[0].maps[MATERIAL_MAP_ALBEDO].texture = LoadTexture("resources/old_car_d.png");
  130. car.materials[0].maps[MATERIAL_MAP_METALNESS].texture = LoadTexture("resources/old_car_mra.png");
  131. car.materials[0].maps[MATERIAL_MAP_NORMAL].texture = LoadTexture("resources/old_car_n.png");
  132. car.materials[0].maps[MATERIAL_MAP_EMISSION].texture = LoadTexture("resources/old_car_e.png");
  133. // Load floor model mesh and assign material parameters
  134. // NOTE: A basic plane shape can be generated instead of being loaded from a model file
  135. Model floor = LoadModel("resources/models/plane.glb");
  136. //Mesh floorMesh = GenMeshPlane(10, 10, 10, 10);
  137. //GenMeshTangents(&floorMesh); // TODO: Review tangents generation
  138. //Model floor = LoadModelFromMesh(floorMesh);
  139. // Assign material shader for our floor model, same PBR shader
  140. floor.materials[0].shader = shader;
  141. floor.materials[0].maps[MATERIAL_MAP_ALBEDO].color = WHITE;
  142. floor.materials[0].maps[MATERIAL_MAP_METALNESS].value = 0.0f;
  143. floor.materials[0].maps[MATERIAL_MAP_ROUGHNESS].value = 0.0f;
  144. floor.materials[0].maps[MATERIAL_MAP_OCCLUSION].value = 1.0f;
  145. floor.materials[0].maps[MATERIAL_MAP_EMISSION].color = BLACK;
  146. floor.materials[0].maps[MATERIAL_MAP_ALBEDO].texture = LoadTexture("resources/road_a.png");
  147. floor.materials[0].maps[MATERIAL_MAP_METALNESS].texture = LoadTexture("resources/road_mra.png");
  148. floor.materials[0].maps[MATERIAL_MAP_NORMAL].texture = LoadTexture("resources/road_n.png");
  149. // Models texture tiling parameter can be stored in the Material struct if required (CURRENTLY NOT USED)
  150. // NOTE: Material.params[4] are available for generic parameters storage (float)
  151. Vector2 carTextureTiling = (Vector2){ 0.5f, 0.5f };
  152. Vector2 floorTextureTiling = (Vector2){ 0.5f, 0.5f };
  153. // Create some lights
  154. Light lights[MAX_LIGHTS] = { 0 };
  155. lights[0] = CreateLight(LIGHT_POINT, (Vector3){ -1, 1, -2 }, (Vector3){0,0,0}, YELLOW,4, shader);
  156. lights[1] = CreateLight(LIGHT_POINT, (Vector3){ 2, 1, 1 }, (Vector3){0,0,0}, GREEN,3.3, shader);
  157. lights[2] = CreateLight(LIGHT_POINT, (Vector3){ -2, 1, 1 }, (Vector3){0,0,0}, RED,8.3, shader);
  158. lights[3] = CreateLight(LIGHT_POINT, (Vector3){ 1, 1, -2 }, (Vector3){0,0,0}, BLUE,2, shader);
  159. // Setup material texture maps usage in shader
  160. // NOTE: By default, the texture maps are always used
  161. int usage = 1;
  162. SetShaderValue(shader, GetShaderLocation(shader, "useTexAlbedo"), &usage, SHADER_UNIFORM_INT);
  163. SetShaderValue(shader, GetShaderLocation(shader, "useTexNormal"), &usage, SHADER_UNIFORM_INT);
  164. SetShaderValue(shader, GetShaderLocation(shader, "useTexMRA"), &usage, SHADER_UNIFORM_INT);
  165. SetShaderValue(shader, GetShaderLocation(shader, "useTexEmissive"), &usage, SHADER_UNIFORM_INT);
  166. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  167. //---------------------------------------------------------------------------------------
  168. // Main game loop
  169. while (!WindowShouldClose()) // Detect window close button or ESC key
  170. {
  171. // Update
  172. //----------------------------------------------------------------------------------
  173. UpdateCamera(&camera, CAMERA_ORBITAL);
  174. // Update the shader with the camera view vector (points towards { 0.0f, 0.0f, 0.0f })
  175. float cameraPos[3] = {camera.position.x, camera.position.y, camera.position.z};
  176. SetShaderValue(shader, shader.locs[SHADER_LOC_VECTOR_VIEW], cameraPos, SHADER_UNIFORM_VEC3);
  177. // Check key inputs to enable/disable lights
  178. if (IsKeyPressed(KEY_ONE)) { lights[2].enabled = !lights[2].enabled; }
  179. if (IsKeyPressed(KEY_TWO)) { lights[1].enabled = !lights[1].enabled; }
  180. if (IsKeyPressed(KEY_THREE)) { lights[3].enabled = !lights[3].enabled; }
  181. if (IsKeyPressed(KEY_FOUR)) { lights[0].enabled = !lights[0].enabled; }
  182. // Update light values on shader (actually, only enable/disable them)
  183. for (int i = 0; i < MAX_LIGHTS; i++) UpdateLight(shader, lights[i]);
  184. //----------------------------------------------------------------------------------
  185. // Draw
  186. //----------------------------------------------------------------------------------
  187. BeginDrawing();
  188. ClearBackground(BLACK);
  189. BeginMode3D(camera);
  190. // Set floor model texture tiling and emissive color parameters on shader
  191. SetShaderValue(shader, textureTilingLoc, &floorTextureTiling, SHADER_UNIFORM_VEC2);
  192. Vector4 floorEmissiveColor = ColorNormalize(floor.materials[0].maps[MATERIAL_MAP_EMISSION].color);
  193. SetShaderValue(shader, emissiveColorLoc, &floorEmissiveColor, SHADER_UNIFORM_VEC4);
  194. DrawModel(floor, (Vector3){ 0.0f, 0.0f, 0.0f }, 5.0f, WHITE); // Draw floor model
  195. // Set old car model texture tiling, emissive color and emissive intensity parameters on shader
  196. SetShaderValue(shader, textureTilingLoc, &carTextureTiling, SHADER_UNIFORM_VEC2);
  197. Vector4 carEmissiveColor = ColorNormalize(car.materials[0].maps[MATERIAL_MAP_EMISSION].color);
  198. SetShaderValue(shader, emissiveColorLoc, &carEmissiveColor, SHADER_UNIFORM_VEC4);
  199. float emissiveIntensity = 0.01f;
  200. SetShaderValue(shader, emissiveIntensityLoc, &emissiveIntensity, SHADER_UNIFORM_FLOAT);
  201. DrawModel(car, (Vector3){ 0.0f, 0.0f, 0.0f }, 0.005f, WHITE); // Draw car model
  202. // Draw spheres to show the lights positions
  203. for (int i = 0; i < MAX_LIGHTS; i++)
  204. {
  205. Color lightColor = (Color){ lights[i].color[0]*255, lights[i].color[1]*255, lights[i].color[2]*255, lights[i].color[3]*255 };
  206. if (lights[i].enabled) DrawSphereEx(lights[i].position, 0.2f, 8, 8, lightColor);
  207. else DrawSphereWires(lights[i].position, 0.2f, 8, 8, ColorAlpha(lightColor, 0.3f));
  208. }
  209. EndMode3D();
  210. DrawText("Toggle lights: [1][2][3][4]", 10, 40, 20, LIGHTGRAY);
  211. DrawText("(c) Old Rusty Car model by Renafox (https://skfb.ly/LxRy)", screenWidth - 320, screenHeight - 20, 10, LIGHTGRAY);
  212. DrawFPS(10, 10);
  213. EndDrawing();
  214. //----------------------------------------------------------------------------------
  215. }
  216. // De-Initialization
  217. //--------------------------------------------------------------------------------------
  218. // Unbind (disconnect) shader from car.material[0]
  219. // to avoid UnloadMaterial() trying to unload it automatically
  220. car.materials[0].shader = (Shader){ 0 };
  221. UnloadMaterial(car.materials[0]);
  222. car.materials[0].maps = NULL;
  223. UnloadModel(car);
  224. floor.materials[0].shader = (Shader){ 0 };
  225. UnloadMaterial(floor.materials[0]);
  226. floor.materials[0].maps = NULL;
  227. UnloadModel(floor);
  228. UnloadShader(shader); // Unload Shader
  229. CloseWindow(); // Close window and OpenGL context
  230. //--------------------------------------------------------------------------------------
  231. return 0;
  232. }
  233. // Create light with provided data
  234. // NOTE: It updated the global lightCount and it's limited to MAX_LIGHTS
  235. static Light CreateLight(int type, Vector3 position, Vector3 target, Color color, float intensity, Shader shader)
  236. {
  237. Light light = { 0 };
  238. if (lightCount < MAX_LIGHTS)
  239. {
  240. light.enabled = 1;
  241. light.type = type;
  242. light.position = position;
  243. light.target = target;
  244. light.color[0] = (float)color.r / (float)255;
  245. light.color[1] = (float)color.g / (float)255;
  246. light.color[2] = (float)color.b / (float)255;
  247. light.color[3] = (float)color.a / (float)255;
  248. light.intensity = intensity;
  249. // NOTE: Lighting shader naming must be the provided ones
  250. light.enabledLoc = GetShaderLocation(shader, TextFormat("lights[%i].enabled", lightCount));
  251. light.typeLoc = GetShaderLocation(shader, TextFormat("lights[%i].type", lightCount));
  252. light.positionLoc = GetShaderLocation(shader, TextFormat("lights[%i].position", lightCount));
  253. light.targetLoc = GetShaderLocation(shader, TextFormat("lights[%i].target", lightCount));
  254. light.colorLoc = GetShaderLocation(shader, TextFormat("lights[%i].color", lightCount));
  255. light.intensityLoc = GetShaderLocation(shader, TextFormat("lights[%i].intensity", lightCount));
  256. UpdateLight(shader, light);
  257. lightCount++;
  258. }
  259. return light;
  260. }
  261. // Send light properties to shader
  262. // NOTE: Light shader locations should be available
  263. static void UpdateLight(Shader shader, Light light)
  264. {
  265. SetShaderValue(shader, light.enabledLoc, &light.enabled, SHADER_UNIFORM_INT);
  266. SetShaderValue(shader, light.typeLoc, &light.type, SHADER_UNIFORM_INT);
  267. // Send to shader light position values
  268. float position[3] = { light.position.x, light.position.y, light.position.z };
  269. SetShaderValue(shader, light.positionLoc, position, SHADER_UNIFORM_VEC3);
  270. // Send to shader light target position values
  271. float target[3] = { light.target.x, light.target.y, light.target.z };
  272. SetShaderValue(shader, light.targetLoc, target, SHADER_UNIFORM_VEC3);
  273. SetShaderValue(shader, light.colorLoc, light.color, SHADER_UNIFORM_VEC4);
  274. SetShaderValue(shader, light.intensityLoc, &light.intensity, SHADER_UNIFORM_FLOAT);
  275. }