13_Ragdolls.cs 9.8 KB

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