CharacterDemo.cpp 11 KB

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