CharacterDemo.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #include "AnimatedModel.h"
  2. #include "AnimationController.h"
  3. #include "Camera.h"
  4. #include "Character.h"
  5. #include "CharacterDemo.h"
  6. #include "CollisionShape.h"
  7. #include "Context.h"
  8. #include "Controls.h"
  9. #include "CoreEvents.h"
  10. #include "DebugRenderer.h"
  11. #include "Engine.h"
  12. #include "Font.h"
  13. #include "Input.h"
  14. #include "Light.h"
  15. #include "Material.h"
  16. #include "Model.h"
  17. #include "Octree.h"
  18. #include "PhysicsWorld.h"
  19. #include "ProcessUtils.h"
  20. #include "Renderer.h"
  21. #include "RigidBody.h"
  22. #include "ResourceCache.h"
  23. #include "Scene.h"
  24. #include "StaticModel.h"
  25. #include "Text.h"
  26. #include "UI.h"
  27. #include "Zone.h"
  28. #include "Main.h"
  29. #include "DebugNew.h"
  30. const float CAMERA_MIN_DIST = 1.0f;
  31. const float CAMERA_MAX_DIST = 5.0f;
  32. DEFINE_APPLICATION_MAIN(CharacterDemo)
  33. CharacterDemo::CharacterDemo(Context* context) :
  34. Application(context),
  35. cache_(GetSubsystem<ResourceCache>()),
  36. firstPerson_(false)
  37. {
  38. // Register factory for the Character component so it can be created via CreateComponent
  39. context_->RegisterFactory<Character>();
  40. }
  41. int CharacterDemo::Start()
  42. {
  43. CreateScene();
  44. CreateCharacter();
  45. SubscribeToEvents();
  46. // Go on to the main loop
  47. return EXIT_SUCCESS;
  48. }
  49. void CharacterDemo::CreateScene()
  50. {
  51. scene_ = new Scene(context_);
  52. // Create scene subsystem components
  53. scene_->CreateComponent<Octree>();
  54. scene_->CreateComponent<PhysicsWorld>();
  55. scene_->CreateComponent<DebugRenderer>();
  56. // Create camera and define viewport. Camera does not necessarily have to belong to the scene
  57. cameraNode_ = new Node(context_);
  58. Camera* camera = cameraNode_->CreateComponent<Camera>();
  59. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, scene_, camera));
  60. // Create static scene content, same as in TestScene.as
  61. Node* zoneNode = scene_->CreateChild("Zone");
  62. Zone* zone = zoneNode->CreateComponent<Zone>();
  63. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  64. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  65. zone->SetFogStart(100.0f);
  66. zone->SetFogEnd(300.0f);
  67. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  68. {
  69. Node* lightNode = scene_->CreateChild("GlobalLight");
  70. lightNode->SetDirection(Vector3(0.3f, -0.5f, 0.425f));
  71. Light* light = lightNode->CreateComponent<Light>();
  72. light->SetLightType(LIGHT_DIRECTIONAL);
  73. light->SetCastShadows(true);
  74. light->SetShadowBias(BiasParameters(0.0001f, 0.5f));
  75. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  76. light->SetSpecularIntensity(0.5f);
  77. }
  78. {
  79. Node* objectNode = scene_->CreateChild("Floor");
  80. objectNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  81. objectNode->SetScale(Vector3(200.0f, 1.0f, 200.0f));
  82. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  83. object->SetModel(cache_->GetResource<Model>("Models/Box.mdl"));
  84. object->SetMaterial(cache_->GetResource<Material>("Materials/Stone.xml"));
  85. object->SetOccluder(true);
  86. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  87. body->SetCollisionLayer(2);
  88. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  89. shape->SetBox(Vector3::ONE);
  90. }
  91. for (unsigned i = 0; i < 50; ++i)
  92. {
  93. Node* objectNode = scene_->CreateChild("Box");
  94. objectNode->SetPosition(Vector3(Random() * 180.0f - 90.0f, 1.0f, Random() * 180.0f - 90.0f));
  95. objectNode->SetScale(2.0f);
  96. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  97. object->SetModel(cache_->GetResource<Model>("Models/Box.mdl"));
  98. object->SetMaterial(cache_->GetResource<Material>("Materials/Stone.xml"));
  99. object->SetCastShadows(true);
  100. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  101. body->SetCollisionLayer(2);
  102. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  103. shape->SetBox(Vector3::ONE);
  104. }
  105. for (unsigned i = 0; i < 10; ++i)
  106. {
  107. Node* objectNode = scene_->CreateChild("Box");
  108. objectNode->SetPosition(Vector3(Random() * 180.0f - 90.0f, 10.0f, Random() * 180.0f - 90.0f));
  109. objectNode->SetScale(20);
  110. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  111. object->SetModel(cache_->GetResource<Model>("Models/Box.mdl"));
  112. object->SetMaterial(cache_->GetResource<Material>("Materials/Stone.xml"));
  113. object->SetCastShadows(true);
  114. object->SetOccluder(true);
  115. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  116. body->SetCollisionLayer(2);
  117. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  118. shape->SetBox(Vector3::ONE);
  119. }
  120. for (unsigned i = 0; i < 50; ++i)
  121. {
  122. Node* objectNode = scene_->CreateChild("Mushroom");
  123. objectNode->SetPosition(Vector3(Random() * 180.0f - 90.0f, 0.0f, Random() * 180.0f - 90.0f));
  124. objectNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  125. objectNode->SetScale(5.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 CharacterDemo::CreateCharacter()
  137. {
  138. Node* objectNode = scene_->CreateChild("Jack");
  139. objectNode->SetPosition(Vector3(0.0f, 1.0f, 0.0f));
  140. // Create the rendering component + animation controller
  141. AnimatedModel* object = objectNode->CreateComponent<AnimatedModel>();
  142. object->SetModel(cache_->GetResource<Model>("Models/Jack.mdl"));
  143. object->SetMaterial(cache_->GetResource<Material>("Materials/Jack.xml"));
  144. object->SetCastShadows(true);
  145. objectNode->CreateComponent<AnimationController>();
  146. // Create rigidbody, and set non-zero mass so that the body becomes dynamic
  147. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  148. body->SetCollisionLayer(1);
  149. body->SetMass(1.0f);
  150. // Set zero angular factor so that physics doesn't turn the character on its own.
  151. // Instead we will control the character yaw manually
  152. body->SetAngularFactor(Vector3::ZERO);
  153. // Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly
  154. body->SetCollisionEventMode(COLLISION_ALWAYS);
  155. // Set a capsule shape for collision
  156. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  157. shape->SetCapsule(0.7f, 1.8f, Vector3(0.0f, 0.9f, 0.0f));
  158. // Create the character logic component, which takes care of steering the rigidbody
  159. // Remember it so that we can set the controls. Use a WeakPtr because the scene hierarchy already owns it
  160. // and keeps it alive as long as it's not removed from the hierarchy
  161. character_ = objectNode->CreateComponent<Character>();
  162. }
  163. void CharacterDemo::SubscribeToEvents()
  164. {
  165. SubscribeToEvent(E_UPDATE, HANDLER(CharacterDemo, HandleUpdate));
  166. SubscribeToEvent(E_POSTUPDATE, HANDLER(CharacterDemo, HandlePostUpdate));
  167. }
  168. void CharacterDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  169. {
  170. using namespace Update;
  171. float timeStep = eventData[P_TIMESTEP].GetFloat();
  172. Input* input = GetSubsystem<Input>();
  173. if (input->GetKeyDown(KEY_ESC))
  174. engine_->Exit();
  175. if (input->GetKeyPress('F'))
  176. firstPerson_ = !firstPerson_;
  177. if (character_)
  178. {
  179. // Get movement controls and assign them to the character logic component
  180. character_->controls_.Set(CTRL_UP, input->GetKeyDown('W'));
  181. character_->controls_.Set(CTRL_DOWN, input->GetKeyDown('S'));
  182. character_->controls_.Set(CTRL_LEFT, input->GetKeyDown('A'));
  183. character_->controls_.Set(CTRL_RIGHT, input->GetKeyDown('D'));
  184. character_->controls_.Set(CTRL_JUMP, input->GetKeyDown(KEY_SPACE));
  185. // Add character yaw & pitch from the mouse motion
  186. character_->controls_.yaw_ += (float)input->GetMouseMoveX() * YAW_SENSITIVITY;
  187. character_->controls_.pitch_ += (float)input->GetMouseMoveY() * YAW_SENSITIVITY;
  188. // Limit pitch
  189. character_->controls_.pitch_ = Clamp(character_->controls_.pitch_, -80.0f, 80.0f);
  190. // Set rotation already here so that it's updated every rendering frame instead of every physics frame
  191. character_->GetNode()->SetRotation(Quaternion(character_->controls_.yaw_, Vector3::UP));
  192. }
  193. }
  194. void CharacterDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  195. {
  196. if (!character_)
  197. return;
  198. Node* characterNode = character_->GetNode();
  199. // Get camera lookat dir from character yaw + pitch
  200. Quaternion rot = characterNode->GetRotation();
  201. Quaternion dir = rot * Quaternion(character_->controls_.pitch_, Vector3::RIGHT);
  202. if (firstPerson_)
  203. {
  204. // First person camera: position to the head bone + offset slightly forward & up
  205. Node* headNode = characterNode->GetChild("Bip01_Head", true);
  206. if (headNode)
  207. {
  208. cameraNode_->SetPosition(headNode->GetWorldPosition() + rot * Vector3(0.0f, 0.15f, 0.2f));
  209. cameraNode_->SetRotation(dir);
  210. }
  211. }
  212. else
  213. {
  214. // Third person camera: position behind the character
  215. Vector3 aimPoint = characterNode->GetPosition() + rot * Vector3(0.0f, 1.7f, 0.0f);
  216. // Collide camera ray with static physics objects (layer bitmask 2) to ensure we see the character properly
  217. Vector3 rayDir = dir * Vector3::BACK;
  218. float rayDistance = CAMERA_MAX_DIST;
  219. PhysicsRaycastResult result;
  220. scene_->GetComponent<PhysicsWorld>()->RaycastSingle(result, Ray(aimPoint, rayDir), rayDistance, 2);
  221. if (result.body_)
  222. rayDistance = Min(rayDistance, result.distance_);
  223. rayDistance = Clamp(rayDistance, CAMERA_MIN_DIST, CAMERA_MAX_DIST);
  224. cameraNode_->SetPosition(aimPoint + rayDir * rayDistance);
  225. cameraNode_->SetRotation(dir);
  226. }
  227. }