instanced.c 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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());
  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. R3D_InstanceBuffer instances = R3D_LoadInstanceBuffer(INSTANCE_COUNT, R3D_INSTANCE_POSITION | R3D_INSTANCE_ROTATION | R3D_INSTANCE_SCALE | R3D_INSTANCE_COLOR);
  18. Vector3* positions = R3D_MapInstances(instances, R3D_INSTANCE_POSITION);
  19. Quaternion* rotations = R3D_MapInstances(instances, R3D_INSTANCE_ROTATION);
  20. Vector3* scales = R3D_MapInstances(instances, R3D_INSTANCE_SCALE);
  21. Color* colors = R3D_MapInstances(instances, R3D_INSTANCE_COLOR);
  22. for (int i = 0; i < INSTANCE_COUNT; i++)
  23. {
  24. positions[i] = (Vector3) {
  25. (float)GetRandomValue(-50000, 50000) / 1000,
  26. (float)GetRandomValue(-50000, 50000) / 1000,
  27. (float)GetRandomValue(-50000, 50000) / 1000
  28. };
  29. rotations[i] = QuaternionFromEuler(
  30. (float)GetRandomValue(-314000, 314000) / 100000,
  31. (float)GetRandomValue(-314000, 314000) / 100000,
  32. (float)GetRandomValue(-314000, 314000) / 100000
  33. );
  34. scales[i] = (Vector3) {
  35. (float)GetRandomValue(100, 2000) / 1000,
  36. (float)GetRandomValue(100, 2000) / 1000,
  37. (float)GetRandomValue(100, 2000) / 1000
  38. };
  39. colors[i] = ColorFromHSV(
  40. (float)GetRandomValue(0, 360000) / 1000, 1.0f, 1.0f
  41. );
  42. }
  43. R3D_UnmapInstances(instances, R3D_INSTANCE_POSITION | R3D_INSTANCE_ROTATION | R3D_INSTANCE_SCALE | R3D_INSTANCE_COLOR);
  44. // Setup directional light
  45. R3D_Light light = R3D_CreateLight(R3D_LIGHT_DIR);
  46. R3D_SetLightDirection(light, (Vector3){0, -1, 0});
  47. R3D_SetLightActive(light, true);
  48. // Setup camera
  49. Camera3D camera = {
  50. .position = {0, 2, 2},
  51. .target = {0, 0, 0},
  52. .up = {0, 1, 0},
  53. .fovy = 60
  54. };
  55. // Capture mouse
  56. DisableCursor();
  57. // Main loop
  58. while (!WindowShouldClose())
  59. {
  60. UpdateCamera(&camera, CAMERA_FREE);
  61. BeginDrawing();
  62. ClearBackground(RAYWHITE);
  63. R3D_Begin(camera);
  64. R3D_DrawMeshInstanced(mesh, material, instances, INSTANCE_COUNT);
  65. R3D_End();
  66. DrawFPS(10, 10);
  67. EndDrawing();
  68. }
  69. // Cleanup
  70. R3D_UnloadMaterial(material);
  71. R3D_UnloadMesh(mesh);
  72. R3D_Close();
  73. CloseWindow();
  74. return 0;
  75. }