CharacterDemo.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // Copyright (c) 2008-2023 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/AnimatedModel.h>
  7. #include <Urho3D/Graphics/AnimationController.h>
  8. #include <Urho3D/Graphics/Camera.h>
  9. #include <Urho3D/Graphics/Light.h>
  10. #include <Urho3D/Graphics/Material.h>
  11. #include <Urho3D/Graphics/Octree.h>
  12. #include <Urho3D/Graphics/Renderer.h>
  13. #include <Urho3D/Graphics/Zone.h>
  14. #include <Urho3D/Input/Controls.h>
  15. #include <Urho3D/Input/Input.h>
  16. #include <Urho3D/IO/FileSystem.h>
  17. #include <Urho3D/Physics/CollisionShape.h>
  18. #include <Urho3D/Physics/PhysicsWorld.h>
  19. #include <Urho3D/Physics/RigidBody.h>
  20. #include <Urho3D/Resource/ResourceCache.h>
  21. #include <Urho3D/Scene/Scene.h>
  22. #include <Urho3D/UI/Font.h>
  23. #include <Urho3D/UI/Text.h>
  24. #include <Urho3D/UI/UI.h>
  25. #include "Character.h"
  26. #include "CharacterDemo.h"
  27. #include "Touch.h"
  28. #include <Urho3D/DebugNew.h>
  29. URHO3D_DEFINE_APPLICATION_MAIN(CharacterDemo)
  30. CharacterDemo::CharacterDemo(Context* context) :
  31. Sample(context),
  32. firstPerson_(false)
  33. {
  34. // Register factory and attributes for the Character component so it can be created via CreateComponent, and loaded / saved
  35. Character::RegisterObject(context);
  36. }
  37. CharacterDemo::~CharacterDemo() = default;
  38. void CharacterDemo::Start()
  39. {
  40. // Execute base class startup
  41. Sample::Start();
  42. if (touchEnabled_)
  43. touch_ = new Touch(context_, TOUCH_SENSITIVITY);
  44. // Create static scene content
  45. CreateScene();
  46. // Create the controllable character
  47. CreateCharacter();
  48. // Create the UI content
  49. CreateInstructions();
  50. // Subscribe to necessary events
  51. SubscribeToEvents();
  52. // Set the mouse mode to use in the sample
  53. Sample::InitMouseMode(MM_RELATIVE);
  54. }
  55. void CharacterDemo::CreateScene()
  56. {
  57. auto* cache = GetSubsystem<ResourceCache>();
  58. scene_ = new Scene(context_);
  59. // Create scene subsystem components
  60. scene_->CreateComponent<Octree>();
  61. scene_->CreateComponent<PhysicsWorld>();
  62. // Create camera and define viewport. We will be doing load / save, so it's convenient to create the camera outside the scene,
  63. // so that it won't be destroyed and recreated, and we don't have to redefine the viewport on load
  64. cameraNode_ = new Node(context_);
  65. auto* camera = cameraNode_->CreateComponent<Camera>();
  66. camera->SetFarClip(300.0f);
  67. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, scene_, camera));
  68. // Create static scene content. First create a zone for ambient lighting and fog control
  69. Node* zoneNode = scene_->CreateChild("Zone");
  70. auto* zone = zoneNode->CreateComponent<Zone>();
  71. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  72. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  73. zone->SetFogStart(100.0f);
  74. zone->SetFogEnd(300.0f);
  75. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  76. // Create a directional light with cascaded shadow mapping
  77. Node* lightNode = scene_->CreateChild("DirectionalLight");
  78. lightNode->SetDirection(Vector3(0.3f, -0.5f, 0.425f));
  79. auto* light = lightNode->CreateComponent<Light>();
  80. light->SetLightType(LIGHT_DIRECTIONAL);
  81. light->SetCastShadows(true);
  82. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  83. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  84. light->SetSpecularIntensity(0.5f);
  85. // Create the floor object
  86. Node* floorNode = scene_->CreateChild("Floor");
  87. floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  88. floorNode->SetScale(Vector3(200.0f, 1.0f, 200.0f));
  89. auto* object = floorNode->CreateComponent<StaticModel>();
  90. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  91. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  92. auto* body = floorNode->CreateComponent<RigidBody>();
  93. // Use collision layer bit 2 to mark world scenery. This is what we will raycast against to prevent camera from going
  94. // inside geometry
  95. body->SetCollisionLayer(2);
  96. auto* shape = floorNode->CreateComponent<CollisionShape>();
  97. shape->SetBox(Vector3::ONE);
  98. // Create mushrooms of varying sizes
  99. const unsigned NUM_MUSHROOMS = 60;
  100. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  101. {
  102. Node* objectNode = scene_->CreateChild("Mushroom");
  103. objectNode->SetPosition(Vector3(Random(180.0f) - 90.0f, 0.0f, Random(180.0f) - 90.0f));
  104. objectNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  105. objectNode->SetScale(2.0f + Random(5.0f));
  106. auto* object = objectNode->CreateComponent<StaticModel>();
  107. object->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  108. object->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  109. object->SetCastShadows(true);
  110. auto* body = objectNode->CreateComponent<RigidBody>();
  111. body->SetCollisionLayer(2);
  112. auto* shape = objectNode->CreateComponent<CollisionShape>();
  113. shape->SetTriangleMesh(object->GetModel(), 0);
  114. }
  115. // Create movable boxes. Let them fall from the sky at first
  116. const unsigned NUM_BOXES = 100;
  117. for (unsigned i = 0; i < NUM_BOXES; ++i)
  118. {
  119. float scale = Random(2.0f) + 0.5f;
  120. Node* objectNode = scene_->CreateChild("Box");
  121. objectNode->SetPosition(Vector3(Random(180.0f) - 90.0f, Random(10.0f) + 10.0f, Random(180.0f) - 90.0f));
  122. objectNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
  123. objectNode->SetScale(scale);
  124. auto* object = objectNode->CreateComponent<StaticModel>();
  125. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  126. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  127. object->SetCastShadows(true);
  128. auto* body = objectNode->CreateComponent<RigidBody>();
  129. body->SetCollisionLayer(2);
  130. // Bigger boxes will be heavier and harder to move
  131. body->SetMass(scale * 2.0f);
  132. auto* shape = objectNode->CreateComponent<CollisionShape>();
  133. shape->SetBox(Vector3::ONE);
  134. }
  135. }
  136. void CharacterDemo::CreateCharacter()
  137. {
  138. auto* cache = GetSubsystem<ResourceCache>();
  139. Node* objectNode = scene_->CreateChild("Jack");
  140. objectNode->SetPosition(Vector3(0.0f, 1.0f, 0.0f));
  141. // spin node
  142. Node* adjustNode = objectNode->CreateChild("AdjNode");
  143. adjustNode->SetRotation( Quaternion(180, Vector3(0,1,0) ) );
  144. // Create the rendering component + animation controller
  145. auto* object = adjustNode->CreateComponent<AnimatedModel>();
  146. object->SetModel(cache->GetResource<Model>("Models/Mutant/Mutant.mdl"));
  147. object->SetMaterial(cache->GetResource<Material>("Models/Mutant/Materials/mutant_M.xml"));
  148. object->SetCastShadows(true);
  149. adjustNode->CreateComponent<AnimationController>();
  150. // Set the head bone for manual control
  151. object->GetSkeleton().GetBone("Mutant:Head")->animated_ = false;
  152. // Create rigidbody, and set non-zero mass so that the body becomes dynamic
  153. auto* body = objectNode->CreateComponent<RigidBody>();
  154. body->SetCollisionLayer(1);
  155. body->SetMass(1.0f);
  156. // Set zero angular factor so that physics doesn't turn the character on its own.
  157. // Instead we will control the character yaw manually
  158. body->SetAngularFactor(Vector3::ZERO);
  159. // Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly
  160. body->SetCollisionEventMode(COLLISION_ALWAYS);
  161. // Set a capsule shape for collision
  162. auto* shape = objectNode->CreateComponent<CollisionShape>();
  163. shape->SetCapsule(0.7f, 1.8f, Vector3(0.0f, 0.9f, 0.0f));
  164. // Create the character logic component, which takes care of steering the rigidbody
  165. // Remember it so that we can set the controls. Use a WeakPtr because the scene hierarchy already owns it
  166. // and keeps it alive as long as it's not removed from the hierarchy
  167. character_ = objectNode->CreateComponent<Character>();
  168. }
  169. void CharacterDemo::CreateInstructions()
  170. {
  171. auto* cache = GetSubsystem<ResourceCache>();
  172. auto* ui = GetSubsystem<UI>();
  173. // Construct new Text object, set string to display and font to use
  174. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  175. instructionText->SetText(
  176. "Use WASD keys and mouse/touch to move\n"
  177. "Space to jump, F to toggle 1st/3rd person\n"
  178. "F5 to save scene, F7 to load"
  179. );
  180. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  181. // The text has multiple rows. Center them in relation to each other
  182. instructionText->SetTextAlignment(HA_CENTER);
  183. // Position the text relative to the screen center
  184. instructionText->SetHorizontalAlignment(HA_CENTER);
  185. instructionText->SetVerticalAlignment(VA_CENTER);
  186. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  187. }
  188. void CharacterDemo::SubscribeToEvents()
  189. {
  190. // Subscribe to Update event for setting the character controls before physics simulation
  191. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(CharacterDemo, HandleUpdate));
  192. // Subscribe to PostUpdate event for updating the camera position after physics simulation
  193. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(CharacterDemo, HandlePostUpdate));
  194. // Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample
  195. UnsubscribeFromEvent(E_SCENEUPDATE);
  196. }
  197. void CharacterDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  198. {
  199. using namespace Update;
  200. auto* input = GetSubsystem<Input>();
  201. if (character_)
  202. {
  203. // Clear previous controls
  204. character_->controls_.Set(CTRL_FORWARD | CTRL_BACK | CTRL_LEFT | CTRL_RIGHT | CTRL_JUMP, false);
  205. // Update controls using touch utility class
  206. if (touch_)
  207. touch_->UpdateTouches(character_->controls_);
  208. // Update controls using keys
  209. auto* ui = GetSubsystem<UI>();
  210. if (!ui->GetFocusElement())
  211. {
  212. if (!touch_ || !touch_->useGyroscope_)
  213. {
  214. character_->controls_.Set(CTRL_FORWARD, input->GetKeyDown(KEY_W));
  215. character_->controls_.Set(CTRL_BACK, input->GetKeyDown(KEY_S));
  216. character_->controls_.Set(CTRL_LEFT, input->GetKeyDown(KEY_A));
  217. character_->controls_.Set(CTRL_RIGHT, input->GetKeyDown(KEY_D));
  218. }
  219. character_->controls_.Set(CTRL_JUMP, input->GetKeyDown(KEY_SPACE));
  220. // Add character yaw & pitch from the mouse motion or touch input
  221. if (touchEnabled_)
  222. {
  223. for (unsigned i = 0; i < input->GetNumTouches(); ++i)
  224. {
  225. TouchState* state = input->GetTouch(i);
  226. if (!state->touchedElement_) // Touch on empty space
  227. {
  228. auto* camera = cameraNode_->GetComponent<Camera>();
  229. if (!camera)
  230. return;
  231. auto* graphics = GetSubsystem<Graphics>();
  232. character_->controls_.yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_;
  233. character_->controls_.pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_;
  234. }
  235. }
  236. }
  237. else
  238. {
  239. character_->controls_.yaw_ += (float)input->GetMouseMoveX() * YAW_SENSITIVITY;
  240. character_->controls_.pitch_ += (float)input->GetMouseMoveY() * YAW_SENSITIVITY;
  241. }
  242. // Limit pitch
  243. character_->controls_.pitch_ = Clamp(character_->controls_.pitch_, -80.0f, 80.0f);
  244. // Set rotation already here so that it's updated every rendering frame instead of every physics frame
  245. character_->GetNode()->SetRotation(Quaternion(character_->controls_.yaw_, Vector3::UP));
  246. // Switch between 1st and 3rd person
  247. if (input->GetKeyPress(KEY_F))
  248. firstPerson_ = !firstPerson_;
  249. // Turn on/off gyroscope on mobile platform
  250. if (touch_ && input->GetKeyPress(KEY_G))
  251. touch_->useGyroscope_ = !touch_->useGyroscope_;
  252. // Check for loading / saving the scene
  253. if (input->GetKeyPress(KEY_F5))
  254. {
  255. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CharacterDemo.xml", FILE_WRITE);
  256. scene_->SaveXML(saveFile);
  257. }
  258. if (input->GetKeyPress(KEY_F7))
  259. {
  260. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CharacterDemo.xml", FILE_READ);
  261. scene_->LoadXML(loadFile);
  262. // After loading we have to reacquire the weak pointer to the Character component, as it has been recreated
  263. // Simply find the character's scene node by name as there's only one of them
  264. Node* characterNode = scene_->GetChild("Jack", true);
  265. if (characterNode)
  266. character_ = characterNode->GetComponent<Character>();
  267. }
  268. }
  269. }
  270. }
  271. void CharacterDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  272. {
  273. if (!character_)
  274. return;
  275. Node* characterNode = character_->GetNode();
  276. // Get camera lookat dir from character yaw + pitch
  277. const Quaternion& rot = characterNode->GetRotation();
  278. Quaternion dir = rot * Quaternion(character_->controls_.pitch_, Vector3::RIGHT);
  279. // Turn head to camera pitch, but limit to avoid unnatural animation
  280. Node* headNode = characterNode->GetChild("Mutant:Head", true);
  281. float limitPitch = Clamp(character_->controls_.pitch_, -45.0f, 45.0f);
  282. Quaternion headDir = rot * Quaternion(limitPitch, Vector3(1.0f, 0.0f, 0.0f));
  283. // This could be expanded to look at an arbitrary target, now just look at a point in front
  284. Vector3 headWorldTarget = headNode->GetWorldPosition() + headDir * Vector3(0.0f, 0.0f, -1.0f);
  285. headNode->LookAt(headWorldTarget, Vector3(0.0f, 1.0f, 0.0f));
  286. if (firstPerson_)
  287. {
  288. cameraNode_->SetPosition(headNode->GetWorldPosition() + rot * Vector3(0.0f, 0.15f, 0.2f));
  289. cameraNode_->SetRotation(dir);
  290. }
  291. else
  292. {
  293. // Third person camera: position behind the character
  294. Vector3 aimPoint = characterNode->GetPosition() + rot * Vector3(0.0f, 1.7f, 0.0f);
  295. // Collide camera ray with static physics objects (layer bitmask 2) to ensure we see the character properly
  296. Vector3 rayDir = dir * Vector3::BACK;
  297. float rayDistance = touch_ ? touch_->cameraDistance_ : CAMERA_INITIAL_DIST;
  298. PhysicsRaycastResult result;
  299. scene_->GetComponent<PhysicsWorld>()->RaycastSingle(result, Ray(aimPoint, rayDir), rayDistance, 2);
  300. if (result.body_)
  301. rayDistance = Min(rayDistance, result.distance_);
  302. rayDistance = Clamp(rayDistance, CAMERA_MIN_DIST, CAMERA_MAX_DIST);
  303. cameraNode_->SetPosition(aimPoint + rayDir * rayDistance);
  304. cameraNode_->SetRotation(dir);
  305. }
  306. }