11_Physics.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 PhysicsSample : Sample
  28. {
  29. Scene scene;
  30. bool drawDebug;
  31. public PhysicsSample() : 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. // Subscribe HandlePostRenderUpdate() function for
  46. // processing the post-render update event, sent after
  47. // Renderer subsystem is done with defining the draw
  48. // calls for the viewports (but before actually
  49. // executing them.) We will request debug geometry
  50. // rendering during that event
  51. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  52. {
  53. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  54. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  55. // bones properly
  56. if (drawDebug)
  57. {
  58. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  59. }
  60. });
  61. }
  62. protected override void Update(float timeStep)
  63. {
  64. base.Update(timeStep);
  65. var input = GetSubsystem<Input>();
  66. var fileSystem = GetSubsystem<FileSystem>();
  67. SimpleMoveCamera3D(timeStep);
  68. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  69. SpawnObject();
  70. /* TODO: Scene.SaveXML/Scene.LoadXML
  71. if (input.GetKeyPress(Constants.KEY_F5))
  72. scene.SaveXml(fileSystem.UserDocumentsDir + "/Scenes/Physics.xml");
  73. if (input.GetKeyPress(Constants.KEY_F7))
  74. scene.LoadXml(fileSystem.UserDocumentsDir + "/Scenes/Physics.xml");
  75. */
  76. if (input.GetKeyPress(Constants.KEY_SPACE))
  77. drawDebug = !drawDebug;
  78. }
  79. void SetupViewport()
  80. {
  81. var renderer = GetSubsystem<Renderer>();
  82. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  83. }
  84. void CreateScene()
  85. {
  86. var cache = GetSubsystem<ResourceCache>();
  87. scene = new Scene();
  88. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  89. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  90. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  91. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  92. scene.CreateComponent<Octree>();
  93. scene.CreateComponent<PhysicsWorld>();
  94. scene.CreateComponent<DebugRenderer>();
  95. // Create a Zone component for ambient lighting & fog control
  96. Node zoneNode = scene.CreateChild("Zone");
  97. Zone zone = zoneNode.CreateComponent<Zone>();
  98. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  99. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  100. zone.FogColor = new Color(1.0f, 1.0f, 1.0f);
  101. zone.FogStart = 300.0f;
  102. zone.FogEnd = 500.0f;
  103. // Create a directional light to the world. Enable cascaded shadows on it
  104. Node lightNode = scene.CreateChild("DirectionalLight");
  105. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  106. Light light = lightNode.CreateComponent<Light>();
  107. light.LightType = LightType.LIGHT_DIRECTIONAL;
  108. light.CastShadows = true;
  109. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  110. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  111. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  112. // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  113. // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  114. // generate the necessary 3D texture coordinates for cube mapping
  115. Node skyNode = scene.CreateChild("Sky");
  116. skyNode.SetScale(500.0f); // The scale actually does not matter
  117. Skybox skybox = skyNode.CreateComponent<Skybox>();
  118. skybox.Model = cache.Get<Model>("Models/Box.mdl");
  119. skybox.SetMaterial(cache.Get<Material>("Materials/Skybox.xml"));
  120. {
  121. // Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
  122. Node floorNode = scene.CreateChild("Floor");
  123. floorNode.Position = new Vector3(0.0f, -0.5f, 0.0f);
  124. floorNode.Scale = new Vector3(1000.0f, 1.0f, 1000.0f);
  125. StaticModel floorObject = floorNode.CreateComponent<StaticModel>();
  126. floorObject.Model = cache.Get<Model>("Models/Box.mdl");
  127. floorObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  128. // Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
  129. // parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
  130. // in the physics simulation
  131. floorNode.CreateComponent<RigidBody>();
  132. CollisionShape shape = floorNode.CreateComponent<CollisionShape>();
  133. // 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
  134. // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  135. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  136. }
  137. {
  138. // Create a pyramid of movable physics objects
  139. for (int y = 0; y < 8; ++y)
  140. {
  141. for (int x = -y; x <= y; ++x)
  142. {
  143. Node boxNode = scene.CreateChild("Box");
  144. boxNode.Position = new Vector3((float)x, -(float)y + 8.0f, 0.0f);
  145. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  146. boxObject.Model = cache.Get<Model>("Models/Box.mdl");
  147. boxObject.SetMaterial(cache.Get<Material>("Materials/StoneEnvMapSmall.xml"));
  148. boxObject.CastShadows = true;
  149. // Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
  150. // and also adjust friction. The actual mass is not important; only the mass ratios between colliding
  151. // objects are significant
  152. RigidBody body = boxNode.CreateComponent<RigidBody>();
  153. body.Mass = 1.0f;
  154. body.Friction = 0.75f;
  155. CollisionShape shape = boxNode.CreateComponent<CollisionShape>();
  156. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  157. }
  158. }
  159. }
  160. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  161. // the scene, because we want it to be unaffected by scene load / save
  162. CameraNode = new Node();
  163. Camera camera = CameraNode.CreateComponent<Camera>();
  164. camera.FarClip = 500.0f;
  165. // Set an initial position for the camera scene node above the floor
  166. CameraNode.Position = (new Vector3(0.0f, 5.0f, -20.0f));
  167. }
  168. void SpawnObject()
  169. {
  170. var cache = GetSubsystem<ResourceCache>();
  171. var boxNode = scene.CreateChild("SmallBox");
  172. boxNode.Position = CameraNode.Position;
  173. boxNode.Rotation = CameraNode.Rotation;
  174. boxNode.SetScale(0.25f);
  175. StaticModel boxModel = boxNode.CreateComponent<StaticModel>();
  176. boxModel.Model = cache.Get<Model>("Models/Box.mdl");
  177. boxModel.SetMaterial(cache.Get<Material>("Materials/StoneEnvMapSmall.xml"));
  178. boxModel.CastShadows = true;
  179. var body = boxNode.CreateComponent<RigidBody>();
  180. body.Mass = 0.25f;
  181. body.Friction = 0.75f;
  182. var shape = boxNode.CreateComponent<CollisionShape>();
  183. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  184. const float objectVelocity = 10.0f;
  185. body.SetLinearVelocity(CameraNode.Rotation * new Vector3(0f, 0.25f, 1f) * objectVelocity);
  186. }
  187. }
  188. }