💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2306 lines
74 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. /*
  2. * Copyright (C) 2017-2019 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper Source Code.
  5. *
  6. * Antkeeper Source Code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper Source Code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "game.hpp"
  20. #include "resources/csv-table.hpp"
  21. #include "states/game-state.hpp"
  22. #include "states/splash-state.hpp"
  23. #include "states/sandbox-state.hpp"
  24. #include "filesystem.hpp"
  25. #include "timestamp.hpp"
  26. #include "ui/ui.hpp"
  27. #include "graphics/ui-render-pass.hpp"
  28. #include "graphics/shadow-map-render-pass.hpp"
  29. #include "graphics/clear-render-pass.hpp"
  30. #include "graphics/sky-render-pass.hpp"
  31. #include "graphics/lighting-render-pass.hpp"
  32. #include "graphics/silhouette-render-pass.hpp"
  33. #include "graphics/final-render-pass.hpp"
  34. #include "resources/resource-manager.hpp"
  35. #include "resources/text-file.hpp"
  36. #include "game/camera-rig.hpp"
  37. #include "game/lens.hpp"
  38. #include "game/forceps.hpp"
  39. #include "game/brush.hpp"
  40. #include "entity/component-manager.hpp"
  41. #include "entity/components/transform-component.hpp"
  42. #include "entity/components/model-component.hpp"
  43. #include "entity/components/terrain-patch-component.hpp"
  44. #include "entity/entity-manager.hpp"
  45. #include "entity/entity-template.hpp"
  46. #include "entity/system-manager.hpp"
  47. #include "entity/systems/sound-system.hpp"
  48. #include "entity/systems/collision-system.hpp"
  49. #include "entity/systems/render-system.hpp"
  50. #include "entity/systems/camera-system.hpp"
  51. #include "entity/systems/tool-system.hpp"
  52. #include "entity/systems/locomotion-system.hpp"
  53. #include "entity/systems/behavior-system.hpp"
  54. #include "entity/systems/steering-system.hpp"
  55. #include "entity/systems/particle-system.hpp"
  56. #include "entity/systems/terrain-system.hpp"
  57. #include "stb/stb_image_write.h"
  58. #include <algorithm>
  59. #include <cctype>
  60. #include <fstream>
  61. #include <sstream>
  62. #include <stdexcept>
  63. #include <thread>
  64. template <>
  65. bool Game::readSetting<std::string>(const std::string& name, std::string* value) const
  66. {
  67. auto it = settingsMap.find(name);
  68. if (it == settingsMap.end())
  69. {
  70. return false;
  71. }
  72. *value = (*settingsTable)[it->second][1];
  73. return true;
  74. }
  75. template <>
  76. bool Game::readSetting<bool>(const std::string& name, bool* value) const
  77. {
  78. auto it = settingsMap.find(name);
  79. if (it == settingsMap.end())
  80. {
  81. return false;
  82. }
  83. const std::string& string = (*settingsTable)[it->second][1];
  84. if (string == "true" || string == "on" || string == "1")
  85. {
  86. *value = true;
  87. return true;
  88. }
  89. else if (string == "false" || string == "off" || string == "0")
  90. {
  91. *value = false;
  92. return true;
  93. }
  94. return false;
  95. }
  96. template <>
  97. bool Game::readSetting<int>(const std::string& name, int* value) const
  98. {
  99. auto it = settingsMap.find(name);
  100. if (it == settingsMap.end())
  101. {
  102. return false;
  103. }
  104. std::stringstream stream;
  105. stream << (*settingsTable)[it->second][1];
  106. stream >> (*value);
  107. return (!stream.fail());
  108. }
  109. template <>
  110. bool Game::readSetting<float>(const std::string& name, float* value) const
  111. {
  112. auto it = settingsMap.find(name);
  113. if (it == settingsMap.end())
  114. {
  115. return false;
  116. }
  117. std::stringstream stream;
  118. stream << (*settingsTable)[it->second][1];
  119. stream >> (*value);
  120. return (!stream.fail());
  121. }
  122. template <>
  123. bool Game::readSetting<Vector2>(const std::string& name, Vector2* value) const
  124. {
  125. auto it = settingsMap.find(name);
  126. if (it == settingsMap.end())
  127. {
  128. return false;
  129. }
  130. std::stringstream stream;
  131. stream << (*settingsTable)[it->second][1];
  132. stream >> value->x;
  133. stream.str(std::string());
  134. stream.clear();
  135. stream << (*settingsTable)[it->second][2];
  136. stream >> value->y;
  137. return (!stream.fail());
  138. }
  139. Game::Game(int argc, char* argv[]):
  140. currentState(nullptr),
  141. window(nullptr)
  142. {
  143. // Determine application name
  144. std::string applicationName;
  145. #if defined(_WIN32)
  146. applicationName = "Antkeeper";
  147. #else
  148. applicationName = "antkeeper";
  149. #endif
  150. // Form resource paths
  151. dataPath = getDataPath(applicationName);
  152. configPath = getConfigPath(applicationName);
  153. controlsPath = configPath + "/controls/";
  154. std::cout << "Data path: " << dataPath << std::endl;
  155. std::cout << "Config path: " << configPath << std::endl;
  156. // Create nonexistent config directories
  157. std::vector<std::string> configPaths;
  158. configPaths.push_back(configPath);
  159. configPaths.push_back(controlsPath);
  160. for (const std::string& path: configPaths)
  161. {
  162. if (!pathExists(path))
  163. {
  164. createDirectory(path);
  165. }
  166. }
  167. // Setup resource manager
  168. resourceManager = new ResourceManager();
  169. // Include resource search paths in order of priority
  170. resourceManager->include(controlsPath);
  171. resourceManager->include(configPath);
  172. resourceManager->include(dataPath);
  173. splashState = new SplashState(this);
  174. sandboxState = new SandboxState(this);
  175. }
  176. Game::~Game()
  177. {
  178. if (window)
  179. {
  180. windowManager->destroyWindow(window);
  181. }
  182. }
  183. void Game::changeState(GameState* state)
  184. {
  185. if (currentState != nullptr)
  186. {
  187. currentState->exit();
  188. }
  189. currentState = state;
  190. if (currentState != nullptr)
  191. {
  192. currentState->enter();
  193. }
  194. }
  195. std::string Game::getString(std::size_t languageIndex, const std::string& name) const
  196. {
  197. std::string value;
  198. auto it = stringMap.find(name);
  199. if (it != stringMap.end())
  200. {
  201. value = (*stringTable)[it->second][languageIndex + 1];
  202. if (value.empty())
  203. {
  204. value = std::string("# EMPTY STRING: ") + name + std::string(" #");
  205. }
  206. }
  207. else
  208. {
  209. value = std::string("# MISSING STRING: ") + name + std::string(" #");
  210. }
  211. return value;
  212. }
  213. void Game::changeLanguage(std::size_t languageIndex)
  214. {
  215. this->languageIndex = languageIndex;
  216. window->setTitle(getString(getLanguageIndex(), "title").c_str());
  217. restringUI();
  218. resizeUI(w, h);
  219. }
  220. void Game::toggleFullscreen()
  221. {
  222. fullscreen = !fullscreen;
  223. window->setFullscreen(fullscreen);
  224. }
  225. void Game::setUpdateRate(double frequency)
  226. {
  227. stepScheduler.setStepFrequency(frequency);
  228. }
  229. void Game::setup()
  230. {
  231. loadSettings();
  232. setupDebugging();
  233. setupLocalization();
  234. setupWindow();
  235. setupGraphics();
  236. setupUI();
  237. setupControls();
  238. setupGameplay();
  239. #if defined(DEBUG)
  240. toggleWireframe();
  241. #endif // DEBUG
  242. screenshotQueued = false;
  243. // Load model resources
  244. try
  245. {
  246. lensModel = resourceManager->load<Model>("lens.mdl");
  247. forcepsModel = resourceManager->load<Model>("forceps.mdl");
  248. brushModel = resourceManager->load<Model>("brush.mdl");
  249. smokeMaterial = resourceManager->load<Material>("smoke.mtl");
  250. }
  251. catch (const std::exception& e)
  252. {
  253. std::cerr << "Failed to load one or more models: \"" << e.what() << "\"" << std::endl;
  254. close(EXIT_FAILURE);
  255. }
  256. time = 0.0f;
  257. // Tools
  258. currentTool = nullptr;
  259. lens = new Lens(lensModel, &animator);
  260. lens->setOrbitCam(orbitCam);
  261. worldScene->addObject(lens->getModelInstance());
  262. worldScene->addObject(lens->getSpotlight());
  263. lens->setSunDirection(-sunlightCamera.getForward());
  264. ModelInstance* modelInstance = lens->getModelInstance();
  265. for (std::size_t i = 0; i < modelInstance->getModel()->getGroupCount(); ++i)
  266. {
  267. Material* material = modelInstance->getModel()->getGroup(i)->material->clone();
  268. material->setFlags(material->getFlags() | 256);
  269. modelInstance->setMaterialSlot(i, material);
  270. }
  271. // Forceps
  272. forceps = new Forceps(forcepsModel, &animator);
  273. forceps->setOrbitCam(orbitCam);
  274. worldScene->addObject(forceps->getModelInstance());
  275. // Brush
  276. brush = new Brush(brushModel, &animator);
  277. brush->setOrbitCam(orbitCam);
  278. worldScene->addObject(brush->getModelInstance());
  279. // Initialize component manager
  280. componentManager = new ComponentManager();
  281. // Initialize entity manager
  282. entityManager = new EntityManager(componentManager);
  283. // Initialize systems
  284. soundSystem = new SoundSystem(componentManager);
  285. collisionSystem = new CollisionSystem(componentManager);
  286. cameraSystem = new CameraSystem(componentManager);
  287. renderSystem = new RenderSystem(componentManager, worldScene);
  288. toolSystem = new ToolSystem(componentManager);
  289. toolSystem->setPickingCamera(&camera);
  290. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  291. eventDispatcher.subscribe<MouseMovedEvent>(toolSystem);
  292. behaviorSystem = new BehaviorSystem(componentManager);
  293. steeringSystem = new SteeringSystem(componentManager);
  294. locomotionSystem = new LocomotionSystem(componentManager);
  295. terrainSystem = new TerrainSystem(componentManager);
  296. terrainSystem->setPatchSize(500.0f);
  297. particleSystem = new ParticleSystem(componentManager);
  298. particleSystem->resize(1000);
  299. particleSystem->setMaterial(smokeMaterial);
  300. particleSystem->setDirection(Vector3(0, 1, 0));
  301. lens->setParticleSystem(particleSystem);
  302. particleSystem->getBillboardBatch()->setAlignment(&camera, BillboardAlignmentMode::SPHERICAL);
  303. worldScene->addObject(particleSystem->getBillboardBatch());
  304. // Initialize system manager
  305. systemManager = new SystemManager();
  306. systemManager->addSystem(soundSystem);
  307. systemManager->addSystem(behaviorSystem);
  308. systemManager->addSystem(steeringSystem);
  309. systemManager->addSystem(locomotionSystem);
  310. systemManager->addSystem(collisionSystem);
  311. systemManager->addSystem(toolSystem);
  312. systemManager->addSystem(terrainSystem);
  313. systemManager->addSystem(particleSystem);
  314. systemManager->addSystem(cameraSystem);
  315. systemManager->addSystem(renderSystem);
  316. /*
  317. EntityID sidewalkPanel;
  318. sidewalkPanel = createInstanceOf("sidewalk-panel");
  319. EntityID antHill = createInstanceOf("ant-hill");
  320. setTranslation(antHill, Vector3(20, 0, 40));
  321. EntityID antNest = createInstanceOf("ant-nest");
  322. setTranslation(antNest, Vector3(20, 0, 40));
  323. EntityID lollipop = createInstanceOf("lollipop");
  324. setTranslation(lollipop, Vector3(30.0f, 3.5f * 0.5f, -30.0f));
  325. setRotation(lollipop, glm::angleAxis(glm::radians(8.85f), Vector3(1.0f, 0.0f, 0.0f)));
  326. */
  327. // Load navmesh
  328. TriangleMesh* navmesh = resourceManager->load<TriangleMesh>("sidewalk.mesh");
  329. // Find surface
  330. TriangleMesh::Triangle* surface = nullptr;
  331. Vector3 barycentricPosition;
  332. Ray ray;
  333. ray.origin = Vector3(0, 100, 0);
  334. ray.direction = Vector3(0, -1, 0);
  335. auto intersection = ray.intersects(*navmesh);
  336. if (std::get<0>(intersection))
  337. {
  338. surface = (*navmesh->getTriangles())[std::get<3>(intersection)];
  339. Vector3 position = ray.extrapolate(std::get<1>(intersection));
  340. Vector3 a = surface->edge->vertex->position;
  341. Vector3 b = surface->edge->next->vertex->position;
  342. Vector3 c = surface->edge->previous->vertex->position;
  343. barycentricPosition = barycentric(position, a, b, c);
  344. }
  345. for (int i = 0; i < 0; ++i)
  346. {
  347. EntityID ant = createInstanceOf("worker-ant");
  348. setTranslation(ant, Vector3(0.0f, 0, 0.0f));
  349. BehaviorComponent* behavior = new BehaviorComponent();
  350. SteeringComponent* steering = new SteeringComponent();
  351. LeggedLocomotionComponent* locomotion = new LeggedLocomotionComponent();
  352. componentManager->addComponent(ant, behavior);
  353. componentManager->addComponent(ant, steering);
  354. componentManager->addComponent(ant, locomotion);
  355. locomotion->surface = surface;
  356. behavior->wanderTriangle = surface;
  357. locomotion->barycentricPosition = barycentricPosition;
  358. }
  359. //EntityID tool0 = createInstanceOf("lens");
  360. int highResolutionDiameter = 3;
  361. int mediumResolutionDiameter = highResolutionDiameter + 2;
  362. int lowResolutionDiameter = 20;
  363. float lowResolutionRadius = static_cast<float>(lowResolutionDiameter) / 2.0f;
  364. float mediumResolutionRadius = static_cast<float>(mediumResolutionDiameter) / 2.0f;
  365. float highResolutionRadius = static_cast<float>(highResolutionDiameter) / 2.0f;
  366. for (int i = 0; i < lowResolutionDiameter; ++i)
  367. {
  368. for (int j = 0; j < lowResolutionDiameter; ++j)
  369. {
  370. EntityID patch;
  371. int x = i - lowResolutionDiameter / 2;
  372. int z = j - lowResolutionDiameter / 2;
  373. if (std::abs(x) < highResolutionRadius && std::abs(z) < highResolutionRadius)
  374. {
  375. patch = createInstanceOf("terrain-patch-high-resolution");
  376. }
  377. else if (std::abs(x) < mediumResolutionRadius && std::abs(z) < mediumResolutionRadius)
  378. {
  379. patch = createInstanceOf("terrain-patch-medium-resolution");
  380. }
  381. else
  382. {
  383. patch = createInstanceOf("terrain-patch-low-resolution");
  384. }
  385. setTerrainPatchPosition(patch, {x, z});
  386. }
  387. }
  388. changeState(sandboxState);
  389. }
  390. void Game::update(float t, float dt)
  391. {
  392. this->time = t;
  393. // Execute current state
  394. if (currentState != nullptr)
  395. {
  396. currentState->execute();
  397. }
  398. // Update systems
  399. systemManager->update(t, dt);
  400. // Update animations
  401. animator.animate(dt);
  402. if (fpsLabel->isVisible())
  403. {
  404. std::stringstream stream;
  405. stream.precision(2);
  406. stream << std::fixed << (performanceSampler.getMeanFrameDuration() * 1000.0f);
  407. fpsLabel->setText(stream.str());
  408. }
  409. uiRootElement->update();
  410. }
  411. void Game::input()
  412. {
  413. controls.update();
  414. }
  415. void Game::render()
  416. {
  417. // Perform sub-frame interpolation on UI elements
  418. uiRootElement->interpolate(stepScheduler.getScheduledSubsteps());
  419. // Update and batch UI elements
  420. uiBatcher->batch(uiBatch, uiRootElement);
  421. // Perform sub-frame interpolation particles
  422. particleSystem->getBillboardBatch()->interpolate(stepScheduler.getScheduledSubsteps());
  423. particleSystem->getBillboardBatch()->batch();
  424. // Render scene
  425. renderer.render(*worldScene);
  426. renderer.render(*uiScene);
  427. if (screenshotQueued)
  428. {
  429. screenshot();
  430. screenshotQueued = false;
  431. }
  432. // Swap window framebuffers
  433. window->swapBuffers();
  434. }
  435. void Game::exit()
  436. {}
  437. void Game::handleEvent(const WindowResizedEvent& event)
  438. {
  439. w = event.width;
  440. h = event.height;
  441. defaultRenderTarget.width = event.width;
  442. defaultRenderTarget.height = event.height;
  443. glViewport(0, 0, event.width, event.height);
  444. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  445. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  446. resizeUI(event.width, event.height);
  447. }
  448. void Game::handleEvent(const GamepadConnectedEvent& event)
  449. {
  450. // Unmap all controls
  451. inputRouter->reset();
  452. // Reload control profile
  453. loadControlProfile();
  454. }
  455. void Game::handleEvent(const GamepadDisconnectedEvent& event)
  456. {}
  457. void Game::setupDebugging()
  458. {
  459. // Setup performance sampling
  460. performanceSampler.setSampleSize(30);
  461. // Disable wireframe drawing
  462. wireframe = false;
  463. }
  464. void Game::setupLocalization()
  465. {
  466. // Load strings
  467. loadStrings();
  468. // Determine number of available languages
  469. languageCount = (*stringTable)[0].size() - 1;
  470. // Match language code with language index
  471. languageIndex = 0;
  472. CSVRow* languageCodes = &(*stringTable)[0];
  473. for (std::size_t i = 1; i < languageCodes->size(); ++i)
  474. {
  475. if (language == (*languageCodes)[i])
  476. {
  477. languageIndex = i - 1;
  478. break;
  479. }
  480. }
  481. }
  482. void Game::setupWindow()
  483. {
  484. // Get display resolution
  485. const Display* display = deviceManager->getDisplays()->front();
  486. int displayWidth = std::get<0>(display->getDimensions());
  487. int displayHeight = std::get<1>(display->getDimensions());
  488. if (fullscreen)
  489. {
  490. w = static_cast<int>(fullscreenResolution.x);
  491. h = static_cast<int>(fullscreenResolution.y);
  492. }
  493. else
  494. {
  495. w = static_cast<int>(windowedResolution.x);
  496. h = static_cast<int>(windowedResolution.y);
  497. }
  498. // Determine window position
  499. int x = std::get<0>(display->getPosition()) + displayWidth / 2 - w / 2;
  500. int y = std::get<1>(display->getPosition()) + displayHeight / 2 - h / 2;
  501. // Read title string
  502. std::string title = getString(getLanguageIndex(), "title");
  503. // Create window
  504. window = windowManager->createWindow(title.c_str(), x, y, w, h, fullscreen, WindowFlag::RESIZABLE);
  505. if (!window)
  506. {
  507. throw std::runtime_error("Game::Game(): Failed to create window.");
  508. }
  509. // Set v-sync mode
  510. window->setVSync(vsync);
  511. }
  512. void Game::setupGraphics()
  513. {
  514. // Setup OpenGL
  515. glEnable(GL_MULTISAMPLE);
  516. // Setup default render target
  517. defaultRenderTarget.width = w;
  518. defaultRenderTarget.height = h;
  519. defaultRenderTarget.framebuffer = 0;
  520. // Set shadow map resolution
  521. shadowMapResolution = 4096;
  522. // Setup shadow map framebuffer
  523. glGenFramebuffers(1, &shadowMapFramebuffer);
  524. glBindFramebuffer(GL_FRAMEBUFFER, shadowMapFramebuffer);
  525. glGenTextures(1, &shadowMapDepthTextureID);
  526. glBindTexture(GL_TEXTURE_2D, shadowMapDepthTextureID);
  527. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadowMapResolution, shadowMapResolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
  528. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  529. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  530. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  531. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  532. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  533. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  534. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMapDepthTextureID, 0);
  535. glDrawBuffer(GL_NONE);
  536. glReadBuffer(GL_NONE);
  537. glBindTexture(GL_TEXTURE_2D, 0);
  538. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  539. // Setup shadow map render target
  540. shadowMapRenderTarget.width = shadowMapResolution;
  541. shadowMapRenderTarget.height = shadowMapResolution;
  542. shadowMapRenderTarget.framebuffer = shadowMapFramebuffer;
  543. // Setup shadow map depth texture
  544. shadowMapDepthTexture.setTextureID(shadowMapDepthTextureID);
  545. shadowMapDepthTexture.setWidth(shadowMapResolution);
  546. shadowMapDepthTexture.setHeight(shadowMapResolution);
  547. // Setup silhouette framebuffer
  548. glGenTextures(1, &silhouetteRenderTarget.texture);
  549. glBindTexture(GL_TEXTURE_2D, silhouetteRenderTarget.texture);
  550. glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
  551. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  552. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  553. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  554. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  555. glGenFramebuffers(1, &silhouetteRenderTarget.framebuffer);
  556. glBindFramebuffer(GL_FRAMEBUFFER, silhouetteRenderTarget.framebuffer);
  557. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, silhouetteRenderTarget.texture, 0);
  558. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  559. glReadBuffer(GL_NONE);
  560. glBindTexture(GL_TEXTURE_2D, 0);
  561. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  562. // Setup silhouette render target
  563. silhouetteRenderTarget.width = w;
  564. silhouetteRenderTarget.height = h;
  565. // Setup shadow map render pass
  566. shadowMapPass = new ShadowMapRenderPass(resourceManager);
  567. shadowMapPass->setRenderTarget(&shadowMapRenderTarget);
  568. shadowMapPass->setViewCamera(&camera);
  569. shadowMapPass->setLightCamera(&sunlightCamera);
  570. // Setup shadow map compositor
  571. shadowMapCompositor.addPass(shadowMapPass);
  572. shadowMapCompositor.load(nullptr);
  573. // Setup clear render pass
  574. clearPass = new ClearRenderPass();
  575. clearPass->setRenderTarget(&defaultRenderTarget);
  576. clearPass->setClear(true, true, false);
  577. clearPass->setClearColor(Vector4(0.0f));
  578. clearPass->setClearDepth(1.0f);
  579. // Setup sky render pass
  580. skyPass = new SkyRenderPass(resourceManager);
  581. skyPass->setRenderTarget(&defaultRenderTarget);
  582. // Setup lighting pass
  583. lightingPass = new LightingRenderPass(resourceManager);
  584. lightingPass->setRenderTarget(&defaultRenderTarget);
  585. lightingPass->setShadowMapPass(shadowMapPass);
  586. lightingPass->setShadowMap(&shadowMapDepthTexture);
  587. // Setup clear silhouette pass
  588. clearSilhouettePass = new ClearRenderPass();
  589. clearSilhouettePass->setRenderTarget(&silhouetteRenderTarget);
  590. clearSilhouettePass->setClear(true, false, false);
  591. clearSilhouettePass->setClearColor(Vector4(0.0f));
  592. // Setup silhouette pass
  593. silhouettePass = new SilhouetteRenderPass(resourceManager);
  594. silhouettePass->setRenderTarget(&silhouetteRenderTarget);
  595. // Setup final pass
  596. finalPass = new FinalRenderPass(resourceManager);
  597. finalPass->setRenderTarget(&defaultRenderTarget);
  598. finalPass->setSilhouetteRenderTarget(&silhouetteRenderTarget);
  599. // Setup default compositor
  600. defaultCompositor.addPass(clearPass);
  601. defaultCompositor.addPass(skyPass);
  602. defaultCompositor.addPass(lightingPass);
  603. defaultCompositor.addPass(clearSilhouettePass);
  604. defaultCompositor.addPass(silhouettePass);
  605. //defaultCompositor.addPass(finalPass);
  606. defaultCompositor.load(nullptr);
  607. // Setup UI render pass
  608. uiPass = new UIRenderPass(resourceManager);
  609. uiPass->setRenderTarget(&defaultRenderTarget);
  610. // Setup UI compositor
  611. uiCompositor.addPass(uiPass);
  612. uiCompositor.load(nullptr);
  613. // Create scenes
  614. worldScene = new Scene(&stepInterpolator);
  615. uiScene = new Scene(&stepInterpolator);
  616. // Setup camera
  617. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  618. camera.lookAt(Vector3(0.0f, 4.0f, 2.0f), Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f));
  619. camera.setCompositor(&defaultCompositor);
  620. camera.setCompositeIndex(1);
  621. worldScene->addObject(&camera);
  622. // Setup sun
  623. sunlight.setDirection(Vector3(0, -1, 0));
  624. setTimeOfDay(11.0f);
  625. worldScene->addObject(&sunlight);
  626. // Setup sunlight camera
  627. sunlightCamera.setOrthographic(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
  628. sunlightCamera.setCompositor(&shadowMapCompositor);
  629. sunlightCamera.setCompositeIndex(0);
  630. sunlightCamera.setCullingEnabled(true);
  631. sunlightCamera.setCullingMask(&camera.getViewFrustum());
  632. worldScene->addObject(&sunlightCamera);
  633. }
  634. void Game::setupUI()
  635. {
  636. // Get DPI and convert font size to pixels
  637. const Display* display = deviceManager->getDisplays()->front();
  638. dpi = display->getDPI();
  639. fontSizePX = fontSizePT * (1.0f / 72.0f) * dpi;
  640. // Load label typeface
  641. labelTypeface = resourceManager->load<Typeface>("caveat-bold.ttf");
  642. labelFont = labelTypeface->createFont(fontSizePX);
  643. // Load debugging typeface
  644. debugTypeface = resourceManager->load<Typeface>("inconsolata-bold.ttf");
  645. debugFont = debugTypeface->createFont(fontSizePX);
  646. debugTypeface->loadCharset(debugFont, UnicodeRange::BASIC_LATIN);
  647. // Character set test
  648. std::set<char32_t> charset;
  649. charset.emplace(U'A');
  650. labelTypeface->loadCharset(labelFont, UnicodeRange::BASIC_LATIN);
  651. labelTypeface->loadCharset(labelFont, charset);
  652. // Load splash screen texture
  653. splashTexture = resourceManager->load<Texture2D>("epigraph.png");
  654. // Load HUD texture
  655. hudSpriteSheetTexture = resourceManager->load<Texture2D>("hud.png");
  656. // Read texture atlas file
  657. CSVTable* atlasTable = resourceManager->load<CSVTable>("hud-atlas.csv");
  658. // Build texture atlas
  659. for (int row = 0; row < atlasTable->size(); ++row)
  660. {
  661. std::stringstream ss;
  662. float x;
  663. float y;
  664. float w;
  665. float h;
  666. ss << (*atlasTable)[row][1];
  667. ss >> x;
  668. ss.str(std::string());
  669. ss.clear();
  670. ss << (*atlasTable)[row][2];
  671. ss >> y;
  672. ss.str(std::string());
  673. ss.clear();
  674. ss << (*atlasTable)[row][3];
  675. ss >> w;
  676. ss.str(std::string());
  677. ss.clear();
  678. ss << (*atlasTable)[row][4];
  679. ss >> h;
  680. ss.str(std::string());
  681. y = static_cast<float>(hudSpriteSheetTexture->getHeight()) - y - h;
  682. x = (int)(x + 0.5f);
  683. y = (int)(y + 0.5f);
  684. w = (int)(w + 0.5f);
  685. h = (int)(h + 0.5f);
  686. hudTextureAtlas.insert((*atlasTable)[row][0], Rect(Vector2(x, y), Vector2(x + w, y + h)));
  687. }
  688. // Setup UI batching
  689. uiBatch = new BillboardBatch();
  690. uiBatch->resize(1024);
  691. uiBatcher = new UIBatcher();
  692. // Setup root UI element
  693. uiRootElement = new UIContainer();
  694. eventDispatcher.subscribe<MouseMovedEvent>(uiRootElement);
  695. eventDispatcher.subscribe<MouseButtonPressedEvent>(uiRootElement);
  696. eventDispatcher.subscribe<MouseButtonReleasedEvent>(uiRootElement);
  697. // Create splash screen background element
  698. splashBackgroundImage = new UIImage();
  699. splashBackgroundImage->setLayerOffset(-1);
  700. splashBackgroundImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  701. splashBackgroundImage->setVisible(false);
  702. uiRootElement->addChild(splashBackgroundImage);
  703. // Create splash screen element
  704. splashImage = new UIImage();
  705. splashImage->setTexture(splashTexture);
  706. splashImage->setVisible(false);
  707. uiRootElement->addChild(splashImage);
  708. Rect hudTextureAtlasBounds(Vector2(0), Vector2(hudSpriteSheetTexture->getWidth(), hudSpriteSheetTexture->getHeight()));
  709. auto normalizeTextureBounds = [](const Rect& texture, const Rect& atlas)
  710. {
  711. Vector2 atlasDimensions = Vector2(atlas.getWidth(), atlas.getHeight());
  712. return Rect(texture.getMin() / atlasDimensions, texture.getMax() / atlasDimensions);
  713. };
  714. // Create HUD elements
  715. hudContainer = new UIContainer();
  716. hudContainer->setVisible(false);
  717. uiRootElement->addChild(hudContainer);
  718. toolIndicatorBGImage = new UIImage();
  719. toolIndicatorBGImage->setTexture(hudSpriteSheetTexture);
  720. toolIndicatorBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds));
  721. hudContainer->addChild(toolIndicatorBGImage);
  722. toolIndicatorsBounds = new Rect[8];
  723. toolIndicatorsBounds[0] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-brush"), hudTextureAtlasBounds);
  724. toolIndicatorsBounds[1] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-spade"), hudTextureAtlasBounds);
  725. toolIndicatorsBounds[2] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-lens"), hudTextureAtlasBounds);
  726. toolIndicatorsBounds[3] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-test-tube"), hudTextureAtlasBounds);
  727. toolIndicatorsBounds[4] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-forceps"), hudTextureAtlasBounds);
  728. toolIndicatorsBounds[5] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  729. toolIndicatorsBounds[6] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  730. toolIndicatorsBounds[7] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  731. toolIndicatorIconImage = new UIImage();
  732. toolIndicatorIconImage->setTexture(hudSpriteSheetTexture);
  733. toolIndicatorIconImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  734. toolIndicatorBGImage->addChild(toolIndicatorIconImage);
  735. buttonContainer = new UIContainer();
  736. hudContainer->addChild(buttonContainer);
  737. playButtonBGImage = new UIImage();
  738. playButtonBGImage->setTexture(hudSpriteSheetTexture);
  739. playButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  740. //buttonContainer->addChild(playButtonBGImage);
  741. pauseButtonBGImage = new UIImage();
  742. pauseButtonBGImage->setTexture(hudSpriteSheetTexture);
  743. pauseButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  744. //buttonContainer->addChild(pauseButtonBGImage);
  745. fastForwardButtonBGImage = new UIImage();
  746. fastForwardButtonBGImage->setTexture(hudSpriteSheetTexture);
  747. fastForwardButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  748. //buttonContainer->addChild(fastForwardButtonBGImage);
  749. playButtonImage = new UIImage();
  750. playButtonImage->setTexture(hudSpriteSheetTexture);
  751. playButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-play"), hudTextureAtlasBounds));
  752. //buttonContainer->addChild(playButtonImage);
  753. fastForwardButtonImage = new UIImage();
  754. fastForwardButtonImage->setTexture(hudSpriteSheetTexture);
  755. fastForwardButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-fast-forward-2x"), hudTextureAtlasBounds));
  756. //buttonContainer->addChild(fastForwardButtonImage);
  757. pauseButtonImage = new UIImage();
  758. pauseButtonImage->setTexture(hudSpriteSheetTexture);
  759. pauseButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-pause"), hudTextureAtlasBounds));
  760. //buttonContainer->addChild(pauseButtonImage);
  761. radialMenuContainer = new UIContainer();
  762. radialMenuContainer->setVisible(false);
  763. uiRootElement->addChild(radialMenuContainer);
  764. radialMenuBackgroundImage = new UIImage();
  765. radialMenuBackgroundImage->setTintColor(Vector4(Vector3(0.0f), 0.25f));
  766. radialMenuContainer->addChild(radialMenuBackgroundImage);
  767. radialMenuImage = new UIImage();
  768. radialMenuImage->setTexture(hudSpriteSheetTexture);
  769. radialMenuImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu"), hudTextureAtlasBounds));
  770. radialMenuContainer->addChild(radialMenuImage);
  771. radialMenuSelectorImage = new UIImage();
  772. radialMenuSelectorImage->setTexture(hudSpriteSheetTexture);
  773. radialMenuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu-selector"), hudTextureAtlasBounds));
  774. radialMenuContainer->addChild(radialMenuSelectorImage);
  775. toolIconBrushImage = new UIImage();
  776. toolIconBrushImage->setTexture(hudSpriteSheetTexture);
  777. toolIconBrushImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  778. radialMenuImage->addChild(toolIconBrushImage);
  779. toolIconLensImage = new UIImage();
  780. toolIconLensImage->setTexture(hudSpriteSheetTexture);
  781. toolIconLensImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-lens"), hudTextureAtlasBounds));
  782. radialMenuImage->addChild(toolIconLensImage);
  783. toolIconForcepsImage = new UIImage();
  784. toolIconForcepsImage->setTexture(hudSpriteSheetTexture);
  785. toolIconForcepsImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-forceps"), hudTextureAtlasBounds));
  786. radialMenuImage->addChild(toolIconForcepsImage);
  787. toolIconSpadeImage = new UIImage();
  788. toolIconSpadeImage->setTexture(hudSpriteSheetTexture);
  789. toolIconSpadeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-spade"), hudTextureAtlasBounds));
  790. //radialMenuImage->addChild(toolIconSpadeImage);
  791. toolIconCameraImage = new UIImage();
  792. toolIconCameraImage->setTexture(hudSpriteSheetTexture);
  793. toolIconCameraImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-camera"), hudTextureAtlasBounds));
  794. radialMenuImage->addChild(toolIconCameraImage);
  795. toolIconMicrochipImage = new UIImage();
  796. toolIconMicrochipImage->setTexture(hudSpriteSheetTexture);
  797. toolIconMicrochipImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-microchip"), hudTextureAtlasBounds));
  798. radialMenuImage->addChild(toolIconMicrochipImage);
  799. toolIconTestTubeImage = new UIImage();
  800. toolIconTestTubeImage->setTexture(hudSpriteSheetTexture);
  801. toolIconTestTubeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-test-tube"), hudTextureAtlasBounds));
  802. //radialMenuImage->addChild(toolIconTestTubeImage);
  803. antTag = new UIContainer();
  804. antTag->setLayerOffset(-10);
  805. antTag->setVisible(false);
  806. uiRootElement->addChild(antTag);
  807. antLabelContainer = new UIContainer();
  808. antTag->addChild(antLabelContainer);
  809. antLabelTL = new UIImage();
  810. antLabelTR = new UIImage();
  811. antLabelBL = new UIImage();
  812. antLabelBR = new UIImage();
  813. antLabelCC = new UIImage();
  814. antLabelCT = new UIImage();
  815. antLabelCB = new UIImage();
  816. antLabelCL = new UIImage();
  817. antLabelCR = new UIImage();
  818. antLabelTL->setTexture(hudSpriteSheetTexture);
  819. antLabelTR->setTexture(hudSpriteSheetTexture);
  820. antLabelBL->setTexture(hudSpriteSheetTexture);
  821. antLabelBR->setTexture(hudSpriteSheetTexture);
  822. antLabelCC->setTexture(hudSpriteSheetTexture);
  823. antLabelCT->setTexture(hudSpriteSheetTexture);
  824. antLabelCB->setTexture(hudSpriteSheetTexture);
  825. antLabelCL->setTexture(hudSpriteSheetTexture);
  826. antLabelCR->setTexture(hudSpriteSheetTexture);
  827. Rect labelTLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tl"), hudTextureAtlasBounds);
  828. Rect labelTRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tr"), hudTextureAtlasBounds);
  829. Rect labelBLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-bl"), hudTextureAtlasBounds);
  830. Rect labelBRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-br"), hudTextureAtlasBounds);
  831. Rect labelCCBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cc"), hudTextureAtlasBounds);
  832. Rect labelCTBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-ct"), hudTextureAtlasBounds);
  833. Rect labelCBBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cb"), hudTextureAtlasBounds);
  834. Rect labelCLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cl"), hudTextureAtlasBounds);
  835. Rect labelCRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cr"), hudTextureAtlasBounds);
  836. Vector2 labelTLMin = labelTLBounds.getMin();
  837. Vector2 labelTRMin = labelTRBounds.getMin();
  838. Vector2 labelBLMin = labelBLBounds.getMin();
  839. Vector2 labelBRMin = labelBRBounds.getMin();
  840. Vector2 labelCCMin = labelCCBounds.getMin();
  841. Vector2 labelCTMin = labelCTBounds.getMin();
  842. Vector2 labelCBMin = labelCBBounds.getMin();
  843. Vector2 labelCLMin = labelCLBounds.getMin();
  844. Vector2 labelCRMin = labelCRBounds.getMin();
  845. Vector2 labelTLMax = labelTLBounds.getMax();
  846. Vector2 labelTRMax = labelTRBounds.getMax();
  847. Vector2 labelBLMax = labelBLBounds.getMax();
  848. Vector2 labelBRMax = labelBRBounds.getMax();
  849. Vector2 labelCCMax = labelCCBounds.getMax();
  850. Vector2 labelCTMax = labelCTBounds.getMax();
  851. Vector2 labelCBMax = labelCBBounds.getMax();
  852. Vector2 labelCLMax = labelCLBounds.getMax();
  853. Vector2 labelCRMax = labelCRBounds.getMax();
  854. antLabelTL->setTextureBounds(labelTLBounds);
  855. antLabelTR->setTextureBounds(labelTRBounds);
  856. antLabelBL->setTextureBounds(labelBLBounds);
  857. antLabelBR->setTextureBounds(labelBRBounds);
  858. antLabelCC->setTextureBounds(labelCCBounds);
  859. antLabelCT->setTextureBounds(labelCTBounds);
  860. antLabelCB->setTextureBounds(labelCBBounds);
  861. antLabelCL->setTextureBounds(labelCLBounds);
  862. antLabelCR->setTextureBounds(labelCRBounds);
  863. antLabelContainer->addChild(antLabelTL);
  864. antLabelContainer->addChild(antLabelTR);
  865. antLabelContainer->addChild(antLabelBL);
  866. antLabelContainer->addChild(antLabelBR);
  867. antLabelContainer->addChild(antLabelCC);
  868. antLabelContainer->addChild(antLabelCT);
  869. antLabelContainer->addChild(antLabelCB);
  870. antLabelContainer->addChild(antLabelCL);
  871. antLabelContainer->addChild(antLabelCR);
  872. antLabel = new UILabel();
  873. antLabel->setFont(labelFont);
  874. antLabel->setText("Boggy B.");
  875. antLabel->setTintColor(Vector4(Vector3(0.0f), 1.0f));
  876. antLabel->setLayerOffset(1);
  877. antLabelContainer->addChild(antLabel);
  878. fpsLabel = new UILabel();
  879. fpsLabel->setFont(debugFont);
  880. fpsLabel->setTintColor(Vector4(1, 1, 0, 1));
  881. fpsLabel->setLayerOffset(50);
  882. fpsLabel->setAnchor(Anchor::TOP_LEFT);
  883. uiRootElement->addChild(fpsLabel);
  884. antPin = new UIImage();
  885. antPin->setTexture(hudSpriteSheetTexture);
  886. antPin->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin"), hudTextureAtlasBounds));
  887. antTag->addChild(antPin);
  888. antLabelPinHole = new UIImage();
  889. antLabelPinHole->setTexture(hudSpriteSheetTexture);
  890. antLabelPinHole->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin-hole"), hudTextureAtlasBounds));
  891. antLabelContainer->addChild(antLabelPinHole);
  892. // Construct box selection
  893. boxSelectionImageBackground = new UIImage();
  894. boxSelectionImageBackground->setAnchor(Anchor::CENTER);
  895. boxSelectionImageTop = new UIImage();
  896. boxSelectionImageTop->setAnchor(Anchor::TOP_LEFT);
  897. boxSelectionImageBottom = new UIImage();
  898. boxSelectionImageBottom->setAnchor(Anchor::BOTTOM_LEFT);
  899. boxSelectionImageLeft = new UIImage();
  900. boxSelectionImageLeft->setAnchor(Anchor::TOP_LEFT);
  901. boxSelectionImageRight = new UIImage();
  902. boxSelectionImageRight->setAnchor(Anchor::TOP_RIGHT);
  903. boxSelectionContainer = new UIContainer();
  904. boxSelectionContainer->setLayerOffset(80);
  905. boxSelectionContainer->addChild(boxSelectionImageBackground);
  906. boxSelectionContainer->addChild(boxSelectionImageTop);
  907. boxSelectionContainer->addChild(boxSelectionImageBottom);
  908. boxSelectionContainer->addChild(boxSelectionImageLeft);
  909. boxSelectionContainer->addChild(boxSelectionImageRight);
  910. boxSelectionContainer->setVisible(false);
  911. uiRootElement->addChild(boxSelectionContainer);
  912. boxSelectionImageBackground->setTintColor(Vector4(1.0f, 1.0f, 1.0f, 0.5f));
  913. boxSelectionContainer->setTintColor(Vector4(1.0f, 0.0f, 0.0f, 1.0f));
  914. boxSelectionBorderWidth = 2.0f;
  915. cameraGridColor = Vector4(1, 1, 1, 0.5f);
  916. cameraReticleColor = Vector4(1, 1, 1, 0.75f);
  917. cameraGridY0Image = new UIImage();
  918. cameraGridY0Image->setAnchor(Vector2(0.5f, (1.0f / 3.0f)));
  919. cameraGridY0Image->setTintColor(cameraGridColor);
  920. cameraGridY1Image = new UIImage();
  921. cameraGridY1Image->setAnchor(Vector2(0.5f, (2.0f / 3.0f)));
  922. cameraGridY1Image->setTintColor(cameraGridColor);
  923. cameraGridX0Image = new UIImage();
  924. cameraGridX0Image->setAnchor(Vector2((1.0f / 3.0f), 0.5f));
  925. cameraGridX0Image->setTintColor(cameraGridColor);
  926. cameraGridX1Image = new UIImage();
  927. cameraGridX1Image->setAnchor(Vector2((2.0f / 3.0f), 0.5f));
  928. cameraGridX1Image->setTintColor(cameraGridColor);
  929. cameraReticleImage = new UIImage();
  930. cameraReticleImage->setAnchor(Anchor::CENTER);
  931. cameraReticleImage->setTintColor(cameraReticleColor);
  932. cameraReticleImage->setTexture(hudSpriteSheetTexture);
  933. cameraReticleImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("camera-reticle"), hudTextureAtlasBounds));
  934. cameraGridContainer = new UIContainer();
  935. cameraGridContainer->addChild(cameraGridY0Image);
  936. cameraGridContainer->addChild(cameraGridY1Image);
  937. cameraGridContainer->addChild(cameraGridX0Image);
  938. cameraGridContainer->addChild(cameraGridX1Image);
  939. cameraGridContainer->addChild(cameraReticleImage);
  940. cameraGridContainer->setVisible(false);
  941. uiRootElement->addChild(cameraGridContainer);
  942. cameraFlashImage = new UIImage();
  943. cameraFlashImage->setLayerOffset(99);
  944. cameraFlashImage->setTintColor(Vector4(1.0f));
  945. cameraFlashImage->setVisible(false);
  946. uiRootElement->addChild(cameraFlashImage);
  947. blackoutImage = new UIImage();
  948. blackoutImage->setLayerOffset(98);
  949. blackoutImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  950. blackoutImage->setVisible(false);
  951. uiRootElement->addChild(blackoutImage);
  952. // Construct fade-in animation clip
  953. fadeInClip.setInterpolator(easeOutCubic<float>);
  954. AnimationChannel<float>* channel;
  955. channel = fadeInClip.addChannel(0);
  956. channel->insertKeyframe(0.0f, 1.0f);
  957. channel->insertKeyframe(1.0f, 0.0f);
  958. // Construct fade-out animation clip
  959. fadeOutClip.setInterpolator(easeOutCubic<float>);
  960. channel = fadeOutClip.addChannel(0);
  961. channel->insertKeyframe(0.0f, 0.0f);
  962. channel->insertKeyframe(1.0f, 1.0f);
  963. // Setup fade-in animation callbacks
  964. fadeInAnimation.setAnimateCallback
  965. (
  966. [this](std::size_t id, float opacity)
  967. {
  968. Vector3 color = Vector3(blackoutImage->getTintColor());
  969. blackoutImage->setTintColor(Vector4(color, opacity));
  970. }
  971. );
  972. fadeInAnimation.setEndCallback
  973. (
  974. [this]()
  975. {
  976. blackoutImage->setVisible(false);
  977. if (fadeInEndCallback != nullptr)
  978. {
  979. fadeInEndCallback();
  980. }
  981. }
  982. );
  983. // Setup fade-out animation callbacks
  984. fadeOutAnimation.setAnimateCallback
  985. (
  986. [this](std::size_t id, float opacity)
  987. {
  988. Vector3 color = Vector3(blackoutImage->getTintColor());
  989. blackoutImage->setTintColor(Vector4(color, opacity));
  990. }
  991. );
  992. fadeOutAnimation.setEndCallback
  993. (
  994. [this]()
  995. {
  996. blackoutImage->setVisible(false);
  997. if (fadeOutEndCallback != nullptr)
  998. {
  999. fadeOutEndCallback();
  1000. }
  1001. }
  1002. );
  1003. animator.addAnimation(&fadeInAnimation);
  1004. animator.addAnimation(&fadeOutAnimation);
  1005. // Construct camera flash animation clip
  1006. cameraFlashClip.setInterpolator(easeOutQuad<float>);
  1007. channel = cameraFlashClip.addChannel(0);
  1008. channel->insertKeyframe(0.0f, 1.0f);
  1009. channel->insertKeyframe(1.0f, 0.0f);
  1010. // Setup camera flash animation
  1011. float flashDuration = 0.5f;
  1012. cameraFlashAnimation.setSpeed(1.0f / flashDuration);
  1013. cameraFlashAnimation.setLoop(false);
  1014. cameraFlashAnimation.setClip(&cameraFlashClip);
  1015. cameraFlashAnimation.setTimeFrame(cameraFlashClip.getTimeFrame());
  1016. cameraFlashAnimation.setAnimateCallback
  1017. (
  1018. [this](std::size_t id, float opacity)
  1019. {
  1020. cameraFlashImage->setTintColor(Vector4(Vector3(1.0f), opacity));
  1021. }
  1022. );
  1023. cameraFlashAnimation.setStartCallback
  1024. (
  1025. [this]()
  1026. {
  1027. cameraFlashImage->setVisible(true);
  1028. cameraFlashImage->setTintColor(Vector4(1.0f));
  1029. cameraFlashImage->resetTweens();
  1030. }
  1031. );
  1032. cameraFlashAnimation.setEndCallback
  1033. (
  1034. [this]()
  1035. {
  1036. cameraFlashImage->setVisible(false);
  1037. }
  1038. );
  1039. animator.addAnimation(&cameraFlashAnimation);
  1040. // Setup UI scene
  1041. uiScene->addObject(uiBatch);
  1042. uiScene->addObject(&uiCamera);
  1043. // Setup UI camera
  1044. uiCamera.lookAt(Vector3(0), Vector3(0, 0, -1), Vector3(0, 1, 0));
  1045. uiCamera.resetTweens();
  1046. uiCamera.setCompositor(&uiCompositor);
  1047. uiCamera.setCompositeIndex(0);
  1048. uiCamera.setCullingEnabled(false);
  1049. restringUI();
  1050. resizeUI(w, h);
  1051. }
  1052. void Game::setupControls()
  1053. {
  1054. // Get keyboard and mouse
  1055. keyboard = deviceManager->getKeyboards()->front();
  1056. mouse = deviceManager->getMice()->front();
  1057. // Build the master control set
  1058. controls.addControl(&exitControl);
  1059. controls.addControl(&toggleFullscreenControl);
  1060. controls.addControl(&screenshotControl);
  1061. controls.addControl(&menuUpControl);
  1062. controls.addControl(&menuDownControl);
  1063. controls.addControl(&menuLeftControl);
  1064. controls.addControl(&menuRightControl);
  1065. controls.addControl(&menuBackControl);
  1066. controls.addControl(&moveForwardControl);
  1067. controls.addControl(&moveBackControl);
  1068. controls.addControl(&moveLeftControl);
  1069. controls.addControl(&moveRightControl);
  1070. controls.addControl(&zoomInControl);
  1071. controls.addControl(&zoomOutControl);
  1072. controls.addControl(&orbitCCWControl);
  1073. controls.addControl(&orbitCWControl);
  1074. controls.addControl(&adjustCameraControl);
  1075. controls.addControl(&dragCameraControl);
  1076. controls.addControl(&openToolMenuControl);
  1077. controls.addControl(&useToolControl);
  1078. controls.addControl(&toggleEditModeControl);
  1079. controls.addControl(&toggleWireframeControl);
  1080. // Build the system control set
  1081. systemControls.addControl(&exitControl);
  1082. systemControls.addControl(&toggleFullscreenControl);
  1083. systemControls.addControl(&screenshotControl);
  1084. // Build the menu control set
  1085. menuControls.addControl(&menuUpControl);
  1086. menuControls.addControl(&menuDownControl);
  1087. menuControls.addControl(&menuLeftControl);
  1088. menuControls.addControl(&menuRightControl);
  1089. menuControls.addControl(&menuSelectControl);
  1090. menuControls.addControl(&menuBackControl);
  1091. // Build the camera control set
  1092. cameraControls.addControl(&moveForwardControl);
  1093. cameraControls.addControl(&moveBackControl);
  1094. cameraControls.addControl(&moveLeftControl);
  1095. cameraControls.addControl(&moveRightControl);
  1096. cameraControls.addControl(&zoomInControl);
  1097. cameraControls.addControl(&zoomOutControl);
  1098. cameraControls.addControl(&orbitCCWControl);
  1099. cameraControls.addControl(&orbitCWControl);
  1100. cameraControls.addControl(&adjustCameraControl);
  1101. cameraControls.addControl(&dragCameraControl);
  1102. // Build the tool control set
  1103. toolControls.addControl(&openToolMenuControl);
  1104. toolControls.addControl(&useToolControl);
  1105. // Build the editor control set
  1106. editorControls.addControl(&toggleEditModeControl);
  1107. // Setup control callbacks
  1108. exitControl.setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1109. toggleFullscreenControl.setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1110. screenshotControl.setActivatedCallback(std::bind(&Game::queueScreenshot, this));
  1111. toggleWireframeControl.setActivatedCallback(std::bind(&Game::toggleWireframe, this));
  1112. // Build map of control names
  1113. controlNameMap["exit"] = &exitControl;
  1114. controlNameMap["toggle-fullscreen"] = &toggleFullscreenControl;
  1115. controlNameMap["screenshot"] = &screenshotControl;
  1116. controlNameMap["menu-up"] = &menuUpControl;
  1117. controlNameMap["menu-down"] = &menuDownControl;
  1118. controlNameMap["menu-left"] = &menuLeftControl;
  1119. controlNameMap["menu-right"] = &menuRightControl;
  1120. controlNameMap["menu-back"] = &menuBackControl;
  1121. controlNameMap["move-forward"] = &moveForwardControl;
  1122. controlNameMap["move-back"] = &moveBackControl;
  1123. controlNameMap["move-left"] = &moveLeftControl;
  1124. controlNameMap["move-right"] = &moveRightControl;
  1125. controlNameMap["zoom-in"] = &zoomInControl;
  1126. controlNameMap["zoom-out"] = &zoomOutControl;
  1127. controlNameMap["orbit-ccw"] = &orbitCCWControl;
  1128. controlNameMap["orbit-cw"] = &orbitCWControl;
  1129. controlNameMap["adjust-camera"] = &adjustCameraControl;
  1130. controlNameMap["drag-camera"] = &dragCameraControl;
  1131. controlNameMap["open-tool-menu"] = &openToolMenuControl;
  1132. controlNameMap["use-tool"] = &useToolControl;
  1133. controlNameMap["toggle-edit-mode"] = &toggleEditModeControl;
  1134. controlNameMap["toggle-wireframe"] = &toggleWireframeControl;
  1135. // Load control profile
  1136. loadControlProfile();
  1137. // Setup input mapper
  1138. inputMapper = new InputMapper(&eventDispatcher);
  1139. inputMapper->setCallback(std::bind(&Game::mapInput, this, std::placeholders::_1));
  1140. inputMapper->setControl(nullptr);
  1141. inputMapper->setEnabled(false);
  1142. }
  1143. void Game::setupGameplay()
  1144. {
  1145. // Setup step scheduler
  1146. double maxFrameDuration = 0.25;
  1147. double stepFrequency = 60.0;
  1148. stepScheduler.setMaxFrameDuration(maxFrameDuration);
  1149. stepScheduler.setStepFrequency(stepFrequency);
  1150. timestep = stepScheduler.getStepPeriod();
  1151. // Setup camera rigs
  1152. cameraRig = nullptr;
  1153. orbitCam = new OrbitCam();
  1154. orbitCam->attachCamera(&camera);
  1155. freeCam = new FreeCam();
  1156. freeCam->attachCamera(&camera);
  1157. }
  1158. void Game::resetSettings()
  1159. {
  1160. // Set default language
  1161. language = "en-us";
  1162. // Set default resolutions
  1163. const Display* display = deviceManager->getDisplays()->front();
  1164. int displayWidth = std::get<0>(display->getDimensions());
  1165. int displayHeight = std::get<1>(display->getDimensions());
  1166. float windowedResolutionRatio = 5.0f / 6.0f;
  1167. windowedResolution = Vector2(displayWidth, displayHeight) * 5.0f / 6.0f;
  1168. windowedResolution.x = static_cast<int>(windowedResolution.x);
  1169. windowedResolution.y = static_cast<int>(windowedResolution.y);
  1170. fullscreenResolution = Vector2(displayWidth, displayHeight);
  1171. // Set default fullscreen mode
  1172. fullscreen = false;
  1173. // Set default vsync mode
  1174. vsync = true;
  1175. // Set default font size
  1176. fontSizePT = 14.0f;
  1177. // Set default control profile name
  1178. controlProfileName = "default-controls";
  1179. }
  1180. void Game::loadSettings()
  1181. {
  1182. // Reset settings to default values
  1183. resetSettings();
  1184. // Load settings table
  1185. try
  1186. {
  1187. settingsTable = resourceManager->load<CSVTable>("settings.csv");
  1188. }
  1189. catch (const std::exception& e)
  1190. {
  1191. settingsTable = new CSVTable();
  1192. }
  1193. // Build settings map
  1194. for (std::size_t i = 0; i < settingsTable->size(); ++i)
  1195. {
  1196. const CSVRow& row = (*settingsTable)[i];
  1197. settingsMap[row[0]] = i;
  1198. }
  1199. // Read settings from table
  1200. readSetting("language", &language);
  1201. readSetting("windowed-resolution", &windowedResolution);
  1202. readSetting("fullscreen-resolution", &fullscreenResolution);
  1203. readSetting("fullscreen", &fullscreen);
  1204. readSetting("vsync", &vsync);
  1205. readSetting("font-size", &fontSizePT);
  1206. readSetting("control-profile", &controlProfileName);
  1207. }
  1208. void Game::saveSettings()
  1209. {}
  1210. void Game::loadStrings()
  1211. {
  1212. // Read strings file
  1213. stringTable = resourceManager->load<CSVTable>("strings.csv");
  1214. // Build string map
  1215. for (int row = 0; row < stringTable->size(); ++row)
  1216. {
  1217. stringMap[(*stringTable)[row][0]] = row;
  1218. }
  1219. }
  1220. void Game::loadControlProfile()
  1221. {
  1222. // Load control profile
  1223. std::string controlProfilePath = controlProfileName + ".csv";
  1224. CSVTable* controlProfile = resourceManager->load<CSVTable>(controlProfilePath);
  1225. for (const CSVRow& row: *controlProfile)
  1226. {
  1227. // Skip empty rows and comments
  1228. if (row.empty() || row[0].empty() || row[0][0] == '#')
  1229. {
  1230. continue;
  1231. }
  1232. // Get control name
  1233. const std::string& controlName = row[0];
  1234. // Lookup control in control name map
  1235. auto it = controlNameMap.find(controlName);
  1236. if (it == controlNameMap.end())
  1237. {
  1238. std::cerr << "Game::loadControlProfile(): Unknown control name \"" << controlName << "\"" << std::endl;
  1239. continue;
  1240. }
  1241. // Get pointer to the control
  1242. Control* control = it->second;
  1243. // Determine type of input mapping
  1244. const std::string& deviceType = row[1];
  1245. if (deviceType == "keyboard")
  1246. {
  1247. const std::string& eventType = row[2];
  1248. const std::string& scancodeName = row[3];
  1249. // Get scancode from string
  1250. Scancode scancode = Keyboard::getScancodeFromName(scancodeName.c_str());
  1251. // Map control
  1252. if (scancode != Scancode::UNKNOWN)
  1253. {
  1254. inputRouter->addMapping(KeyMapping(control, keyboard, scancode));
  1255. }
  1256. }
  1257. else if (deviceType == "mouse")
  1258. {
  1259. const std::string& eventType = row[2];
  1260. if (eventType == "motion")
  1261. {
  1262. const std::string& axisName = row[3];
  1263. // Get axis from string
  1264. MouseMotionAxis axis;
  1265. bool negative = (axisName.find('-') != std::string::npos);
  1266. if (axisName.find('x') != std::string::npos)
  1267. {
  1268. axis = (negative) ? MouseMotionAxis::NEGATIVE_X : MouseMotionAxis::POSITIVE_X;
  1269. }
  1270. else if (axisName.find('y') != std::string::npos)
  1271. {
  1272. axis = (negative) ? MouseMotionAxis::NEGATIVE_Y : MouseMotionAxis::POSITIVE_Y;
  1273. }
  1274. else
  1275. {
  1276. std::cerr << "Game::loadControlProfile(): Unknown mouse motion axis \"" << axisName << "\"" << std::endl;
  1277. continue;
  1278. }
  1279. // Map control
  1280. inputRouter->addMapping(MouseMotionMapping(control, mouse, axis));
  1281. }
  1282. else if (eventType == "wheel")
  1283. {
  1284. const std::string& axisName = row[3];
  1285. // Get axis from string
  1286. MouseWheelAxis axis;
  1287. bool negative = (axisName.find('-') != std::string::npos);
  1288. if (axisName.find('x') != std::string::npos)
  1289. {
  1290. axis = (negative) ? MouseWheelAxis::NEGATIVE_X : MouseWheelAxis::POSITIVE_X;
  1291. }
  1292. else if (axisName.find('y') != std::string::npos)
  1293. {
  1294. axis = (negative) ? MouseWheelAxis::NEGATIVE_Y : MouseWheelAxis::POSITIVE_Y;
  1295. }
  1296. else
  1297. {
  1298. std::cerr << "Game::loadControlProfile(): Unknown mouse wheel axis \"" << axisName << "\"" << std::endl;
  1299. continue;
  1300. }
  1301. // Map control
  1302. inputRouter->addMapping(MouseWheelMapping(control, mouse, axis));
  1303. }
  1304. else if (eventType == "button")
  1305. {
  1306. const std::string& buttonName = row[3];
  1307. // Get button from string
  1308. int button;
  1309. std::stringstream stream;
  1310. stream << buttonName;
  1311. stream >> button;
  1312. // Map control
  1313. inputRouter->addMapping(MouseButtonMapping(control, mouse, button));
  1314. }
  1315. else
  1316. {
  1317. std::cerr << "Game::loadControlProfile(): Unknown mouse event type \"" << eventType << "\"" << std::endl;
  1318. continue;
  1319. }
  1320. }
  1321. else if (deviceType == "gamepad")
  1322. {
  1323. const std::string& eventType = row[2];
  1324. if (eventType == "axis")
  1325. {
  1326. std::string axisName = row[3];
  1327. // Determine whether axis is negative or positive
  1328. bool negative = (axisName.find('-') != std::string::npos);
  1329. // Remove sign from axis name
  1330. std::size_t plusPosition = axisName.find('+');
  1331. std::size_t minusPosition = axisName.find('-');
  1332. if (plusPosition != std::string::npos)
  1333. {
  1334. axisName.erase(plusPosition);
  1335. }
  1336. else if (minusPosition != std::string::npos)
  1337. {
  1338. axisName.erase(minusPosition);
  1339. }
  1340. // Get axis from string
  1341. int axis;
  1342. std::stringstream stream;
  1343. stream << axisName;
  1344. stream >> axis;
  1345. // Map control to each gamepad
  1346. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1347. for (Gamepad* gamepad: *gamepads)
  1348. {
  1349. inputRouter->addMapping(GamepadAxisMapping(control, gamepad, axis, negative));
  1350. }
  1351. }
  1352. else if (eventType == "button")
  1353. {
  1354. const std::string& buttonName = row[3];
  1355. // Get button from string
  1356. int button;
  1357. std::stringstream stream;
  1358. stream << buttonName;
  1359. stream >> button;
  1360. // Map control to each gamepad
  1361. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1362. for (Gamepad* gamepad: *gamepads)
  1363. {
  1364. inputRouter->addMapping(GamepadButtonMapping(control, gamepad, button));
  1365. }
  1366. }
  1367. else
  1368. {
  1369. std::cerr << "Game::loadControlProfile(): Unknown gamepad event type \"" << eventType << "\"" << std::endl;
  1370. continue;
  1371. }
  1372. }
  1373. else
  1374. {
  1375. std::cerr << "Game::loadControlProfile(): Unknown input device type \"" << deviceType << "\"" << std::endl;
  1376. continue;
  1377. }
  1378. }
  1379. }
  1380. void Game::saveControlProfile()
  1381. {
  1382. // Build control profile CSV table
  1383. CSVTable* table = new CSVTable();
  1384. for (auto it = controlNameMap.begin(); it != controlNameMap.end(); ++it)
  1385. {
  1386. // Get control name
  1387. const std::string& controlName = it->first;
  1388. // Get pointer to the control
  1389. Control* control = it->second;
  1390. // Look up list of mappings for the control
  1391. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  1392. if (!mappings)
  1393. {
  1394. continue;
  1395. }
  1396. // For each input mapping
  1397. for (const InputMapping* mapping: *mappings)
  1398. {
  1399. // Add row to the table
  1400. table->push_back(CSVRow());
  1401. CSVRow* row = &table->back();
  1402. // Add control name column
  1403. row->push_back(controlName);
  1404. switch (mapping->getType())
  1405. {
  1406. case InputMappingType::KEY:
  1407. {
  1408. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  1409. row->push_back("keyboard");
  1410. row->push_back("key");
  1411. std::string scancodeName = std::string("\"") + std::string(Keyboard::getScancodeName(keyMapping->scancode)) + std::string("\"");
  1412. row->push_back(scancodeName);
  1413. break;
  1414. }
  1415. case InputMappingType::MOUSE_MOTION:
  1416. {
  1417. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  1418. row->push_back("mouse");
  1419. row->push_back("motion");
  1420. std::string axisName;
  1421. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  1422. {
  1423. axisName = "+x";
  1424. }
  1425. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  1426. {
  1427. axisName = "-x";
  1428. }
  1429. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  1430. {
  1431. axisName = "+y";
  1432. }
  1433. else
  1434. {
  1435. axisName = "-y";
  1436. }
  1437. row->push_back(axisName);
  1438. break;
  1439. }
  1440. case InputMappingType::MOUSE_WHEEL:
  1441. {
  1442. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  1443. row->push_back("mouse");
  1444. row->push_back("wheel");
  1445. std::string axisName;
  1446. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  1447. {
  1448. axisName = "+x";
  1449. }
  1450. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  1451. {
  1452. axisName = "-x";
  1453. }
  1454. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  1455. {
  1456. axisName = "+y";
  1457. }
  1458. else
  1459. {
  1460. axisName = "-y";
  1461. }
  1462. row->push_back(axisName);
  1463. break;
  1464. }
  1465. case InputMappingType::MOUSE_BUTTON:
  1466. {
  1467. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  1468. row->push_back("mouse");
  1469. row->push_back("button");
  1470. std::string buttonName;
  1471. std::stringstream stream;
  1472. stream << static_cast<int>(mouseButtonMapping->button);
  1473. stream >> buttonName;
  1474. row->push_back(buttonName);
  1475. break;
  1476. }
  1477. case InputMappingType::GAMEPAD_AXIS:
  1478. {
  1479. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  1480. row->push_back("gamepad");
  1481. row->push_back("axis");
  1482. std::stringstream stream;
  1483. if (gamepadAxisMapping->negative)
  1484. {
  1485. stream << "-";
  1486. }
  1487. else
  1488. {
  1489. stream << "+";
  1490. }
  1491. stream << gamepadAxisMapping->axis;
  1492. std::string axisName;
  1493. stream >> axisName;
  1494. row->push_back(axisName);
  1495. break;
  1496. }
  1497. case InputMappingType::GAMEPAD_BUTTON:
  1498. {
  1499. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  1500. row->push_back("gamepad");
  1501. row->push_back("button");
  1502. std::string buttonName;
  1503. std::stringstream stream;
  1504. stream << static_cast<int>(gamepadButtonMapping->button);
  1505. stream >> buttonName;
  1506. row->push_back(buttonName);
  1507. break;
  1508. }
  1509. default:
  1510. break;
  1511. }
  1512. }
  1513. }
  1514. // Form full path to control profile file
  1515. std::string controlProfilePath = controlsPath + controlProfileName + ".csv";
  1516. // Save control profile
  1517. resourceManager->save<CSVTable>(table, controlProfilePath);
  1518. // Free control profile CSV table
  1519. delete table;
  1520. }
  1521. void Game::resizeUI(int w, int h)
  1522. {
  1523. // Adjust root element dimensions
  1524. uiRootElement->setDimensions(Vector2(w, h));
  1525. uiRootElement->update();
  1526. splashBackgroundImage->setDimensions(Vector2(w, h));
  1527. splashBackgroundImage->setAnchor(Anchor::TOP_LEFT);
  1528. // Resize splash screen image
  1529. splashImage->setAnchor(Anchor::CENTER);
  1530. splashImage->setDimensions(Vector2(splashTexture->getWidth(), splashTexture->getHeight()));
  1531. // Adjust UI camera projection matrix
  1532. uiCamera.setOrthographic(0.0f, w, h, 0.0f, -1.0f, 1.0f);
  1533. uiCamera.resetTweens();
  1534. // Resize camera flash image
  1535. cameraFlashImage->setDimensions(Vector2(w, h));
  1536. cameraFlashImage->setAnchor(Anchor::CENTER);
  1537. // Resize blackout image
  1538. blackoutImage->setDimensions(Vector2(w, h));
  1539. blackoutImage->setAnchor(Anchor::CENTER);
  1540. // Resize HUD
  1541. float hudPadding = 20.0f;
  1542. hudContainer->setDimensions(Vector2(w - hudPadding * 2.0f, h - hudPadding * 2.0f));
  1543. hudContainer->setAnchor(Anchor::CENTER);
  1544. // Tool indicator
  1545. Rect toolIndicatorBounds = hudTextureAtlas.getBounds("tool-indicator");
  1546. toolIndicatorBGImage->setDimensions(Vector2(toolIndicatorBounds.getWidth(), toolIndicatorBounds.getHeight()));
  1547. toolIndicatorBGImage->setAnchor(Anchor::TOP_LEFT);
  1548. Rect toolIndicatorIconBounds = hudTextureAtlas.getBounds("tool-indicator-lens");
  1549. toolIndicatorIconImage->setDimensions(Vector2(toolIndicatorIconBounds.getWidth(), toolIndicatorIconBounds.getHeight()));
  1550. toolIndicatorIconImage->setAnchor(Anchor::CENTER);
  1551. // Buttons
  1552. Rect playButtonBounds = hudTextureAtlas.getBounds("button-play");
  1553. Rect fastForwardButtonBounds = hudTextureAtlas.getBounds("button-fast-forward-2x");
  1554. Rect pauseButtonBounds = hudTextureAtlas.getBounds("button-pause");
  1555. Rect buttonBackgroundBounds = hudTextureAtlas.getBounds("button-background");
  1556. Vector2 buttonBGDimensions = Vector2(buttonBackgroundBounds.getWidth(), buttonBackgroundBounds.getHeight());
  1557. float buttonMargin = 10.0f;
  1558. float buttonDepth = 15.0f;
  1559. float buttonContainerWidth = fastForwardButtonBounds.getWidth();
  1560. float buttonContainerHeight = fastForwardButtonBounds.getHeight();
  1561. buttonContainer->setDimensions(Vector2(buttonContainerWidth, buttonContainerHeight));
  1562. buttonContainer->setAnchor(Anchor::TOP_RIGHT);
  1563. playButtonImage->setDimensions(Vector2(playButtonBounds.getWidth(), playButtonBounds.getHeight()));
  1564. playButtonImage->setAnchor(Vector2(0.0f, 0.0f));
  1565. playButtonBGImage->setDimensions(buttonBGDimensions);
  1566. playButtonBGImage->setAnchor(Vector2(0.0f, 1.0f));
  1567. fastForwardButtonImage->setDimensions(Vector2(fastForwardButtonBounds.getWidth(), fastForwardButtonBounds.getHeight()));
  1568. fastForwardButtonImage->setAnchor(Vector2(0.5f, 5.0f));
  1569. fastForwardButtonBGImage->setDimensions(buttonBGDimensions);
  1570. fastForwardButtonBGImage->setAnchor(Vector2(0.5f, 0.5f));
  1571. pauseButtonImage->setDimensions(Vector2(pauseButtonBounds.getWidth(), pauseButtonBounds.getHeight()));
  1572. pauseButtonImage->setAnchor(Vector2(1.0f, 0.0f));
  1573. pauseButtonBGImage->setDimensions(buttonBGDimensions);
  1574. pauseButtonBGImage->setAnchor(Vector2(1.0f, 1.0f));
  1575. // Radial menu
  1576. Rect radialMenuBounds = hudTextureAtlas.getBounds("radial-menu");
  1577. radialMenuContainer->setDimensions(Vector2(w, h));
  1578. radialMenuContainer->setAnchor(Anchor::CENTER);
  1579. radialMenuContainer->setLayerOffset(30);
  1580. radialMenuBackgroundImage->setDimensions(Vector2(w, h));
  1581. radialMenuBackgroundImage->setAnchor(Anchor::CENTER);
  1582. radialMenuBackgroundImage->setLayerOffset(-1);
  1583. //radialMenuImage->setDimensions(Vector2(w * 0.5f, h * 0.5f));
  1584. radialMenuImage->setDimensions(Vector2(radialMenuBounds.getWidth(), radialMenuBounds.getHeight()));
  1585. radialMenuImage->setAnchor(Anchor::CENTER);
  1586. Rect radialMenuSelectorBounds = hudTextureAtlas.getBounds("radial-menu-selector");
  1587. radialMenuSelectorImage->setDimensions(Vector2(radialMenuSelectorBounds.getWidth(), radialMenuSelectorBounds.getHeight()));
  1588. radialMenuSelectorImage->setAnchor(Anchor::CENTER);
  1589. Rect toolIconBrushBounds = hudTextureAtlas.getBounds("tool-icon-brush");
  1590. toolIconBrushImage->setDimensions(Vector2(toolIconBrushBounds.getWidth(), toolIconBrushBounds.getHeight()));
  1591. toolIconBrushImage->setAnchor(Anchor::CENTER);
  1592. Rect toolIconLensBounds = hudTextureAtlas.getBounds("tool-icon-lens");
  1593. toolIconLensImage->setDimensions(Vector2(toolIconLensBounds.getWidth(), toolIconLensBounds.getHeight()));
  1594. toolIconLensImage->setAnchor(Anchor::CENTER);
  1595. Rect toolIconForcepsBounds = hudTextureAtlas.getBounds("tool-icon-forceps");
  1596. toolIconForcepsImage->setDimensions(Vector2(toolIconForcepsBounds.getWidth(), toolIconForcepsBounds.getHeight()));
  1597. toolIconForcepsImage->setAnchor(Anchor::CENTER);
  1598. Rect toolIconSpadeBounds = hudTextureAtlas.getBounds("tool-icon-spade");
  1599. toolIconSpadeImage->setDimensions(Vector2(toolIconSpadeBounds.getWidth(), toolIconSpadeBounds.getHeight()));
  1600. toolIconSpadeImage->setAnchor(Anchor::CENTER);
  1601. Rect toolIconCameraBounds = hudTextureAtlas.getBounds("tool-icon-camera");
  1602. toolIconCameraImage->setDimensions(Vector2(toolIconCameraBounds.getWidth(), toolIconCameraBounds.getHeight()));
  1603. toolIconCameraImage->setAnchor(Anchor::CENTER);
  1604. Rect toolIconMicrochipBounds = hudTextureAtlas.getBounds("tool-icon-microchip");
  1605. toolIconMicrochipImage->setDimensions(Vector2(toolIconMicrochipBounds.getWidth(), toolIconMicrochipBounds.getHeight()));
  1606. toolIconMicrochipImage->setAnchor(Anchor::CENTER);
  1607. Rect toolIconTestTubeBounds = hudTextureAtlas.getBounds("tool-icon-test-tube");
  1608. toolIconTestTubeImage->setDimensions(Vector2(toolIconTestTubeBounds.getWidth(), toolIconTestTubeBounds.getHeight()));
  1609. toolIconTestTubeImage->setAnchor(Anchor::CENTER);
  1610. Rect labelCornerBounds = hudTextureAtlas.getBounds("label-tl");
  1611. Vector2 labelCornerDimensions(labelCornerBounds.getWidth(), labelCornerBounds.getHeight());
  1612. Vector2 antLabelPadding(10.0f, 6.0f);
  1613. antLabelContainer->setDimensions(antLabel->getDimensions() + antLabelPadding * 2.0f);
  1614. antLabelContainer->setTranslation(Vector2(0.0f, (int)(-antPin->getDimensions().y * 0.125f)));
  1615. antLabelTL->setDimensions(labelCornerDimensions);
  1616. antLabelTR->setDimensions(labelCornerDimensions);
  1617. antLabelBL->setDimensions(labelCornerDimensions);
  1618. antLabelBR->setDimensions(labelCornerDimensions);
  1619. antLabelCC->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  1620. antLabelCT->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  1621. antLabelCB->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  1622. antLabelCL->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  1623. antLabelCR->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  1624. antLabelContainer->setAnchor(Vector2(0.5f, 0.5f));
  1625. antLabelTL->setAnchor(Anchor::TOP_LEFT);
  1626. antLabelTR->setAnchor(Anchor::TOP_RIGHT);
  1627. antLabelBL->setAnchor(Anchor::BOTTOM_LEFT);
  1628. antLabelBR->setAnchor(Anchor::BOTTOM_RIGHT);
  1629. antLabelCC->setAnchor(Anchor::CENTER);
  1630. antLabelCT->setAnchor(Vector2(0.5f, 0.0f));
  1631. antLabelCB->setAnchor(Vector2(0.5f, 1.0f));
  1632. antLabelCL->setAnchor(Vector2(0.0f, 0.5f));
  1633. antLabelCR->setAnchor(Vector2(1.0f, 0.5f));
  1634. antLabel->setAnchor(Anchor::CENTER);
  1635. Rect antPinBounds = hudTextureAtlas.getBounds("label-pin");
  1636. antPin->setDimensions(Vector2(antPinBounds.getWidth(), antPinBounds.getHeight()));
  1637. antPin->setAnchor(Vector2(0.5f, 1.0f));
  1638. Rect pinHoleBounds = hudTextureAtlas.getBounds("label-pin-hole");
  1639. antLabelPinHole->setDimensions(Vector2(pinHoleBounds.getWidth(), pinHoleBounds.getHeight()));
  1640. antLabelPinHole->setAnchor(Vector2(0.5f, 0.0f));
  1641. antLabelPinHole->setTranslation(Vector2(0.0f, -antLabelPinHole->getDimensions().y * 0.5f));
  1642. antLabelPinHole->setLayerOffset(2);
  1643. float pinDistance = 20.0f;
  1644. antTag->setAnchor(Anchor::CENTER);
  1645. antTag->setDimensions(Vector2(antLabelContainer->getDimensions().x, antPin->getDimensions().y));
  1646. float cameraGridLineWidth = 2.0f;
  1647. float cameraReticleDiameter = 6.0f;
  1648. cameraGridContainer->setDimensions(Vector2(w, h));
  1649. cameraGridY0Image->setDimensions(Vector2(w, cameraGridLineWidth));
  1650. cameraGridY1Image->setDimensions(Vector2(w, cameraGridLineWidth));
  1651. cameraGridX0Image->setDimensions(Vector2(cameraGridLineWidth, h));
  1652. cameraGridX1Image->setDimensions(Vector2(cameraGridLineWidth, h));
  1653. cameraReticleImage->setDimensions(Vector2(cameraReticleDiameter));
  1654. cameraGridY0Image->setTranslation(Vector2(0));
  1655. cameraGridY1Image->setTranslation(Vector2(0));
  1656. cameraGridX0Image->setTranslation(Vector2(0));
  1657. cameraGridX1Image->setTranslation(Vector2(0));
  1658. cameraReticleImage->setTranslation(Vector2(0));
  1659. UIImage* icons[] =
  1660. {
  1661. toolIconBrushImage,
  1662. nullptr,
  1663. toolIconLensImage,
  1664. nullptr,
  1665. toolIconForcepsImage,
  1666. toolIconMicrochipImage,
  1667. toolIconCameraImage,
  1668. nullptr
  1669. };
  1670. Rect radialMenuIconRingBounds = hudTextureAtlas.getBounds("radial-menu-icon-ring");
  1671. float iconOffset = radialMenuIconRingBounds.getWidth() * 0.5f;
  1672. float sectorAngle = (2.0f * 3.14159264f) / 8.0f;
  1673. for (int i = 0; i < 8; ++i)
  1674. {
  1675. float angle = sectorAngle * static_cast<float>(i - 4);
  1676. Vector2 translation = Vector2(std::cos(angle), std::sin(angle)) * iconOffset;
  1677. translation.x = (int)(translation.x + 0.5f);
  1678. translation.y = (int)(translation.y + 0.5f);
  1679. if (icons[i] != nullptr)
  1680. {
  1681. icons[i]->setTranslation(translation);
  1682. }
  1683. }
  1684. }
  1685. void Game::restringUI()
  1686. {
  1687. }
  1688. void Game::setTimeOfDay(float time)
  1689. {
  1690. Vector3 midnight = Vector3(0.0f, 1.0f, 0.0f);
  1691. Vector3 sunrise = Vector3(-1.0f, 0.0f, 0.0f);
  1692. Vector3 noon = Vector3(0, -1.0f, 0.0f);
  1693. Vector3 sunset = Vector3(1.0f, 0.0f, 0.0f);
  1694. float angles[4] =
  1695. {
  1696. glm::radians(270.0f), // 00:00
  1697. glm::radians(0.0f), // 06:00
  1698. glm::radians(90.0f), // 12:00
  1699. glm::radians(180.0f) // 18:00
  1700. };
  1701. int index0 = static_cast<int>(fmod(time, 24.0f) / 6.0f);
  1702. int index1 = (index0 + 1) % 4;
  1703. float t = (time - (static_cast<float>(index0) * 6.0f)) / 6.0f;
  1704. Quaternion rotation0 = glm::angleAxis(angles[index0], Vector3(1, 0, 0));
  1705. Quaternion rotation1 = glm::angleAxis(angles[index1], Vector3(1, 0, 0));
  1706. Quaternion rotation = glm::normalize(glm::slerp(rotation0, rotation1, t));
  1707. Vector3 direction = glm::normalize(rotation * Vector3(0, 0, 1));
  1708. sunlight.setDirection(direction);
  1709. Vector3 up = glm::normalize(rotation * Vector3(0, 1, 0));
  1710. sunlightCamera.lookAt(Vector3(0, 0, 0), sunlight.getDirection(), up);
  1711. }
  1712. void Game::toggleWireframe()
  1713. {
  1714. wireframe = !wireframe;
  1715. float width = (wireframe) ? 1.0f : 0.0f;
  1716. lightingPass->setWireframeLineWidth(width);
  1717. }
  1718. void Game::queueScreenshot()
  1719. {
  1720. screenshotQueued = true;
  1721. cameraFlashImage->setVisible(false);
  1722. cameraGridContainer->setVisible(false);
  1723. fpsLabel->setVisible(false);
  1724. soundSystem->scrot();
  1725. }
  1726. void Game::screenshot()
  1727. {
  1728. screenshotQueued = false;
  1729. // Read pixel data from framebuffer
  1730. unsigned char* pixels = new unsigned char[w * h * 3];
  1731. glReadBuffer(GL_BACK);
  1732. glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  1733. // Get game title in current language
  1734. std::string title = getString(getLanguageIndex(), "title");
  1735. // Convert title to lowercase
  1736. std::transform(title.begin(), title.end(), title.begin(), ::tolower);
  1737. // Create screenshot directory if it doesn't exist
  1738. std::string screenshotDirectory = configPath + std::string("/screenshots/");
  1739. if (!pathExists(screenshotDirectory))
  1740. {
  1741. createDirectory(screenshotDirectory);
  1742. }
  1743. // Build screenshot file name
  1744. std::string filename = screenshotDirectory + title + "-" + timestamp() + ".png";
  1745. // Write screenshot to file in separate thread
  1746. std::thread screenshotThread(Game::saveScreenshot, filename, w, h, pixels);
  1747. screenshotThread.detach();
  1748. // Play camera flash animation
  1749. cameraFlashAnimation.stop();
  1750. cameraFlashAnimation.rewind();
  1751. cameraFlashAnimation.play();
  1752. // Play camera shutter sound
  1753. // Restore camera UI visibility
  1754. //cameraGridContainer->setVisible(true);
  1755. fpsLabel->setVisible(true);
  1756. // Whiteout screen immediately
  1757. glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
  1758. glClear(GL_COLOR_BUFFER_BIT);
  1759. }
  1760. void Game::mapInput(const InputMapping& mapping)
  1761. {
  1762. // Skip mouse motion events
  1763. if (mapping.getType() == InputMappingType::MOUSE_MOTION)
  1764. {
  1765. return;
  1766. }
  1767. // Add input mapping to input router
  1768. if (mapping.control != nullptr)
  1769. {
  1770. inputRouter->addMapping(mapping);
  1771. }
  1772. // Disable input mapping generation
  1773. inputMapper->setControl(nullptr);
  1774. inputMapper->setEnabled(false);
  1775. }
  1776. void Game::boxSelect(float x, float y, float w, float h)
  1777. {
  1778. boxSelectionContainer->setTranslation(Vector2(x, y));
  1779. boxSelectionContainer->setDimensions(Vector2(w, h));
  1780. boxSelectionImageBackground->setDimensions(Vector2(w, h));
  1781. boxSelectionImageTop->setDimensions(Vector2(w, boxSelectionBorderWidth));
  1782. boxSelectionImageBottom->setDimensions(Vector2(w, boxSelectionBorderWidth));
  1783. boxSelectionImageLeft->setDimensions(Vector2(boxSelectionBorderWidth, h));
  1784. boxSelectionImageRight->setDimensions(Vector2(boxSelectionBorderWidth, h));
  1785. boxSelectionContainer->setVisible(true);
  1786. }
  1787. void Game::fadeIn(float duration, const Vector3& color, std::function<void()> callback)
  1788. {
  1789. if (fadeInAnimation.isPlaying())
  1790. {
  1791. return;
  1792. }
  1793. fadeOutAnimation.stop();
  1794. this->fadeInEndCallback = callback;
  1795. blackoutImage->setTintColor(Vector4(color, 1.0f));
  1796. blackoutImage->setVisible(true);
  1797. fadeInAnimation.setSpeed(1.0f / duration);
  1798. fadeInAnimation.setLoop(false);
  1799. fadeInAnimation.setClip(&fadeInClip);
  1800. fadeInAnimation.setTimeFrame(fadeInClip.getTimeFrame());
  1801. fadeInAnimation.rewind();
  1802. fadeInAnimation.play();
  1803. blackoutImage->resetTweens();
  1804. uiRootElement->update();
  1805. }
  1806. void Game::fadeOut(float duration, const Vector3& color, std::function<void()> callback)
  1807. {
  1808. if (fadeOutAnimation.isPlaying())
  1809. {
  1810. return;
  1811. }
  1812. fadeInAnimation.stop();
  1813. this->fadeOutEndCallback = callback;
  1814. blackoutImage->setVisible(true);
  1815. blackoutImage->setTintColor(Vector4(color, 0.0f));
  1816. fadeOutAnimation.setSpeed(1.0f / duration);
  1817. fadeOutAnimation.setLoop(false);
  1818. fadeOutAnimation.setClip(&fadeOutClip);
  1819. fadeOutAnimation.setTimeFrame(fadeOutClip.getTimeFrame());
  1820. fadeOutAnimation.rewind();
  1821. fadeOutAnimation.play();
  1822. blackoutImage->resetTweens();
  1823. uiRootElement->update();
  1824. }
  1825. void Game::selectTool(int toolIndex)
  1826. {
  1827. Tool* tools[] =
  1828. {
  1829. brush,
  1830. nullptr,
  1831. lens,
  1832. nullptr,
  1833. forceps,
  1834. nullptr,
  1835. nullptr,
  1836. nullptr
  1837. };
  1838. Tool* nextTool = tools[toolIndex];
  1839. if (nextTool != currentTool)
  1840. {
  1841. if (currentTool)
  1842. {
  1843. currentTool->setActive(false);
  1844. currentTool->update(0.0f);
  1845. }
  1846. currentTool = nextTool;
  1847. if (currentTool)
  1848. {
  1849. currentTool->setActive(true);
  1850. }
  1851. }
  1852. if (1)
  1853. {
  1854. toolIndicatorIconImage->setTextureBounds(toolIndicatorsBounds[toolIndex]);
  1855. toolIndicatorIconImage->setVisible(true);
  1856. }
  1857. else
  1858. {
  1859. toolIndicatorIconImage->setVisible(false);
  1860. }
  1861. }
  1862. EntityID Game::createInstance()
  1863. {
  1864. return entityManager->createEntity();
  1865. }
  1866. EntityID Game::createInstanceOf(const std::string& templateName)
  1867. {
  1868. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  1869. EntityID entity = entityManager->createEntity();
  1870. entityTemplate->apply(entity, componentManager);
  1871. return entity;
  1872. }
  1873. void Game::destroyInstance(EntityID entity)
  1874. {
  1875. entityManager->destroyEntity(entity);
  1876. }
  1877. void Game::addComponent(EntityID entity, ComponentBase* component)
  1878. {
  1879. componentManager->addComponent(entity, component);
  1880. }
  1881. void Game::removeComponent(EntityID entity, ComponentType type)
  1882. {
  1883. ComponentBase* component = componentManager->removeComponent(entity, type);
  1884. delete component;
  1885. }
  1886. void Game::setTranslation(EntityID entity, const Vector3& translation)
  1887. {
  1888. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  1889. if (!component)
  1890. {
  1891. return;
  1892. }
  1893. component->transform.translation = translation;
  1894. }
  1895. void Game::setRotation(EntityID entity, const Quaternion& rotation)
  1896. {
  1897. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  1898. if (!component)
  1899. {
  1900. return;
  1901. }
  1902. component->transform.rotation = rotation;
  1903. }
  1904. void Game::setScale(EntityID entity, const Vector3& scale)
  1905. {
  1906. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  1907. if (!component)
  1908. {
  1909. return;
  1910. }
  1911. component->transform.scale = scale;
  1912. }
  1913. void Game::setTerrainPatchPosition(EntityID entity, const std::tuple<int, int>& position)
  1914. {
  1915. TerrainPatchComponent* component = componentManager->getComponent<TerrainPatchComponent>(entity);
  1916. if (!component)
  1917. {
  1918. return;
  1919. }
  1920. component->position = position;
  1921. }
  1922. void Game::saveScreenshot(const std::string& filename, unsigned int width, unsigned int height, unsigned char* pixels)
  1923. {
  1924. stbi_flip_vertically_on_write(1);
  1925. stbi_write_png(filename.c_str(), width, height, 3, pixels, width * 3);
  1926. delete[] pixels;
  1927. }