💿🐜 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.

3587 lines
114 KiB

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/string-table.hpp"
  21. #include "states/game-state.hpp"
  22. #include "states/sandbox-state.hpp"
  23. #include "filesystem.hpp"
  24. #include "timestamp.hpp"
  25. #include "ui/ui.hpp"
  26. #include "graphics/ui-render-pass.hpp"
  27. #include "graphics/shadow-map-render-pass.hpp"
  28. #include "graphics/clear-render-pass.hpp"
  29. #include "graphics/sky-render-pass.hpp"
  30. #include "graphics/lighting-render-pass.hpp"
  31. #include "graphics/silhouette-render-pass.hpp"
  32. #include "graphics/final-render-pass.hpp"
  33. #include "resources/resource-manager.hpp"
  34. #include "resources/text-file.hpp"
  35. #include "game/camera-rig.hpp"
  36. #include "game/lens.hpp"
  37. #include "game/forceps.hpp"
  38. #include "game/brush.hpp"
  39. #include "entity/component-manager.hpp"
  40. #include "entity/components/transform-component.hpp"
  41. #include "entity/components/model-component.hpp"
  42. #include "entity/components/terrain-patch-component.hpp"
  43. #include "entity/entity-manager.hpp"
  44. #include "entity/entity-template.hpp"
  45. #include "entity/system-manager.hpp"
  46. #include "entity/systems/sound-system.hpp"
  47. #include "entity/systems/collision-system.hpp"
  48. #include "entity/systems/render-system.hpp"
  49. #include "entity/systems/camera-system.hpp"
  50. #include "entity/systems/tool-system.hpp"
  51. #include "entity/systems/locomotion-system.hpp"
  52. #include "entity/systems/behavior-system.hpp"
  53. #include "entity/systems/steering-system.hpp"
  54. #include "entity/systems/particle-system.hpp"
  55. #include "entity/systems/terrain-system.hpp"
  56. #include "configuration.hpp"
  57. #include "stb/stb_image_write.h"
  58. #include "menu.hpp"
  59. #include <algorithm>
  60. #include <cctype>
  61. #include <fstream>
  62. #include <sstream>
  63. #include <stdexcept>
  64. #include <thread>
  65. #include "debug/command-interpreter.hpp"
  66. #include "debug/logger.hpp"
  67. #include "debug/ansi-escape-codes.hpp"
  68. template <>
  69. bool Game::readSetting<std::string>(const std::string& name, std::string* value) const
  70. {
  71. auto it = settingsTableIndex.find(name);
  72. if (it == settingsTableIndex.end())
  73. {
  74. return false;
  75. }
  76. *value = (*settingsTable)[it->second][1];
  77. return true;
  78. }
  79. template <>
  80. bool Game::readSetting<bool>(const std::string& name, bool* value) const
  81. {
  82. auto it = settingsTableIndex.find(name);
  83. if (it == settingsTableIndex.end())
  84. {
  85. return false;
  86. }
  87. const std::string& string = (*settingsTable)[it->second][1];
  88. if (string == "true" || string == "on" || string == "1")
  89. {
  90. *value = true;
  91. return true;
  92. }
  93. else if (string == "false" || string == "off" || string == "0")
  94. {
  95. *value = false;
  96. return true;
  97. }
  98. return false;
  99. }
  100. template <>
  101. bool Game::readSetting<int>(const std::string& name, int* value) const
  102. {
  103. auto it = settingsTableIndex.find(name);
  104. if (it == settingsTableIndex.end())
  105. {
  106. return false;
  107. }
  108. std::stringstream stream;
  109. stream << (*settingsTable)[it->second][1];
  110. stream >> (*value);
  111. return (!stream.fail());
  112. }
  113. template <>
  114. bool Game::readSetting<float>(const std::string& name, float* value) const
  115. {
  116. auto it = settingsTableIndex.find(name);
  117. if (it == settingsTableIndex.end())
  118. {
  119. return false;
  120. }
  121. std::stringstream stream;
  122. stream << (*settingsTable)[it->second][1];
  123. stream >> (*value);
  124. return (!stream.fail());
  125. }
  126. template <>
  127. bool Game::readSetting<Vector2>(const std::string& name, Vector2* value) const
  128. {
  129. auto it = settingsTableIndex.find(name);
  130. if (it == settingsTableIndex.end())
  131. {
  132. return false;
  133. }
  134. std::stringstream stream;
  135. stream << (*settingsTable)[it->second][1];
  136. stream >> value->x;
  137. stream.str(std::string());
  138. stream.clear();
  139. stream << (*settingsTable)[it->second][2];
  140. stream >> value->y;
  141. return (!stream.fail());
  142. }
  143. Game::Game(int argc, char* argv[]):
  144. currentState(nullptr),
  145. window(nullptr)
  146. {
  147. // Determine application name
  148. std::string applicationName;
  149. #if defined(_WIN32)
  150. applicationName = "Antkeeper";
  151. #else
  152. applicationName = "antkeeper";
  153. #endif
  154. // Form resource paths
  155. dataPath = getDataPath(applicationName) + "data/";
  156. configPath = getConfigPath(applicationName);
  157. controlsPath = configPath + "controls/";
  158. // Create nonexistent config directories
  159. std::vector<std::string> configPaths;
  160. configPaths.push_back(configPath);
  161. configPaths.push_back(controlsPath);
  162. for (const std::string& path: configPaths)
  163. {
  164. if (!pathExists(path))
  165. {
  166. createDirectory(path);
  167. }
  168. }
  169. // Setup resource manager
  170. resourceManager = new ResourceManager();
  171. // Include resource search paths in order of priority
  172. resourceManager->include(controlsPath);
  173. resourceManager->include(configPath);
  174. resourceManager->include(dataPath);
  175. // Subscribe the game to scheduled function events
  176. eventDispatcher.subscribe<ScheduledFunctionEvent>(this);
  177. toggleFullscreenDisabled = false;
  178. sandboxState = new SandboxState(this);
  179. }
  180. Game::~Game()
  181. {
  182. if (window)
  183. {
  184. windowManager->destroyWindow(window);
  185. }
  186. }
  187. void Game::changeState(GameState* state)
  188. {
  189. if (currentState != nullptr)
  190. {
  191. currentState->exit();
  192. }
  193. currentState = state;
  194. if (currentState != nullptr)
  195. {
  196. currentState->enter();
  197. }
  198. }
  199. std::string Game::getString(const std::string& name, std::optional<std::size_t> languageIndex) const
  200. {
  201. std::string value;
  202. if (languageIndex == std::nullopt)
  203. {
  204. languageIndex = currentLanguageIndex;
  205. }
  206. auto it = stringTableIndex.find(name);
  207. if (it != stringTableIndex.end())
  208. {
  209. value = (*stringTable)[it->second][(*languageIndex) + 2];
  210. if (value.empty())
  211. {
  212. value = std::string("# EMPTY STRING: ") + name + std::string(" #");
  213. }
  214. }
  215. else
  216. {
  217. value = std::string("# MISSING STRING: ") + name + std::string(" #");
  218. }
  219. return value;
  220. }
  221. void Game::changeLanguage(std::size_t nextLanguageIndex)
  222. {
  223. // Get names of fonts
  224. std::string menuFontFilename = getString("menu-font-filename");
  225. // Unload fonts
  226. delete menuFont;
  227. resourceManager->unload(menuFontFilename);
  228. // Change current language index
  229. currentLanguageIndex = nextLanguageIndex;
  230. // Reload fonts
  231. loadFonts();
  232. // Set window title
  233. window->setTitle(getString("title").c_str());
  234. // Repopulate UI element strings
  235. restringUI();
  236. // Resize the UI
  237. resizeUI(w, h);
  238. // Reselect menu item
  239. if (currentMenuItem)
  240. {
  241. menuSelectorSlideAnimation.stop();
  242. selectMenuItem(menuItemIndex, false);
  243. uiRootElement->update();
  244. currentMenu->getContainer()->resetTweens();
  245. }
  246. }
  247. void Game::nextLanguage()
  248. {
  249. changeLanguage((currentLanguageIndex + 1) % languageCount);
  250. }
  251. void Game::openMenu(Menu* menu, int selectedItemIndex)
  252. {
  253. if (currentMenu)
  254. {
  255. closeCurrentMenu();
  256. }
  257. currentMenu = menu;
  258. uiRootElement->addChild(currentMenu->getContainer());
  259. currentMenu->getContainer()->addChild(menuSelectorImage);
  260. currentMenu->getContainer()->setTintColor(Vector4(1.0f));
  261. for (MenuItem* item: *currentMenu->getItems())
  262. {
  263. item->getContainer()->setTintColor(menuItemInactiveColor);
  264. }
  265. selectMenuItem(selectedItemIndex, false);
  266. uiRootElement->update();
  267. currentMenu->getContainer()->resetTweens();
  268. }
  269. void Game::closeCurrentMenu()
  270. {
  271. uiRootElement->removeChild(currentMenu->getContainer());
  272. currentMenu->getContainer()->removeChild(menuSelectorImage);
  273. currentMenu->getContainer()->setTintColor(Vector4(1.0f));
  274. for (MenuItem* item: *currentMenu->getItems())
  275. {
  276. item->getContainer()->setTintColor(menuItemInactiveColor);
  277. }
  278. currentMenu = nullptr;
  279. currentMenuItem = nullptr;
  280. menuItemIndex = -1;
  281. menuFadeAnimation.stop();
  282. menuSelectorSlideAnimation.stop();
  283. menuItemSelectAnimation.stop();
  284. menuItemDeselectAnimation.stop();
  285. previousMenu = currentMenu;
  286. currentMenu = nullptr;
  287. }
  288. void Game::selectMenuItem(int index, bool tween)
  289. {
  290. bool reselected = false;
  291. if (index != menuItemIndex)
  292. {
  293. if (menuItemSelectAnimation.isPlaying())
  294. {
  295. menuItemSelectAnimation.stop();
  296. currentMenuItem->getContainer()->setTintColor(menuItemActiveColor);
  297. }
  298. if (menuItemDeselectAnimation.isPlaying())
  299. {
  300. menuItemDeselectAnimation.stop();
  301. previousMenuItem->getContainer()->setTintColor(menuItemInactiveColor);
  302. }
  303. // Save previous menu item
  304. previousMenuItem = currentMenuItem;
  305. // Determine current menu item
  306. menuItemIndex = index;
  307. currentMenuItem = (*(currentMenu->getItems()))[index];
  308. }
  309. else
  310. {
  311. reselected = true;
  312. }
  313. // Determine target position of menu item selector
  314. Vector2 itemTranslation = currentMenuItem->getContainer()->getPosition() - currentMenu->getContainer()->getPosition();
  315. Vector2 itemDimensions = currentMenuItem->getContainer()->getDimensions();
  316. float spacing = fontSizePX;
  317. Vector2 translation;
  318. translation.x = itemTranslation.x - menuSelectorImage->getDimensions().x - spacing;
  319. translation.y = itemTranslation.y + itemDimensions.y * 0.5f - menuSelectorImage->getDimensions().y * 0.5;
  320. // Create tween animations
  321. if (!reselected && tween && previousMenuItem != nullptr)
  322. {
  323. float tweenDuration = 0.2f;
  324. Vector2 oldTranslation = menuSelectorImage->getTranslation();
  325. Vector2 newTranslation = translation;
  326. // Slide animation
  327. {
  328. menuSelectorSlideClip.removeChannels();
  329. AnimationChannel<float>* channel = menuSelectorSlideClip.addChannel(0);
  330. channel->insertKeyframe(0.0f, oldTranslation.y);
  331. channel->insertKeyframe(tweenDuration, newTranslation.y);
  332. menuSelectorSlideAnimation.setTimeFrame(menuSelectorSlideClip.getTimeFrame());
  333. menuSelectorSlideAnimation.rewind();
  334. menuSelectorSlideAnimation.play();
  335. }
  336. // Color animations
  337. {
  338. menuItemSelectClip.removeChannels();
  339. AnimationChannel<Vector4>* channel = menuItemSelectClip.addChannel(0);
  340. channel->insertKeyframe(0.0f, menuItemInactiveColor);
  341. channel->insertKeyframe(tweenDuration, menuItemActiveColor);
  342. menuItemSelectAnimation.setTimeFrame(menuItemSelectClip.getTimeFrame());
  343. menuItemSelectAnimation.rewind();
  344. menuItemSelectAnimation.play();
  345. if (previousMenuItem)
  346. {
  347. menuItemDeselectClip.removeChannels();
  348. channel = menuItemDeselectClip.addChannel(0);
  349. channel->insertKeyframe(0.0f, menuItemActiveColor);
  350. channel->insertKeyframe(tweenDuration, menuItemInactiveColor);
  351. menuItemDeselectAnimation.setTimeFrame(menuItemDeselectClip.getTimeFrame());
  352. menuItemDeselectAnimation.rewind();
  353. menuItemDeselectAnimation.play();
  354. }
  355. }
  356. menuSelectorImage->setTranslation(Vector2(newTranslation.x, oldTranslation.y));
  357. }
  358. else if (!tween)
  359. {
  360. menuSelectorImage->setTranslation(translation);
  361. currentMenuItem->getContainer()->setTintColor(menuItemActiveColor);
  362. if (previousMenuItem)
  363. {
  364. previousMenuItem->getContainer()->setTintColor(menuItemInactiveColor);
  365. }
  366. }
  367. }
  368. void Game::selectNextMenuItem()
  369. {
  370. int index = (menuItemIndex + 1) % currentMenu->getItems()->size();
  371. selectMenuItem(index, true);
  372. }
  373. void Game::selectPreviousMenuItem()
  374. {
  375. int index = (menuItemIndex + (currentMenu->getItems()->size() - 1)) % currentMenu->getItems()->size();
  376. selectMenuItem(index, true);
  377. }
  378. void Game::activateMenuItem()
  379. {
  380. currentMenuItem->activate();
  381. }
  382. void Game::activateLastMenuItem()
  383. {
  384. if (currentMenu)
  385. {
  386. (*currentMenu->getItems())[currentMenu->getItems()->size() - 1]->activate();
  387. }
  388. }
  389. void Game::toggleFullscreen()
  390. {
  391. if (!toggleFullscreenDisabled)
  392. {
  393. fullscreen = !fullscreen;
  394. window->setFullscreen(fullscreen);
  395. restringUI();
  396. // Disable fullscreen toggles for 500ms
  397. toggleFullscreenDisabled = true;
  398. ScheduledFunctionEvent event;
  399. event.caller = static_cast<void*>(this);
  400. event.function = [this]()
  401. {
  402. toggleFullscreenDisabled = false;
  403. };
  404. eventDispatcher.schedule(event, time + 0.5f);
  405. }
  406. }
  407. void Game::toggleVSync()
  408. {
  409. vsync = !vsync;
  410. window->setVSync(vsync);
  411. restringUI();
  412. }
  413. void Game::setUpdateRate(double frequency)
  414. {
  415. stepScheduler.setStepFrequency(frequency);
  416. }
  417. void Game::disableNonSystemControls()
  418. {
  419. controls.setCallbacksEnabled(false);
  420. systemControls.setCallbacksEnabled(true);
  421. }
  422. void Game::setup()
  423. {
  424. setupDebugging();
  425. loadSettings();
  426. setupLocalization();
  427. setupWindow();
  428. setupGraphics();
  429. setupControls();
  430. setupUI();
  431. setupGameplay();
  432. screenshotQueued = false;
  433. paused = false;
  434. // Load model resources
  435. try
  436. {
  437. lensModel = resourceManager->load<Model>("lens.mdl");
  438. forcepsModel = resourceManager->load<Model>("forceps.mdl");
  439. brushModel = resourceManager->load<Model>("brush.mdl");
  440. smokeMaterial = resourceManager->load<Material>("smoke.mtl");
  441. }
  442. catch (const std::exception& e)
  443. {
  444. logger->error("Failed to load one or more models: \"" + std::string(e.what()) + "\"\n");
  445. close(EXIT_FAILURE);
  446. }
  447. time = 0.0f;
  448. // Tools
  449. currentTool = nullptr;
  450. lens = new Lens(lensModel, &animator);
  451. lens->setOrbitCam(orbitCam);
  452. worldScene->addObject(lens->getModelInstance());
  453. worldScene->addObject(lens->getSpotlight());
  454. lens->setSunDirection(-sunlightCamera.getForward());
  455. // Forceps
  456. forceps = new Forceps(forcepsModel, &animator);
  457. forceps->setOrbitCam(orbitCam);
  458. worldScene->addObject(forceps->getModelInstance());
  459. // Brush
  460. brush = new Brush(brushModel, &animator);
  461. brush->setOrbitCam(orbitCam);
  462. worldScene->addObject(brush->getModelInstance());
  463. // Initialize component manager
  464. componentManager = new ComponentManager();
  465. // Initialize entity manager
  466. entityManager = new EntityManager(componentManager);
  467. // Initialize systems
  468. soundSystem = new SoundSystem(componentManager);
  469. collisionSystem = new CollisionSystem(componentManager);
  470. cameraSystem = new CameraSystem(componentManager);
  471. renderSystem = new RenderSystem(componentManager, worldScene);
  472. toolSystem = new ToolSystem(componentManager);
  473. toolSystem->setPickingCamera(&camera);
  474. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  475. eventDispatcher.subscribe<MouseMovedEvent>(toolSystem);
  476. behaviorSystem = new BehaviorSystem(componentManager);
  477. steeringSystem = new SteeringSystem(componentManager);
  478. locomotionSystem = new LocomotionSystem(componentManager);
  479. terrainSystem = new TerrainSystem(componentManager);
  480. terrainSystem->setPatchSize(500.0f);
  481. particleSystem = new ParticleSystem(componentManager);
  482. particleSystem->resize(1000);
  483. particleSystem->setMaterial(smokeMaterial);
  484. particleSystem->setDirection(Vector3(0, 1, 0));
  485. lens->setParticleSystem(particleSystem);
  486. particleSystem->getBillboardBatch()->setAlignment(&camera, BillboardAlignmentMode::SPHERICAL);
  487. worldScene->addObject(particleSystem->getBillboardBatch());
  488. // Initialize system manager
  489. systemManager = new SystemManager();
  490. systemManager->addSystem(soundSystem);
  491. systemManager->addSystem(behaviorSystem);
  492. systemManager->addSystem(steeringSystem);
  493. systemManager->addSystem(locomotionSystem);
  494. systemManager->addSystem(collisionSystem);
  495. systemManager->addSystem(toolSystem);
  496. systemManager->addSystem(terrainSystem);
  497. systemManager->addSystem(particleSystem);
  498. systemManager->addSystem(cameraSystem);
  499. systemManager->addSystem(renderSystem);
  500. // Load navmesh
  501. TriangleMesh* navmesh = resourceManager->load<TriangleMesh>("sidewalk.mesh");
  502. int highResolutionDiameter = 3;
  503. int mediumResolutionDiameter = highResolutionDiameter + 2;
  504. int lowResolutionDiameter = 20;
  505. float lowResolutionRadius = static_cast<float>(lowResolutionDiameter) / 2.0f;
  506. float mediumResolutionRadius = static_cast<float>(mediumResolutionDiameter) / 2.0f;
  507. float highResolutionRadius = static_cast<float>(highResolutionDiameter) / 2.0f;
  508. for (int i = 0; i < lowResolutionDiameter; ++i)
  509. {
  510. for (int j = 0; j < lowResolutionDiameter; ++j)
  511. {
  512. EntityID patch;
  513. int x = i - lowResolutionDiameter / 2;
  514. int z = j - lowResolutionDiameter / 2;
  515. if (std::abs(x) < highResolutionRadius && std::abs(z) < highResolutionRadius)
  516. {
  517. patch = createInstanceOf("terrain-patch-high-resolution");
  518. }
  519. else if (std::abs(x) < mediumResolutionRadius && std::abs(z) < mediumResolutionRadius)
  520. {
  521. patch = createInstanceOf("terrain-patch-medium-resolution");
  522. }
  523. else
  524. {
  525. patch = createInstanceOf("terrain-patch-low-resolution");
  526. }
  527. setTerrainPatchPosition(patch, {x, z});
  528. }
  529. }
  530. // Setup state machine states
  531. languageSelectState =
  532. {
  533. std::bind(&Game::enterLanguageSelectState, this),
  534. std::bind(&Game::exitLanguageSelectState, this)
  535. };
  536. splashState =
  537. {
  538. std::bind(&Game::enterSplashState, this),
  539. std::bind(&Game::exitSplashState, this)
  540. };
  541. loadingState =
  542. {
  543. std::bind(&Game::enterLoadingState, this),
  544. std::bind(&Game::exitLoadingState, this)
  545. };
  546. titleState =
  547. {
  548. std::bind(&Game::enterTitleState, this),
  549. std::bind(&Game::exitTitleState, this)
  550. };
  551. playState =
  552. {
  553. std::bind(&Game::enterPlayState, this),
  554. std::bind(&Game::exitPlayState, this)
  555. };
  556. // Initialize state machine
  557. if (firstRun)
  558. {
  559. StateMachine::changeState(&languageSelectState);
  560. }
  561. else
  562. {
  563. #if defined(DEBUG)
  564. StateMachine::changeState(&titleState);
  565. #else
  566. StateMachine::changeState(&splashState);
  567. #endif
  568. }
  569. changeState(sandboxState);
  570. }
  571. void Game::update(float t, float dt)
  572. {
  573. this->time = t;
  574. // Execute current state
  575. if (currentState != nullptr)
  576. {
  577. currentState->execute();
  578. }
  579. // Update systems
  580. systemManager->update(t, dt);
  581. // Update animations
  582. animator.animate(dt);
  583. if (fpsLabel->isVisible())
  584. {
  585. std::stringstream stream;
  586. stream.precision(2);
  587. stream << std::fixed << (performanceSampler.getMeanFrameDuration() * 1000.0f);
  588. fpsLabel->setText(stream.str());
  589. }
  590. uiRootElement->update();
  591. }
  592. void Game::input()
  593. {
  594. controls.update();
  595. }
  596. void Game::render()
  597. {
  598. // Perform sub-frame interpolation on UI elements
  599. uiRootElement->interpolate(stepScheduler.getScheduledSubsteps());
  600. // Update and batch UI elements
  601. uiBatcher->batch(uiBatch, uiRootElement);
  602. // Perform sub-frame interpolation particles
  603. particleSystem->getBillboardBatch()->interpolate(stepScheduler.getScheduledSubsteps());
  604. particleSystem->getBillboardBatch()->batch();
  605. // Render scene
  606. renderer.render(*worldScene);
  607. renderer.render(*uiScene);
  608. if (screenshotQueued)
  609. {
  610. screenshot();
  611. screenshotQueued = false;
  612. }
  613. // Swap window framebuffers
  614. window->swapBuffers();
  615. }
  616. void Game::exit()
  617. {}
  618. void Game::handleEvent(const WindowResizedEvent& event)
  619. {
  620. w = event.width;
  621. h = event.height;
  622. defaultRenderTarget.width = event.width;
  623. defaultRenderTarget.height = event.height;
  624. glViewport(0, 0, event.width, event.height);
  625. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  626. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  627. resizeUI(event.width, event.height);
  628. skipSplash();
  629. }
  630. void Game::handleEvent(const GamepadConnectedEvent& event)
  631. {
  632. // Unmap all controls
  633. inputRouter->reset();
  634. // Reload control profile
  635. loadControlProfile(controlProfileName);
  636. }
  637. void Game::handleEvent(const GamepadDisconnectedEvent& event)
  638. {}
  639. void Game::handleEvent(const ScheduledFunctionEvent& event)
  640. {
  641. if (event.caller == static_cast<void*>(this))
  642. {
  643. event.function();
  644. }
  645. }
  646. void Game::setupDebugging()
  647. {
  648. // Setup logging
  649. {
  650. logger = new Logger();
  651. // Style log format
  652. std::string logPrefix = std::string();
  653. std::string logPostfix = "\n";
  654. std::string warningPrefix = "Warning: ";
  655. std::string warningPostfix = std::string();
  656. std::string errorPrefix = "Error: ";
  657. std::string errorPostfix = std::string();
  658. std::string successPrefix = std::string();
  659. std::string successPostfix = std::string();
  660. // Enable colored messages on debug builds
  661. #if defined(DEBUG)
  662. warningPrefix = std::string(ANSI_CODE_BOLD) + std::string(ANSI_CODE_YELLOW) + std::string("Warning: ") + std::string(ANSI_CODE_RESET) + std::string(ANSI_CODE_YELLOW);
  663. warningPostfix.append(ANSI_CODE_RESET);
  664. errorPrefix = std::string(ANSI_CODE_BOLD) + std::string(ANSI_CODE_RED) + std::string("Error: ") + std::string(ANSI_CODE_RESET) + std::string(ANSI_CODE_RED);
  665. errorPostfix.append(ANSI_CODE_RESET);
  666. successPrefix.insert(0, ANSI_CODE_GREEN);
  667. successPostfix.append(ANSI_CODE_RESET);
  668. #endif
  669. logger->setLogPrefix(logPrefix);
  670. logger->setLogPostfix(logPostfix);
  671. logger->setWarningPrefix(warningPrefix);
  672. logger->setWarningPostfix(warningPostfix);
  673. logger->setErrorPrefix(errorPrefix);
  674. logger->setErrorPostfix(errorPostfix);
  675. logger->setSuccessPrefix(successPrefix);
  676. logger->setSuccessPostfix(successPostfix);
  677. // Redirect logger output to log file on release builds
  678. #if !defined(DEBUG)
  679. std::string logFilename = configPath + "log.txt";
  680. logFileStream.open(logFilename.c_str());
  681. logger->redirect(&logFileStream);
  682. #endif
  683. }
  684. // Create CLI
  685. cli = new CommandInterpreter();
  686. // Register CLI commands
  687. std::function<void(std::string, std::string)> setCommand = std::bind(&CommandInterpreter::set, cli, std::placeholders::_1, std::placeholders::_2);
  688. std::function<void(std::string)> unsetCommand = std::bind(&CommandInterpreter::unset, cli, std::placeholders::_1);
  689. std::function<void()> exitCommand = std::bind(std::exit, EXIT_SUCCESS);
  690. std::function<void(int, float, float, float)> setScaleCommand = [this](int id, float x, float y, float z) {
  691. setScale(id, {x, y, z});
  692. };
  693. std::function<void(int, float, float, float)> setTranslationCommand = [this](int id, float x, float y, float z) {
  694. setTranslation(id, {x, y, z});
  695. };
  696. std::function<void()> createInstanceCommand = std::bind(&Game::createInstance, this);
  697. std::function<void(std::string)> createNamedInstanceCommand = std::bind(&Game::createNamedInstance, this, std::placeholders::_1);
  698. std::function<void(std::string)> createInstanceOfCommand = std::bind(&Game::createInstanceOf, this, std::placeholders::_1);
  699. std::function<void(std::string, std::string)> createNamedInstanceOfCommand = std::bind(&Game::createNamedInstanceOf, this, std::placeholders::_1, std::placeholders::_2);
  700. std::function<void(float)> toggleWireframeCommand = [this](float width){ lightingPass->setWireframeLineWidth(width); };
  701. std::function<void()> helpCommand = [this]()
  702. {
  703. auto& helpStrings = cli->help();
  704. for (auto it = helpStrings.begin(); it != helpStrings.end(); ++it)
  705. {
  706. if (it->second.empty())
  707. {
  708. continue;
  709. }
  710. std::cout << it->second << std::endl;
  711. }
  712. };
  713. std::function<void()> variablesCommand = [this]()
  714. {
  715. auto& variables = cli->variables();
  716. for (auto it = variables.begin(); it != variables.end(); ++it)
  717. {
  718. std::cout << it->first << "=\"" << it->second << "\"" << std::endl;
  719. }
  720. };
  721. std::string exitHelp = "exit";
  722. std::string setHelp = "set <variable name> <value>";
  723. std::string unsetHelp = "unset <variable name>";
  724. std::string createInstanceHelp = "createinstance <template name>";
  725. std::string createNamedInstanceHelp = "createnamedinstance <template name> <instance name>";
  726. std::string createInstanceOfHelp = "createinstanceof <template name>";
  727. std::string createNamedInstanceOfHelp = "createnamedinstanceof <template name> <instance name>";
  728. std::string setTranslationHelp = "settranslation <id> <x> <y> <z>";
  729. std::string setScaleHelp = "setscale <id> <sx> <sy> <sz>";
  730. std::string wireframeHelp = "wireframe <width>";
  731. std::string variablesHelp = "variables";
  732. cli->registerCommand("exit", exitCommand, exitHelp);
  733. cli->registerCommand("set", setCommand, setHelp);
  734. cli->registerCommand("unset", setCommand, unsetHelp);
  735. cli->registerCommand("createinstance", createInstanceCommand, createInstanceHelp);
  736. cli->registerCommand("createnamedinstance", createNamedInstanceCommand, createNamedInstanceHelp);
  737. cli->registerCommand("createinstanceof", createInstanceOfCommand, createInstanceOfHelp);
  738. cli->registerCommand("createnamedinstanceof", createNamedInstanceOfCommand, createNamedInstanceOfHelp);
  739. cli->registerCommand("setscale", setScaleCommand, setScaleHelp);
  740. cli->registerCommand("settranslation", setTranslationCommand, setTranslationHelp);
  741. cli->registerCommand("wireframe", toggleWireframeCommand, wireframeHelp);
  742. cli->registerCommand("variables", variablesCommand, variablesHelp);
  743. cli->registerCommand("help", helpCommand);
  744. // Start CLI thread
  745. std::thread cliThread(&Game::interpretCommands, this);
  746. cliThread.detach();
  747. // Setup performance sampling
  748. performanceSampler.setSampleSize(30);
  749. }
  750. void Game::setupLocalization()
  751. {
  752. // Load strings
  753. loadStrings();
  754. // Determine number of available languages
  755. languageCount = (*stringTable)[0].size() - 2;
  756. // Match language code with language index
  757. currentLanguageIndex = 0;
  758. StringTableRow* languageCodes = &(*stringTable)[1];
  759. for (std::size_t i = 2; i < languageCodes->size(); ++i)
  760. {
  761. if (language == (*languageCodes)[i])
  762. {
  763. currentLanguageIndex = i - 2;
  764. break;
  765. }
  766. }
  767. }
  768. void Game::setupWindow()
  769. {
  770. // Get display resolution
  771. const Display* display = deviceManager->getDisplays()->front();
  772. int displayWidth = std::get<0>(display->getDimensions());
  773. int displayHeight = std::get<1>(display->getDimensions());
  774. if (fullscreen)
  775. {
  776. w = static_cast<int>(fullscreenResolution.x);
  777. h = static_cast<int>(fullscreenResolution.y);
  778. }
  779. else
  780. {
  781. w = static_cast<int>(windowedResolution.x);
  782. h = static_cast<int>(windowedResolution.y);
  783. }
  784. // Determine window position
  785. int x = std::get<0>(display->getPosition()) + displayWidth / 2 - w / 2;
  786. int y = std::get<1>(display->getPosition()) + displayHeight / 2 - h / 2;
  787. // Read title string
  788. std::string title = getString("title");
  789. // Create window
  790. window = windowManager->createWindow(title.c_str(), x, y, w, h, fullscreen, WindowFlag::RESIZABLE);
  791. if (!window)
  792. {
  793. throw std::runtime_error("Game::Game(): Failed to create window.");
  794. }
  795. // Set v-sync mode
  796. window->setVSync(vsync);
  797. debugFont = nullptr;
  798. menuFont = nullptr;
  799. }
  800. void Game::setupGraphics()
  801. {
  802. // Setup OpenGL
  803. glEnable(GL_MULTISAMPLE);
  804. // Setup default render target
  805. defaultRenderTarget.width = w;
  806. defaultRenderTarget.height = h;
  807. defaultRenderTarget.framebuffer = 0;
  808. // Set shadow map resolution
  809. shadowMapResolution = 4096;
  810. // Setup shadow map framebuffer
  811. glGenFramebuffers(1, &shadowMapFramebuffer);
  812. glBindFramebuffer(GL_FRAMEBUFFER, shadowMapFramebuffer);
  813. glGenTextures(1, &shadowMapDepthTextureID);
  814. glBindTexture(GL_TEXTURE_2D, shadowMapDepthTextureID);
  815. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadowMapResolution, shadowMapResolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
  816. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  817. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  818. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  819. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  820. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  821. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  822. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMapDepthTextureID, 0);
  823. glDrawBuffer(GL_NONE);
  824. glReadBuffer(GL_NONE);
  825. glBindTexture(GL_TEXTURE_2D, 0);
  826. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  827. // Setup shadow map render target
  828. shadowMapRenderTarget.width = shadowMapResolution;
  829. shadowMapRenderTarget.height = shadowMapResolution;
  830. shadowMapRenderTarget.framebuffer = shadowMapFramebuffer;
  831. // Setup shadow map depth texture
  832. shadowMapDepthTexture.setTextureID(shadowMapDepthTextureID);
  833. shadowMapDepthTexture.setWidth(shadowMapResolution);
  834. shadowMapDepthTexture.setHeight(shadowMapResolution);
  835. // Setup silhouette framebuffer
  836. glGenTextures(1, &silhouetteRenderTarget.texture);
  837. glBindTexture(GL_TEXTURE_2D, silhouetteRenderTarget.texture);
  838. glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
  839. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  840. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  841. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  842. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  843. glGenFramebuffers(1, &silhouetteRenderTarget.framebuffer);
  844. glBindFramebuffer(GL_FRAMEBUFFER, silhouetteRenderTarget.framebuffer);
  845. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, silhouetteRenderTarget.texture, 0);
  846. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  847. glReadBuffer(GL_NONE);
  848. glBindTexture(GL_TEXTURE_2D, 0);
  849. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  850. // Setup silhouette render target
  851. silhouetteRenderTarget.width = w;
  852. silhouetteRenderTarget.height = h;
  853. // Setup shadow map render pass
  854. shadowMapPass = new ShadowMapRenderPass(resourceManager);
  855. shadowMapPass->setRenderTarget(&shadowMapRenderTarget);
  856. shadowMapPass->setViewCamera(&camera);
  857. shadowMapPass->setLightCamera(&sunlightCamera);
  858. // Setup shadow map compositor
  859. shadowMapCompositor.addPass(shadowMapPass);
  860. shadowMapCompositor.load(nullptr);
  861. // Setup clear render pass
  862. clearPass = new ClearRenderPass();
  863. clearPass->setRenderTarget(&defaultRenderTarget);
  864. clearPass->setClear(true, true, false);
  865. clearPass->setClearColor(Vector4(0.0f));
  866. clearPass->setClearDepth(1.0f);
  867. // Setup sky render pass
  868. skyPass = new SkyRenderPass(resourceManager);
  869. skyPass->setRenderTarget(&defaultRenderTarget);
  870. // Setup lighting pass
  871. lightingPass = new LightingRenderPass(resourceManager);
  872. lightingPass->setRenderTarget(&defaultRenderTarget);
  873. lightingPass->setShadowMapPass(shadowMapPass);
  874. lightingPass->setShadowMap(&shadowMapDepthTexture);
  875. // Setup clear silhouette pass
  876. clearSilhouettePass = new ClearRenderPass();
  877. clearSilhouettePass->setRenderTarget(&silhouetteRenderTarget);
  878. clearSilhouettePass->setClear(true, false, false);
  879. clearSilhouettePass->setClearColor(Vector4(0.0f));
  880. // Setup silhouette pass
  881. silhouettePass = new SilhouetteRenderPass(resourceManager);
  882. silhouettePass->setRenderTarget(&silhouetteRenderTarget);
  883. // Setup final pass
  884. finalPass = new FinalRenderPass(resourceManager);
  885. finalPass->setRenderTarget(&defaultRenderTarget);
  886. finalPass->setSilhouetteRenderTarget(&silhouetteRenderTarget);
  887. // Setup default compositor
  888. defaultCompositor.addPass(clearPass);
  889. defaultCompositor.addPass(skyPass);
  890. defaultCompositor.addPass(lightingPass);
  891. defaultCompositor.addPass(clearSilhouettePass);
  892. defaultCompositor.addPass(silhouettePass);
  893. //defaultCompositor.addPass(finalPass);
  894. defaultCompositor.load(nullptr);
  895. // Setup UI render pass
  896. uiPass = new UIRenderPass(resourceManager);
  897. uiPass->setRenderTarget(&defaultRenderTarget);
  898. // Setup UI compositor
  899. uiCompositor.addPass(uiPass);
  900. uiCompositor.load(nullptr);
  901. // Create scenes
  902. worldScene = new Scene(&stepInterpolator);
  903. uiScene = new Scene(&stepInterpolator);
  904. // Setup camera
  905. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  906. camera.lookAt(Vector3(0.0f, 4.0f, 2.0f), Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f));
  907. camera.setCompositor(&defaultCompositor);
  908. camera.setCompositeIndex(1);
  909. worldScene->addObject(&camera);
  910. // Setup sun
  911. sunlight.setDirection(Vector3(0, -1, 0));
  912. setTimeOfDay(11.0f);
  913. worldScene->addObject(&sunlight);
  914. // Setup sunlight camera
  915. sunlightCamera.setOrthographic(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
  916. sunlightCamera.setCompositor(&shadowMapCompositor);
  917. sunlightCamera.setCompositeIndex(0);
  918. sunlightCamera.setCullingEnabled(true);
  919. sunlightCamera.setCullingMask(&camera.getViewFrustum());
  920. worldScene->addObject(&sunlightCamera);
  921. }
  922. void Game::setupUI()
  923. {
  924. // Get DPI and convert font size to pixels
  925. const Display* display = deviceManager->getDisplays()->front();
  926. dpi = display->getDPI();
  927. fontSizePX = fontSizePT * (1.0f / 96.0f) * dpi;
  928. logger->log("Detected display DPI as " + std::to_string(dpi) + ".");
  929. logger->log("Fonts size = " + std::to_string(fontSizePT) + " PT = " + std::to_string(fontSizePX) + " PX.");
  930. // Load fonts
  931. loadFonts();
  932. // Load splash screen texture
  933. splashTexture = resourceManager->load<Texture2D>("splash.png");
  934. // Load HUD texture
  935. hudSpriteSheetTexture = resourceManager->load<Texture2D>("hud.png");
  936. // Read texture atlas file
  937. StringTable* atlasTable = resourceManager->load<StringTable>("hud-atlas.csv");
  938. // Build texture atlas
  939. for (int row = 0; row < atlasTable->size(); ++row)
  940. {
  941. std::stringstream ss;
  942. float x;
  943. float y;
  944. float w;
  945. float h;
  946. ss << (*atlasTable)[row][1];
  947. ss >> x;
  948. ss.str(std::string());
  949. ss.clear();
  950. ss << (*atlasTable)[row][2];
  951. ss >> y;
  952. ss.str(std::string());
  953. ss.clear();
  954. ss << (*atlasTable)[row][3];
  955. ss >> w;
  956. ss.str(std::string());
  957. ss.clear();
  958. ss << (*atlasTable)[row][4];
  959. ss >> h;
  960. ss.str(std::string());
  961. y = static_cast<float>(hudSpriteSheetTexture->getHeight()) - y - h;
  962. x = (int)(x + 0.5f);
  963. y = (int)(y + 0.5f);
  964. w = (int)(w + 0.5f);
  965. h = (int)(h + 0.5f);
  966. hudTextureAtlas.insert((*atlasTable)[row][0], Rect(Vector2(x, y), Vector2(x + w, y + h)));
  967. }
  968. // Setup UI batching
  969. uiBatch = new BillboardBatch();
  970. uiBatch->resize(1024);
  971. uiBatcher = new UIBatcher();
  972. // Setup root UI element
  973. uiRootElement = new UIContainer();
  974. eventDispatcher.subscribe<MouseMovedEvent>(uiRootElement);
  975. eventDispatcher.subscribe<MouseButtonPressedEvent>(uiRootElement);
  976. eventDispatcher.subscribe<MouseButtonReleasedEvent>(uiRootElement);
  977. // Create splash screen background element
  978. splashBackgroundImage = new UIImage();
  979. splashBackgroundImage->setLayerOffset(-1);
  980. splashBackgroundImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  981. splashBackgroundImage->setVisible(false);
  982. uiRootElement->addChild(splashBackgroundImage);
  983. // Create splash screen element
  984. splashImage = new UIImage();
  985. splashImage->setTexture(splashTexture);
  986. splashImage->setVisible(false);
  987. uiRootElement->addChild(splashImage);
  988. Rect hudTextureAtlasBounds(Vector2(0), Vector2(hudSpriteSheetTexture->getWidth(), hudSpriteSheetTexture->getHeight()));
  989. auto normalizeTextureBounds = [](const Rect& texture, const Rect& atlas)
  990. {
  991. Vector2 atlasDimensions = Vector2(atlas.getWidth(), atlas.getHeight());
  992. return Rect(texture.getMin() / atlasDimensions, texture.getMax() / atlasDimensions);
  993. };
  994. // Create HUD elements
  995. hudContainer = new UIContainer();
  996. hudContainer->setVisible(false);
  997. uiRootElement->addChild(hudContainer);
  998. toolIndicatorBGImage = new UIImage();
  999. toolIndicatorBGImage->setTexture(hudSpriteSheetTexture);
  1000. toolIndicatorBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds));
  1001. hudContainer->addChild(toolIndicatorBGImage);
  1002. toolIndicatorsBounds = new Rect[8];
  1003. toolIndicatorsBounds[0] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-brush"), hudTextureAtlasBounds);
  1004. toolIndicatorsBounds[1] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-spade"), hudTextureAtlasBounds);
  1005. toolIndicatorsBounds[2] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-lens"), hudTextureAtlasBounds);
  1006. toolIndicatorsBounds[3] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-test-tube"), hudTextureAtlasBounds);
  1007. toolIndicatorsBounds[4] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-forceps"), hudTextureAtlasBounds);
  1008. toolIndicatorsBounds[5] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  1009. toolIndicatorsBounds[6] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  1010. toolIndicatorsBounds[7] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  1011. toolIndicatorIconImage = new UIImage();
  1012. toolIndicatorIconImage->setTexture(hudSpriteSheetTexture);
  1013. toolIndicatorIconImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  1014. toolIndicatorBGImage->addChild(toolIndicatorIconImage);
  1015. buttonContainer = new UIContainer();
  1016. hudContainer->addChild(buttonContainer);
  1017. playButtonBGImage = new UIImage();
  1018. playButtonBGImage->setTexture(hudSpriteSheetTexture);
  1019. playButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1020. //buttonContainer->addChild(playButtonBGImage);
  1021. pauseButtonBGImage = new UIImage();
  1022. pauseButtonBGImage->setTexture(hudSpriteSheetTexture);
  1023. pauseButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1024. //buttonContainer->addChild(pauseButtonBGImage);
  1025. fastForwardButtonBGImage = new UIImage();
  1026. fastForwardButtonBGImage->setTexture(hudSpriteSheetTexture);
  1027. fastForwardButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1028. //buttonContainer->addChild(fastForwardButtonBGImage);
  1029. playButtonImage = new UIImage();
  1030. playButtonImage->setTexture(hudSpriteSheetTexture);
  1031. playButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-play"), hudTextureAtlasBounds));
  1032. //buttonContainer->addChild(playButtonImage);
  1033. fastForwardButtonImage = new UIImage();
  1034. fastForwardButtonImage->setTexture(hudSpriteSheetTexture);
  1035. fastForwardButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-fast-forward-2x"), hudTextureAtlasBounds));
  1036. //buttonContainer->addChild(fastForwardButtonImage);
  1037. pauseButtonImage = new UIImage();
  1038. pauseButtonImage->setTexture(hudSpriteSheetTexture);
  1039. pauseButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-pause"), hudTextureAtlasBounds));
  1040. //buttonContainer->addChild(pauseButtonImage);
  1041. radialMenuContainer = new UIContainer();
  1042. radialMenuContainer->setVisible(false);
  1043. uiRootElement->addChild(radialMenuContainer);
  1044. radialMenuBackgroundImage = new UIImage();
  1045. radialMenuBackgroundImage->setTintColor(Vector4(Vector3(0.0f), 0.25f));
  1046. radialMenuContainer->addChild(radialMenuBackgroundImage);
  1047. radialMenuImage = new UIImage();
  1048. radialMenuImage->setTexture(hudSpriteSheetTexture);
  1049. radialMenuImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu"), hudTextureAtlasBounds));
  1050. radialMenuContainer->addChild(radialMenuImage);
  1051. radialMenuSelectorImage = new UIImage();
  1052. radialMenuSelectorImage->setTexture(hudSpriteSheetTexture);
  1053. radialMenuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu-selector"), hudTextureAtlasBounds));
  1054. radialMenuContainer->addChild(radialMenuSelectorImage);
  1055. toolIconBrushImage = new UIImage();
  1056. toolIconBrushImage->setTexture(hudSpriteSheetTexture);
  1057. toolIconBrushImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  1058. radialMenuImage->addChild(toolIconBrushImage);
  1059. toolIconLensImage = new UIImage();
  1060. toolIconLensImage->setTexture(hudSpriteSheetTexture);
  1061. toolIconLensImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-lens"), hudTextureAtlasBounds));
  1062. radialMenuImage->addChild(toolIconLensImage);
  1063. toolIconForcepsImage = new UIImage();
  1064. toolIconForcepsImage->setTexture(hudSpriteSheetTexture);
  1065. toolIconForcepsImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-forceps"), hudTextureAtlasBounds));
  1066. radialMenuImage->addChild(toolIconForcepsImage);
  1067. toolIconSpadeImage = new UIImage();
  1068. toolIconSpadeImage->setTexture(hudSpriteSheetTexture);
  1069. toolIconSpadeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-spade"), hudTextureAtlasBounds));
  1070. //radialMenuImage->addChild(toolIconSpadeImage);
  1071. toolIconCameraImage = new UIImage();
  1072. toolIconCameraImage->setTexture(hudSpriteSheetTexture);
  1073. toolIconCameraImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-camera"), hudTextureAtlasBounds));
  1074. radialMenuImage->addChild(toolIconCameraImage);
  1075. toolIconMicrochipImage = new UIImage();
  1076. toolIconMicrochipImage->setTexture(hudSpriteSheetTexture);
  1077. toolIconMicrochipImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-microchip"), hudTextureAtlasBounds));
  1078. radialMenuImage->addChild(toolIconMicrochipImage);
  1079. toolIconTestTubeImage = new UIImage();
  1080. toolIconTestTubeImage->setTexture(hudSpriteSheetTexture);
  1081. toolIconTestTubeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-test-tube"), hudTextureAtlasBounds));
  1082. //radialMenuImage->addChild(toolIconTestTubeImage);
  1083. antTag = new UIContainer();
  1084. antTag->setLayerOffset(-10);
  1085. antTag->setVisible(false);
  1086. uiRootElement->addChild(antTag);
  1087. antLabelContainer = new UIContainer();
  1088. antTag->addChild(antLabelContainer);
  1089. antLabelTL = new UIImage();
  1090. antLabelTR = new UIImage();
  1091. antLabelBL = new UIImage();
  1092. antLabelBR = new UIImage();
  1093. antLabelCC = new UIImage();
  1094. antLabelCT = new UIImage();
  1095. antLabelCB = new UIImage();
  1096. antLabelCL = new UIImage();
  1097. antLabelCR = new UIImage();
  1098. antLabelTL->setTexture(hudSpriteSheetTexture);
  1099. antLabelTR->setTexture(hudSpriteSheetTexture);
  1100. antLabelBL->setTexture(hudSpriteSheetTexture);
  1101. antLabelBR->setTexture(hudSpriteSheetTexture);
  1102. antLabelCC->setTexture(hudSpriteSheetTexture);
  1103. antLabelCT->setTexture(hudSpriteSheetTexture);
  1104. antLabelCB->setTexture(hudSpriteSheetTexture);
  1105. antLabelCL->setTexture(hudSpriteSheetTexture);
  1106. antLabelCR->setTexture(hudSpriteSheetTexture);
  1107. Rect labelTLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tl"), hudTextureAtlasBounds);
  1108. Rect labelTRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tr"), hudTextureAtlasBounds);
  1109. Rect labelBLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-bl"), hudTextureAtlasBounds);
  1110. Rect labelBRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-br"), hudTextureAtlasBounds);
  1111. Rect labelCCBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cc"), hudTextureAtlasBounds);
  1112. Rect labelCTBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-ct"), hudTextureAtlasBounds);
  1113. Rect labelCBBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cb"), hudTextureAtlasBounds);
  1114. Rect labelCLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cl"), hudTextureAtlasBounds);
  1115. Rect labelCRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cr"), hudTextureAtlasBounds);
  1116. Vector2 labelTLMin = labelTLBounds.getMin();
  1117. Vector2 labelTRMin = labelTRBounds.getMin();
  1118. Vector2 labelBLMin = labelBLBounds.getMin();
  1119. Vector2 labelBRMin = labelBRBounds.getMin();
  1120. Vector2 labelCCMin = labelCCBounds.getMin();
  1121. Vector2 labelCTMin = labelCTBounds.getMin();
  1122. Vector2 labelCBMin = labelCBBounds.getMin();
  1123. Vector2 labelCLMin = labelCLBounds.getMin();
  1124. Vector2 labelCRMin = labelCRBounds.getMin();
  1125. Vector2 labelTLMax = labelTLBounds.getMax();
  1126. Vector2 labelTRMax = labelTRBounds.getMax();
  1127. Vector2 labelBLMax = labelBLBounds.getMax();
  1128. Vector2 labelBRMax = labelBRBounds.getMax();
  1129. Vector2 labelCCMax = labelCCBounds.getMax();
  1130. Vector2 labelCTMax = labelCTBounds.getMax();
  1131. Vector2 labelCBMax = labelCBBounds.getMax();
  1132. Vector2 labelCLMax = labelCLBounds.getMax();
  1133. Vector2 labelCRMax = labelCRBounds.getMax();
  1134. antLabelTL->setTextureBounds(labelTLBounds);
  1135. antLabelTR->setTextureBounds(labelTRBounds);
  1136. antLabelBL->setTextureBounds(labelBLBounds);
  1137. antLabelBR->setTextureBounds(labelBRBounds);
  1138. antLabelCC->setTextureBounds(labelCCBounds);
  1139. antLabelCT->setTextureBounds(labelCTBounds);
  1140. antLabelCB->setTextureBounds(labelCBBounds);
  1141. antLabelCL->setTextureBounds(labelCLBounds);
  1142. antLabelCR->setTextureBounds(labelCRBounds);
  1143. antLabelContainer->addChild(antLabelTL);
  1144. antLabelContainer->addChild(antLabelTR);
  1145. antLabelContainer->addChild(antLabelBL);
  1146. antLabelContainer->addChild(antLabelBR);
  1147. antLabelContainer->addChild(antLabelCC);
  1148. antLabelContainer->addChild(antLabelCT);
  1149. antLabelContainer->addChild(antLabelCB);
  1150. antLabelContainer->addChild(antLabelCL);
  1151. antLabelContainer->addChild(antLabelCR);
  1152. antLabel = new UILabel();
  1153. antLabel->setFont(nullptr);
  1154. antLabel->setText("");
  1155. antLabel->setTintColor(Vector4(Vector3(0.0f), 1.0f));
  1156. antLabel->setLayerOffset(1);
  1157. antLabelContainer->addChild(antLabel);
  1158. fpsLabel = new UILabel();
  1159. fpsLabel->setFont(debugFont);
  1160. fpsLabel->setTintColor(Vector4(1, 1, 0, 1));
  1161. fpsLabel->setLayerOffset(50);
  1162. fpsLabel->setAnchor(Anchor::TOP_LEFT);
  1163. uiRootElement->addChild(fpsLabel);
  1164. antPin = new UIImage();
  1165. antPin->setTexture(hudSpriteSheetTexture);
  1166. antPin->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin"), hudTextureAtlasBounds));
  1167. antTag->addChild(antPin);
  1168. antLabelPinHole = new UIImage();
  1169. antLabelPinHole->setTexture(hudSpriteSheetTexture);
  1170. antLabelPinHole->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin-hole"), hudTextureAtlasBounds));
  1171. antLabelContainer->addChild(antLabelPinHole);
  1172. // Construct box selection
  1173. boxSelectionImageBackground = new UIImage();
  1174. boxSelectionImageBackground->setAnchor(Anchor::CENTER);
  1175. boxSelectionImageTop = new UIImage();
  1176. boxSelectionImageTop->setAnchor(Anchor::TOP_LEFT);
  1177. boxSelectionImageBottom = new UIImage();
  1178. boxSelectionImageBottom->setAnchor(Anchor::BOTTOM_LEFT);
  1179. boxSelectionImageLeft = new UIImage();
  1180. boxSelectionImageLeft->setAnchor(Anchor::TOP_LEFT);
  1181. boxSelectionImageRight = new UIImage();
  1182. boxSelectionImageRight->setAnchor(Anchor::TOP_RIGHT);
  1183. boxSelectionContainer = new UIContainer();
  1184. boxSelectionContainer->setLayerOffset(80);
  1185. boxSelectionContainer->addChild(boxSelectionImageBackground);
  1186. boxSelectionContainer->addChild(boxSelectionImageTop);
  1187. boxSelectionContainer->addChild(boxSelectionImageBottom);
  1188. boxSelectionContainer->addChild(boxSelectionImageLeft);
  1189. boxSelectionContainer->addChild(boxSelectionImageRight);
  1190. boxSelectionContainer->setVisible(false);
  1191. uiRootElement->addChild(boxSelectionContainer);
  1192. boxSelectionImageBackground->setTintColor(Vector4(1.0f, 1.0f, 1.0f, 0.5f));
  1193. boxSelectionContainer->setTintColor(Vector4(1.0f, 0.0f, 0.0f, 1.0f));
  1194. boxSelectionBorderWidth = 2.0f;
  1195. cameraGridColor = Vector4(1, 1, 1, 0.5f);
  1196. cameraReticleColor = Vector4(1, 1, 1, 0.75f);
  1197. cameraGridY0Image = new UIImage();
  1198. cameraGridY0Image->setAnchor(Vector2(0.5f, (1.0f / 3.0f)));
  1199. cameraGridY0Image->setTintColor(cameraGridColor);
  1200. cameraGridY1Image = new UIImage();
  1201. cameraGridY1Image->setAnchor(Vector2(0.5f, (2.0f / 3.0f)));
  1202. cameraGridY1Image->setTintColor(cameraGridColor);
  1203. cameraGridX0Image = new UIImage();
  1204. cameraGridX0Image->setAnchor(Vector2((1.0f / 3.0f), 0.5f));
  1205. cameraGridX0Image->setTintColor(cameraGridColor);
  1206. cameraGridX1Image = new UIImage();
  1207. cameraGridX1Image->setAnchor(Vector2((2.0f / 3.0f), 0.5f));
  1208. cameraGridX1Image->setTintColor(cameraGridColor);
  1209. cameraReticleImage = new UIImage();
  1210. cameraReticleImage->setAnchor(Anchor::CENTER);
  1211. cameraReticleImage->setTintColor(cameraReticleColor);
  1212. cameraReticleImage->setTexture(hudSpriteSheetTexture);
  1213. cameraReticleImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("camera-reticle"), hudTextureAtlasBounds));
  1214. cameraGridContainer = new UIContainer();
  1215. cameraGridContainer->addChild(cameraGridY0Image);
  1216. cameraGridContainer->addChild(cameraGridY1Image);
  1217. cameraGridContainer->addChild(cameraGridX0Image);
  1218. cameraGridContainer->addChild(cameraGridX1Image);
  1219. cameraGridContainer->addChild(cameraReticleImage);
  1220. cameraGridContainer->setVisible(false);
  1221. uiRootElement->addChild(cameraGridContainer);
  1222. cameraFlashImage = new UIImage();
  1223. cameraFlashImage->setLayerOffset(99);
  1224. cameraFlashImage->setTintColor(Vector4(1.0f));
  1225. cameraFlashImage->setVisible(false);
  1226. uiRootElement->addChild(cameraFlashImage);
  1227. blackoutImage = new UIImage();
  1228. blackoutImage->setLayerOffset(98);
  1229. blackoutImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1230. blackoutImage->setVisible(false);
  1231. uiRootElement->addChild(blackoutImage);
  1232. languageSelectBGImage = new UIImage();
  1233. languageSelectBGImage->setLayerOffset(-1);
  1234. languageSelectBGImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1235. languageSelectBGImage->setVisible(true);
  1236. standardMenuActiveColor = Vector4(Vector3(0.2f), 1.0f);
  1237. standardMenuInactiveColor = Vector4(Vector3(0.2f), 0.5f);
  1238. languageMenuActiveColor = Vector4(Vector3(1.0f), 1.0f);
  1239. languageMenuInactiveColor = Vector4(Vector3(1.0f), 0.5f);
  1240. menuItemActiveColor = standardMenuActiveColor;
  1241. menuItemInactiveColor = standardMenuInactiveColor;
  1242. menuItemIndex = -1;
  1243. currentMenu = nullptr;
  1244. currentMenuItem = nullptr;
  1245. previousMenuItem = nullptr;
  1246. previousMenu = nullptr;
  1247. menuSelectorImage = new UIImage();
  1248. menuSelectorImage->setAnchor(Anchor::TOP_LEFT);
  1249. menuSelectorImage->setTexture(hudSpriteSheetTexture);
  1250. menuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("menu-selector"), hudTextureAtlasBounds));
  1251. menuSelectorImage->setTintColor(menuItemActiveColor);
  1252. // Build main menu
  1253. mainMenu = new Menu();
  1254. mainMenuContinueItem = mainMenu->addItem();
  1255. mainMenuNewGameItem = mainMenu->addItem();
  1256. mainMenuColoniesItem = mainMenu->addItem();
  1257. mainMenuSettingsItem = mainMenu->addItem();
  1258. mainMenuQuitItem = mainMenu->addItem();
  1259. // Build settings menu
  1260. settingsMenu = new Menu();
  1261. settingsMenuControlsItem = settingsMenu->addItem();
  1262. settingsMenuFullscreenItem = settingsMenu->addItem();
  1263. settingsMenuVSyncItem = settingsMenu->addItem();
  1264. settingsMenuLanguageItem = settingsMenu->addItem();
  1265. settingsMenuBackItem = settingsMenu->addItem();
  1266. // Build controls menu
  1267. controlsMenu = new Menu();
  1268. controlsMenuMoveForwardItem = controlsMenu->addItem();
  1269. controlsMenuMoveLeftItem = controlsMenu->addItem();
  1270. controlsMenuMoveBackItem = controlsMenu->addItem();
  1271. controlsMenuMoveRightItem = controlsMenu->addItem();
  1272. controlsMenuChangeToolItem = controlsMenu->addItem();
  1273. controlsMenuUseToolItem = controlsMenu->addItem();
  1274. controlsMenuAdjustCameraItem = controlsMenu->addItem();
  1275. controlsMenuPauseItem = controlsMenu->addItem();
  1276. controlsMenuToggleFullscreenItem = controlsMenu->addItem();
  1277. controlsMenuTakeScreenshotItem = controlsMenu->addItem();
  1278. controlsMenuResetToDefaultItem = controlsMenu->addItem();
  1279. controlsMenuBackItem = controlsMenu->addItem();
  1280. // Build pause menu
  1281. pauseMenu = new Menu();
  1282. pauseMenuResumeItem = pauseMenu->addItem();
  1283. pauseMenuSettingsItem = pauseMenu->addItem();
  1284. pauseMenuMainMenuItem = pauseMenu->addItem();
  1285. pauseMenuQuitItem = pauseMenu->addItem();
  1286. // Build language menu
  1287. languageMenu = new Menu();
  1288. for (std::size_t i = 0; i < languageCount; ++i)
  1289. {
  1290. MenuItem* item = languageMenu->addItem();
  1291. item->setActivatedCallback
  1292. (
  1293. [this, i]()
  1294. {
  1295. changeLanguage(i);
  1296. languageSelected();
  1297. }
  1298. );
  1299. item->getContainer()->setTintColor(languageMenuInactiveColor);
  1300. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1301. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1302. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1303. languageMenuItems.push_back(item);
  1304. }
  1305. // Setup main menu callbacks
  1306. mainMenuContinueItem->setActivatedCallback(std::bind(&Game::continueGame, this));
  1307. mainMenuNewGameItem->setActivatedCallback(std::bind(&Game::newGame, this));
  1308. mainMenuSettingsItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1309. mainMenuQuitItem->setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1310. // Setup settings menu callbacks
  1311. settingsMenuControlsItem->setActivatedCallback(std::bind(&Game::openMenu, this, controlsMenu, 0));
  1312. settingsMenuFullscreenItem->setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1313. settingsMenuVSyncItem->setActivatedCallback(std::bind(&Game::toggleVSync, this));
  1314. settingsMenuLanguageItem->setActivatedCallback(std::bind(&Game::nextLanguage, this));
  1315. settingsMenuBackItem->setActivatedCallback(std::bind(&Game::openMenu, this, mainMenu, 3));
  1316. // Setup controls menu callbacks
  1317. controlsMenuMoveForwardItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveForwardControl));
  1318. controlsMenuMoveLeftItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveLeftControl));
  1319. controlsMenuMoveBackItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveBackControl));
  1320. controlsMenuMoveRightItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveRightControl));
  1321. controlsMenuChangeToolItem->setActivatedCallback(std::bind(&Game::remapControl, this, &changeToolControl));
  1322. controlsMenuUseToolItem->setActivatedCallback(std::bind(&Game::remapControl, this, &useToolControl));
  1323. controlsMenuAdjustCameraItem->setActivatedCallback(std::bind(&Game::remapControl, this, &adjustCameraControl));
  1324. controlsMenuPauseItem->setActivatedCallback(std::bind(&Game::remapControl, this, &pauseControl));
  1325. controlsMenuToggleFullscreenItem->setActivatedCallback(std::bind(&Game::remapControl, this, &toggleFullscreenControl));
  1326. controlsMenuTakeScreenshotItem->setActivatedCallback(std::bind(&Game::remapControl, this, &takeScreenshotControl));
  1327. controlsMenuResetToDefaultItem->setActivatedCallback(std::bind(&Game::resetControls, this));
  1328. controlsMenuBackItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1329. // Setup pause menu callbacks
  1330. pauseMenuResumeItem->setActivatedCallback(std::bind(&Game::togglePause, this));
  1331. pauseMenuSettingsItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1332. pauseMenuMainMenuItem->setActivatedCallback(std::bind(&Game::returnToMainMenu, this));
  1333. pauseMenuQuitItem->setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1334. // Setup standard callbacks for all menu items
  1335. for (std::size_t i = 0; i < mainMenu->getItems()->size(); ++i)
  1336. {
  1337. MenuItem* item = (*mainMenu->getItems())[i];
  1338. item->getContainer()->setTintColor(menuItemInactiveColor);
  1339. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1340. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1341. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1342. }
  1343. for (std::size_t i = 0; i < settingsMenu->getItems()->size(); ++i)
  1344. {
  1345. MenuItem* item = (*settingsMenu->getItems())[i];
  1346. item->getContainer()->setTintColor(menuItemInactiveColor);
  1347. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1348. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1349. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1350. }
  1351. for (std::size_t i = 0; i < controlsMenu->getItems()->size(); ++i)
  1352. {
  1353. MenuItem* item = (*controlsMenu->getItems())[i];
  1354. item->getContainer()->setTintColor(menuItemInactiveColor);
  1355. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1356. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1357. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1358. }
  1359. for (std::size_t i = 0; i < pauseMenu->getItems()->size(); ++i)
  1360. {
  1361. MenuItem* item = (*pauseMenu->getItems())[i];
  1362. item->getContainer()->setTintColor(menuItemInactiveColor);
  1363. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1364. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1365. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1366. }
  1367. // Set fonts for all menus
  1368. mainMenu->setFonts(menuFont);
  1369. settingsMenu->setFonts(menuFont);
  1370. controlsMenu->setFonts(menuFont);
  1371. pauseMenu->setFonts(menuFont);
  1372. AnimationChannel<float>* channel;
  1373. // Setup splash fade-in animation
  1374. splashFadeInClip.setInterpolator(easeOutCubic<float>);
  1375. channel = splashFadeInClip.addChannel(0);
  1376. channel->insertKeyframe(0.0f, 0.0f);
  1377. channel->insertKeyframe(1.0f, 1.0f);
  1378. channel->insertKeyframe(3.0f, 1.0f);
  1379. splashFadeInAnimation.setClip(&splashFadeInClip);
  1380. splashFadeInAnimation.setTimeFrame(splashFadeInClip.getTimeFrame());
  1381. splashFadeInAnimation.setAnimateCallback
  1382. (
  1383. [this](std::size_t id, float opacity)
  1384. {
  1385. Vector3 color = Vector3(splashImage->getTintColor());
  1386. splashImage->setTintColor(Vector4(color, opacity));
  1387. }
  1388. );
  1389. splashFadeInAnimation.setEndCallback
  1390. (
  1391. [this]()
  1392. {
  1393. splashFadeOutAnimation.rewind();
  1394. splashFadeOutAnimation.play();
  1395. }
  1396. );
  1397. // Setup splash fade-out animation
  1398. splashFadeOutClip.setInterpolator(easeOutCubic<float>);
  1399. channel = splashFadeOutClip.addChannel(0);
  1400. channel->insertKeyframe(0.0f, 1.0f);
  1401. channel->insertKeyframe(1.0f, 0.0f);
  1402. channel->insertKeyframe(1.5f, 0.0f);
  1403. splashFadeOutAnimation.setClip(&splashFadeOutClip);
  1404. splashFadeOutAnimation.setTimeFrame(splashFadeOutClip.getTimeFrame());
  1405. splashFadeOutAnimation.setAnimateCallback
  1406. (
  1407. [this](std::size_t id, float opacity)
  1408. {
  1409. Vector3 color = Vector3(splashImage->getTintColor());
  1410. splashImage->setTintColor(Vector4(color, opacity));
  1411. }
  1412. );
  1413. splashFadeOutAnimation.setEndCallback(std::bind(&StateMachine::changeState, this, &titleState));
  1414. // Ant-hill zoom animation
  1415. antHillZoomClip.setInterpolator(easeOutCubic<float>);
  1416. channel = antHillZoomClip.addChannel(0);
  1417. channel->insertKeyframe(0.0f, 0.0f);
  1418. channel->insertKeyframe(3.0f, 40.0f);
  1419. antHillZoomAnimation.setClip(&antHillZoomClip);
  1420. antHillZoomAnimation.setTimeFrame(antHillZoomClip.getTimeFrame());
  1421. antHillZoomAnimation.setAnimateCallback
  1422. (
  1423. [this](std::size_t id, float distance)
  1424. {
  1425. orbitCam->setFocalDistance(distance);
  1426. orbitCam->setTargetFocalDistance(distance);
  1427. }
  1428. );
  1429. // Menu fade animation
  1430. menuFadeInClip.setInterpolator(easeOutCubic<float>);
  1431. channel = menuFadeInClip.addChannel(0);
  1432. channel->insertKeyframe(0.0f, 0.0f);
  1433. channel->insertKeyframe(3.0f, 0.0f);
  1434. channel->insertKeyframe(5.0f, 1.0f);
  1435. menuFadeOutClip.setInterpolator(easeOutCubic<float>);
  1436. channel = menuFadeOutClip.addChannel(0);
  1437. channel->insertKeyframe(0.0f, 1.0f);
  1438. channel->insertKeyframe(0.125f, 0.0f);
  1439. menuFadeAnimation.setClip(&menuFadeInClip);
  1440. menuFadeAnimation.setTimeFrame(menuFadeInClip.getTimeFrame());
  1441. menuFadeAnimation.setAnimateCallback
  1442. (
  1443. [this](std::size_t id, float opacity)
  1444. {
  1445. currentMenu->getContainer()->setTintColor(Vector4(opacity));
  1446. }
  1447. );
  1448. animator.addAnimation(&menuFadeAnimation);
  1449. // Menu selector animation
  1450. menuSelectorSlideClip.setInterpolator(easeOutCubic<float>);
  1451. menuSelectorSlideAnimation.setClip(&menuSelectorSlideClip);
  1452. menuSelectorSlideAnimation.setAnimateCallback
  1453. (
  1454. [this](std::size_t id, float offset)
  1455. {
  1456. Vector2 translation = menuSelectorImage->getTranslation();
  1457. translation.y = offset;
  1458. menuSelectorImage->setTranslation(translation);
  1459. }
  1460. );
  1461. animator.addAnimation(&menuSelectorSlideAnimation);
  1462. // Menu item select animation
  1463. menuItemSelectClip.setInterpolator(easeOutCubic<Vector4>);
  1464. menuItemSelectAnimation.setClip(&menuItemSelectClip);
  1465. menuItemSelectAnimation.setAnimateCallback
  1466. (
  1467. [this](std::size_t id, const Vector4& color)
  1468. {
  1469. currentMenuItem->getContainer()->setTintColor(color);
  1470. }
  1471. );
  1472. // Menu item deselect animation
  1473. menuItemDeselectClip.setInterpolator(easeOutCubic<Vector4>);
  1474. menuItemDeselectAnimation.setClip(&menuItemDeselectClip);
  1475. menuItemDeselectAnimation.setAnimateCallback
  1476. (
  1477. [this](std::size_t id, const Vector4& color)
  1478. {
  1479. previousMenuItem->getContainer()->setTintColor(color);
  1480. }
  1481. );
  1482. animator.addAnimation(&menuItemSelectAnimation);
  1483. animator.addAnimation(&menuItemDeselectAnimation);
  1484. // Construct fade-in animation clip
  1485. fadeInClip.setInterpolator(easeOutCubic<float>);
  1486. channel = fadeInClip.addChannel(0);
  1487. channel->insertKeyframe(0.0f, 1.0f);
  1488. channel->insertKeyframe(1.0f, 0.0f);
  1489. // Construct fade-out animation clip
  1490. fadeOutClip.setInterpolator(easeOutCubic<float>);
  1491. channel = fadeOutClip.addChannel(0);
  1492. channel->insertKeyframe(0.0f, 0.0f);
  1493. channel->insertKeyframe(1.0f, 1.0f);
  1494. // Setup fade-in animation callbacks
  1495. fadeInAnimation.setAnimateCallback
  1496. (
  1497. [this](std::size_t id, float opacity)
  1498. {
  1499. Vector3 color = Vector3(blackoutImage->getTintColor());
  1500. blackoutImage->setTintColor(Vector4(color, opacity));
  1501. }
  1502. );
  1503. fadeInAnimation.setEndCallback
  1504. (
  1505. [this]()
  1506. {
  1507. blackoutImage->setVisible(false);
  1508. if (fadeInEndCallback != nullptr)
  1509. {
  1510. fadeInEndCallback();
  1511. }
  1512. }
  1513. );
  1514. // Setup fade-out animation callbacks
  1515. fadeOutAnimation.setAnimateCallback
  1516. (
  1517. [this](std::size_t id, float opacity)
  1518. {
  1519. Vector3 color = Vector3(blackoutImage->getTintColor());
  1520. blackoutImage->setTintColor(Vector4(color, opacity));
  1521. }
  1522. );
  1523. fadeOutAnimation.setEndCallback
  1524. (
  1525. [this]()
  1526. {
  1527. blackoutImage->setVisible(false);
  1528. if (fadeOutEndCallback != nullptr)
  1529. {
  1530. fadeOutEndCallback();
  1531. }
  1532. }
  1533. );
  1534. animator.addAnimation(&fadeInAnimation);
  1535. animator.addAnimation(&fadeOutAnimation);
  1536. // Construct camera flash animation clip
  1537. cameraFlashClip.setInterpolator(easeOutQuad<float>);
  1538. channel = cameraFlashClip.addChannel(0);
  1539. channel->insertKeyframe(0.0f, 1.0f);
  1540. channel->insertKeyframe(1.0f, 0.0f);
  1541. // Setup camera flash animation
  1542. float flashDuration = 0.5f;
  1543. cameraFlashAnimation.setSpeed(1.0f / flashDuration);
  1544. cameraFlashAnimation.setLoop(false);
  1545. cameraFlashAnimation.setClip(&cameraFlashClip);
  1546. cameraFlashAnimation.setTimeFrame(cameraFlashClip.getTimeFrame());
  1547. cameraFlashAnimation.setAnimateCallback
  1548. (
  1549. [this](std::size_t id, float opacity)
  1550. {
  1551. cameraFlashImage->setTintColor(Vector4(Vector3(1.0f), opacity));
  1552. }
  1553. );
  1554. cameraFlashAnimation.setStartCallback
  1555. (
  1556. [this]()
  1557. {
  1558. cameraFlashImage->setVisible(true);
  1559. cameraFlashImage->setTintColor(Vector4(1.0f));
  1560. cameraFlashImage->resetTweens();
  1561. }
  1562. );
  1563. cameraFlashAnimation.setEndCallback
  1564. (
  1565. [this]()
  1566. {
  1567. cameraFlashImage->setVisible(false);
  1568. }
  1569. );
  1570. animator.addAnimation(&cameraFlashAnimation);
  1571. // Setup UI scene
  1572. uiScene->addObject(uiBatch);
  1573. uiScene->addObject(&uiCamera);
  1574. // Setup UI camera
  1575. uiCamera.lookAt(Vector3(0), Vector3(0, 0, -1), Vector3(0, 1, 0));
  1576. uiCamera.resetTweens();
  1577. uiCamera.setCompositor(&uiCompositor);
  1578. uiCamera.setCompositeIndex(0);
  1579. uiCamera.setCullingEnabled(false);
  1580. restringUI();
  1581. resizeUI(w, h);
  1582. }
  1583. void Game::setupControls()
  1584. {
  1585. // Get keyboard and mouse
  1586. keyboard = deviceManager->getKeyboards()->front();
  1587. mouse = deviceManager->getMice()->front();
  1588. // Build the master control set
  1589. controls.addControl(&exitControl);
  1590. controls.addControl(&toggleFullscreenControl);
  1591. controls.addControl(&takeScreenshotControl);
  1592. controls.addControl(&menuUpControl);
  1593. controls.addControl(&menuDownControl);
  1594. controls.addControl(&menuLeftControl);
  1595. controls.addControl(&menuRightControl);
  1596. controls.addControl(&menuActivateControl);
  1597. controls.addControl(&menuBackControl);
  1598. controls.addControl(&moveForwardControl);
  1599. controls.addControl(&moveBackControl);
  1600. controls.addControl(&moveLeftControl);
  1601. controls.addControl(&moveRightControl);
  1602. controls.addControl(&zoomInControl);
  1603. controls.addControl(&zoomOutControl);
  1604. controls.addControl(&orbitCCWControl);
  1605. controls.addControl(&orbitCWControl);
  1606. controls.addControl(&adjustCameraControl);
  1607. controls.addControl(&dragCameraControl);
  1608. controls.addControl(&pauseControl);
  1609. controls.addControl(&changeToolControl);
  1610. controls.addControl(&useToolControl);
  1611. controls.addControl(&toggleEditModeControl);
  1612. // Build the system control set
  1613. systemControls.addControl(&exitControl);
  1614. systemControls.addControl(&toggleFullscreenControl);
  1615. systemControls.addControl(&takeScreenshotControl);
  1616. // Build the menu control set
  1617. menuControls.addControl(&menuUpControl);
  1618. menuControls.addControl(&menuDownControl);
  1619. menuControls.addControl(&menuLeftControl);
  1620. menuControls.addControl(&menuRightControl);
  1621. menuControls.addControl(&menuActivateControl);
  1622. menuControls.addControl(&menuBackControl);
  1623. // Build the camera control set
  1624. cameraControls.addControl(&moveForwardControl);
  1625. cameraControls.addControl(&moveBackControl);
  1626. cameraControls.addControl(&moveLeftControl);
  1627. cameraControls.addControl(&moveRightControl);
  1628. cameraControls.addControl(&zoomInControl);
  1629. cameraControls.addControl(&zoomOutControl);
  1630. cameraControls.addControl(&orbitCCWControl);
  1631. cameraControls.addControl(&orbitCWControl);
  1632. cameraControls.addControl(&adjustCameraControl);
  1633. cameraControls.addControl(&dragCameraControl);
  1634. cameraControls.addControl(&pauseControl);
  1635. // Build the tool control set
  1636. toolControls.addControl(&changeToolControl);
  1637. toolControls.addControl(&useToolControl);
  1638. // Build the editor control set
  1639. editorControls.addControl(&toggleEditModeControl);
  1640. // Setup control callbacks
  1641. menuDownControl.setActivatedCallback(std::bind(&Game::selectNextMenuItem, this));
  1642. menuUpControl.setActivatedCallback(std::bind(&Game::selectPreviousMenuItem, this));
  1643. menuActivateControl.setActivatedCallback(std::bind(&Game::activateMenuItem, this));
  1644. menuBackControl.setActivatedCallback(std::bind(&Game::activateLastMenuItem, this));
  1645. pauseControl.setActivatedCallback(std::bind(&Game::togglePause, this));
  1646. exitControl.setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1647. toggleFullscreenControl.setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1648. takeScreenshotControl.setActivatedCallback(std::bind(&Game::queueScreenshot, this));
  1649. // Build map of control names
  1650. controlNameMap["exit"] = &exitControl;
  1651. controlNameMap["toggle-fullscreen"] = &toggleFullscreenControl;
  1652. controlNameMap["take-screenshot"] = &takeScreenshotControl;
  1653. controlNameMap["menu-up"] = &menuUpControl;
  1654. controlNameMap["menu-down"] = &menuDownControl;
  1655. controlNameMap["menu-left"] = &menuLeftControl;
  1656. controlNameMap["menu-right"] = &menuRightControl;
  1657. controlNameMap["menu-activate"] = &menuActivateControl;
  1658. controlNameMap["menu-back"] = &menuBackControl;
  1659. controlNameMap["move-forward"] = &moveForwardControl;
  1660. controlNameMap["move-back"] = &moveBackControl;
  1661. controlNameMap["move-left"] = &moveLeftControl;
  1662. controlNameMap["move-right"] = &moveRightControl;
  1663. controlNameMap["zoom-in"] = &zoomInControl;
  1664. controlNameMap["zoom-out"] = &zoomOutControl;
  1665. controlNameMap["orbit-ccw"] = &orbitCCWControl;
  1666. controlNameMap["orbit-cw"] = &orbitCWControl;
  1667. controlNameMap["adjust-camera"] = &adjustCameraControl;
  1668. controlNameMap["drag-camera"] = &dragCameraControl;
  1669. controlNameMap["pause"] = &pauseControl;
  1670. controlNameMap["change-tool"] = &changeToolControl;
  1671. controlNameMap["use-tool"] = &useToolControl;
  1672. controlNameMap["toggle-edit-mode"] = &toggleEditModeControl;
  1673. // Load control profile
  1674. if (pathExists(controlsPath + controlProfileName + ".csv"))
  1675. {
  1676. loadControlProfile(controlProfileName);
  1677. }
  1678. else
  1679. {
  1680. loadControlProfile("default-keyboard-controls");
  1681. saveControlProfile(controlProfileName);
  1682. }
  1683. // Setup input mapper
  1684. inputMapper = new InputMapper(&eventDispatcher);
  1685. inputMapper->setCallback(std::bind(&Game::inputMapped, this, std::placeholders::_1));
  1686. inputMapper->setControl(nullptr);
  1687. inputMapper->setEnabled(false);
  1688. }
  1689. void Game::setupGameplay()
  1690. {
  1691. // Setup step scheduler
  1692. double maxFrameDuration = 0.25;
  1693. double stepFrequency = 60.0;
  1694. stepScheduler.setMaxFrameDuration(maxFrameDuration);
  1695. stepScheduler.setStepFrequency(stepFrequency);
  1696. timestep = stepScheduler.getStepPeriod();
  1697. // Setup camera rigs
  1698. orbitCam = new OrbitCam();
  1699. orbitCam->attachCamera(&camera);
  1700. freeCam = new FreeCam();
  1701. freeCam->attachCamera(&camera);
  1702. cameraRig = orbitCam;
  1703. }
  1704. void Game::resetSettings()
  1705. {
  1706. // Set default language
  1707. language = "en-us";
  1708. // Set default resolutions
  1709. const Display* display = deviceManager->getDisplays()->front();
  1710. int displayWidth = std::get<0>(display->getDimensions());
  1711. int displayHeight = std::get<1>(display->getDimensions());
  1712. float windowedResolutionRatio = 5.0f / 6.0f;
  1713. windowedResolution = Vector2(displayWidth, displayHeight) * 5.0f / 6.0f;
  1714. windowedResolution.x = static_cast<int>(windowedResolution.x);
  1715. windowedResolution.y = static_cast<int>(windowedResolution.y);
  1716. fullscreenResolution = Vector2(displayWidth, displayHeight);
  1717. // Set default fullscreen mode
  1718. fullscreen = false;
  1719. // Set default vsync mode
  1720. vsync = true;
  1721. // Set default font size
  1722. fontSizePT = 14.0f;
  1723. // Set control profile name
  1724. controlProfileName = "controls";
  1725. }
  1726. void Game::loadSettings()
  1727. {
  1728. // Reset settings to default values
  1729. resetSettings();
  1730. firstRun = false;
  1731. // Load settings table
  1732. try
  1733. {
  1734. settingsTable = resourceManager->load<StringTable>("settings.csv");
  1735. }
  1736. catch (const std::exception& e)
  1737. {
  1738. logger->warning("No user settings found. First run assumed.");
  1739. firstRun = true;
  1740. try
  1741. {
  1742. settingsTable = resourceManager->load<StringTable>("default-settings.csv");
  1743. }
  1744. catch (const std::exception& e)
  1745. {
  1746. logger->error("Failed to load default settings.");
  1747. }
  1748. }
  1749. // Build settings table index
  1750. settingsTableIndex = createIndex(*settingsTable);
  1751. // Read settings from table
  1752. readSetting("language", &language);
  1753. readSetting("windowed-resolution", &windowedResolution);
  1754. readSetting("fullscreen-resolution", &fullscreenResolution);
  1755. readSetting("fullscreen", &fullscreen);
  1756. readSetting("vsync", &vsync);
  1757. readSetting("font-size", &fontSizePT);
  1758. readSetting("control-profile", &controlProfileName);
  1759. }
  1760. void Game::saveSettings()
  1761. {
  1762. }
  1763. void Game::loadStrings()
  1764. {
  1765. // Read strings file
  1766. stringTable = resourceManager->load<StringTable>("strings.csv");
  1767. // Build string table index
  1768. stringTableIndex = createIndex(*stringTable);
  1769. }
  1770. void Game::loadFonts()
  1771. {
  1772. // If the language selection fonts haven't been loaded
  1773. if (languageSelectionFonts.empty())
  1774. {
  1775. // Load one font for each available language
  1776. for (std::size_t i = 0; i < languageCount; ++i)
  1777. {
  1778. // Get language name and font filename for that language
  1779. std::string languageName = getString("language-name", i);
  1780. std::string fontFilename = getString("menu-font-filename", i);
  1781. // Check if language has a name
  1782. if (languageName.empty())
  1783. {
  1784. logger->error("Language #" + std::to_string(i) + " has no name string.");
  1785. languageSelectionFonts.push_back(nullptr);
  1786. continue;
  1787. }
  1788. // Check if language has a font filename
  1789. if (fontFilename.empty())
  1790. {
  1791. logger->error("No font for language #" + std::to_string(i) + ".");
  1792. languageSelectionFonts.push_back(nullptr);
  1793. continue;
  1794. }
  1795. // Load typeface for the font
  1796. Typeface* typeface = resourceManager->load<Typeface>(fontFilename);
  1797. // Create a font at default font size
  1798. Font* font = typeface->createFont(fontSizePX);
  1799. // Build a character set containing only the characters in the language name
  1800. std::set<char32_t> characterSet;
  1801. std::u32string languageNameUTF32 = toUTF32(languageName);
  1802. for (char32_t charcode: languageNameUTF32)
  1803. {
  1804. characterSet.emplace(charcode);
  1805. }
  1806. // Load glyphs for all characters in the character set
  1807. typeface->loadCharset(font, characterSet);
  1808. // Unload the typeface
  1809. resourceManager->unload(fontFilename);
  1810. // Add the font to the language selection fonts
  1811. languageSelectionFonts.push_back(font);
  1812. }
  1813. }
  1814. // Get filenames of fonts
  1815. std::string menuFontFilename = getString("menu-font-filename");
  1816. std::string debugFontFilename = "inconsolata-bold.ttf";
  1817. // Load debugging font
  1818. if (!debugFont)
  1819. {
  1820. // Load debug font typeface
  1821. Typeface* debugTypeface = resourceManager->load<Typeface>(debugFontFilename);
  1822. // Create debug font
  1823. debugFont = debugTypeface->createFont(fontSizePX);
  1824. // Load basic latin characyer set
  1825. debugTypeface->loadCharset(debugFont, UnicodeRange::BASIC_LATIN);
  1826. // Unload debug font typeface
  1827. resourceManager->unload(debugFontFilename);
  1828. }
  1829. // Load menu font typeface
  1830. Typeface* menuTypeface = resourceManager->load<Typeface>(menuFontFilename);
  1831. // Create menu font
  1832. menuFont = menuTypeface->createFont(fontSizePX);
  1833. // Load basic latin character set
  1834. menuTypeface->loadCharset(menuFont, UnicodeRange::BASIC_LATIN);
  1835. // Build character set for all strings in current language
  1836. std::set<char32_t> characterSet;
  1837. for (const StringTableRow& row: *stringTable)
  1838. {
  1839. // Convert to UTF-8 string to UTF-32
  1840. std::u32string string = toUTF32(row[currentLanguageIndex + 2]);
  1841. // Add each character in the string to the charater set
  1842. for (char32_t charcode: string)
  1843. {
  1844. characterSet.emplace(charcode);
  1845. }
  1846. }
  1847. // Load custom character set
  1848. menuTypeface->loadCharset(menuFont, characterSet);
  1849. // Unload menu typeface
  1850. resourceManager->unload(menuFontFilename);
  1851. }
  1852. void Game::loadControlProfile(const std::string& profileName)
  1853. {
  1854. // Load control profile
  1855. std::string controlProfilePath = profileName + ".csv";
  1856. StringTable* controlProfile = resourceManager->load<StringTable>(controlProfilePath);
  1857. for (const StringTableRow& row: *controlProfile)
  1858. {
  1859. // Skip empty rows and comments
  1860. if (row.empty() || row[0].empty() || row[0][0] == '#')
  1861. {
  1862. continue;
  1863. }
  1864. // Get control name
  1865. const std::string& controlName = row[0];
  1866. // Lookup control in control name map
  1867. auto it = controlNameMap.find(controlName);
  1868. if (it == controlNameMap.end())
  1869. {
  1870. logger->warning("Game::loadControlProfile(): Unknown control name \"" + controlName + "\"\n");
  1871. continue;
  1872. }
  1873. // Get pointer to the control
  1874. Control* control = it->second;
  1875. // Determine type of input mapping
  1876. const std::string& deviceType = row[1];
  1877. if (deviceType == "keyboard")
  1878. {
  1879. const std::string& eventType = row[2];
  1880. const std::string& scancodeName = row[3];
  1881. // Get scancode from string
  1882. Scancode scancode = Keyboard::getScancodeFromName(scancodeName.c_str());
  1883. // Map control
  1884. if (scancode != Scancode::UNKNOWN)
  1885. {
  1886. inputRouter->addMapping(KeyMapping(control, keyboard, scancode));
  1887. }
  1888. }
  1889. else if (deviceType == "mouse")
  1890. {
  1891. const std::string& eventType = row[2];
  1892. if (eventType == "motion")
  1893. {
  1894. const std::string& axisName = row[3];
  1895. // Get axis from string
  1896. MouseMotionAxis axis;
  1897. bool negative = (axisName.find('-') != std::string::npos);
  1898. if (axisName.find('x') != std::string::npos)
  1899. {
  1900. axis = (negative) ? MouseMotionAxis::NEGATIVE_X : MouseMotionAxis::POSITIVE_X;
  1901. }
  1902. else if (axisName.find('y') != std::string::npos)
  1903. {
  1904. axis = (negative) ? MouseMotionAxis::NEGATIVE_Y : MouseMotionAxis::POSITIVE_Y;
  1905. }
  1906. else
  1907. {
  1908. logger->warning("Game::loadControlProfile(): Unknown mouse motion axis \"" + axisName + "\"\n");
  1909. continue;
  1910. }
  1911. // Map control
  1912. inputRouter->addMapping(MouseMotionMapping(control, mouse, axis));
  1913. }
  1914. else if (eventType == "wheel")
  1915. {
  1916. const std::string& axisName = row[3];
  1917. // Get axis from string
  1918. MouseWheelAxis axis;
  1919. bool negative = (axisName.find('-') != std::string::npos);
  1920. if (axisName.find('x') != std::string::npos)
  1921. {
  1922. axis = (negative) ? MouseWheelAxis::NEGATIVE_X : MouseWheelAxis::POSITIVE_X;
  1923. }
  1924. else if (axisName.find('y') != std::string::npos)
  1925. {
  1926. axis = (negative) ? MouseWheelAxis::NEGATIVE_Y : MouseWheelAxis::POSITIVE_Y;
  1927. }
  1928. else
  1929. {
  1930. logger->warning("Game::loadControlProfile(): Unknown mouse wheel axis \"" + axisName + "\"\n");
  1931. continue;
  1932. }
  1933. // Map control
  1934. inputRouter->addMapping(MouseWheelMapping(control, mouse, axis));
  1935. }
  1936. else if (eventType == "button")
  1937. {
  1938. const std::string& buttonName = row[3];
  1939. // Get button from string
  1940. int button;
  1941. std::stringstream stream;
  1942. stream << buttonName;
  1943. stream >> button;
  1944. // Map control
  1945. inputRouter->addMapping(MouseButtonMapping(control, mouse, button));
  1946. }
  1947. else
  1948. {
  1949. logger->warning("Game::loadControlProfile(): Unknown mouse event type \"" + eventType + "\"\n");
  1950. continue;
  1951. }
  1952. }
  1953. else if (deviceType == "gamepad")
  1954. {
  1955. const std::string& eventType = row[2];
  1956. if (eventType == "axis")
  1957. {
  1958. std::string axisName = row[3];
  1959. // Determine whether axis is negative or positive
  1960. bool negative = (axisName.find('-') != std::string::npos);
  1961. // Remove sign from axis name
  1962. std::size_t plusPosition = axisName.find('+');
  1963. std::size_t minusPosition = axisName.find('-');
  1964. if (plusPosition != std::string::npos)
  1965. {
  1966. axisName.erase(plusPosition);
  1967. }
  1968. else if (minusPosition != std::string::npos)
  1969. {
  1970. axisName.erase(minusPosition);
  1971. }
  1972. // Get axis from string
  1973. int axis;
  1974. std::stringstream stream;
  1975. stream << axisName;
  1976. stream >> axis;
  1977. // Map control to each gamepad
  1978. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1979. for (Gamepad* gamepad: *gamepads)
  1980. {
  1981. inputRouter->addMapping(GamepadAxisMapping(control, gamepad, axis, negative));
  1982. }
  1983. }
  1984. else if (eventType == "button")
  1985. {
  1986. const std::string& buttonName = row[3];
  1987. // Get button from string
  1988. int button;
  1989. std::stringstream stream;
  1990. stream << buttonName;
  1991. stream >> button;
  1992. // Map control to each gamepad
  1993. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1994. for (Gamepad* gamepad: *gamepads)
  1995. {
  1996. inputRouter->addMapping(GamepadButtonMapping(control, gamepad, button));
  1997. }
  1998. }
  1999. else
  2000. {
  2001. logger->warning("Game::loadControlProfile(): Unknown gamepad event type \"" + eventType + "\"\n");
  2002. continue;
  2003. }
  2004. }
  2005. else
  2006. {
  2007. logger->warning("Game::loadControlProfile(): Unknown input device type \"" + deviceType + "\"\n");
  2008. continue;
  2009. }
  2010. }
  2011. }
  2012. void Game::saveControlProfile(const std::string& profileName)
  2013. {
  2014. // Build control profile string table
  2015. StringTable* table = new StringTable();
  2016. for (auto it = controlNameMap.begin(); it != controlNameMap.end(); ++it)
  2017. {
  2018. // Get control name
  2019. const std::string& controlName = it->first;
  2020. // Get pointer to the control
  2021. Control* control = it->second;
  2022. // Look up list of mappings for the control
  2023. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  2024. if (!mappings)
  2025. {
  2026. continue;
  2027. }
  2028. // For each input mapping
  2029. for (const InputMapping* mapping: *mappings)
  2030. {
  2031. // Add row to the table
  2032. table->push_back(StringTableRow());
  2033. StringTableRow* row = &table->back();
  2034. // Add control name column
  2035. row->push_back(controlName);
  2036. switch (mapping->getType())
  2037. {
  2038. case InputMappingType::KEY:
  2039. {
  2040. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  2041. row->push_back("keyboard");
  2042. row->push_back("key");
  2043. std::string scancodeName = std::string("\"") + std::string(Keyboard::getScancodeName(keyMapping->scancode)) + std::string("\"");
  2044. row->push_back(scancodeName);
  2045. break;
  2046. }
  2047. case InputMappingType::MOUSE_MOTION:
  2048. {
  2049. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  2050. row->push_back("mouse");
  2051. row->push_back("motion");
  2052. std::string axisName;
  2053. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  2054. {
  2055. axisName = "+x";
  2056. }
  2057. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  2058. {
  2059. axisName = "-x";
  2060. }
  2061. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  2062. {
  2063. axisName = "+y";
  2064. }
  2065. else
  2066. {
  2067. axisName = "-y";
  2068. }
  2069. row->push_back(axisName);
  2070. break;
  2071. }
  2072. case InputMappingType::MOUSE_WHEEL:
  2073. {
  2074. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  2075. row->push_back("mouse");
  2076. row->push_back("wheel");
  2077. std::string axisName;
  2078. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  2079. {
  2080. axisName = "+x";
  2081. }
  2082. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  2083. {
  2084. axisName = "-x";
  2085. }
  2086. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  2087. {
  2088. axisName = "+y";
  2089. }
  2090. else
  2091. {
  2092. axisName = "-y";
  2093. }
  2094. row->push_back(axisName);
  2095. break;
  2096. }
  2097. case InputMappingType::MOUSE_BUTTON:
  2098. {
  2099. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  2100. row->push_back("mouse");
  2101. row->push_back("button");
  2102. std::string buttonName;
  2103. std::stringstream stream;
  2104. stream << static_cast<int>(mouseButtonMapping->button);
  2105. stream >> buttonName;
  2106. row->push_back(buttonName);
  2107. break;
  2108. }
  2109. case InputMappingType::GAMEPAD_AXIS:
  2110. {
  2111. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  2112. row->push_back("gamepad");
  2113. row->push_back("axis");
  2114. std::stringstream stream;
  2115. if (gamepadAxisMapping->negative)
  2116. {
  2117. stream << "-";
  2118. }
  2119. else
  2120. {
  2121. stream << "+";
  2122. }
  2123. stream << gamepadAxisMapping->axis;
  2124. std::string axisName;
  2125. stream >> axisName;
  2126. row->push_back(axisName);
  2127. break;
  2128. }
  2129. case InputMappingType::GAMEPAD_BUTTON:
  2130. {
  2131. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  2132. row->push_back("gamepad");
  2133. row->push_back("button");
  2134. std::string buttonName;
  2135. std::stringstream stream;
  2136. stream << static_cast<int>(gamepadButtonMapping->button);
  2137. stream >> buttonName;
  2138. row->push_back(buttonName);
  2139. break;
  2140. }
  2141. default:
  2142. break;
  2143. }
  2144. }
  2145. }
  2146. // Form full path to control profile file
  2147. std::string controlProfilePath = controlsPath + profileName + ".csv";
  2148. // Save control profile
  2149. resourceManager->save<StringTable>(table, controlProfilePath);
  2150. // Free control profile string table
  2151. delete table;
  2152. }
  2153. std::array<std::string, 3> Game::getInputMappingStrings(const InputMapping* mapping)
  2154. {
  2155. std::string deviceString;
  2156. std::string typeString;
  2157. std::string eventString;
  2158. switch (mapping->getType())
  2159. {
  2160. case InputMappingType::KEY:
  2161. {
  2162. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  2163. deviceString = "keyboard";
  2164. typeString = "key";
  2165. eventString = std::string(Keyboard::getScancodeName(keyMapping->scancode));
  2166. break;
  2167. }
  2168. case InputMappingType::MOUSE_MOTION:
  2169. {
  2170. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  2171. deviceString = "mouse";
  2172. eventString = "motion";
  2173. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  2174. {
  2175. eventString = "+x";
  2176. }
  2177. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  2178. {
  2179. eventString = "-x";
  2180. }
  2181. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  2182. {
  2183. eventString = "+y";
  2184. }
  2185. else
  2186. {
  2187. eventString = "-y";
  2188. }
  2189. break;
  2190. }
  2191. case InputMappingType::MOUSE_WHEEL:
  2192. {
  2193. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  2194. deviceString = "mouse";
  2195. typeString = "wheel";
  2196. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  2197. {
  2198. eventString = "+x";
  2199. }
  2200. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  2201. {
  2202. eventString = "-x";
  2203. }
  2204. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  2205. {
  2206. eventString = "+y";
  2207. }
  2208. else
  2209. {
  2210. eventString = "-y";
  2211. }
  2212. break;
  2213. }
  2214. case InputMappingType::MOUSE_BUTTON:
  2215. {
  2216. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  2217. deviceString = "mouse";
  2218. typeString = "button";
  2219. std::stringstream stream;
  2220. stream << static_cast<int>(mouseButtonMapping->button);
  2221. stream >> eventString;
  2222. break;
  2223. }
  2224. case InputMappingType::GAMEPAD_AXIS:
  2225. {
  2226. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  2227. deviceString = "gamepad";
  2228. typeString = "axis";
  2229. std::stringstream stream;
  2230. if (gamepadAxisMapping->negative)
  2231. {
  2232. stream << "-";
  2233. }
  2234. else
  2235. {
  2236. stream << "+";
  2237. }
  2238. stream << gamepadAxisMapping->axis;
  2239. stream >> eventString;
  2240. break;
  2241. }
  2242. case InputMappingType::GAMEPAD_BUTTON:
  2243. {
  2244. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  2245. deviceString = "gamepad";
  2246. typeString = "button";
  2247. std::stringstream stream;
  2248. stream << static_cast<int>(gamepadButtonMapping->button);
  2249. stream >> eventString;
  2250. break;
  2251. }
  2252. default:
  2253. break;
  2254. }
  2255. return {deviceString, typeString, eventString};
  2256. }
  2257. void Game::remapControl(Control* control)
  2258. {
  2259. // Remove previously set input mappings for the control
  2260. inputRouter->removeMappings(control);
  2261. // Start mapping new input
  2262. inputMapper->setControl(control);
  2263. inputMapper->setEnabled(true);
  2264. // Restring UI to show control mappings have been removed.
  2265. restringUI();
  2266. // Disable UI callbacks
  2267. uiRootElement->setCallbacksEnabled(false);
  2268. // Disable menu control callbacks
  2269. menuControls.setCallbacksEnabled(false);
  2270. }
  2271. void Game::resetControls()
  2272. {
  2273. inputRouter->reset();
  2274. loadControlProfile("default-keyboard-controls");
  2275. saveControlProfile(controlProfileName);
  2276. restringUI();
  2277. }
  2278. void Game::resizeUI(int w, int h)
  2279. {
  2280. // Adjust root element dimensions
  2281. uiRootElement->setDimensions(Vector2(w, h));
  2282. uiRootElement->update();
  2283. splashBackgroundImage->setDimensions(Vector2(w, h));
  2284. splashBackgroundImage->setAnchor(Anchor::TOP_LEFT);
  2285. // Resize splash screen image
  2286. splashImage->setAnchor(Anchor::CENTER);
  2287. splashImage->setDimensions(Vector2(splashTexture->getWidth(), splashTexture->getHeight()));
  2288. // Adjust UI camera projection matrix
  2289. uiCamera.setOrthographic(0.0f, w, h, 0.0f, -1.0f, 1.0f);
  2290. uiCamera.resetTweens();
  2291. // Resize camera flash image
  2292. cameraFlashImage->setDimensions(Vector2(w, h));
  2293. cameraFlashImage->setAnchor(Anchor::CENTER);
  2294. // Resize blackout image
  2295. blackoutImage->setDimensions(Vector2(w, h));
  2296. blackoutImage->setAnchor(Anchor::CENTER);
  2297. // Resize language select background image
  2298. languageSelectBGImage->setDimensions(Vector2(w, h));
  2299. languageSelectBGImage->setAnchor(Anchor::CENTER);
  2300. // Resize HUD
  2301. float hudPadding = 20.0f;
  2302. hudContainer->setDimensions(Vector2(w - hudPadding * 2.0f, h - hudPadding * 2.0f));
  2303. hudContainer->setAnchor(Anchor::CENTER);
  2304. // Tool indicator
  2305. Rect toolIndicatorBounds = hudTextureAtlas.getBounds("tool-indicator");
  2306. toolIndicatorBGImage->setDimensions(Vector2(toolIndicatorBounds.getWidth(), toolIndicatorBounds.getHeight()));
  2307. toolIndicatorBGImage->setAnchor(Anchor::TOP_LEFT);
  2308. Rect toolIndicatorIconBounds = hudTextureAtlas.getBounds("tool-indicator-lens");
  2309. toolIndicatorIconImage->setDimensions(Vector2(toolIndicatorIconBounds.getWidth(), toolIndicatorIconBounds.getHeight()));
  2310. toolIndicatorIconImage->setAnchor(Anchor::CENTER);
  2311. // Buttons
  2312. Rect playButtonBounds = hudTextureAtlas.getBounds("button-play");
  2313. Rect fastForwardButtonBounds = hudTextureAtlas.getBounds("button-fast-forward-2x");
  2314. Rect pauseButtonBounds = hudTextureAtlas.getBounds("button-pause");
  2315. Rect buttonBackgroundBounds = hudTextureAtlas.getBounds("button-background");
  2316. Vector2 buttonBGDimensions = Vector2(buttonBackgroundBounds.getWidth(), buttonBackgroundBounds.getHeight());
  2317. float buttonMargin = 10.0f;
  2318. float buttonDepth = 15.0f;
  2319. float buttonContainerWidth = fastForwardButtonBounds.getWidth();
  2320. float buttonContainerHeight = fastForwardButtonBounds.getHeight();
  2321. buttonContainer->setDimensions(Vector2(buttonContainerWidth, buttonContainerHeight));
  2322. buttonContainer->setAnchor(Anchor::TOP_RIGHT);
  2323. playButtonImage->setDimensions(Vector2(playButtonBounds.getWidth(), playButtonBounds.getHeight()));
  2324. playButtonImage->setAnchor(Vector2(0.0f, 0.0f));
  2325. playButtonBGImage->setDimensions(buttonBGDimensions);
  2326. playButtonBGImage->setAnchor(Vector2(0.0f, 1.0f));
  2327. fastForwardButtonImage->setDimensions(Vector2(fastForwardButtonBounds.getWidth(), fastForwardButtonBounds.getHeight()));
  2328. fastForwardButtonImage->setAnchor(Vector2(0.5f, 5.0f));
  2329. fastForwardButtonBGImage->setDimensions(buttonBGDimensions);
  2330. fastForwardButtonBGImage->setAnchor(Vector2(0.5f, 0.5f));
  2331. pauseButtonImage->setDimensions(Vector2(pauseButtonBounds.getWidth(), pauseButtonBounds.getHeight()));
  2332. pauseButtonImage->setAnchor(Vector2(1.0f, 0.0f));
  2333. pauseButtonBGImage->setDimensions(buttonBGDimensions);
  2334. pauseButtonBGImage->setAnchor(Vector2(1.0f, 1.0f));
  2335. // Radial menu
  2336. Rect radialMenuBounds = hudTextureAtlas.getBounds("radial-menu");
  2337. radialMenuContainer->setDimensions(Vector2(w, h));
  2338. radialMenuContainer->setAnchor(Anchor::CENTER);
  2339. radialMenuContainer->setLayerOffset(30);
  2340. radialMenuBackgroundImage->setDimensions(Vector2(w, h));
  2341. radialMenuBackgroundImage->setAnchor(Anchor::CENTER);
  2342. radialMenuBackgroundImage->setLayerOffset(-1);
  2343. //radialMenuImage->setDimensions(Vector2(w * 0.5f, h * 0.5f));
  2344. radialMenuImage->setDimensions(Vector2(radialMenuBounds.getWidth(), radialMenuBounds.getHeight()));
  2345. radialMenuImage->setAnchor(Anchor::CENTER);
  2346. Rect radialMenuSelectorBounds = hudTextureAtlas.getBounds("radial-menu-selector");
  2347. radialMenuSelectorImage->setDimensions(Vector2(radialMenuSelectorBounds.getWidth(), radialMenuSelectorBounds.getHeight()));
  2348. radialMenuSelectorImage->setAnchor(Anchor::CENTER);
  2349. Rect toolIconBrushBounds = hudTextureAtlas.getBounds("tool-icon-brush");
  2350. toolIconBrushImage->setDimensions(Vector2(toolIconBrushBounds.getWidth(), toolIconBrushBounds.getHeight()));
  2351. toolIconBrushImage->setAnchor(Anchor::CENTER);
  2352. Rect toolIconLensBounds = hudTextureAtlas.getBounds("tool-icon-lens");
  2353. toolIconLensImage->setDimensions(Vector2(toolIconLensBounds.getWidth(), toolIconLensBounds.getHeight()));
  2354. toolIconLensImage->setAnchor(Anchor::CENTER);
  2355. Rect toolIconForcepsBounds = hudTextureAtlas.getBounds("tool-icon-forceps");
  2356. toolIconForcepsImage->setDimensions(Vector2(toolIconForcepsBounds.getWidth(), toolIconForcepsBounds.getHeight()));
  2357. toolIconForcepsImage->setAnchor(Anchor::CENTER);
  2358. Rect toolIconSpadeBounds = hudTextureAtlas.getBounds("tool-icon-spade");
  2359. toolIconSpadeImage->setDimensions(Vector2(toolIconSpadeBounds.getWidth(), toolIconSpadeBounds.getHeight()));
  2360. toolIconSpadeImage->setAnchor(Anchor::CENTER);
  2361. Rect toolIconCameraBounds = hudTextureAtlas.getBounds("tool-icon-camera");
  2362. toolIconCameraImage->setDimensions(Vector2(toolIconCameraBounds.getWidth(), toolIconCameraBounds.getHeight()));
  2363. toolIconCameraImage->setAnchor(Anchor::CENTER);
  2364. Rect toolIconMicrochipBounds = hudTextureAtlas.getBounds("tool-icon-microchip");
  2365. toolIconMicrochipImage->setDimensions(Vector2(toolIconMicrochipBounds.getWidth(), toolIconMicrochipBounds.getHeight()));
  2366. toolIconMicrochipImage->setAnchor(Anchor::CENTER);
  2367. Rect toolIconTestTubeBounds = hudTextureAtlas.getBounds("tool-icon-test-tube");
  2368. toolIconTestTubeImage->setDimensions(Vector2(toolIconTestTubeBounds.getWidth(), toolIconTestTubeBounds.getHeight()));
  2369. toolIconTestTubeImage->setAnchor(Anchor::CENTER);
  2370. Rect labelCornerBounds = hudTextureAtlas.getBounds("label-tl");
  2371. Vector2 labelCornerDimensions(labelCornerBounds.getWidth(), labelCornerBounds.getHeight());
  2372. Vector2 antLabelPadding(10.0f, 6.0f);
  2373. antLabelContainer->setDimensions(antLabel->getDimensions() + antLabelPadding * 2.0f);
  2374. antLabelContainer->setTranslation(Vector2(0.0f, (int)(-antPin->getDimensions().y * 0.125f)));
  2375. antLabelTL->setDimensions(labelCornerDimensions);
  2376. antLabelTR->setDimensions(labelCornerDimensions);
  2377. antLabelBL->setDimensions(labelCornerDimensions);
  2378. antLabelBR->setDimensions(labelCornerDimensions);
  2379. 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));
  2380. antLabelCT->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  2381. antLabelCB->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  2382. antLabelCL->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2383. antLabelCR->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2384. antLabelContainer->setAnchor(Vector2(0.5f, 0.5f));
  2385. antLabelTL->setAnchor(Anchor::TOP_LEFT);
  2386. antLabelTR->setAnchor(Anchor::TOP_RIGHT);
  2387. antLabelBL->setAnchor(Anchor::BOTTOM_LEFT);
  2388. antLabelBR->setAnchor(Anchor::BOTTOM_RIGHT);
  2389. antLabelCC->setAnchor(Anchor::CENTER);
  2390. antLabelCT->setAnchor(Vector2(0.5f, 0.0f));
  2391. antLabelCB->setAnchor(Vector2(0.5f, 1.0f));
  2392. antLabelCL->setAnchor(Vector2(0.0f, 0.5f));
  2393. antLabelCR->setAnchor(Vector2(1.0f, 0.5f));
  2394. antLabel->setAnchor(Anchor::CENTER);
  2395. Rect antPinBounds = hudTextureAtlas.getBounds("label-pin");
  2396. antPin->setDimensions(Vector2(antPinBounds.getWidth(), antPinBounds.getHeight()));
  2397. antPin->setAnchor(Vector2(0.5f, 1.0f));
  2398. Rect pinHoleBounds = hudTextureAtlas.getBounds("label-pin-hole");
  2399. antLabelPinHole->setDimensions(Vector2(pinHoleBounds.getWidth(), pinHoleBounds.getHeight()));
  2400. antLabelPinHole->setAnchor(Vector2(0.5f, 0.0f));
  2401. antLabelPinHole->setTranslation(Vector2(0.0f, -antLabelPinHole->getDimensions().y * 0.5f));
  2402. antLabelPinHole->setLayerOffset(2);
  2403. float pinDistance = 20.0f;
  2404. antTag->setAnchor(Anchor::CENTER);
  2405. antTag->setDimensions(Vector2(antLabelContainer->getDimensions().x, antPin->getDimensions().y));
  2406. float cameraGridLineWidth = 2.0f;
  2407. float cameraReticleDiameter = 6.0f;
  2408. cameraGridContainer->setDimensions(Vector2(w, h));
  2409. cameraGridY0Image->setDimensions(Vector2(w, cameraGridLineWidth));
  2410. cameraGridY1Image->setDimensions(Vector2(w, cameraGridLineWidth));
  2411. cameraGridX0Image->setDimensions(Vector2(cameraGridLineWidth, h));
  2412. cameraGridX1Image->setDimensions(Vector2(cameraGridLineWidth, h));
  2413. cameraReticleImage->setDimensions(Vector2(cameraReticleDiameter));
  2414. cameraGridY0Image->setTranslation(Vector2(0));
  2415. cameraGridY1Image->setTranslation(Vector2(0));
  2416. cameraGridX0Image->setTranslation(Vector2(0));
  2417. cameraGridX1Image->setTranslation(Vector2(0));
  2418. cameraReticleImage->setTranslation(Vector2(0));
  2419. Rect menuSelectorBounds = hudTextureAtlas.getBounds("menu-selector");
  2420. menuSelectorImage->setDimensions(Vector2(menuSelectorBounds.getWidth(), menuSelectorBounds.getHeight()));
  2421. UIImage* icons[] =
  2422. {
  2423. toolIconBrushImage,
  2424. nullptr,
  2425. toolIconLensImage,
  2426. nullptr,
  2427. toolIconForcepsImage,
  2428. toolIconMicrochipImage,
  2429. toolIconCameraImage,
  2430. nullptr
  2431. };
  2432. Rect radialMenuIconRingBounds = hudTextureAtlas.getBounds("radial-menu-icon-ring");
  2433. float iconOffset = radialMenuIconRingBounds.getWidth() * 0.5f;
  2434. float sectorAngle = (2.0f * 3.14159264f) / 8.0f;
  2435. for (int i = 0; i < 8; ++i)
  2436. {
  2437. float angle = sectorAngle * static_cast<float>(i - 4);
  2438. Vector2 translation = Vector2(std::cos(angle), std::sin(angle)) * iconOffset;
  2439. translation.x = (int)(translation.x + 0.5f);
  2440. translation.y = (int)(translation.y + 0.5f);
  2441. if (icons[i] != nullptr)
  2442. {
  2443. icons[i]->setTranslation(translation);
  2444. }
  2445. }
  2446. // Main menu size
  2447. float mainMenuWidth = 0.0f;
  2448. float mainMenuHeight = 0.0f;
  2449. float mainMenuSpacing = 0.5f * fontSizePX;
  2450. float mainMenuPadding = fontSizePX * 4.0f;
  2451. for (const MenuItem* item: *mainMenu->getItems())
  2452. {
  2453. mainMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2454. mainMenuHeight += mainMenuSpacing;
  2455. mainMenuWidth = std::max<float>(mainMenuWidth, item->getNameLabel()->getDimensions().x);
  2456. }
  2457. mainMenuHeight -= mainMenuSpacing;
  2458. mainMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2459. mainMenu->resize(mainMenuWidth, mainMenuHeight);
  2460. mainMenu->getContainer()->setTranslation(Vector2(-mainMenuPadding));
  2461. // Settings menu size
  2462. float settingsMenuWidth = 0.0f;
  2463. float settingsMenuHeight = 0.0f;
  2464. float settingsMenuSpacing = 0.5f * fontSizePX;
  2465. float settingsMenuPadding = fontSizePX * 4.0f;
  2466. float settingsMenuValueMargin = fontSizePX * 4.0f;
  2467. for (const MenuItem* item: *settingsMenu->getItems())
  2468. {
  2469. settingsMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2470. settingsMenuHeight += settingsMenuSpacing;
  2471. float itemWidth = item->getNameLabel()->getDimensions().x;
  2472. if (!item->getValueLabel()->getText().empty())
  2473. {
  2474. itemWidth += item->getValueLabel()->getDimensions().x + settingsMenuValueMargin;
  2475. }
  2476. settingsMenuWidth = std::max<float>(settingsMenuWidth, itemWidth);
  2477. }
  2478. settingsMenuHeight -= settingsMenuSpacing;
  2479. settingsMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2480. settingsMenu->resize(settingsMenuWidth, settingsMenuHeight);
  2481. settingsMenu->getContainer()->setTranslation(Vector2(-settingsMenuPadding));
  2482. // Controls menu size
  2483. float controlsMenuWidth = 0.0f;
  2484. float controlsMenuHeight = 0.0f;
  2485. float controlsMenuSpacing = 0.5f * fontSizePX;
  2486. float controlsMenuPadding = fontSizePX * 4.0f;
  2487. float controlsMenuValueMargin = fontSizePX * 4.0f;
  2488. for (const MenuItem* item: *controlsMenu->getItems())
  2489. {
  2490. controlsMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2491. controlsMenuHeight += controlsMenuSpacing;
  2492. float itemWidth = item->getNameLabel()->getDimensions().x;
  2493. if (!item->getValueLabel()->getText().empty())
  2494. {
  2495. itemWidth += item->getValueLabel()->getDimensions().x + controlsMenuValueMargin;
  2496. }
  2497. controlsMenuWidth = std::max<float>(controlsMenuWidth, itemWidth);
  2498. }
  2499. controlsMenuWidth += controlsMenuValueMargin;
  2500. controlsMenuHeight -= controlsMenuSpacing;
  2501. controlsMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2502. controlsMenu->resize(controlsMenuWidth, controlsMenuHeight);
  2503. controlsMenu->getContainer()->setTranslation(Vector2(-controlsMenuPadding));
  2504. // Pause menu size
  2505. float pauseMenuWidth = 0.0f;
  2506. float pauseMenuHeight = 0.0f;
  2507. float pauseMenuSpacing = 0.5f * fontSizePX;
  2508. float pauseMenuPadding = fontSizePX * 4.0f;
  2509. for (const MenuItem* item: *pauseMenu->getItems())
  2510. {
  2511. pauseMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2512. pauseMenuHeight += pauseMenuSpacing;
  2513. pauseMenuWidth = std::max<float>(pauseMenuWidth, item->getNameLabel()->getDimensions().x);
  2514. }
  2515. pauseMenuHeight -= pauseMenuSpacing;
  2516. pauseMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2517. pauseMenu->resize(pauseMenuWidth, pauseMenuHeight);
  2518. pauseMenu->getContainer()->setTranslation(Vector2(-pauseMenuPadding));
  2519. // Language menu size
  2520. float languageMenuWidth = 0.0f;
  2521. float languageMenuHeight = 0.0f;
  2522. float languageMenuSpacing = 0.75f * fontSizePX;
  2523. for (const MenuItem* item: *languageMenu->getItems())
  2524. {
  2525. Font* font = item->getNameLabel()->getFont();
  2526. if (font)
  2527. {
  2528. float lineHeight = font->getMetrics().getAscender() - font->getMetrics().getDescender();
  2529. languageMenuHeight += lineHeight + languageMenuSpacing;
  2530. languageMenuWidth = std::max<float>(languageMenuWidth, item->getNameLabel()->getDimensions().x);
  2531. }
  2532. item->getNameLabel()->setAnchor(Vector2(0.5f, 0.0f));
  2533. }
  2534. languageMenuHeight -= languageMenuSpacing;
  2535. languageMenu->getContainer()->setAnchor(Anchor::CENTER);
  2536. languageMenu->resize(languageMenuWidth, languageMenuHeight);
  2537. }
  2538. void Game::restringUI()
  2539. {
  2540. // Reset fonts
  2541. mainMenu->setFonts(menuFont);
  2542. settingsMenu->setFonts(menuFont);
  2543. controlsMenu->setFonts(menuFont);
  2544. pauseMenu->setFonts(menuFont);
  2545. // Get common strings
  2546. std::string offString = getString("off");
  2547. std::string onString = getString("on");
  2548. std::string backString = getString("back");
  2549. // Main menu strings
  2550. mainMenuContinueItem->setName(getString("continue"));
  2551. mainMenuNewGameItem->setName(getString("new-game"));
  2552. mainMenuColoniesItem->setName(getString("colonies"));
  2553. mainMenuSettingsItem->setName(getString("settings"));
  2554. mainMenuQuitItem->setName(getString("quit"));
  2555. // Settings menu strings
  2556. settingsMenuControlsItem->setName(getString("controls"));
  2557. settingsMenuControlsItem->setValue(getString("ellipsis"));
  2558. settingsMenuFullscreenItem->setName(getString("fullscreen"));
  2559. settingsMenuFullscreenItem->setValue((fullscreen) ? onString : offString);
  2560. settingsMenuVSyncItem->setName(getString("v-sync"));
  2561. settingsMenuVSyncItem->setValue((vsync) ? onString : offString);
  2562. settingsMenuLanguageItem->setName(getString("language"));
  2563. settingsMenuLanguageItem->setValue(getString("language-name"));
  2564. settingsMenuBackItem->setName(backString);
  2565. // Controls menu strings
  2566. restringControlMenuItem(controlsMenuMoveForwardItem, "move-forward");
  2567. restringControlMenuItem(controlsMenuMoveLeftItem, "move-left");
  2568. restringControlMenuItem(controlsMenuMoveBackItem, "move-back");
  2569. restringControlMenuItem(controlsMenuMoveRightItem, "move-right");
  2570. restringControlMenuItem(controlsMenuChangeToolItem, "change-tool");
  2571. restringControlMenuItem(controlsMenuUseToolItem, "use-tool");
  2572. restringControlMenuItem(controlsMenuAdjustCameraItem, "adjust-camera");
  2573. restringControlMenuItem(controlsMenuPauseItem, "pause");
  2574. restringControlMenuItem(controlsMenuToggleFullscreenItem, "toggle-fullscreen");
  2575. restringControlMenuItem(controlsMenuTakeScreenshotItem, "take-screenshot");
  2576. controlsMenuResetToDefaultItem->setName(getString("reset-to-default"));
  2577. controlsMenuBackItem->setName(backString);
  2578. // Pause menu strings
  2579. pauseMenuResumeItem->setName(getString("resume"));
  2580. pauseMenuSettingsItem->setName(getString("settings"));
  2581. pauseMenuMainMenuItem->setName(getString("main-menu"));
  2582. pauseMenuQuitItem->setName(getString("quit"));
  2583. // Language menu strings
  2584. for (std::size_t i = 0; i < languageCount; ++i)
  2585. {
  2586. languageMenuItems[i]->setName(getString("language-name", i));
  2587. }
  2588. // Reset menu tweens
  2589. uiRootElement->update();
  2590. mainMenu->getContainer()->resetTweens();
  2591. settingsMenu->getContainer()->resetTweens();
  2592. controlsMenu->getContainer()->resetTweens();
  2593. pauseMenu->getContainer()->resetTweens();
  2594. languageMenu->getContainer()->resetTweens();
  2595. }
  2596. void Game::restringControlMenuItem(MenuItem* item, const std::string& name)
  2597. {
  2598. item->setName(getString(name));
  2599. Control* control = controlNameMap.find(name)->second;
  2600. std::string value;
  2601. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  2602. if (mappings != nullptr)
  2603. {
  2604. std::size_t i = 0;
  2605. for (const InputMapping* mapping: *mappings)
  2606. {
  2607. std::array<std::string, 3> mappingStrings = getInputMappingStrings(mapping);
  2608. // keyboard-key, mouse-button, gamepad-axis, etc.
  2609. std::string typeName = mappingStrings[0] + "-" + mappingStrings[1];
  2610. std::string type = getString(typeName);
  2611. if (mapping->getType() != InputMappingType::KEY)
  2612. {
  2613. value += type;
  2614. value += " ";
  2615. }
  2616. value += mappingStrings[2];
  2617. if (i < mappings->size() - 1)
  2618. {
  2619. value += ", ";
  2620. }
  2621. ++i;
  2622. }
  2623. }
  2624. item->setValue(value);
  2625. }
  2626. void Game::setTimeOfDay(float time)
  2627. {
  2628. Vector3 midnight = Vector3(0.0f, 1.0f, 0.0f);
  2629. Vector3 sunrise = Vector3(-1.0f, 0.0f, 0.0f);
  2630. Vector3 noon = Vector3(0, -1.0f, 0.0f);
  2631. Vector3 sunset = Vector3(1.0f, 0.0f, 0.0f);
  2632. float angles[4] =
  2633. {
  2634. glm::radians(270.0f), // 00:00
  2635. glm::radians(0.0f), // 06:00
  2636. glm::radians(90.0f), // 12:00
  2637. glm::radians(180.0f) // 18:00
  2638. };
  2639. int index0 = static_cast<int>(fmod(time, 24.0f) / 6.0f);
  2640. int index1 = (index0 + 1) % 4;
  2641. float t = (time - (static_cast<float>(index0) * 6.0f)) / 6.0f;
  2642. Quaternion rotation0 = glm::angleAxis(angles[index0], Vector3(1, 0, 0));
  2643. Quaternion rotation1 = glm::angleAxis(angles[index1], Vector3(1, 0, 0));
  2644. Quaternion rotation = glm::normalize(glm::slerp(rotation0, rotation1, t));
  2645. Vector3 direction = glm::normalize(rotation * Vector3(0, 0, 1));
  2646. sunlight.setDirection(direction);
  2647. Vector3 up = glm::normalize(rotation * Vector3(0, 1, 0));
  2648. sunlightCamera.lookAt(Vector3(0, 0, 0), sunlight.getDirection(), up);
  2649. }
  2650. void Game::queueScreenshot()
  2651. {
  2652. screenshotQueued = true;
  2653. cameraFlashImage->setVisible(false);
  2654. cameraGridContainer->setVisible(false);
  2655. fpsLabel->setVisible(false);
  2656. soundSystem->scrot();
  2657. }
  2658. void Game::screenshot()
  2659. {
  2660. screenshotQueued = false;
  2661. // Read pixel data from framebuffer
  2662. unsigned char* pixels = new unsigned char[w * h * 3];
  2663. glReadBuffer(GL_BACK);
  2664. glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  2665. // Get game title in current language
  2666. std::string title = getString("title");
  2667. // Convert title to lowercase
  2668. std::transform(title.begin(), title.end(), title.begin(), ::tolower);
  2669. // Create screenshot directory if it doesn't exist
  2670. std::string screenshotDirectory = configPath + std::string("screenshots/");
  2671. if (!pathExists(screenshotDirectory))
  2672. {
  2673. createDirectory(screenshotDirectory);
  2674. }
  2675. // Build screenshot file name
  2676. std::string filename = screenshotDirectory + title + "-" + timestamp() + ".png";
  2677. // Write screenshot to file in separate thread
  2678. std::thread screenshotThread(Game::saveScreenshot, filename, w, h, pixels);
  2679. screenshotThread.detach();
  2680. // Play camera flash animation
  2681. cameraFlashAnimation.stop();
  2682. cameraFlashAnimation.rewind();
  2683. cameraFlashAnimation.play();
  2684. // Play camera shutter sound
  2685. // Restore camera UI visibility
  2686. //cameraGridContainer->setVisible(true);
  2687. fpsLabel->setVisible(true);
  2688. // Whiteout screen immediately
  2689. glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
  2690. glClear(GL_COLOR_BUFFER_BIT);
  2691. }
  2692. void Game::inputMapped(const InputMapping& mapping)
  2693. {
  2694. // Skip mouse motion events
  2695. if (mapping.getType() == InputMappingType::MOUSE_MOTION)
  2696. {
  2697. return;
  2698. }
  2699. // Add input mapping to input router
  2700. if (mapping.control != nullptr)
  2701. {
  2702. inputRouter->addMapping(mapping);
  2703. }
  2704. // Disable input mapping generation
  2705. inputMapper->setControl(nullptr);
  2706. inputMapper->setEnabled(false);
  2707. // Restring UI
  2708. restringUI();
  2709. // Schedule callbacks to be enabled in 100ms
  2710. ScheduledFunctionEvent event;
  2711. event.caller = static_cast<void*>(this);
  2712. event.function = [this]()
  2713. {
  2714. // Re-enable UI callbacks
  2715. uiRootElement->setCallbacksEnabled(true);
  2716. // Re-enable menu controls
  2717. menuControls.setCallbacksEnabled(true);
  2718. };
  2719. eventDispatcher.schedule(event, time + 0.1f);
  2720. // Save control profile
  2721. saveControlProfile(controlProfileName);
  2722. }
  2723. void Game::languageSelected()
  2724. {
  2725. // Disable non-system controls
  2726. disableNonSystemControls();
  2727. // Disable UI callbacks
  2728. uiRootElement->setCallbacksEnabled(false);
  2729. // Begin to fade out
  2730. fadeOut(0.5f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &titleState));
  2731. }
  2732. void Game::skipSplash()
  2733. {
  2734. if (StateMachine::getCurrentState() == &splashState)
  2735. {
  2736. StateMachine::changeState(&titleState);
  2737. }
  2738. }
  2739. void Game::togglePause()
  2740. {
  2741. paused = !paused;
  2742. if (paused)
  2743. {
  2744. openMenu(pauseMenu, 0);
  2745. // Enable menu controls and UI callbacks
  2746. uiRootElement->setCallbacksEnabled(true);
  2747. menuControls.setCallbacksEnabled(true);
  2748. }
  2749. else
  2750. {
  2751. closeCurrentMenu();
  2752. // Disable menu controls and UI callbacks
  2753. uiRootElement->setCallbacksEnabled(false);
  2754. menuControls.setCallbacksEnabled(false);
  2755. }
  2756. }
  2757. void Game::continueGame()
  2758. {
  2759. // Disable non-system controls
  2760. disableNonSystemControls();
  2761. // Disable UI callbacks
  2762. uiRootElement->setCallbacksEnabled(false);
  2763. // Start fading out main menu
  2764. menuFadeAnimation.setClip(&menuFadeOutClip);
  2765. menuFadeAnimation.setTimeFrame(menuFadeOutClip.getTimeFrame());
  2766. menuFadeAnimation.rewind();
  2767. menuFadeAnimation.play();
  2768. // Close menu and enter play state after it fades out
  2769. menuFadeAnimation.setEndCallback
  2770. (
  2771. [this]()
  2772. {
  2773. closeCurrentMenu();
  2774. StateMachine::changeState(&playState);
  2775. }
  2776. );
  2777. }
  2778. void Game::newGame()
  2779. {
  2780. // Disable non-system controls
  2781. disableNonSystemControls();
  2782. // Disable UI callbacks
  2783. uiRootElement->setCallbacksEnabled(false);
  2784. // Start fading out main menu
  2785. menuFadeAnimation.setClip(&menuFadeOutClip);
  2786. menuFadeAnimation.setTimeFrame(menuFadeOutClip.getTimeFrame());
  2787. menuFadeAnimation.rewind();
  2788. menuFadeAnimation.play();
  2789. // Close menu and enter play state after it fades out
  2790. menuFadeAnimation.setEndCallback
  2791. (
  2792. [this]()
  2793. {
  2794. closeCurrentMenu();
  2795. }
  2796. );
  2797. // Start to play state
  2798. fadeOut(3.0f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &playState));
  2799. }
  2800. void Game::returnToMainMenu()
  2801. {
  2802. // Disable non-system controls
  2803. disableNonSystemControls();
  2804. // Disable UI callbacks
  2805. uiRootElement->setCallbacksEnabled(false);
  2806. // Close pause menu
  2807. closeCurrentMenu();
  2808. // Fade to title state
  2809. fadeOut(3.0f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &titleState));
  2810. }
  2811. void Game::interpretCommands()
  2812. {
  2813. while (true)
  2814. {
  2815. std::cout << "> " << std::flush;
  2816. std::string line;
  2817. std::getline(std::cin, line);
  2818. try
  2819. {
  2820. auto [commandName, arguments, call] = cli->interpret(line);
  2821. if (call)
  2822. {
  2823. call();
  2824. }
  2825. else
  2826. {
  2827. if (!commandName.empty())
  2828. {
  2829. std::cout << "Unknown command " << commandName << std::endl;
  2830. }
  2831. }
  2832. }
  2833. catch (const std::invalid_argument& e)
  2834. {
  2835. std::string commandName = line.substr(0, line.find(' '));
  2836. auto& helpStrings = cli->help();
  2837. if (auto it = helpStrings.find(commandName); it != helpStrings.end())
  2838. {
  2839. std::cout << "Usage: " << it->second << std::endl;
  2840. }
  2841. else
  2842. {
  2843. std::cout << commandName << ": Invalid arguments" << std::endl;
  2844. }
  2845. }
  2846. }
  2847. }
  2848. void Game::boxSelect(float x, float y, float w, float h)
  2849. {
  2850. boxSelectionContainer->setTranslation(Vector2(x, y));
  2851. boxSelectionContainer->setDimensions(Vector2(w, h));
  2852. boxSelectionImageBackground->setDimensions(Vector2(w, h));
  2853. boxSelectionImageTop->setDimensions(Vector2(w, boxSelectionBorderWidth));
  2854. boxSelectionImageBottom->setDimensions(Vector2(w, boxSelectionBorderWidth));
  2855. boxSelectionImageLeft->setDimensions(Vector2(boxSelectionBorderWidth, h));
  2856. boxSelectionImageRight->setDimensions(Vector2(boxSelectionBorderWidth, h));
  2857. boxSelectionContainer->setVisible(true);
  2858. }
  2859. void Game::fadeIn(float duration, const Vector3& color, std::function<void()> callback)
  2860. {
  2861. if (fadeInAnimation.isPlaying())
  2862. {
  2863. return;
  2864. }
  2865. fadeOutAnimation.stop();
  2866. this->fadeInEndCallback = callback;
  2867. blackoutImage->setTintColor(Vector4(color, 1.0f));
  2868. blackoutImage->setVisible(true);
  2869. fadeInAnimation.setSpeed(1.0f / duration);
  2870. fadeInAnimation.setLoop(false);
  2871. fadeInAnimation.setClip(&fadeInClip);
  2872. fadeInAnimation.setTimeFrame(fadeInClip.getTimeFrame());
  2873. fadeInAnimation.rewind();
  2874. fadeInAnimation.play();
  2875. blackoutImage->resetTweens();
  2876. uiRootElement->update();
  2877. }
  2878. void Game::fadeOut(float duration, const Vector3& color, std::function<void()> callback)
  2879. {
  2880. if (fadeOutAnimation.isPlaying())
  2881. {
  2882. return;
  2883. }
  2884. fadeInAnimation.stop();
  2885. this->fadeOutEndCallback = callback;
  2886. blackoutImage->setVisible(true);
  2887. blackoutImage->setTintColor(Vector4(color, 0.0f));
  2888. fadeOutAnimation.setSpeed(1.0f / duration);
  2889. fadeOutAnimation.setLoop(false);
  2890. fadeOutAnimation.setClip(&fadeOutClip);
  2891. fadeOutAnimation.setTimeFrame(fadeOutClip.getTimeFrame());
  2892. fadeOutAnimation.rewind();
  2893. fadeOutAnimation.play();
  2894. blackoutImage->resetTweens();
  2895. uiRootElement->update();
  2896. }
  2897. void Game::stopFade()
  2898. {
  2899. fadeInAnimation.stop();
  2900. fadeOutAnimation.stop();
  2901. blackoutImage->setVisible(false);
  2902. uiRootElement->update();
  2903. }
  2904. void Game::selectTool(int toolIndex)
  2905. {
  2906. Tool* tools[] =
  2907. {
  2908. brush,
  2909. nullptr,
  2910. lens,
  2911. nullptr,
  2912. forceps,
  2913. nullptr,
  2914. nullptr,
  2915. nullptr
  2916. };
  2917. Tool* nextTool = tools[toolIndex];
  2918. if (nextTool != currentTool)
  2919. {
  2920. if (currentTool)
  2921. {
  2922. currentTool->setActive(false);
  2923. currentTool->update(0.0f);
  2924. }
  2925. currentTool = nextTool;
  2926. if (currentTool)
  2927. {
  2928. currentTool->setActive(true);
  2929. }
  2930. }
  2931. if (1)
  2932. {
  2933. toolIndicatorIconImage->setTextureBounds(toolIndicatorsBounds[toolIndex]);
  2934. toolIndicatorIconImage->setVisible(true);
  2935. }
  2936. else
  2937. {
  2938. toolIndicatorIconImage->setVisible(false);
  2939. }
  2940. }
  2941. EntityID Game::createInstance()
  2942. {
  2943. return entityManager->createEntity();
  2944. }
  2945. EntityID Game::createNamedInstance(const std::string& instanceName)
  2946. {
  2947. EntityID entity = entityManager->createEntity();
  2948. cli->set(instanceName, std::to_string(entity));
  2949. return entity;
  2950. }
  2951. EntityID Game::createInstanceOf(const std::string& templateName)
  2952. {
  2953. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  2954. EntityID entity = entityManager->createEntity();
  2955. entityTemplate->apply(entity, componentManager);
  2956. return entity;
  2957. }
  2958. EntityID Game::createNamedInstanceOf(const std::string& templateName, const std::string& instanceName)
  2959. {
  2960. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  2961. EntityID entity = entityManager->createEntity();
  2962. entityTemplate->apply(entity, componentManager);
  2963. cli->set(instanceName, std::to_string(entity));
  2964. return entity;
  2965. }
  2966. void Game::destroyInstance(EntityID entity)
  2967. {
  2968. entityManager->destroyEntity(entity);
  2969. }
  2970. void Game::addComponent(EntityID entity, ComponentBase* component)
  2971. {
  2972. componentManager->addComponent(entity, component);
  2973. }
  2974. void Game::removeComponent(EntityID entity, ComponentType type)
  2975. {
  2976. ComponentBase* component = componentManager->removeComponent(entity, type);
  2977. delete component;
  2978. }
  2979. void Game::setTranslation(EntityID entity, const Vector3& translation)
  2980. {
  2981. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2982. if (!component)
  2983. {
  2984. return;
  2985. }
  2986. component->transform.translation = translation;
  2987. }
  2988. void Game::setRotation(EntityID entity, const Quaternion& rotation)
  2989. {
  2990. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2991. if (!component)
  2992. {
  2993. return;
  2994. }
  2995. component->transform.rotation = rotation;
  2996. }
  2997. void Game::setScale(EntityID entity, const Vector3& scale)
  2998. {
  2999. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  3000. if (!component)
  3001. {
  3002. return;
  3003. }
  3004. component->transform.scale = scale;
  3005. }
  3006. void Game::setTerrainPatchPosition(EntityID entity, const std::tuple<int, int>& position)
  3007. {
  3008. TerrainPatchComponent* component = componentManager->getComponent<TerrainPatchComponent>(entity);
  3009. if (!component)
  3010. {
  3011. return;
  3012. }
  3013. component->position = position;
  3014. }
  3015. void Game::saveScreenshot(const std::string& filename, unsigned int width, unsigned int height, unsigned char* pixels)
  3016. {
  3017. stbi_flip_vertically_on_write(1);
  3018. stbi_write_png(filename.c_str(), width, height, 3, pixels, width * 3);
  3019. delete[] pixels;
  3020. }