instanced.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include "./common.h"
  2. /* === Constants === */
  3. #define INSTANCE_COUNT 1000
  4. /* === Resources === */
  5. static Camera3D camera = { 0 };
  6. static R3D_Mesh mesh = { 0 };
  7. static R3D_Material material = { 0 };
  8. static Matrix transforms[INSTANCE_COUNT] = { 0 };
  9. static Color colors[INSTANCE_COUNT] = { 0 };
  10. /* === Example === */
  11. const char* Init(void)
  12. {
  13. /* --- Initialize R3D with its internal resolution --- */
  14. R3D_Init(GetScreenWidth(), GetScreenHeight(), 0);
  15. SetTargetFPS(60);
  16. /* --- Generates a cube mesh and a default material to render it --- */
  17. mesh = R3D_GenMeshCube(1, 1, 1);
  18. material = R3D_GetDefaultMaterial();
  19. /* --- Randomly generate the transformation and color of each cube instance --- */
  20. for (int i = 0; i < INSTANCE_COUNT; i++) {
  21. Matrix translate = MatrixTranslate(
  22. (float)GetRandomValue(-50000, 50000) / 1000,
  23. (float)GetRandomValue(-50000, 50000) / 1000,
  24. (float)GetRandomValue(-50000, 50000) / 1000
  25. );
  26. Matrix rotate = MatrixRotateXYZ((Vector3) {
  27. (float)GetRandomValue(-314000, 314000) / 100000,
  28. (float)GetRandomValue(-314000, 314000) / 100000,
  29. (float)GetRandomValue(-314000, 314000) / 100000
  30. });
  31. Matrix scale = MatrixScale(
  32. (float)GetRandomValue(100, 2000) / 1000,
  33. (float)GetRandomValue(100, 2000) / 1000,
  34. (float)GetRandomValue(100, 2000) / 1000
  35. );
  36. transforms[i] = MatrixMultiply(MatrixMultiply(scale, rotate), translate);
  37. colors[i] = ColorFromHSV((float)GetRandomValue(0, 360000) / 1000, 1.0f, 1.0f);
  38. }
  39. /* --- Setup the scene lighting --- */
  40. R3D_Light light = R3D_CreateLight(R3D_LIGHT_DIR);
  41. {
  42. R3D_SetLightDirection(light, (Vector3) { 0, -1, 0 });
  43. R3D_SetLightActive(light, true);
  44. }
  45. /* --- Setup the camera --- */
  46. camera = (Camera3D){
  47. .position = (Vector3) { 0, 2, 2 },
  48. .target = (Vector3) { 0, 0, 0 },
  49. .up = (Vector3) { 0, 1, 0 },
  50. .fovy = 60,
  51. };
  52. /* --- Capture the mouse and ready to go! --- */
  53. DisableCursor();
  54. return "[r3d] - Instanced rendering example";
  55. }
  56. void Update(float delta)
  57. {
  58. UpdateCamera(&camera, CAMERA_FREE);
  59. }
  60. void Draw(void)
  61. {
  62. R3D_Begin(camera);
  63. R3D_DrawMeshInstancedEx(&mesh, &material, transforms, colors, INSTANCE_COUNT);
  64. R3D_End();
  65. DrawFPS(10, 10);
  66. }
  67. void Close(void)
  68. {
  69. R3D_UnloadMaterial(&material);
  70. R3D_UnloadMesh(&mesh);
  71. R3D_Close();
  72. }