Application.cpp 34 KB

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