VehicleDemo.cpp 11 KB

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