instanced.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <r3d/r3d.h>
  2. #include <raymath.h>
  3. #define INSTANCE_COUNT 1000
  4. int main(void)
  5. {
  6. // Initialize window
  7. InitWindow(800, 450, "[r3d] - Instanced rendering example");
  8. SetTargetFPS(60);
  9. // Initialize R3D
  10. R3D_Init(GetScreenWidth(), GetScreenHeight(), 0);
  11. // Set ambient light
  12. R3D_ENVIRONMENT_SET(ambient.color, DARKGRAY);
  13. // Create cube mesh and default material
  14. R3D_Mesh mesh = R3D_GenMeshCube(1, 1, 1);
  15. R3D_Material material = R3D_GetDefaultMaterial();
  16. // Generate random transforms and colors for instances
  17. Matrix transforms[INSTANCE_COUNT];
  18. Color colors[INSTANCE_COUNT];
  19. for (int i = 0; i < INSTANCE_COUNT; i++)
  20. {
  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 directional light
  40. R3D_Light light = R3D_CreateLight(R3D_LIGHT_DIR);
  41. R3D_SetLightDirection(light, (Vector3){0, -1, 0});
  42. R3D_SetLightActive(light, true);
  43. // Setup camera
  44. Camera3D camera = {
  45. .position = {0, 2, 2},
  46. .target = {0, 0, 0},
  47. .up = {0, 1, 0},
  48. .fovy = 60
  49. };
  50. // Capture mouse
  51. DisableCursor();
  52. // Main loop
  53. while (!WindowShouldClose())
  54. {
  55. UpdateCamera(&camera, CAMERA_FREE);
  56. BeginDrawing();
  57. ClearBackground(RAYWHITE);
  58. R3D_Begin(camera);
  59. R3D_DrawMeshInstancedEx(&mesh, &material, transforms, colors, INSTANCE_COUNT);
  60. R3D_End();
  61. DrawFPS(10, 10);
  62. EndDrawing();
  63. }
  64. // Cleanup
  65. R3D_UnloadMesh(&mesh);
  66. R3D_UnloadMaterial(&material);
  67. R3D_Close();
  68. CloseWindow();
  69. return 0;
  70. }