12_PhysicsStressTest.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. // Copyright (c) 2015 Xamarin Inc
  4. // Copyright (c) 2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. using AtomicEngine;
  25. namespace FeatureExamples
  26. {
  27. public class PhysicsStressTestSample : Sample
  28. {
  29. Scene scene;
  30. bool drawDebug;
  31. public PhysicsStressTestSample() : base() { }
  32. public override void Start()
  33. {
  34. base.Start();
  35. CreateScene();
  36. SimpleCreateInstructionsWithWasd(
  37. "\nLMB to spawn physics objects\n" +
  38. "F5 to save scene, F7 to load\n" +
  39. "Space to toggle physics debug geometry");
  40. SetupViewport();
  41. SubscribeToEvents();
  42. }
  43. void SubscribeToEvents()
  44. {
  45. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  46. {
  47. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  48. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  49. // bones properly
  50. if (drawDebug)
  51. {
  52. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  53. }
  54. });
  55. }
  56. protected override void Update(float timeStep)
  57. {
  58. base.Update(timeStep);
  59. SimpleMoveCamera3D(timeStep);
  60. var input = GetSubsystem<Input>();
  61. // "Shoot" a physics object with left mousebutton
  62. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  63. SpawnObject();
  64. /* TODO: Scene.SaveXML/Scene.LoadXML
  65. if (input.GetKeyPress(Constants.KEY_F5))
  66. scene.SaveXml(fileSystem.UserDocumentsDir + "/Scenes/PhysicsStressTest.xml");
  67. if (input.GetKeyPress(Constants.KEY_F7))
  68. scene.LoadXml(fileSystem.UserDocumentsDir + "/Scenes/PhysicsStressTest.xml");
  69. */
  70. if (input.GetKeyPress(Constants.KEY_SPACE))
  71. drawDebug = !drawDebug;
  72. }
  73. void SetupViewport()
  74. {
  75. var renderer = GetSubsystem<Renderer>();
  76. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  77. }
  78. void SpawnObject()
  79. {
  80. var cache = GetSubsystem<ResourceCache>();
  81. // Create a smaller box at camera position
  82. Node boxNode = scene.CreateChild("SmallBox");
  83. boxNode.Position = CameraNode.Position;
  84. boxNode.Rotation = CameraNode.Rotation;
  85. boxNode.SetScale(0.25f);
  86. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  87. boxObject.Model = (cache.Get<Model>("Models/Box.mdl"));
  88. boxObject.SetMaterial(cache.Get<Material>("Materials/StoneSmall.xml"));
  89. boxObject.CastShadows = true;
  90. // Create physics components, use a smaller mass also
  91. RigidBody body = boxNode.CreateComponent<RigidBody>();
  92. body.Mass = 0.25f;
  93. body.Friction = 0.75f;
  94. CollisionShape shape = boxNode.CreateComponent<CollisionShape>();
  95. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  96. const float objectVelocity = 10.0f;
  97. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  98. // to overcome gravity better
  99. body.SetLinearVelocity(CameraNode.Rotation * new Vector3(0.0f, 0.25f, 1.0f) * objectVelocity);
  100. }
  101. void CreateScene()
  102. {
  103. var cache = GetSubsystem<ResourceCache>();
  104. scene = new Scene();
  105. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  106. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  107. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  108. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  109. scene.CreateComponent<Octree>();
  110. scene.CreateComponent<PhysicsWorld>();
  111. scene.CreateComponent<DebugRenderer>();
  112. // Create a Zone component for ambient lighting & fog control
  113. Node zoneNode = scene.CreateChild("Zone");
  114. Zone zone = zoneNode.CreateComponent<Zone>();
  115. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  116. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  117. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  118. zone.FogStart = 100.0f;
  119. zone.FogEnd = 300.0f;
  120. // Create a directional light to the world. Enable cascaded shadows on it
  121. Node lightNode = scene.CreateChild("DirectionalLight");
  122. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  123. Light light = lightNode.CreateComponent<Light>();
  124. light.LightType = LightType.LIGHT_DIRECTIONAL;
  125. light.CastShadows = true;
  126. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  127. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  128. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  129. {
  130. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  131. Node floorNode = scene.CreateChild("Floor");
  132. floorNode.Position = new Vector3(0.0f, -0.5f, 0.0f);
  133. floorNode.Scale = new Vector3(500.0f, 1.0f, 500.0f);
  134. StaticModel floorObject = floorNode.CreateComponent<StaticModel>();
  135. floorObject.Model = cache.Get<Model>("Models/Box.mdl");
  136. floorObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  137. // Make the floor physical by adding RigidBody and CollisionShape components
  138. /*RigidBody* body = */
  139. floorNode.CreateComponent<RigidBody>();
  140. CollisionShape shape = floorNode.CreateComponent<CollisionShape>();
  141. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  142. }
  143. {
  144. // Create static mushrooms with triangle mesh collision
  145. const uint numMushrooms = 50;
  146. for (uint i = 0; i < numMushrooms; ++i)
  147. {
  148. Node mushroomNode = scene.CreateChild("Mushroom");
  149. mushroomNode.Position = new Vector3(NextRandom(400.0f) - 200.0f, 0.0f, NextRandom(400.0f) - 200.0f);
  150. mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
  151. mushroomNode.SetScale(5.0f + NextRandom(5.0f));
  152. StaticModel mushroomObject = mushroomNode.CreateComponent<StaticModel>();
  153. mushroomObject.Model = (cache.Get<Model>("Models/Mushroom.mdl"));
  154. mushroomObject.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  155. mushroomObject.CastShadows = true;
  156. mushroomNode.CreateComponent<RigidBody>();
  157. CollisionShape shape = mushroomNode.CreateComponent<CollisionShape>();
  158. // By default the highest LOD level will be used, the LOD level can be passed as an optional parameter
  159. shape.SetTriangleMesh(mushroomObject.Model, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
  160. }
  161. }
  162. {
  163. // Create a large amount of falling physics objects
  164. const uint numObjects = 1000;
  165. for (uint i = 0; i < numObjects; ++i)
  166. {
  167. Node boxNode = scene.CreateChild("Box");
  168. boxNode.Position = new Vector3(0.0f, i * 2.0f + 100.0f, 0.0f);
  169. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  170. boxObject.Model = cache.Get<Model>("Models/Box.mdl");
  171. boxObject.SetMaterial(cache.Get<Material>("Materials/StoneSmall.xml"));
  172. boxObject.CastShadows = true;
  173. // Give the RigidBody mass to make it movable and also adjust friction
  174. RigidBody body = boxNode.CreateComponent<RigidBody>();
  175. body.Mass = 1.0f;
  176. body.Friction = 1.0f;
  177. // Disable collision event signaling to reduce CPU load of the physics simulation
  178. body.CollisionEventMode = CollisionEventMode.COLLISION_NEVER;
  179. CollisionShape shape = boxNode.CreateComponent<CollisionShape>();
  180. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  181. }
  182. }
  183. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  184. // the scene, because we want it to be unaffected by scene load / save
  185. CameraNode = new Node();
  186. Camera camera = CameraNode.CreateComponent<Camera>();
  187. camera.FarClip = 300.0f;
  188. // Set an initial position for the camera scene node above the floor
  189. CameraNode.Position = new Vector3(0.0f, 3.0f, -20.0f);
  190. }
  191. }
  192. }