CharacterDemo.cpp 11 KB

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