shaders_basic_pbr.c 16 KB

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