19_VehicleDemo.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 VehicleDemo : Sample
  28. {
  29. Vehicle vehicle;
  30. const float CameraDistance = 10.0f;
  31. public VehicleDemo() : base() { }
  32. public override void Start()
  33. {
  34. base.Start();
  35. // Create static scene content
  36. CreateScene();
  37. // Create the controllable vehicle
  38. CreateVehicle();
  39. // Create the UI content
  40. SimpleCreateInstructionsWithWasd("\nF5 to save scene, F7 to load");
  41. // Subscribe to necessary events
  42. SubscribeToEvents();
  43. }
  44. void SubscribeToEvents()
  45. {
  46. SubscribeToEvent<PostUpdateEvent>(e =>
  47. {
  48. if (vehicle == null)
  49. return;
  50. Node vehicleNode = vehicle.Node;
  51. // Physics update has completed. Position camera behind vehicle
  52. Quaternion dir = Quaternion.FromAxisAngle(Vector3.UnitY, vehicleNode.Rotation.YawAngle);
  53. dir = dir * Quaternion.FromAxisAngle(Vector3.UnitY, vehicle.Controls.Yaw);
  54. dir = dir * Quaternion.FromAxisAngle(Vector3.UnitX, vehicle.Controls.Pitch);
  55. Vector3 cameraTargetPos = vehicleNode.Position - (dir * new Vector3(0.0f, 0.0f, CameraDistance));
  56. Vector3 cameraStartPos = vehicleNode.Position;
  57. // and move it closer to the vehicle if something in between
  58. Ray cameraRay = new Ray(cameraStartPos, cameraTargetPos - cameraStartPos);
  59. float cameraRayLength = (cameraTargetPos - cameraStartPos).Length;
  60. // Raycast camera against static objects (physics collision mask 2)
  61. var query = new RayOctreeQuery(cameraRay, RayQueryLevel.RAY_TRIANGLE, cameraRayLength, Constants.DRAWABLE_ANY, 2);
  62. PhysicsRaycastResult result = new PhysicsRaycastResult();
  63. scene.GetComponent<PhysicsWorld>().RaycastSingle(ref result, cameraRay, cameraRayLength, 2);
  64. if (result.Body != null)
  65. {
  66. cameraTargetPos = cameraStartPos + cameraRay.Direction * (result.Distance - 0.5f);
  67. }
  68. CameraNode.Position = cameraTargetPos;
  69. CameraNode.Rotation = dir;
  70. });
  71. }
  72. protected override void Update(float timeStep)
  73. {
  74. Input input = GetSubsystem<Input>();
  75. if (vehicle != null)
  76. {
  77. // Get movement controls and assign them to the vehicle component. If UI has a focused element, clear controls
  78. vehicle.Controls.Set(Vehicle.CtrlForward, input.GetKeyDown(Constants.KEY_W));
  79. vehicle.Controls.Set(Vehicle.CtrlBack, input.GetKeyDown(Constants.KEY_S));
  80. vehicle.Controls.Set(Vehicle.CtrlLeft, input.GetKeyDown(Constants.KEY_A));
  81. vehicle.Controls.Set(Vehicle.CtrlRight, input.GetKeyDown(Constants.KEY_D));
  82. // Add yaw & pitch from the mouse motion or touch input. Used only for the camera, does not affect motion
  83. if (TouchEnabled)
  84. {
  85. for (uint i = 0; i < input.NumTouches; ++i)
  86. {
  87. /*
  88. TouchState state = input.GetTouch(i);
  89. Camera camera = CameraNode.GetComponent<Camera>();
  90. if (camera == null)
  91. return;
  92. var graphics = Graphics;
  93. vehicle.Controls.Yaw += TouchSensitivity * camera.Fov / graphics.Height * state.Delta.X;
  94. vehicle.Controls.Pitch += TouchSensitivity * camera.Fov / graphics.Height * state.Delta.Y;
  95. */
  96. }
  97. }
  98. else
  99. {
  100. vehicle.Controls.Yaw += (float)input.MouseMoveX * Vehicle.YawSensitivity;
  101. vehicle.Controls.Pitch += (float)input.MouseMoveY * Vehicle.YawSensitivity;
  102. }
  103. // Limit pitch
  104. vehicle.Controls.Pitch = MathHelper.Clamp(vehicle.Controls.Pitch, 0.0f, 80.0f);
  105. // Check for loading / saving the scene
  106. /*
  107. if (input.GetKeyPress(Key.F5))
  108. {
  109. scene.SaveXml(FileSystem.ProgramDir + "Data/Scenes/VehicleDemo.xml");
  110. }
  111. if (input.GetKeyPress(Key.F7))
  112. {
  113. scene.LoadXml(FileSystem.ProgramDir + "Data/Scenes/VehicleDemo.xml");
  114. // After loading we have to reacquire the weak pointer to the Vehicle component, as it has been recreated
  115. // Simply find the vehicle's scene node by name as there's only one of them
  116. Node vehicleNode = scene.GetChild("Vehicle", true);
  117. if (vehicleNode != null)
  118. vehicle = vehicleNode.GetComponent<Vehicle>();
  119. }
  120. */
  121. }
  122. else
  123. vehicle.Controls.Set(Vehicle.CtrlForward | Vehicle.CtrlBack | Vehicle.CtrlLeft | Vehicle.CtrlRight, false);
  124. }
  125. void CreateVehicle()
  126. {
  127. Node vehicleNode = scene.CreateChild("Vehicle");
  128. vehicleNode.Position = (new Vector3(0.0f, 5.0f, 0.0f));
  129. // Create the vehicle logic component
  130. vehicle = new Vehicle();
  131. vehicleNode.AddComponent(vehicle);
  132. // Create the rendering and physics components
  133. vehicle.Init();
  134. }
  135. void CreateScene()
  136. {
  137. var cache = GetSubsystem<ResourceCache>();
  138. scene = new Scene();
  139. // Create scene subsystem components
  140. scene.CreateComponent<Octree>();
  141. scene.CreateComponent<PhysicsWorld>();
  142. // Create camera and define viewport. We will be doing load / save, so it's convenient to create the camera outside the scene,
  143. // so that it won't be destroyed and recreated, and we don't have to redefine the viewport on load
  144. CameraNode = new Node();
  145. Camera camera = CameraNode.CreateComponent<Camera>();
  146. camera.FarClip = 500.0f;
  147. GetSubsystem<Renderer>().SetViewport(0, new Viewport(scene, camera));
  148. // Create static scene content. First create a zone for ambient lighting and fog control
  149. Node zoneNode = scene.CreateChild("Zone");
  150. Zone zone = zoneNode.CreateComponent<Zone>();
  151. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  152. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  153. zone.FogStart = 300.0f;
  154. zone.FogEnd = 500.0f;
  155. zone.SetBoundingBox(new BoundingBox(-2000.0f, 2000.0f));
  156. // Create a directional light with cascaded shadow mapping
  157. Node lightNode = scene.CreateChild("DirectionalLight");
  158. lightNode.SetDirection(new Vector3(0.3f, -0.5f, 0.425f));
  159. Light light = lightNode.CreateComponent<Light>();
  160. light.LightType = LightType.LIGHT_DIRECTIONAL;
  161. light.CastShadows = true;
  162. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  163. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  164. light.SpecularIntensity = 0.5f;
  165. // Create heightmap terrain with collision
  166. Node terrainNode = scene.CreateChild("Terrain");
  167. terrainNode.Position = (Vector3.Zero);
  168. Terrain terrain = terrainNode.CreateComponent<Terrain>();
  169. terrain.PatchSize = 64;
  170. terrain.Spacing = new Vector3(2.0f, 0.1f, 2.0f); // Spacing between vertices and vertical resolution of the height map
  171. terrain.Smoothing = true;
  172. terrain.SetHeightMap(cache.Get<Image>("Textures/HeightMap.png"));
  173. terrain.Material = cache.Get<Material>("Materials/Terrain.xml");
  174. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  175. // terrain patches and other objects behind it
  176. terrain.Occluder = true;
  177. RigidBody body = terrainNode.CreateComponent<RigidBody>();
  178. body.CollisionLayer = 2; // Use layer bitmask 2 for static geometry
  179. CollisionShape shape = terrainNode.CreateComponent<CollisionShape>();
  180. shape.SetTerrain(0);
  181. // Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
  182. const uint numMushrooms = 1000;
  183. for (uint i = 0; i < numMushrooms; ++i)
  184. {
  185. Node objectNode = scene.CreateChild("Mushroom");
  186. Vector3 position = new Vector3(NextRandom(2000.0f) - 1000.0f, 0.0f, NextRandom(2000.0f) - 1000.0f);
  187. position.Y = terrain.GetHeight(position) - 0.1f;
  188. objectNode.Position = (position);
  189. // Create a rotation quaternion from up vector to terrain normal
  190. objectNode.Rotation = Quaternion.FromRotationTo(Vector3.UnitY, terrain.GetNormal(position));
  191. objectNode.SetScale(3.0f);
  192. StaticModel sm = objectNode.CreateComponent<StaticModel>();
  193. sm.Model = (cache.Get<Model>("Models/Mushroom.mdl"));
  194. sm.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  195. sm.CastShadows = true;
  196. body = objectNode.CreateComponent<RigidBody>();
  197. body.CollisionLayer = 2;
  198. shape = objectNode.CreateComponent<CollisionShape>();
  199. shape.SetTriangleMesh(sm.Model, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
  200. }
  201. }
  202. }
  203. }