CharacterDemo.cpp 11 KB

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