RaycastVehicleDemo.cpp 13 KB

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