12_PhysicsStressTest.as 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Physics stress test example.
  2. // This sample demonstrates:
  3. // - Physics and rendering performance with a high (1000) moving object count
  4. // - Using triangle meshes for collision
  5. // - Optimizing physics simulation by leaving out collision event signaling
  6. #include "Scripts/Utilities/Sample.as"
  7. Scene@ scene_;
  8. Node@ cameraNode;
  9. float yaw = 0.0f;
  10. float pitch = 0.0f;
  11. bool drawDebug = false;
  12. void Start()
  13. {
  14. // Execute the common startup for samples
  15. SampleStart();
  16. // Create the scene content
  17. CreateScene();
  18. // Create the UI content
  19. CreateInstructions();
  20. // Setup the viewport for displaying the scene
  21. SetupViewport();
  22. // Hook up to the frame update and render post-update events
  23. SubscribeToEvents();
  24. }
  25. void CreateScene()
  26. {
  27. scene_ = Scene();
  28. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  29. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  30. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  31. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  32. scene_.CreateComponent("Octree");
  33. scene_.CreateComponent("PhysicsWorld");
  34. scene_.CreateComponent("DebugRenderer");
  35. // Create a Zone component for ambient lighting & fog control
  36. Node@ zoneNode = scene_.CreateChild("Zone");
  37. Zone@ zone = zoneNode.CreateComponent("Zone");
  38. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  39. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  40. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  41. zone.fogStart = 100.0f;
  42. zone.fogEnd = 300.0f;
  43. // Create a directional light to the world. Enable cascaded shadows on it
  44. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  45. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  46. Light@ light = lightNode.CreateComponent("Light");
  47. light.lightType = LIGHT_DIRECTIONAL;
  48. light.castShadows = true;
  49. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  50. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  51. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  52. {
  53. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  54. Node@ floorNode = scene_.CreateChild("Floor");
  55. floorNode.position = Vector3(0.0f, -0.5f, 0.0f);
  56. floorNode.scale = Vector3(500.0f, 1.0f, 500.0f);
  57. StaticModel@ floorObject = floorNode.CreateComponent("StaticModel");
  58. floorObject.model = cache.GetResource("Model", "Models/Box.mdl");
  59. floorObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  60. // Make the floor physical by adding RigidBody and CollisionShape components
  61. RigidBody@ body = floorNode.CreateComponent("RigidBody");
  62. CollisionShape@ shape = floorNode.CreateComponent("CollisionShape");
  63. // Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
  64. // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  65. shape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  66. }
  67. {
  68. // Create static mushrooms with triangle mesh collision
  69. const uint NUM_MUSHROOMS = 50;
  70. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  71. {
  72. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  73. mushroomNode.position = Vector3(Random(400.0f) - 200.0f, 0.0f, Random(400.0f) - 200.0f);
  74. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  75. mushroomNode.SetScale(5.0f + Random(5.0f));
  76. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  77. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  78. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  79. mushroomObject.castShadows = true;
  80. RigidBody@ body = mushroomNode.CreateComponent("RigidBody");
  81. CollisionShape@ shape = mushroomNode.CreateComponent("CollisionShape");
  82. // By default the highest LOD level will be used, the LOD level can be passed as an optional parameter
  83. shape.SetTriangleMesh(mushroomObject.model);
  84. }
  85. }
  86. {
  87. // Create a large amount of falling physics objects
  88. const uint NUM_OBJECTS = 1000;
  89. for (uint i = 0; i < NUM_OBJECTS; ++i)
  90. {
  91. Node@ boxNode = scene_.CreateChild("Box");
  92. boxNode.position = Vector3(0.0f, i * 2.0f + 100.0f, 0.0f);
  93. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  94. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  95. boxObject.material = cache.GetResource("Material", "Materials/StoneSmall.xml");
  96. boxObject.castShadows = true;
  97. // Give the RigidBody mass to make it movable and also adjust friction
  98. RigidBody@ body = boxNode.CreateComponent("RigidBody");
  99. body.mass = 1.0f;
  100. body.friction = 1.0f;
  101. // Disable collision event signaling to reduce CPU load of the physics simulation
  102. body.collisionEventMode = COLLISION_NEVER;
  103. CollisionShape@ shape = boxNode.CreateComponent("CollisionShape");
  104. shape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  105. }
  106. }
  107. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  108. // the scene, because we want it to be unaffected by scene load / save
  109. cameraNode = Node();
  110. Camera@ camera = cameraNode.CreateComponent("Camera");
  111. camera.farClip = 300.0f;
  112. // Set an initial position for the camera scene node above the floor
  113. cameraNode.position = Vector3(0.0f, 3.0f, -20.0f);
  114. }
  115. void CreateInstructions()
  116. {
  117. // Construct new Text object, set string to display and font to use
  118. Text@ instructionText = ui.root.CreateChild("Text");
  119. instructionText.text =
  120. "Use WASD keys and mouse to move\n"
  121. "LMB to spawn physics objects\n"
  122. "F5 to save scene, F7 to load\n"
  123. "Space to toggle physics debug geometry";
  124. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  125. // The text has multiple rows. Center them in relation to each other
  126. instructionText.textAlignment = HA_CENTER;
  127. // Position the text relative to the screen center
  128. instructionText.horizontalAlignment = HA_CENTER;
  129. instructionText.verticalAlignment = VA_CENTER;
  130. instructionText.SetPosition(0, ui.root.height / 4);
  131. }
  132. void SetupViewport()
  133. {
  134. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  135. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  136. renderer.viewports[0] = viewport;
  137. }
  138. void SubscribeToEvents()
  139. {
  140. // Subscribe HandleUpdate() function for processing update events
  141. SubscribeToEvent("Update", "HandleUpdate");
  142. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  143. // debug geometry
  144. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  145. }
  146. void MoveCamera(float timeStep)
  147. {
  148. // Do not move if the UI has a focused element (the console)
  149. if (ui.focusElement !is null)
  150. return;
  151. // Movement speed as world units per second
  152. const float MOVE_SPEED = 20.0f;
  153. // Mouse sensitivity as degrees per pixel
  154. const float MOUSE_SENSITIVITY = 0.1f;
  155. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  156. IntVector2 mouseMove = input.mouseMove;
  157. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  158. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  159. pitch = Clamp(pitch, -90.0f, 90.0f);
  160. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  161. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  162. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  163. if (input.keyDown['W'])
  164. cameraNode.TranslateRelative(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep);
  165. if (input.keyDown['S'])
  166. cameraNode.TranslateRelative(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep);
  167. if (input.keyDown['A'])
  168. cameraNode.TranslateRelative(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  169. if (input.keyDown['D'])
  170. cameraNode.TranslateRelative(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  171. // "Shoot" a physics object with left mousebutton
  172. if (input.mouseButtonPress[MOUSEB_LEFT])
  173. SpawnObject();
  174. // Check for loading / saving the scene
  175. if (input.keyPress[KEY_F5])
  176. {
  177. File saveFile(fileSystem.programDir + "Data/Scenes/PhysicsStressTest.xml", FILE_WRITE);
  178. scene_.SaveXML(saveFile);
  179. }
  180. if (input.keyPress[KEY_F7])
  181. {
  182. File loadFile(fileSystem.programDir + "Data/Scenes/PhysicsStressTest.xml", FILE_READ);
  183. scene_.LoadXML(loadFile);
  184. }
  185. // Toggle debug geometry with space
  186. if (input.keyPress[KEY_SPACE])
  187. drawDebug = !drawDebug;
  188. }
  189. void SpawnObject()
  190. {
  191. // Create a smaller box at camera position
  192. Node@ boxNode = scene_.CreateChild("SmallBox");
  193. boxNode.position = cameraNode.position;
  194. boxNode.rotation = cameraNode.rotation;
  195. boxNode.SetScale(0.25f);
  196. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  197. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  198. boxObject.material = cache.GetResource("Material", "Materials/StoneSmall.xml");
  199. boxObject.castShadows = true;
  200. // Create physics components, use a smaller mass also
  201. RigidBody@ body = boxNode.CreateComponent("RigidBody");
  202. body.mass = 0.25f;
  203. body.friction = 0.75f;
  204. CollisionShape@ shape = boxNode.CreateComponent("CollisionShape");
  205. shape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  206. const float OBJECT_VELOCITY = 10.0f;
  207. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  208. // to overcome gravity better
  209. body.linearVelocity = cameraNode.rotation * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY;
  210. }
  211. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  212. {
  213. // Take the frame time step, which is stored as a float
  214. float timeStep = eventData["TimeStep"].GetFloat();
  215. // Move the camera, scale movement with time step
  216. MoveCamera(timeStep);
  217. }
  218. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  219. {
  220. // If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  221. if (drawDebug)
  222. scene_.physicsWorld.DrawDebugGeometry(true);
  223. }