13_Ragdolls.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 RagdollSample : Sample
  28. {
  29. bool drawDebug;
  30. Camera camera;
  31. public RagdollSample() : 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. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  52. });
  53. }
  54. protected override void Update(float timeStep)
  55. {
  56. base.Update(timeStep);
  57. SimpleMoveCamera3D(timeStep);
  58. var input = GetSubsystem<Input>();
  59. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  60. SpawnObject();
  61. /* TODO: Scene.SaveXML/Scene.LoadXML
  62. if (input.GetKeyPress(Constants.KEY_F5))
  63. scene.SaveXml(fileSystem.UserDocumentsDir + "/Scenes/Physics.xml");
  64. if (input.GetKeyPress(Constants.KEY_F7))
  65. scene.LoadXml(fileSystem.UserDocumentsDir + "/Scenes/Physics.xml");
  66. */
  67. if (input.GetKeyPress(Constants.KEY_SPACE))
  68. drawDebug = !drawDebug;
  69. }
  70. void SetupViewport()
  71. {
  72. var renderer = GetSubsystem<Renderer>();
  73. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  74. }
  75. void CreateScene()
  76. {
  77. var cache = GetSubsystem<ResourceCache>();
  78. scene = new Scene();
  79. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  80. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  81. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  82. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  83. scene.CreateComponent<Octree>();
  84. scene.CreateComponent<PhysicsWorld>();
  85. scene.CreateComponent<DebugRenderer>();
  86. // Create a Zone component for ambient lighting & fog control
  87. Node zoneNode = scene.CreateChild("Zone");
  88. Zone zone = zoneNode.CreateComponent<Zone>();
  89. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  90. zone.AmbientColor = (new Color(0.15f, 0.15f, 0.15f));
  91. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  92. zone.FogStart = 100.0f;
  93. zone.FogEnd = 300.0f;
  94. // Create a directional light to the world. Enable cascaded shadows on it
  95. Node lightNode = scene.CreateChild("DirectionalLight");
  96. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  97. Light light = lightNode.CreateComponent<Light>();
  98. light.LightType = LightType.LIGHT_DIRECTIONAL;
  99. light.CastShadows = true;
  100. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  101. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  102. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  103. {
  104. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  105. Node floorNode = scene.CreateChild("Floor");
  106. floorNode.Position = new Vector3(0.0f, -0.5f, 0.0f);
  107. floorNode.Scale = new Vector3(500.0f, 1.0f, 500.0f);
  108. StaticModel floorObject = floorNode.CreateComponent<StaticModel>();
  109. floorObject.Model = cache.Get<Model>("Models/Box.mdl");
  110. floorObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  111. // Make the floor physical by adding RigidBody and CollisionShape components
  112. RigidBody body = floorNode.CreateComponent<RigidBody>();
  113. // We will be spawning spherical objects in this sample. The ground also needs non-zero rolling friction so that
  114. // the spheres will eventually come to rest
  115. body.RollingFriction = 0.15f;
  116. CollisionShape shape = floorNode.CreateComponent<CollisionShape>();
  117. // 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
  118. // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  119. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  120. }
  121. // Create animated models
  122. for (int z = -1; z <= 1; ++z)
  123. {
  124. for (int x = -4; x <= 4; ++x)
  125. {
  126. Node modelNode = scene.CreateChild("Jack");
  127. modelNode.Position = new Vector3(x * 5.0f, 0.0f, z * 5.0f);
  128. modelNode.Rotation = new Quaternion(0.0f, 180.0f, 0.0f);
  129. AnimatedModel modelObject = modelNode.CreateComponent<AnimatedModel>();
  130. modelObject.Model = cache.Get<Model>("Models/Jack.mdl");
  131. modelObject.SetMaterial(cache.Get<Material>("Materials/Jack.xml"));
  132. modelObject.CastShadows = true;
  133. // Set the model to also update when invisible to avoid staying invisible when the model should come into
  134. // view, but does not as the bounding box is not updated
  135. modelObject.UpdateInvisible = true;
  136. // Create a rigid body and a collision shape. These will act as a trigger for transforming the
  137. // model into a ragdoll when hit by a moving object
  138. RigidBody body = modelNode.CreateComponent<RigidBody>();
  139. // The Trigger mode makes the rigid body only detect collisions, but impart no forces on the
  140. // colliding objects
  141. body.Trigger = true;
  142. CollisionShape shape = modelNode.CreateComponent<CollisionShape>();
  143. // Create the capsule shape with an offset so that it is correctly aligned with the model, which
  144. // has its origin at the feet
  145. shape.SetCapsule(0.7f, 2.0f, new Vector3(0.0f, 1.0f, 0.0f), Quaternion.Identity);
  146. // Create a custom component that reacts to collisions and creates the ragdoll
  147. modelNode.AddComponent(new Ragdoll());
  148. }
  149. }
  150. // Create the camera. Limit far clip distance to match the fog
  151. CameraNode = new Node();
  152. camera = CameraNode.CreateComponent<Camera>();
  153. camera.FarClip = 300.0f;
  154. // Set an initial position for the camera scene node above the plane
  155. CameraNode.Position = new Vector3(0.0f, 3.0f, -20.0f);
  156. }
  157. void SpawnObject()
  158. {
  159. var cache = GetSubsystem<ResourceCache>();
  160. Node boxNode = scene.CreateChild("Sphere");
  161. boxNode.Position = CameraNode.Position;
  162. boxNode.Rotation = CameraNode.Rotation;
  163. boxNode.SetScale(0.25f);
  164. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  165. boxObject.Model = cache.Get<Model>("Models/Sphere.mdl");
  166. boxObject.SetMaterial(cache.Get<Material>("Materials/StoneSmall.xml"));
  167. boxObject.CastShadows = true;
  168. RigidBody body = boxNode.CreateComponent<RigidBody>();
  169. body.Mass = 1.0f;
  170. body.RollingFriction = 0.15f;
  171. CollisionShape shape = boxNode.CreateComponent<CollisionShape>();
  172. shape.SetSphere(1.0f, Vector3.Zero, Quaternion.Identity);
  173. const float objectVelocity = 10.0f;
  174. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  175. // to overcome gravity better
  176. body.SetLinearVelocity(CameraNode.Rotation * new Vector3(0.0f, 0.25f, 1.0f) * objectVelocity);
  177. }
  178. }
  179. }