VehicleDemo.cpp 12 KB

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