VehicleDemo.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Core/CoreEvents.h>
  24. #include <Atomic/Core/ProcessUtils.h>
  25. #include <Atomic/Engine/Engine.h>
  26. #include <Atomic/Graphics/Camera.h>
  27. #include <Atomic/Graphics/Light.h>
  28. #include <Atomic/Graphics/Material.h>
  29. #include <Atomic/Graphics/Model.h>
  30. #include <Atomic/Graphics/Octree.h>
  31. #include <Atomic/Graphics/Renderer.h>
  32. #include <Atomic/Graphics/StaticModel.h>
  33. #include <Atomic/Graphics/Terrain.h>
  34. #include <Atomic/Graphics/Zone.h>
  35. #include <Atomic/Input/Input.h>
  36. #include <Atomic/IO/FileSystem.h>
  37. #include <Atomic/Physics/CollisionShape.h>
  38. #include <Atomic/Physics/Constraint.h>
  39. #include <Atomic/Physics/PhysicsWorld.h>
  40. #include <Atomic/Physics/RigidBody.h>
  41. #include <Atomic/Resource/ResourceCache.h>
  42. #include <Atomic/Resource/Image.h>
  43. #include <Atomic/Scene/Scene.h>
  44. #include <Atomic/Scene/SceneEvents.h>
  45. #include <Atomic/UI/UI.h>
  46. #include "Vehicle.h"
  47. #include "VehicleDemo.h"
  48. #include <Atomic/DebugNew.h>
  49. const float CAMERA_DISTANCE = 10.0f;
  50. VehicleDemo::VehicleDemo(Context* context) :
  51. Sample(context)
  52. {
  53. // Register factory and attributes for the Vehicle component so it can be created via CreateComponent, and loaded / saved
  54. Vehicle::RegisterObject(context);
  55. }
  56. void VehicleDemo::Start()
  57. {
  58. // Execute base class startup
  59. Sample::Start();
  60. // Create static scene content
  61. CreateScene();
  62. // Create the controllable vehicle
  63. CreateVehicle();
  64. // Create the UI content
  65. CreateInstructions();
  66. // Subscribe to necessary events
  67. SubscribeToEvents();
  68. // Set the mouse mode to use in the sample
  69. Sample::InitMouseMode(MM_RELATIVE);
  70. }
  71. void VehicleDemo::CreateScene()
  72. {
  73. ResourceCache* cache = GetSubsystem<ResourceCache>();
  74. scene_ = new Scene(context_);
  75. // Create scene subsystem components
  76. scene_->CreateComponent<Octree>();
  77. scene_->CreateComponent<PhysicsWorld>();
  78. // Create camera and define viewport. We will be doing load / save, so it's convenient to create the camera outside the scene,
  79. // so that it won't be destroyed and recreated, and we don't have to redefine the viewport on load
  80. cameraNode_ = new Node(context_);
  81. Camera* camera = cameraNode_->CreateComponent<Camera>();
  82. camera->SetFarClip(500.0f);
  83. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, scene_, camera));
  84. // Create static scene content. First create a zone for ambient lighting and fog control
  85. Node* zoneNode = scene_->CreateChild("Zone");
  86. Zone* zone = zoneNode->CreateComponent<Zone>();
  87. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  88. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  89. zone->SetFogStart(300.0f);
  90. zone->SetFogEnd(500.0f);
  91. zone->SetBoundingBox(BoundingBox(-2000.0f, 2000.0f));
  92. // Create a directional light with cascaded shadow mapping
  93. Node* lightNode = scene_->CreateChild("DirectionalLight");
  94. lightNode->SetDirection(Vector3(0.3f, -0.5f, 0.425f));
  95. Light* light = lightNode->CreateComponent<Light>();
  96. light->SetLightType(LIGHT_DIRECTIONAL);
  97. light->SetCastShadows(true);
  98. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  99. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  100. light->SetSpecularIntensity(0.5f);
  101. // Create heightmap terrain with collision
  102. Node* terrainNode = scene_->CreateChild("Terrain");
  103. terrainNode->SetPosition(Vector3::ZERO);
  104. Terrain* terrain = terrainNode->CreateComponent<Terrain>();
  105. terrain->SetPatchSize(64);
  106. terrain->SetSpacing(Vector3(2.0f, 0.1f, 2.0f)); // Spacing between vertices and vertical resolution of the height map
  107. terrain->SetSmoothing(true);
  108. terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
  109. terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
  110. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  111. // terrain patches and other objects behind it
  112. terrain->SetOccluder(true);
  113. RigidBody* body = terrainNode->CreateComponent<RigidBody>();
  114. body->SetCollisionLayer(2); // Use layer bitmask 2 for static geometry
  115. CollisionShape* shape = terrainNode->CreateComponent<CollisionShape>();
  116. shape->SetTerrain();
  117. // Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
  118. const unsigned NUM_MUSHROOMS = 1000;
  119. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  120. {
  121. Node* objectNode = scene_->CreateChild("Mushroom");
  122. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  123. position.y_ = terrain->GetHeight(position) - 0.1f;
  124. objectNode->SetPosition(position);
  125. // Create a rotation quaternion from up vector to terrain normal
  126. objectNode->SetRotation(Quaternion(Vector3::UP, terrain->GetNormal(position)));
  127. objectNode->SetScale(3.0f);
  128. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  129. object->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  130. object->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  131. object->SetCastShadows(true);
  132. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  133. body->SetCollisionLayer(2);
  134. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  135. shape->SetTriangleMesh(object->GetModel(), 0);
  136. }
  137. }
  138. void VehicleDemo::CreateVehicle()
  139. {
  140. Node* vehicleNode = scene_->CreateChild("Vehicle");
  141. vehicleNode->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  142. // Create the vehicle logic component
  143. vehicle_ = vehicleNode->CreateComponent<Vehicle>();
  144. // Create the rendering and physics components
  145. vehicle_->Init();
  146. }
  147. void VehicleDemo::CreateInstructions()
  148. {
  149. SimpleCreateInstructions( "Use WASD keys to drive, mouse/touch to rotate camera\n"
  150. "F5 to save scene, F7 to load" );
  151. }
  152. void VehicleDemo::SubscribeToEvents()
  153. {
  154. // Subscribe to Update event for setting the vehicle controls before physics simulation
  155. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(VehicleDemo, HandleUpdate));
  156. // Subscribe to PostUpdate event for updating the camera position after physics simulation
  157. SubscribeToEvent(E_POSTUPDATE, ATOMIC_HANDLER(VehicleDemo, HandlePostUpdate));
  158. // Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample
  159. UnsubscribeFromEvent(E_SCENEUPDATE);
  160. }
  161. void VehicleDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  162. {
  163. using namespace Update;
  164. Input* input = GetSubsystem<Input>();
  165. if (vehicle_)
  166. {
  167. UI* ui = GetSubsystem<UI>();
  168. vehicle_->controls_.Set(CTRL_FORWARD, input->GetKeyDown(KEY_W));
  169. vehicle_->controls_.Set(CTRL_BACK, input->GetKeyDown(KEY_S));
  170. vehicle_->controls_.Set(CTRL_LEFT, input->GetKeyDown(KEY_A));
  171. vehicle_->controls_.Set(CTRL_RIGHT, input->GetKeyDown(KEY_D));
  172. // Add yaw & pitch from the mouse motion or touch input. Used only for the camera, does not affect motion
  173. if (touchEnabled_)
  174. {
  175. for (unsigned i = 0; i < input->GetNumTouches(); ++i)
  176. {
  177. // ATOMIC FIX
  178. /*
  179. TouchState* state = input->GetTouch(i);
  180. if (!state->touchedElement_) // Touch on empty space
  181. {
  182. Camera* camera = cameraNode_->GetComponent<Camera>();
  183. if (!camera)
  184. return;
  185. Graphics* graphics = GetSubsystem<Graphics>();
  186. vehicle_->controls_.yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_;
  187. vehicle_->controls_.pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_;
  188. }
  189. */
  190. }
  191. }
  192. else
  193. {
  194. vehicle_->controls_.yaw_ += (float)input->GetMouseMoveX() * YAW_SENSITIVITY;
  195. vehicle_->controls_.pitch_ += (float)input->GetMouseMoveY() * YAW_SENSITIVITY;
  196. }
  197. // Limit pitch
  198. vehicle_->controls_.pitch_ = Clamp(vehicle_->controls_.pitch_, 0.0f, 80.0f);
  199. // Check for loading / saving the scene
  200. if (input->GetKeyPress(KEY_F5))
  201. {
  202. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/VehicleDemo.xml",
  203. FILE_WRITE);
  204. scene_->SaveXML(saveFile);
  205. }
  206. if (input->GetKeyPress(KEY_F7))
  207. {
  208. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/VehicleDemo.xml", FILE_READ);
  209. scene_->LoadXML(loadFile);
  210. // After loading we have to reacquire the weak pointer to the Vehicle component, as it has been recreated
  211. // Simply find the vehicle's scene node by name as there's only one of them
  212. Node* vehicleNode = scene_->GetChild("Vehicle", true);
  213. if (vehicleNode)
  214. vehicle_ = vehicleNode->GetComponent<Vehicle>();
  215. }
  216. }
  217. }
  218. void VehicleDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  219. {
  220. if (!vehicle_)
  221. return;
  222. Node* vehicleNode = vehicle_->GetNode();
  223. // Physics update has completed. Position camera behind vehicle
  224. Quaternion dir(vehicleNode->GetRotation().YawAngle(), Vector3::UP);
  225. dir = dir * Quaternion(vehicle_->controls_.yaw_, Vector3::UP);
  226. dir = dir * Quaternion(vehicle_->controls_.pitch_, Vector3::RIGHT);
  227. Vector3 cameraTargetPos = vehicleNode->GetPosition() - dir * Vector3(0.0f, 0.0f, CAMERA_DISTANCE);
  228. Vector3 cameraStartPos = vehicleNode->GetPosition();
  229. // Raycast camera against static objects (physics collision mask 2)
  230. // and move it closer to the vehicle if something in between
  231. Ray cameraRay(cameraStartPos, cameraTargetPos - cameraStartPos);
  232. float cameraRayLength = (cameraTargetPos - cameraStartPos).Length();
  233. PhysicsRaycastResult result;
  234. scene_->GetComponent<PhysicsWorld>()->RaycastSingle(result, cameraRay, cameraRayLength, 2);
  235. if (result.body_)
  236. cameraTargetPos = cameraStartPos + cameraRay.direction_ * (result.distance_ - 0.5f);
  237. cameraNode_->SetPosition(cameraTargetPos);
  238. cameraNode_->SetRotation(dir);
  239. }