Application.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "AnimatedModel.h"
  25. #include "Animation.h"
  26. #include "AnimationState.h"
  27. #include "Audio.h"
  28. #include "Application.h"
  29. #include "BillboardSet.h"
  30. #include "CollisionShape.h"
  31. #include "Cursor.h"
  32. #include "CustomObject.h"
  33. #include "DebugHud.h"
  34. #include "DebugRenderer.h"
  35. #include "Engine.h"
  36. #include "EngineEvents.h"
  37. #include "Exception.h"
  38. #include "File.h"
  39. #include "Font.h"
  40. #include "Geometry.h"
  41. #include "IndexBuffer.h"
  42. #include "Input.h"
  43. #include "InstancedModel.h"
  44. #include "Joint.h"
  45. #include "Light.h"
  46. #include "Log.h"
  47. #include "Material.h"
  48. #include "Mod.h"
  49. #include "OcclusionBuffer.h"
  50. #include "Octree.h"
  51. #include "OctreeQuery.h"
  52. #include "PhysicsEvents.h"
  53. #include "PhysicsWorld.h"
  54. #include "Pipeline.h"
  55. #include "ParticleEmitter.h"
  56. #include "Profiler.h"
  57. #include "Renderer.h"
  58. #include "RendererImpl.h"
  59. #include "ResourceCache.h"
  60. #include "RigidBody.h"
  61. #include "Scene.h"
  62. #include "Skybox.h"
  63. #include "StaticModel.h"
  64. #include "Text.h"
  65. #include "StringUtils.h"
  66. #include "Texture2D.h"
  67. #include "UI.h"
  68. #include "UIEvents.h"
  69. #include "VertexBuffer.h"
  70. #include "Window.h"
  71. #include "XM.h"
  72. #include "XMLFile.h"
  73. #include "Zone.h"
  74. #include "DebugNew.h"
  75. void calculateTangents(float* vertexData, unsigned vertexCount, const unsigned short* indexData, unsigned indexCount);
  76. float vertexData[] =
  77. {
  78. // Side 1
  79. -1, 1, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0,
  80. 1, 1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 0,
  81. 1, -1, -1, 0, 0, -1, 1, 1, 0, 0, 0, 0,
  82. -1, -1, -1, 0, 0, -1, 0, 1, 0, 0, 0, 0,
  83. // Side 2
  84. 1, 1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  85. 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0,
  86. 1, -1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0,
  87. 1, -1, -1, 1, 0, 0, 0, 1, 0, 0, 0, 0,
  88. // Side 3
  89. 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0,
  90. -1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0,
  91. -1, -1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0,
  92. 1, -1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0,
  93. // Side 4
  94. -1, 1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0,
  95. -1, 1, -1, -1, 0, 0, 1, 0, 0, 0, 0, 0,
  96. -1, -1, -1, -1, 0, 0, 1, 1, 0, 0, 0, 0,
  97. -1, -1, 1, -1, 0, 0, 0, 1, 0, 0, 0, 0,
  98. // Side 5
  99. -1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
  100. 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0,
  101. 1, 1, -1, 0, 1, 0, 1, 1, 0, 0, 0, 0,
  102. -1, 1, -1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
  103. // Side 6
  104. -1, -1, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0,
  105. 1, -1, -1, 0, -1, 0, 1, 0, 0, 0, 0, 0,
  106. 1, -1, 1, 0, -1, 0, 1, 1, 0, 0, 0, 0,
  107. -1, -1, 1, 0, -1, 0, 0, 1, 0, 0, 0, 0
  108. };
  109. const unsigned short indexData[] =
  110. {
  111. 0, 1, 2,
  112. 2, 3, 0,
  113. 4, 5, 6,
  114. 6, 7, 4,
  115. 8, 9, 10,
  116. 10, 11, 8,
  117. 12, 13, 14,
  118. 14, 15, 12,
  119. 16, 17, 18,
  120. 18, 19, 16,
  121. 20, 21, 22,
  122. 22, 23, 20
  123. };
  124. float objectangle = 0;
  125. float yaw = 0;
  126. float pitch = 0;
  127. bool paused = true;
  128. int texturequality = 2;
  129. int materialquality = 2;
  130. int fallbacklevel = 0;
  131. int shadowmapsize = 1024;
  132. bool hiresshadowmap = false;
  133. int texturefilter = 2;
  134. bool usespecular = true;
  135. int drawdebug = 0;
  136. bool drawshadows = true;
  137. bool attach = true;
  138. bool useocclusion = true;
  139. bool shadowfocus = true;
  140. static const int NUM_OBJECTS = 250;
  141. static const int NUM_LIGHTS = 20;
  142. static const int NUM_INSTANCENODES = 20;
  143. static const int NUM_INSTANCES = 50;
  144. static const int NUM_BILLBOARDNODES = 20;
  145. static const int NUM_BILLBOARDS = 15;
  146. Application::Application(const std::vector<std::string>& arguments) :
  147. mArguments(arguments)
  148. {
  149. subscribeToEvent(EVENT_UPDATE, EVENT_HANDLER(Application, handleUpdate));
  150. subscribeToEvent(EVENT_POSTRENDERUPDATE, EVENT_HANDLER(Application, handlePostRenderUpdate));
  151. subscribeToEvent(EVENT_MOUSEMOVE, EVENT_HANDLER(Application, handleMouseMove));
  152. subscribeToEvent(EVENT_MOUSEBUTTONDOWN, EVENT_HANDLER(Application, handleMouseButtonDown));
  153. subscribeToEvent(EVENT_MOUSEBUTTONUP, EVENT_HANDLER(Application, handleMouseButtonUp));
  154. }
  155. Application::~Application()
  156. {
  157. if (mEngine)
  158. {
  159. mEngine->dumpResources();
  160. mEngine->dumpProfilingData();
  161. }
  162. }
  163. void Application::run()
  164. {
  165. init();
  166. while (!mEngine->isExiting())
  167. mEngine->runFrame(mScene, mCameraEntity->getComponent<Camera>());
  168. }
  169. void Application::init()
  170. {
  171. mEngine = new Engine("Test.log");
  172. mEngine->init("Urho3D Test", mArguments);
  173. PROFILE(App_Init);
  174. mCache = mEngine->getResourceCache();
  175. mCache->addResourcePath(getSystemFontDirectory());
  176. Renderer* renderer = mEngine->getRenderer();
  177. UI* ui = mEngine->getUI();
  178. UIElement* uiRoot = ui->getRootElement();
  179. XMLFile* uiStyle = mCache->getResource<XMLFile>("UI/DefaultStyle.xml");
  180. Cursor* cursor = new Cursor("Cursor");
  181. cursor->setStyleAuto(uiStyle, mCache);
  182. cursor->setPosition(renderer->getWidth() / 2, renderer->getHeight() / 2);
  183. ui->setCursor(cursor);
  184. //XMLFile* uiLayout = mCache->getResource<XMLFile>("UI/TestLayout.xml");
  185. //uiRoot->addChild(ui->loadLayout(uiLayout, uiStyle));
  186. mScene = mEngine->createScene();
  187. PhysicsWorld* world = mScene->getExtension<PhysicsWorld>();
  188. world->setGravity(Vector3(0.0f, -9.81f, 0.0f));
  189. world->setFps(100);
  190. world->setLinearRestThreshold(0.1f);
  191. world->setAngularRestThreshold(0.1f);
  192. world->setContactSurfaceLayer(0.001f);
  193. DebugHud* debugHud = mEngine->createDebugHud();
  194. debugHud->setFont(mCache->getResource<Font>("cour.ttf"), 12);
  195. debugHud->setMode(DEBUGHUD_SHOW_STATS | DEBUGHUD_SHOW_MODE);
  196. mCameraEntity = mScene->createEntity();
  197. Camera* camera = mCameraEntity->createComponent<Camera>();
  198. camera->setPosition(Vector3(-50.0f, 2.0f, -50.0f));
  199. camera->setAspectRatio((float)renderer->getWidth() / (float)renderer->getHeight());
  200. calculateTangents(vertexData, 24, indexData, 36);
  201. SharedPtr<VertexBuffer> vb(new VertexBuffer(renderer, false));
  202. vb->setSize(24, MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT);
  203. vb->setData(vertexData);
  204. SharedPtr<IndexBuffer> ib(new IndexBuffer(renderer, false));
  205. ib->setSize(36, false);
  206. ib->setData(indexData);
  207. SharedPtr<Geometry> g(new Geometry());
  208. g->setVertexBuffer(0, vb);
  209. g->setIndexBuffer(ib);
  210. g->setDrawRange(TRIANGLE_LIST, 0, ib->getIndexCount());
  211. SharedPtr<Model> box(new Model(renderer, "Models/Box.mdl"));
  212. box->setNumGeometries(1);
  213. box->setNumGeometryLodLevels(0, 1);
  214. box->setGeometry(0, 0, g);
  215. box->setBoundingBox(BoundingBox(-1.0f, 1.0f));
  216. mCache->addManualResource(box);
  217. createScene();
  218. Entity* sun = mScene->createEntity();
  219. Light* sunLight = sun->createComponent<Light>();
  220. sunLight->setLightType(LIGHT_DIRECTIONAL);
  221. sunLight->setDirection(Vector3(0.5f, -1.0f, 0.5f));
  222. sunLight->setColor(Color(0.2f, 0.2f, 0.2f));
  223. sunLight->setSpecularIntensity(1.0);
  224. //sunLight->setCastShadows(true);
  225. //sunLight->setShadowCascade(CascadeParameters(3, 0.95f, 0.2f, 500.0f));
  226. Light* cameraLight = mCameraEntity->createComponent<Light>();
  227. cameraLight->setLightType(LIGHT_SPOT);
  228. cameraLight->setDirection(Vector3(0.0f, 0.0f, 1.0f));
  229. cameraLight->setRange(50.0f);
  230. cameraLight->setColor(Color(2.0f, 2.0f, 2.0f));
  231. cameraLight->setSpecularIntensity(2.0f);
  232. cameraLight->setCastShadows(true);
  233. cameraLight->setShadowResolution(0.5f);
  234. cameraLight->setShadowFocus(FocusParameters(false, false, false, 0.5f, 3.0f));
  235. cameraLight->setRampTexture(mCache->getResource<Texture2D>("Textures/RampWide.png"));
  236. cameraLight->setSpotTexture(mCache->getResource<Texture2D>("Textures/SpotWide.png"));
  237. camera->addChild(cameraLight);
  238. }
  239. void Application::createScene()
  240. {
  241. PROFILE(App_CreateScene);
  242. Octree* octree = mScene->getExtension<Octree>();
  243. PhysicsWorld* world = mScene->getExtension<PhysicsWorld>();
  244. // Create a zone to control the ambient lighting
  245. Zone* zone = new Zone(octree);
  246. zone->setBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  247. zone->setAmbientColor(Color(0.1f, 0.1f, 0.1f));
  248. Entity* newEntity = mScene->createEntity();
  249. newEntity->addComponent(zone);
  250. // Create the "floor"
  251. for (int y = -5; y <= 5; y++)
  252. {
  253. for (int x = -5; x <= 5; x++)
  254. {
  255. RigidBody* body = new RigidBody(world);
  256. body->setPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
  257. body->setScale(Vector3(10.0f, 0.5f, 10.0f));
  258. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Box.xml"));
  259. body->setCollisionGroup(2);
  260. body->setCollisionMask(1);
  261. StaticModel* object = new StaticModel(octree);
  262. object->setModel(mCache->getResource<Model>("Models/Box.mdl"));
  263. object->setMaterial(mCache->getResource<Material>("Materials/Test.xml"));
  264. body->addChild(object);
  265. Entity* newEntity = mScene->createEntity();
  266. newEntity->addComponent(body);
  267. newEntity->addComponent(object);
  268. }
  269. }
  270. // Create 2 occluder walls
  271. for (int x = 0; x < 2; x++)
  272. {
  273. RigidBody* body = new RigidBody(world);
  274. body->setPosition(Vector3(0.0f, 5.0f, 0.0f));
  275. body->setRotation(Quaternion(x * 90.0f, Vector3::sUp));
  276. body->setScale(Vector3(112.0f, 5.0f, 0.5f));
  277. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Box.xml"));
  278. body->setCollisionGroup(2);
  279. body->setCollisionMask(1);
  280. StaticModel* object = new StaticModel(octree);
  281. object->setModel(mCache->getResource<Model>("Models/Box.mdl"));
  282. object->setMaterial(mCache->getResource<Material>("Materials/Test.xml"));
  283. object->setCastShadows(true);
  284. object->setOccluder(true);
  285. body->addChild(object);
  286. Entity* newEntity = mScene->createEntity();
  287. newEntity->addComponent(body);
  288. newEntity->addComponent(object);
  289. }
  290. // Create static mushroom with physics
  291. {
  292. RigidBody* body = new RigidBody(world);
  293. body->setPosition(Vector3(50.0f, 0.0f, 50.0f));
  294. body->setScale(10.0f);
  295. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Mushroom.xml"));
  296. body->setCollisionGroup(2);
  297. body->setCollisionMask(1);
  298. StaticModel* object = new StaticModel(octree);
  299. object->setModel(mCache->getResource<Model>("Models/Mushroom.mdl"));
  300. object->setMaterial(mCache->getResource<Material>("Materials/Mushroom.xml"));
  301. object->setCastShadows(true);
  302. object->setOccluder(true);
  303. body->addChild(object);
  304. Entity* newEntity = mScene->createEntity();
  305. newEntity->addComponent(body);
  306. newEntity->addComponent(object);
  307. }
  308. // Create instanced mushrooms
  309. for (unsigned j = 0; j < NUM_INSTANCENODES; ++j)
  310. {
  311. InstancedModel* instanced = new InstancedModel(octree);
  312. instanced->setModel(mCache->getResource<Model>("Models/Mushroom.mdl"));
  313. instanced->setMaterial(mCache->getResource<Material>("Materials/Mushroom.xml"));
  314. instanced->setPosition(Vector3(random() * 160.0f - 80.0f, 0.0f, random() * 160.0f - 80.0f));
  315. instanced->setCastShadows(true);
  316. instanced->setNumInstances(50);
  317. std::vector<Instance>& instances = instanced->getInstances();
  318. for (unsigned i = 0; i < NUM_INSTANCES; ++i)
  319. {
  320. Vector3 position(random() * 20.0f - 10.0f, 0.0f, random() * 20.0f - 10.0f);
  321. float angle = random() * 360.0f;
  322. float size = 1.0f + random() * 2.0f;
  323. instances[i].mPosition = position;
  324. instances[i].mRotation = Quaternion(angle, Vector3::sUp);
  325. instances[i].mScale = Vector3(size, size, size);
  326. }
  327. instanced->updated();
  328. Entity* newEntity = mScene->createEntity();
  329. newEntity->addComponent(instanced);
  330. }
  331. // Create animated models
  332. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  333. {
  334. AnimatedModel* object = new AnimatedModel(octree);
  335. Vector3 position(random() * 180.0f - 90.0f, 0.0f, random() * 180.0f - 90.0f);
  336. float angle = random() * 360.0f;
  337. object->setPosition(position);
  338. object->setRotation(Quaternion(angle, Vector3::sUp));
  339. object->setCastShadows(true);
  340. object->setScale(1.0f + random() * 0.25f);
  341. object->setModel(mCache->getResource<Model>("Models/Jack.mdl"));
  342. object->setMaterial(mCache->getResource<Material>("Materials/Jack.xml"));
  343. object->setShadowDistance(200.0f);
  344. object->setDrawDistance(300.0f);
  345. AnimationState* anim = object->addAnimationState(mCache->getResource<Animation>("Models/Jack_Walk.ani"));
  346. if (anim)
  347. {
  348. anim->setUseNlerp(true);
  349. anim->setLooped(true);
  350. anim->setWeight(1.0f);
  351. }
  352. Entity* newEntity = mScene->createEntity();
  353. newEntity->addComponent(object);
  354. mAnimatingObjects.push_back(newEntity);
  355. }
  356. // Create floating smoke clouds
  357. for (unsigned b = 0; b < NUM_BILLBOARDNODES; ++b)
  358. {
  359. BillboardSet* billboard = new BillboardSet(octree);
  360. billboard->setNumBillboards(NUM_BILLBOARDS);
  361. billboard->setPosition(Vector3(random() * 200.0f - 100.0f, random() * 15.0f + 5.0f, random() * 200.0f - 100.0f));
  362. billboard->setMaterial(mCache->getResource<Material>("Materials/LitSmoke.xml"));
  363. billboard->setBillboardsSorted(true);
  364. std::vector<Billboard>& bb = billboard->getBillboards();
  365. for (unsigned i = 0; i < NUM_BILLBOARDS; ++i)
  366. {
  367. bb[i].mPosition = Vector3(random() * 15.0f - 7.5f, random() * 8.0f - 4.0f, random() * 15.0f - 7.5f);
  368. bb[i].mSize = Vector2(random() * 2.0f + 3.0f, random() * 2.0f + 3.0f);
  369. bb[i].mRotation = random() * 360.0f;
  370. bb[i].mEnabled = true;
  371. }
  372. billboard->updated();
  373. Entity* newEntity = mScene->createEntity();
  374. newEntity->addComponent(billboard);
  375. mBillboards.push_back(newEntity);
  376. }
  377. // Create lights
  378. for (unsigned i = 0; i < NUM_LIGHTS; ++i)
  379. {
  380. Light* light = new Light(octree);
  381. Vector3 position(
  382. random() * 150.0f - 75.0f,
  383. random() * 30.0f + 30.0f,
  384. random() * 150.0f - 75.0f
  385. );
  386. Color color(
  387. (rand() & 1) * 0.5f + 0.5f,
  388. (rand() & 1) * 0.5f + 0.5f,
  389. (rand() & 1) * 0.5f + 0.5f
  390. );
  391. if ((color.mR == 0.5f) && (color.mG == 0.5f) && (color.mB == 0.5f))
  392. color = Color(1.0f, 1.0f, 1.0f);
  393. float angle = random() * 360.0f;
  394. light->setPosition(position);
  395. light->setDirection(Vector3(sinf(angle * M_DEGTORAD), -1.0f, cosf(angle * M_DEGTORAD)));
  396. light->setLightType(LIGHT_SPOT);
  397. light->setRange(75.0f);
  398. light->setRampTexture(mCache->getResource<Texture2D>("Textures/RampExtreme.png"));
  399. light->setFov(15.0f);
  400. light->setColor(color);
  401. light->setSpecularIntensity(1.0f);
  402. light->setCastShadows(true);
  403. light->setShadowBias(BiasParameters(0.00002f, 0.0f));
  404. light->setShadowResolution(0.5f);
  405. // The spot lights will not have anything near them, so move the near plane of the shadow camera farther
  406. // for better shadow depth resolution
  407. light->setShadowNearFarRatio(0.01f);
  408. Entity* newEntity = mScene->createEntity();
  409. newEntity->addComponent(light);
  410. mLights.push_back(newEntity);
  411. }
  412. }
  413. void Application::handleUpdate(StringHash eventType, VariantMap& eventData)
  414. {
  415. using namespace Update;
  416. float timeStep = eventData[P_TIMESTEP].getFloat();
  417. if (!paused)
  418. {
  419. objectangle += 10.0f * timeStep;
  420. for (unsigned i = 0; i < mLights.size(); ++i)
  421. {
  422. Light* light = mLights[i]->getComponent<Light>();
  423. light->setRotation(Quaternion(0, objectangle * 2, 0));
  424. }
  425. for (unsigned i = 0; i < mAnimatingObjects.size(); ++i)
  426. {
  427. AnimatedModel* model = mAnimatingObjects[i]->getComponent<AnimatedModel>();
  428. const std::vector<AnimationState*>& anims = model->getAnimationStates();
  429. for (unsigned j = 0; j < anims.size(); ++j)
  430. anims[j]->addTime(timeStep);
  431. }
  432. for (unsigned i = 0; i < mBillboards.size(); ++i)
  433. {
  434. BillboardSet* billboard = mBillboards[i]->getComponent<BillboardSet>();
  435. std::vector<Billboard>& bb = billboard->getBillboards();
  436. for (unsigned j = 0; j < bb.size(); ++j)
  437. bb[j].mRotation += 50.0f * timeStep;
  438. billboard->updated();
  439. }
  440. }
  441. UI* ui = mEngine->getUI();
  442. if (!ui->getFocusElement())
  443. {
  444. Input* input = mEngine->getInput();
  445. float speedMultiplier = 1.0f;
  446. if (input->getKeyDown(KEY_SHIFT))
  447. speedMultiplier = 5.0f;
  448. if (input->getKeyDown(KEY_CONTROL))
  449. speedMultiplier = 0.1f;
  450. if (input->getKeyDown('W'))
  451. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(0.0f,0.0f,10.0f) * timeStep * speedMultiplier);
  452. if (input->getKeyDown('S'))
  453. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(0.0f,0.0f,-10.0f) * timeStep * speedMultiplier);
  454. if (input->getKeyDown('A'))
  455. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(-10.0f,0.0f,0.0f) * timeStep * speedMultiplier);
  456. if (input->getKeyDown('D'))
  457. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(10.0f,0.0f,0.0f) * timeStep * speedMultiplier);
  458. if (input->getKeyPress('1'))
  459. {
  460. Renderer* renderer = mEngine->getRenderer();
  461. int nextRenderMode = renderer->getRenderMode();
  462. if (input->getKeyDown(KEY_SHIFT))
  463. {
  464. --nextRenderMode;
  465. if (nextRenderMode < 0)
  466. nextRenderMode = 2;
  467. }
  468. else
  469. {
  470. ++nextRenderMode;
  471. if (nextRenderMode > 2)
  472. nextRenderMode = 0;
  473. }
  474. renderer->setMode((RenderMode)nextRenderMode, renderer->getWidth(), renderer->getHeight(), renderer->getFullscreen(),
  475. renderer->getVsync(), renderer->getMultiSample());
  476. }
  477. if (input->getKeyPress('2'))
  478. {
  479. texturequality++;
  480. if (texturequality > 2)
  481. texturequality = 0;
  482. mEngine->getPipeline()->setTextureQuality(texturequality);
  483. }
  484. if (input->getKeyPress('3'))
  485. {
  486. materialquality++;
  487. if (materialquality > 2)
  488. materialquality = 0;
  489. mEngine->getPipeline()->setMaterialQuality(materialquality);
  490. }
  491. if (input->getKeyPress('4'))
  492. {
  493. usespecular = !usespecular;
  494. mEngine->getPipeline()->setSpecularLighting(usespecular);
  495. }
  496. if (input->getKeyPress('5'))
  497. {
  498. drawshadows = !drawshadows;
  499. mEngine->getPipeline()->setDrawShadows(drawshadows);
  500. }
  501. if (input->getKeyPress('6'))
  502. {
  503. shadowmapsize *= 2;
  504. if (shadowmapsize > 2048)
  505. shadowmapsize = 512;
  506. mEngine->getPipeline()->setShadowMapSize(shadowmapsize);
  507. }
  508. if (input->getKeyPress('7'))
  509. {
  510. hiresshadowmap = !hiresshadowmap;
  511. mEngine->getPipeline()->setShadowMapHiresDepth(hiresshadowmap);
  512. }
  513. if (input->getKeyPress('8'))
  514. {
  515. useocclusion = !useocclusion;
  516. mEngine->getPipeline()->setMaxOccluderTriangles(useocclusion ? 5000 : 0);
  517. }
  518. if (input->getKeyPress('L'))
  519. {
  520. Light* cameraLight = mCameraEntity->getComponent<Light>();
  521. attach = !attach;
  522. if (attach)
  523. {
  524. cameraLight->setPosition(Vector3::sZero);
  525. cameraLight->setRotation(Quaternion::sIdentity);
  526. mCameraEntity->getComponent<Camera>()->addChild(cameraLight);
  527. }
  528. else
  529. {
  530. // Detach child and set world transform to match what it was before detach
  531. mCameraEntity->getComponent<Camera>()->removeChild(cameraLight, true);
  532. }
  533. }
  534. if (input->getKeyPress(' '))
  535. {
  536. drawdebug++;
  537. if (drawdebug > 2) drawdebug = 0;
  538. mEngine->setDebugDrawMode(drawdebug);
  539. }
  540. if (input->getKeyPress('P'))
  541. {
  542. paused = !paused;
  543. }
  544. if (input->getKeyPress('C'))
  545. {
  546. Camera* camera = mCameraEntity->getComponent<Camera>();
  547. camera->setOrthographic(!camera->isOrthographic());
  548. }
  549. if (input->getKeyPress('O'))
  550. {
  551. if (!mOcclusionDebugImage)
  552. {
  553. try
  554. {
  555. Renderer* renderer = mEngine->getRenderer();
  556. UIElement* uiRoot = mEngine->getUIRoot();
  557. mOcclusionDebugTexture = new Texture2D(renderer, TEXTURE_DYNAMIC);
  558. mOcclusionDebugTexture->setNumLevels(1);
  559. mOcclusionDebugTexture->setSize(256, 256, D3DFMT_R32F);
  560. mOcclusionDebugImage = new BorderImage();
  561. mOcclusionDebugImage->setSize(256, 256);
  562. mOcclusionDebugImage->setTexture(mOcclusionDebugTexture);
  563. mOcclusionDebugImage->setAlignment(HA_RIGHT, VA_BOTTOM);
  564. uiRoot->addChild(mOcclusionDebugImage);
  565. }
  566. catch (...)
  567. {
  568. }
  569. }
  570. else
  571. {
  572. mOcclusionDebugImage->setVisible(!mOcclusionDebugImage->isVisible());
  573. }
  574. }
  575. if (input->getKeyPress('T'))
  576. mEngine->getDebugHud()->toggle(DEBUGHUD_SHOW_PROFILER);
  577. if (input->getKeyPress('F'))
  578. {
  579. Pipeline* pipeline = mEngine->getPipeline();
  580. EdgeFilterParameters params = pipeline->getEdgeFilter();
  581. if (params.mMaxFilter > 0.0f)
  582. params.mMaxFilter = 0.0f;
  583. else
  584. params.mMaxFilter = 1.0f;
  585. pipeline->setEdgeFilter(params);
  586. }
  587. if (input->getKeyPress(KEY_ESCAPE))
  588. mEngine->exit();
  589. }
  590. }
  591. void Application::handlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  592. {
  593. using namespace PostRenderUpdate;
  594. float timeStep = eventData[P_TIMESTEP].getFloat();
  595. // Test world raycast
  596. Camera* camera = mCameraEntity->getComponent<Camera>();
  597. UI* ui = mEngine->getUI();
  598. Renderer* renderer = mEngine->getRenderer();
  599. DebugRenderer* debug = mEngine->getDebugRenderer();
  600. if (camera)
  601. {
  602. IntVector2 pos = ui->getCursorPosition();
  603. if (!ui->getElementAt(pos))
  604. {
  605. Ray cameraRay = camera->getScreenRay(((float)pos.mX) / renderer->getWidth(), ((float)pos.mY) / renderer->getHeight());
  606. std::vector<RayQueryResult> result;
  607. RayOctreeQuery query(cameraRay, result, NODE_GEOMETRY, NODE_BILLBOARDSET, false, false, 250.0f, RAY_TRIANGLE);
  608. mScene->getExtension<Octree>()->getNodes(query);
  609. if (result.size())
  610. {
  611. VolumeNode* node = result[0].mNode;
  612. Vector3 rayHitPos = cameraRay.mOrigin + query.mResult[0].mDistance * cameraRay.mDirection;
  613. debug->addBoundingBox(BoundingBox(-0.01f, 0.01f), Matrix4x3(rayHitPos, Quaternion::sIdentity, Vector3::sUnity), Color(1.0f, 1.0f, 1.0f));
  614. // Check for sub-object results (node-specific)
  615. if (result[0].mSubObject < M_MAX_UNSIGNED)
  616. {
  617. // Bone
  618. if (node->getNodeFlags() & NODE_ANIMATEDMODEL)
  619. {
  620. AnimatedModel* anim = static_cast<AnimatedModel*>(node);
  621. Bone* bone = anim->getSkeleton().getBone(result[0].mSubObject);
  622. debug->addBoundingBox(bone->getBoundingBox(), bone->getWorldTransform(), Color(1.0f, 1.0f, 1.0f));
  623. }
  624. // Instance
  625. else if (node->getNodeFlags() & NODE_INSTANCEDMODEL)
  626. {
  627. InstancedModel* instanced = static_cast<InstancedModel*>(node);
  628. Instance* instance = instanced->getInstance(result[0].mSubObject);
  629. Matrix4x3 transform(instance->mPosition, instance->mRotation, instance->mScale);
  630. if (instanced->getInstancesRelative())
  631. transform = instanced->getWorldTransform() * transform;
  632. debug->addBoundingBox(instanced->getBoundingBox().getTransformed(transform), Color(1.0f, 1.0f, 1.0f));
  633. }
  634. // Custom object subgeometry
  635. else if (node->getNodeFlags() & NODE_CUSTOMOBJECT)
  636. {
  637. CustomObject* custom = static_cast<CustomObject*>(node);
  638. const CustomGeometry* geom = custom->getGeometry(result[0].mSubObject);
  639. debug->addBoundingBox(geom->mBoundingBox.getTransformed(custom->getWorldTransform()), Color(1.0f, 1.0f, 1.0f));
  640. }
  641. }
  642. else
  643. debug->addBoundingBox(node->getWorldBoundingBox(), Color(1.0f, 1.0f, 1.0f));
  644. }
  645. }
  646. }
  647. // Update occlusion debug texture if visible
  648. if ((mOcclusionDebugImage) && (mOcclusionDebugImage->isVisible()))
  649. {
  650. PROFILE(App_UpdateOcclusionDebugTextures);
  651. static const float INV_Z_SCALE = 1.0f / (OCCLUSION_Z_SCALE);
  652. // Dump occlusion depth buffer to debug texture
  653. // Get an occlusion buffer matching the aspect ratio, it should be the main view occlusion buffer
  654. const OcclusionBuffer* buffer = mEngine->getPipeline()->getOcclusionBuffer(camera->getAspectRatio());
  655. if (buffer)
  656. {
  657. int width = buffer->getWidth();
  658. int height = buffer->getHeight();
  659. if (buffer->getBuffer())
  660. {
  661. mOcclusionDebugTexture->setSize(width, height, D3DFMT_R32F);
  662. mOcclusionDebugImage->setSize(width, height);
  663. mOcclusionDebugImage->setFullImageRect();
  664. D3DLOCKED_RECT hwRect;
  665. mOcclusionDebugTexture->lock(0, 0, &hwRect);
  666. for (int y = 0; y < height; ++y)
  667. {
  668. float* dest = (float*)(((unsigned char*)hwRect.pBits) + y * hwRect.Pitch);
  669. int* src = buffer->getBuffer() + y * width;
  670. for (int x = 0; x < width; ++x)
  671. {
  672. float depth = src[x] * INV_Z_SCALE;
  673. dest[x] = depth * 0.5f;
  674. }
  675. }
  676. mOcclusionDebugTexture->unlock();
  677. }
  678. }
  679. }
  680. }
  681. void Application::handleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  682. {
  683. using namespace MouseButtonDown;
  684. int button = eventData[P_BUTTON].getInt();
  685. if (button == MOUSEB_RIGHT)
  686. {
  687. UIElement* cursor = mEngine->getUICursor();
  688. if (cursor)
  689. cursor->setVisible(false);
  690. }
  691. UI* ui = mEngine->getUI();
  692. if ((button == MOUSEB_LEFT) && (!ui->getElementAt(ui->getCursorPosition())) && (!ui->getFocusElement()))
  693. {
  694. // Test creating a new physics object
  695. if (mCameraEntity)
  696. {
  697. Camera* camera = mCameraEntity->getComponent<Camera>();
  698. Octree* octree = mScene->getExtension<Octree>();
  699. PhysicsWorld* world = mScene->getExtension<PhysicsWorld>();
  700. Entity* newEntity = mScene->createEntity();
  701. RigidBody* body = new RigidBody(world);
  702. body->setMode(PHYS_DYNAMIC);
  703. body->setPosition(camera->getPosition());
  704. body->setRotation(camera->getRotation());
  705. body->setScale(0.1f);
  706. body->setFriction(1.0f);
  707. body->setAngularMaxVelocity(500.0f);
  708. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Box.xml"));
  709. body->setCollisionGroup(1);
  710. body->setCollisionMask(3);
  711. body->setLinearVelocity(camera->getUpVector() + camera->getForwardVector() * 10.0f);
  712. StaticModel* object = new StaticModel(octree);
  713. object->setModel(mCache->getResource<Model>("Models/Box.mdl"));
  714. object->setMaterial(mCache->getResource<Material>("Materials/Test.xml"));
  715. object->setCastShadows(true);
  716. object->setShadowDistance(75.0f);
  717. object->setDrawDistance(100.0f);
  718. body->addChild(object);
  719. newEntity->addComponent(body);
  720. newEntity->addComponent(object);
  721. }
  722. }
  723. }
  724. void Application::handleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  725. {
  726. using namespace MouseButtonDown;
  727. if (eventData[P_BUTTON].getInt() == MOUSEB_RIGHT)
  728. {
  729. UIElement* cursor = mEngine->getUICursor();
  730. if (cursor)
  731. cursor->setVisible(true);
  732. }
  733. }
  734. void Application::handleMouseMove(StringHash eventType, VariantMap& eventData)
  735. {
  736. using namespace MouseMove;
  737. if (eventData[P_BUTTONS].getInt() & MOUSEB_RIGHT)
  738. {
  739. int mousedx = eventData[P_X].getInt();
  740. int mousedy = eventData[P_Y].getInt();
  741. yaw += mousedx / 10.0f;
  742. pitch += mousedy / 10.0f;
  743. if (pitch < -90.0f)
  744. pitch = -90.0f;
  745. if (pitch > 90.0f)
  746. pitch = 90.0f;
  747. if (mCameraEntity)
  748. mCameraEntity->getComponent<Camera>()->setRotation(Quaternion(yaw, Vector3::sUp) * Quaternion(pitch, Vector3::sRight));
  749. }
  750. }
  751. void calculateTangents(float* vertexData, unsigned vertexCount, const unsigned short* indexData, unsigned indexCount)
  752. {
  753. // Tangent generation from
  754. // http://www.terathon.com/code/tangent.html
  755. static const int V_OFS = 0;
  756. static const int N_OFS = 3;
  757. static const int UV_OFS = 6;
  758. static const int T_OFS = 8;
  759. static const int V_SIZE = 12;
  760. Vector3 *tan1 = new Vector3[vertexCount * 2];
  761. Vector3 *tan2 = tan1 + vertexCount;
  762. memset(tan1, 0, sizeof(Vector3) * vertexCount * 2);
  763. for (unsigned a = 0; a < indexCount; a += 3)
  764. {
  765. unsigned short i1 = indexData[a+0];
  766. unsigned short i2 = indexData[a+1];
  767. unsigned short i3 = indexData[a+2];
  768. const Vector3 v1 = Vector3(&vertexData[i1 * V_SIZE + V_OFS]);
  769. const Vector3 v2 = Vector3(&vertexData[i2 * V_SIZE + V_OFS]);
  770. const Vector3 v3 = Vector3 (&vertexData[i3 * V_SIZE + V_OFS]);
  771. const Vector2 w1 = Vector2(&vertexData[i1 * V_SIZE + UV_OFS]);
  772. const Vector2 w2 = Vector2(&vertexData[i2 * V_SIZE + UV_OFS]);
  773. const Vector2 w3 = Vector2(&vertexData[i3 * V_SIZE + UV_OFS]);
  774. float x1 = v2.mX - v1.mX;
  775. float x2 = v3.mX - v1.mX;
  776. float y1 = v2.mY - v1.mY;
  777. float y2 = v3.mY - v1.mY;
  778. float z1 = v2.mZ - v1.mZ;
  779. float z2 = v3.mZ - v1.mZ;
  780. float s1 = w2.mX - w1.mX;
  781. float s2 = w3.mX - w1.mX;
  782. float t1 = w2.mY - w1.mY;
  783. float t2 = w3.mY - w1.mY;
  784. float r = 1.0f / (s1 * t2 - s2 * t1);
  785. Vector3 sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
  786. (t2 * z1 - t1 * z2) * r);
  787. Vector3 tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
  788. (s1 * z2 - s2 * z1) * r);
  789. tan1[i1] += sdir;
  790. tan1[i2] += sdir;
  791. tan1[i3] += sdir;
  792. tan2[i1] += tdir;
  793. tan2[i2] += tdir;
  794. tan2[i3] += tdir;
  795. }
  796. for (unsigned a = 0; a < vertexCount; a++)
  797. {
  798. const Vector3 n = Vector3(&vertexData[a * V_SIZE + N_OFS]);
  799. const Vector3 t = Vector3(tan1[a]);
  800. Vector3 xyz;
  801. float w;
  802. // Gram-Schmidt orthogonalize
  803. xyz = (t - n * n.dotProduct(t)).getNormalized();
  804. // Calculate handedness
  805. w = n.crossProduct(t).dotProduct(tan2[a]) < 0.0f ? -1.0f : 1.0f;
  806. vertexData[a * V_SIZE + T_OFS] = xyz.mX;
  807. vertexData[a * V_SIZE + T_OFS + 1] = xyz.mY;
  808. vertexData[a * V_SIZE + T_OFS + 2] = xyz.mZ;
  809. vertexData[a * V_SIZE + T_OFS + 3] = w;
  810. }
  811. delete[] tan1;
  812. }