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

3584 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 / 72.0f) * dpi;
  928. // Load fonts
  929. loadFonts();
  930. // Load splash screen texture
  931. splashTexture = resourceManager->load<Texture2D>("splash.png");
  932. // Load HUD texture
  933. hudSpriteSheetTexture = resourceManager->load<Texture2D>("hud.png");
  934. // Read texture atlas file
  935. StringTable* atlasTable = resourceManager->load<StringTable>("hud-atlas.csv");
  936. // Build texture atlas
  937. for (int row = 0; row < atlasTable->size(); ++row)
  938. {
  939. std::stringstream ss;
  940. float x;
  941. float y;
  942. float w;
  943. float h;
  944. ss << (*atlasTable)[row][1];
  945. ss >> x;
  946. ss.str(std::string());
  947. ss.clear();
  948. ss << (*atlasTable)[row][2];
  949. ss >> y;
  950. ss.str(std::string());
  951. ss.clear();
  952. ss << (*atlasTable)[row][3];
  953. ss >> w;
  954. ss.str(std::string());
  955. ss.clear();
  956. ss << (*atlasTable)[row][4];
  957. ss >> h;
  958. ss.str(std::string());
  959. y = static_cast<float>(hudSpriteSheetTexture->getHeight()) - y - h;
  960. x = (int)(x + 0.5f);
  961. y = (int)(y + 0.5f);
  962. w = (int)(w + 0.5f);
  963. h = (int)(h + 0.5f);
  964. hudTextureAtlas.insert((*atlasTable)[row][0], Rect(Vector2(x, y), Vector2(x + w, y + h)));
  965. }
  966. // Setup UI batching
  967. uiBatch = new BillboardBatch();
  968. uiBatch->resize(1024);
  969. uiBatcher = new UIBatcher();
  970. // Setup root UI element
  971. uiRootElement = new UIContainer();
  972. eventDispatcher.subscribe<MouseMovedEvent>(uiRootElement);
  973. eventDispatcher.subscribe<MouseButtonPressedEvent>(uiRootElement);
  974. eventDispatcher.subscribe<MouseButtonReleasedEvent>(uiRootElement);
  975. // Create splash screen background element
  976. splashBackgroundImage = new UIImage();
  977. splashBackgroundImage->setLayerOffset(-1);
  978. splashBackgroundImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  979. splashBackgroundImage->setVisible(false);
  980. uiRootElement->addChild(splashBackgroundImage);
  981. // Create splash screen element
  982. splashImage = new UIImage();
  983. splashImage->setTexture(splashTexture);
  984. splashImage->setVisible(false);
  985. uiRootElement->addChild(splashImage);
  986. Rect hudTextureAtlasBounds(Vector2(0), Vector2(hudSpriteSheetTexture->getWidth(), hudSpriteSheetTexture->getHeight()));
  987. auto normalizeTextureBounds = [](const Rect& texture, const Rect& atlas)
  988. {
  989. Vector2 atlasDimensions = Vector2(atlas.getWidth(), atlas.getHeight());
  990. return Rect(texture.getMin() / atlasDimensions, texture.getMax() / atlasDimensions);
  991. };
  992. // Create HUD elements
  993. hudContainer = new UIContainer();
  994. hudContainer->setVisible(false);
  995. uiRootElement->addChild(hudContainer);
  996. toolIndicatorBGImage = new UIImage();
  997. toolIndicatorBGImage->setTexture(hudSpriteSheetTexture);
  998. toolIndicatorBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds));
  999. hudContainer->addChild(toolIndicatorBGImage);
  1000. toolIndicatorsBounds = new Rect[8];
  1001. toolIndicatorsBounds[0] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-brush"), hudTextureAtlasBounds);
  1002. toolIndicatorsBounds[1] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-spade"), hudTextureAtlasBounds);
  1003. toolIndicatorsBounds[2] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-lens"), hudTextureAtlasBounds);
  1004. toolIndicatorsBounds[3] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-test-tube"), hudTextureAtlasBounds);
  1005. toolIndicatorsBounds[4] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-forceps"), hudTextureAtlasBounds);
  1006. toolIndicatorsBounds[5] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  1007. toolIndicatorsBounds[6] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  1008. toolIndicatorsBounds[7] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  1009. toolIndicatorIconImage = new UIImage();
  1010. toolIndicatorIconImage->setTexture(hudSpriteSheetTexture);
  1011. toolIndicatorIconImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  1012. toolIndicatorBGImage->addChild(toolIndicatorIconImage);
  1013. buttonContainer = new UIContainer();
  1014. hudContainer->addChild(buttonContainer);
  1015. playButtonBGImage = new UIImage();
  1016. playButtonBGImage->setTexture(hudSpriteSheetTexture);
  1017. playButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1018. //buttonContainer->addChild(playButtonBGImage);
  1019. pauseButtonBGImage = new UIImage();
  1020. pauseButtonBGImage->setTexture(hudSpriteSheetTexture);
  1021. pauseButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1022. //buttonContainer->addChild(pauseButtonBGImage);
  1023. fastForwardButtonBGImage = new UIImage();
  1024. fastForwardButtonBGImage->setTexture(hudSpriteSheetTexture);
  1025. fastForwardButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1026. //buttonContainer->addChild(fastForwardButtonBGImage);
  1027. playButtonImage = new UIImage();
  1028. playButtonImage->setTexture(hudSpriteSheetTexture);
  1029. playButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-play"), hudTextureAtlasBounds));
  1030. //buttonContainer->addChild(playButtonImage);
  1031. fastForwardButtonImage = new UIImage();
  1032. fastForwardButtonImage->setTexture(hudSpriteSheetTexture);
  1033. fastForwardButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-fast-forward-2x"), hudTextureAtlasBounds));
  1034. //buttonContainer->addChild(fastForwardButtonImage);
  1035. pauseButtonImage = new UIImage();
  1036. pauseButtonImage->setTexture(hudSpriteSheetTexture);
  1037. pauseButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-pause"), hudTextureAtlasBounds));
  1038. //buttonContainer->addChild(pauseButtonImage);
  1039. radialMenuContainer = new UIContainer();
  1040. radialMenuContainer->setVisible(false);
  1041. uiRootElement->addChild(radialMenuContainer);
  1042. radialMenuBackgroundImage = new UIImage();
  1043. radialMenuBackgroundImage->setTintColor(Vector4(Vector3(0.0f), 0.25f));
  1044. radialMenuContainer->addChild(radialMenuBackgroundImage);
  1045. radialMenuImage = new UIImage();
  1046. radialMenuImage->setTexture(hudSpriteSheetTexture);
  1047. radialMenuImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu"), hudTextureAtlasBounds));
  1048. radialMenuContainer->addChild(radialMenuImage);
  1049. radialMenuSelectorImage = new UIImage();
  1050. radialMenuSelectorImage->setTexture(hudSpriteSheetTexture);
  1051. radialMenuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu-selector"), hudTextureAtlasBounds));
  1052. radialMenuContainer->addChild(radialMenuSelectorImage);
  1053. toolIconBrushImage = new UIImage();
  1054. toolIconBrushImage->setTexture(hudSpriteSheetTexture);
  1055. toolIconBrushImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  1056. radialMenuImage->addChild(toolIconBrushImage);
  1057. toolIconLensImage = new UIImage();
  1058. toolIconLensImage->setTexture(hudSpriteSheetTexture);
  1059. toolIconLensImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-lens"), hudTextureAtlasBounds));
  1060. radialMenuImage->addChild(toolIconLensImage);
  1061. toolIconForcepsImage = new UIImage();
  1062. toolIconForcepsImage->setTexture(hudSpriteSheetTexture);
  1063. toolIconForcepsImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-forceps"), hudTextureAtlasBounds));
  1064. radialMenuImage->addChild(toolIconForcepsImage);
  1065. toolIconSpadeImage = new UIImage();
  1066. toolIconSpadeImage->setTexture(hudSpriteSheetTexture);
  1067. toolIconSpadeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-spade"), hudTextureAtlasBounds));
  1068. //radialMenuImage->addChild(toolIconSpadeImage);
  1069. toolIconCameraImage = new UIImage();
  1070. toolIconCameraImage->setTexture(hudSpriteSheetTexture);
  1071. toolIconCameraImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-camera"), hudTextureAtlasBounds));
  1072. radialMenuImage->addChild(toolIconCameraImage);
  1073. toolIconMicrochipImage = new UIImage();
  1074. toolIconMicrochipImage->setTexture(hudSpriteSheetTexture);
  1075. toolIconMicrochipImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-microchip"), hudTextureAtlasBounds));
  1076. radialMenuImage->addChild(toolIconMicrochipImage);
  1077. toolIconTestTubeImage = new UIImage();
  1078. toolIconTestTubeImage->setTexture(hudSpriteSheetTexture);
  1079. toolIconTestTubeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-test-tube"), hudTextureAtlasBounds));
  1080. //radialMenuImage->addChild(toolIconTestTubeImage);
  1081. antTag = new UIContainer();
  1082. antTag->setLayerOffset(-10);
  1083. antTag->setVisible(false);
  1084. uiRootElement->addChild(antTag);
  1085. antLabelContainer = new UIContainer();
  1086. antTag->addChild(antLabelContainer);
  1087. antLabelTL = new UIImage();
  1088. antLabelTR = new UIImage();
  1089. antLabelBL = new UIImage();
  1090. antLabelBR = new UIImage();
  1091. antLabelCC = new UIImage();
  1092. antLabelCT = new UIImage();
  1093. antLabelCB = new UIImage();
  1094. antLabelCL = new UIImage();
  1095. antLabelCR = new UIImage();
  1096. antLabelTL->setTexture(hudSpriteSheetTexture);
  1097. antLabelTR->setTexture(hudSpriteSheetTexture);
  1098. antLabelBL->setTexture(hudSpriteSheetTexture);
  1099. antLabelBR->setTexture(hudSpriteSheetTexture);
  1100. antLabelCC->setTexture(hudSpriteSheetTexture);
  1101. antLabelCT->setTexture(hudSpriteSheetTexture);
  1102. antLabelCB->setTexture(hudSpriteSheetTexture);
  1103. antLabelCL->setTexture(hudSpriteSheetTexture);
  1104. antLabelCR->setTexture(hudSpriteSheetTexture);
  1105. Rect labelTLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tl"), hudTextureAtlasBounds);
  1106. Rect labelTRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tr"), hudTextureAtlasBounds);
  1107. Rect labelBLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-bl"), hudTextureAtlasBounds);
  1108. Rect labelBRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-br"), hudTextureAtlasBounds);
  1109. Rect labelCCBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cc"), hudTextureAtlasBounds);
  1110. Rect labelCTBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-ct"), hudTextureAtlasBounds);
  1111. Rect labelCBBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cb"), hudTextureAtlasBounds);
  1112. Rect labelCLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cl"), hudTextureAtlasBounds);
  1113. Rect labelCRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cr"), hudTextureAtlasBounds);
  1114. Vector2 labelTLMin = labelTLBounds.getMin();
  1115. Vector2 labelTRMin = labelTRBounds.getMin();
  1116. Vector2 labelBLMin = labelBLBounds.getMin();
  1117. Vector2 labelBRMin = labelBRBounds.getMin();
  1118. Vector2 labelCCMin = labelCCBounds.getMin();
  1119. Vector2 labelCTMin = labelCTBounds.getMin();
  1120. Vector2 labelCBMin = labelCBBounds.getMin();
  1121. Vector2 labelCLMin = labelCLBounds.getMin();
  1122. Vector2 labelCRMin = labelCRBounds.getMin();
  1123. Vector2 labelTLMax = labelTLBounds.getMax();
  1124. Vector2 labelTRMax = labelTRBounds.getMax();
  1125. Vector2 labelBLMax = labelBLBounds.getMax();
  1126. Vector2 labelBRMax = labelBRBounds.getMax();
  1127. Vector2 labelCCMax = labelCCBounds.getMax();
  1128. Vector2 labelCTMax = labelCTBounds.getMax();
  1129. Vector2 labelCBMax = labelCBBounds.getMax();
  1130. Vector2 labelCLMax = labelCLBounds.getMax();
  1131. Vector2 labelCRMax = labelCRBounds.getMax();
  1132. antLabelTL->setTextureBounds(labelTLBounds);
  1133. antLabelTR->setTextureBounds(labelTRBounds);
  1134. antLabelBL->setTextureBounds(labelBLBounds);
  1135. antLabelBR->setTextureBounds(labelBRBounds);
  1136. antLabelCC->setTextureBounds(labelCCBounds);
  1137. antLabelCT->setTextureBounds(labelCTBounds);
  1138. antLabelCB->setTextureBounds(labelCBBounds);
  1139. antLabelCL->setTextureBounds(labelCLBounds);
  1140. antLabelCR->setTextureBounds(labelCRBounds);
  1141. antLabelContainer->addChild(antLabelTL);
  1142. antLabelContainer->addChild(antLabelTR);
  1143. antLabelContainer->addChild(antLabelBL);
  1144. antLabelContainer->addChild(antLabelBR);
  1145. antLabelContainer->addChild(antLabelCC);
  1146. antLabelContainer->addChild(antLabelCT);
  1147. antLabelContainer->addChild(antLabelCB);
  1148. antLabelContainer->addChild(antLabelCL);
  1149. antLabelContainer->addChild(antLabelCR);
  1150. antLabel = new UILabel();
  1151. antLabel->setFont(nullptr);
  1152. antLabel->setText("");
  1153. antLabel->setTintColor(Vector4(Vector3(0.0f), 1.0f));
  1154. antLabel->setLayerOffset(1);
  1155. antLabelContainer->addChild(antLabel);
  1156. fpsLabel = new UILabel();
  1157. fpsLabel->setFont(debugFont);
  1158. fpsLabel->setTintColor(Vector4(1, 1, 0, 1));
  1159. fpsLabel->setLayerOffset(50);
  1160. fpsLabel->setAnchor(Anchor::TOP_LEFT);
  1161. uiRootElement->addChild(fpsLabel);
  1162. antPin = new UIImage();
  1163. antPin->setTexture(hudSpriteSheetTexture);
  1164. antPin->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin"), hudTextureAtlasBounds));
  1165. antTag->addChild(antPin);
  1166. antLabelPinHole = new UIImage();
  1167. antLabelPinHole->setTexture(hudSpriteSheetTexture);
  1168. antLabelPinHole->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin-hole"), hudTextureAtlasBounds));
  1169. antLabelContainer->addChild(antLabelPinHole);
  1170. // Construct box selection
  1171. boxSelectionImageBackground = new UIImage();
  1172. boxSelectionImageBackground->setAnchor(Anchor::CENTER);
  1173. boxSelectionImageTop = new UIImage();
  1174. boxSelectionImageTop->setAnchor(Anchor::TOP_LEFT);
  1175. boxSelectionImageBottom = new UIImage();
  1176. boxSelectionImageBottom->setAnchor(Anchor::BOTTOM_LEFT);
  1177. boxSelectionImageLeft = new UIImage();
  1178. boxSelectionImageLeft->setAnchor(Anchor::TOP_LEFT);
  1179. boxSelectionImageRight = new UIImage();
  1180. boxSelectionImageRight->setAnchor(Anchor::TOP_RIGHT);
  1181. boxSelectionContainer = new UIContainer();
  1182. boxSelectionContainer->setLayerOffset(80);
  1183. boxSelectionContainer->addChild(boxSelectionImageBackground);
  1184. boxSelectionContainer->addChild(boxSelectionImageTop);
  1185. boxSelectionContainer->addChild(boxSelectionImageBottom);
  1186. boxSelectionContainer->addChild(boxSelectionImageLeft);
  1187. boxSelectionContainer->addChild(boxSelectionImageRight);
  1188. boxSelectionContainer->setVisible(false);
  1189. uiRootElement->addChild(boxSelectionContainer);
  1190. boxSelectionImageBackground->setTintColor(Vector4(1.0f, 1.0f, 1.0f, 0.5f));
  1191. boxSelectionContainer->setTintColor(Vector4(1.0f, 0.0f, 0.0f, 1.0f));
  1192. boxSelectionBorderWidth = 2.0f;
  1193. cameraGridColor = Vector4(1, 1, 1, 0.5f);
  1194. cameraReticleColor = Vector4(1, 1, 1, 0.75f);
  1195. cameraGridY0Image = new UIImage();
  1196. cameraGridY0Image->setAnchor(Vector2(0.5f, (1.0f / 3.0f)));
  1197. cameraGridY0Image->setTintColor(cameraGridColor);
  1198. cameraGridY1Image = new UIImage();
  1199. cameraGridY1Image->setAnchor(Vector2(0.5f, (2.0f / 3.0f)));
  1200. cameraGridY1Image->setTintColor(cameraGridColor);
  1201. cameraGridX0Image = new UIImage();
  1202. cameraGridX0Image->setAnchor(Vector2((1.0f / 3.0f), 0.5f));
  1203. cameraGridX0Image->setTintColor(cameraGridColor);
  1204. cameraGridX1Image = new UIImage();
  1205. cameraGridX1Image->setAnchor(Vector2((2.0f / 3.0f), 0.5f));
  1206. cameraGridX1Image->setTintColor(cameraGridColor);
  1207. cameraReticleImage = new UIImage();
  1208. cameraReticleImage->setAnchor(Anchor::CENTER);
  1209. cameraReticleImage->setTintColor(cameraReticleColor);
  1210. cameraReticleImage->setTexture(hudSpriteSheetTexture);
  1211. cameraReticleImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("camera-reticle"), hudTextureAtlasBounds));
  1212. cameraGridContainer = new UIContainer();
  1213. cameraGridContainer->addChild(cameraGridY0Image);
  1214. cameraGridContainer->addChild(cameraGridY1Image);
  1215. cameraGridContainer->addChild(cameraGridX0Image);
  1216. cameraGridContainer->addChild(cameraGridX1Image);
  1217. cameraGridContainer->addChild(cameraReticleImage);
  1218. cameraGridContainer->setVisible(false);
  1219. uiRootElement->addChild(cameraGridContainer);
  1220. cameraFlashImage = new UIImage();
  1221. cameraFlashImage->setLayerOffset(99);
  1222. cameraFlashImage->setTintColor(Vector4(1.0f));
  1223. cameraFlashImage->setVisible(false);
  1224. uiRootElement->addChild(cameraFlashImage);
  1225. blackoutImage = new UIImage();
  1226. blackoutImage->setLayerOffset(98);
  1227. blackoutImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1228. blackoutImage->setVisible(false);
  1229. uiRootElement->addChild(blackoutImage);
  1230. languageSelectBGImage = new UIImage();
  1231. languageSelectBGImage->setLayerOffset(-1);
  1232. languageSelectBGImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1233. languageSelectBGImage->setVisible(true);
  1234. standardMenuActiveColor = Vector4(Vector3(0.2f), 1.0f);
  1235. standardMenuInactiveColor = Vector4(Vector3(0.2f), 0.5f);
  1236. languageMenuActiveColor = Vector4(Vector3(1.0f), 1.0f);
  1237. languageMenuInactiveColor = Vector4(Vector3(1.0f), 0.5f);
  1238. menuItemActiveColor = standardMenuActiveColor;
  1239. menuItemInactiveColor = standardMenuInactiveColor;
  1240. menuItemIndex = -1;
  1241. currentMenu = nullptr;
  1242. currentMenuItem = nullptr;
  1243. previousMenuItem = nullptr;
  1244. previousMenu = nullptr;
  1245. menuSelectorImage = new UIImage();
  1246. menuSelectorImage->setAnchor(Anchor::TOP_LEFT);
  1247. menuSelectorImage->setTexture(hudSpriteSheetTexture);
  1248. menuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("menu-selector"), hudTextureAtlasBounds));
  1249. menuSelectorImage->setTintColor(menuItemActiveColor);
  1250. // Build main menu
  1251. mainMenu = new Menu();
  1252. mainMenuContinueItem = mainMenu->addItem();
  1253. mainMenuNewGameItem = mainMenu->addItem();
  1254. mainMenuColoniesItem = mainMenu->addItem();
  1255. mainMenuSettingsItem = mainMenu->addItem();
  1256. mainMenuQuitItem = mainMenu->addItem();
  1257. // Build settings menu
  1258. settingsMenu = new Menu();
  1259. settingsMenuControlsItem = settingsMenu->addItem();
  1260. settingsMenuFullscreenItem = settingsMenu->addItem();
  1261. settingsMenuVSyncItem = settingsMenu->addItem();
  1262. settingsMenuLanguageItem = settingsMenu->addItem();
  1263. settingsMenuBackItem = settingsMenu->addItem();
  1264. // Build controls menu
  1265. controlsMenu = new Menu();
  1266. controlsMenuMoveForwardItem = controlsMenu->addItem();
  1267. controlsMenuMoveLeftItem = controlsMenu->addItem();
  1268. controlsMenuMoveBackItem = controlsMenu->addItem();
  1269. controlsMenuMoveRightItem = controlsMenu->addItem();
  1270. controlsMenuChangeToolItem = controlsMenu->addItem();
  1271. controlsMenuUseToolItem = controlsMenu->addItem();
  1272. controlsMenuAdjustCameraItem = controlsMenu->addItem();
  1273. controlsMenuPauseItem = controlsMenu->addItem();
  1274. controlsMenuToggleFullscreenItem = controlsMenu->addItem();
  1275. controlsMenuTakeScreenshotItem = controlsMenu->addItem();
  1276. controlsMenuResetToDefaultItem = controlsMenu->addItem();
  1277. controlsMenuBackItem = controlsMenu->addItem();
  1278. // Build pause menu
  1279. pauseMenu = new Menu();
  1280. pauseMenuResumeItem = pauseMenu->addItem();
  1281. pauseMenuSettingsItem = pauseMenu->addItem();
  1282. pauseMenuMainMenuItem = pauseMenu->addItem();
  1283. pauseMenuQuitItem = pauseMenu->addItem();
  1284. // Build language menu
  1285. languageMenu = new Menu();
  1286. for (std::size_t i = 0; i < languageCount; ++i)
  1287. {
  1288. MenuItem* item = languageMenu->addItem();
  1289. item->setActivatedCallback
  1290. (
  1291. [this, i]()
  1292. {
  1293. changeLanguage(i);
  1294. languageSelected();
  1295. }
  1296. );
  1297. item->getContainer()->setTintColor(languageMenuInactiveColor);
  1298. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1299. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1300. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1301. languageMenuItems.push_back(item);
  1302. }
  1303. // Setup main menu callbacks
  1304. mainMenuContinueItem->setActivatedCallback(std::bind(&Game::continueGame, this));
  1305. mainMenuNewGameItem->setActivatedCallback(std::bind(&Game::newGame, this));
  1306. mainMenuSettingsItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1307. mainMenuQuitItem->setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1308. // Setup settings menu callbacks
  1309. settingsMenuControlsItem->setActivatedCallback(std::bind(&Game::openMenu, this, controlsMenu, 0));
  1310. settingsMenuFullscreenItem->setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1311. settingsMenuVSyncItem->setActivatedCallback(std::bind(&Game::toggleVSync, this));
  1312. settingsMenuLanguageItem->setActivatedCallback(std::bind(&Game::nextLanguage, this));
  1313. settingsMenuBackItem->setActivatedCallback(std::bind(&Game::openMenu, this, mainMenu, 3));
  1314. // Setup controls menu callbacks
  1315. controlsMenuMoveForwardItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveForwardControl));
  1316. controlsMenuMoveLeftItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveLeftControl));
  1317. controlsMenuMoveBackItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveBackControl));
  1318. controlsMenuMoveRightItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveRightControl));
  1319. controlsMenuChangeToolItem->setActivatedCallback(std::bind(&Game::remapControl, this, &changeToolControl));
  1320. controlsMenuUseToolItem->setActivatedCallback(std::bind(&Game::remapControl, this, &useToolControl));
  1321. controlsMenuAdjustCameraItem->setActivatedCallback(std::bind(&Game::remapControl, this, &adjustCameraControl));
  1322. controlsMenuPauseItem->setActivatedCallback(std::bind(&Game::remapControl, this, &pauseControl));
  1323. controlsMenuToggleFullscreenItem->setActivatedCallback(std::bind(&Game::remapControl, this, &toggleFullscreenControl));
  1324. controlsMenuTakeScreenshotItem->setActivatedCallback(std::bind(&Game::remapControl, this, &takeScreenshotControl));
  1325. controlsMenuResetToDefaultItem->setActivatedCallback(std::bind(&Game::resetControls, this));
  1326. controlsMenuBackItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1327. // Setup pause menu callbacks
  1328. pauseMenuResumeItem->setActivatedCallback(std::bind(&Game::togglePause, this));
  1329. pauseMenuSettingsItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1330. pauseMenuMainMenuItem->setActivatedCallback(std::bind(&Game::returnToMainMenu, this));
  1331. pauseMenuQuitItem->setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1332. // Setup standard callbacks for all menu items
  1333. for (std::size_t i = 0; i < mainMenu->getItems()->size(); ++i)
  1334. {
  1335. MenuItem* item = (*mainMenu->getItems())[i];
  1336. item->getContainer()->setTintColor(menuItemInactiveColor);
  1337. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1338. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1339. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1340. }
  1341. for (std::size_t i = 0; i < settingsMenu->getItems()->size(); ++i)
  1342. {
  1343. MenuItem* item = (*settingsMenu->getItems())[i];
  1344. item->getContainer()->setTintColor(menuItemInactiveColor);
  1345. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1346. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1347. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1348. }
  1349. for (std::size_t i = 0; i < controlsMenu->getItems()->size(); ++i)
  1350. {
  1351. MenuItem* item = (*controlsMenu->getItems())[i];
  1352. item->getContainer()->setTintColor(menuItemInactiveColor);
  1353. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1354. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1355. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1356. }
  1357. for (std::size_t i = 0; i < pauseMenu->getItems()->size(); ++i)
  1358. {
  1359. MenuItem* item = (*pauseMenu->getItems())[i];
  1360. item->getContainer()->setTintColor(menuItemInactiveColor);
  1361. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1362. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1363. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1364. }
  1365. // Set fonts for all menus
  1366. mainMenu->setFonts(menuFont);
  1367. settingsMenu->setFonts(menuFont);
  1368. controlsMenu->setFonts(menuFont);
  1369. pauseMenu->setFonts(menuFont);
  1370. AnimationChannel<float>* channel;
  1371. // Setup splash fade-in animation
  1372. splashFadeInClip.setInterpolator(easeOutCubic<float>);
  1373. channel = splashFadeInClip.addChannel(0);
  1374. channel->insertKeyframe(0.0f, 0.0f);
  1375. channel->insertKeyframe(1.0f, 1.0f);
  1376. channel->insertKeyframe(3.0f, 1.0f);
  1377. splashFadeInAnimation.setClip(&splashFadeInClip);
  1378. splashFadeInAnimation.setTimeFrame(splashFadeInClip.getTimeFrame());
  1379. splashFadeInAnimation.setAnimateCallback
  1380. (
  1381. [this](std::size_t id, float opacity)
  1382. {
  1383. Vector3 color = Vector3(splashImage->getTintColor());
  1384. splashImage->setTintColor(Vector4(color, opacity));
  1385. }
  1386. );
  1387. splashFadeInAnimation.setEndCallback
  1388. (
  1389. [this]()
  1390. {
  1391. splashFadeOutAnimation.rewind();
  1392. splashFadeOutAnimation.play();
  1393. }
  1394. );
  1395. // Setup splash fade-out animation
  1396. splashFadeOutClip.setInterpolator(easeOutCubic<float>);
  1397. channel = splashFadeOutClip.addChannel(0);
  1398. channel->insertKeyframe(0.0f, 1.0f);
  1399. channel->insertKeyframe(1.0f, 0.0f);
  1400. channel->insertKeyframe(1.5f, 0.0f);
  1401. splashFadeOutAnimation.setClip(&splashFadeOutClip);
  1402. splashFadeOutAnimation.setTimeFrame(splashFadeOutClip.getTimeFrame());
  1403. splashFadeOutAnimation.setAnimateCallback
  1404. (
  1405. [this](std::size_t id, float opacity)
  1406. {
  1407. Vector3 color = Vector3(splashImage->getTintColor());
  1408. splashImage->setTintColor(Vector4(color, opacity));
  1409. }
  1410. );
  1411. splashFadeOutAnimation.setEndCallback(std::bind(&StateMachine::changeState, this, &titleState));
  1412. // Ant-hill zoom animation
  1413. antHillZoomClip.setInterpolator(easeOutCubic<float>);
  1414. channel = antHillZoomClip.addChannel(0);
  1415. channel->insertKeyframe(0.0f, 0.0f);
  1416. channel->insertKeyframe(3.0f, 40.0f);
  1417. antHillZoomAnimation.setClip(&antHillZoomClip);
  1418. antHillZoomAnimation.setTimeFrame(antHillZoomClip.getTimeFrame());
  1419. antHillZoomAnimation.setAnimateCallback
  1420. (
  1421. [this](std::size_t id, float distance)
  1422. {
  1423. orbitCam->setFocalDistance(distance);
  1424. orbitCam->setTargetFocalDistance(distance);
  1425. }
  1426. );
  1427. // Menu fade animation
  1428. menuFadeInClip.setInterpolator(easeOutCubic<float>);
  1429. channel = menuFadeInClip.addChannel(0);
  1430. channel->insertKeyframe(0.0f, 0.0f);
  1431. channel->insertKeyframe(3.0f, 0.0f);
  1432. channel->insertKeyframe(5.0f, 1.0f);
  1433. menuFadeOutClip.setInterpolator(easeOutCubic<float>);
  1434. channel = menuFadeOutClip.addChannel(0);
  1435. channel->insertKeyframe(0.0f, 1.0f);
  1436. channel->insertKeyframe(0.125f, 0.0f);
  1437. menuFadeAnimation.setClip(&menuFadeInClip);
  1438. menuFadeAnimation.setTimeFrame(menuFadeInClip.getTimeFrame());
  1439. menuFadeAnimation.setAnimateCallback
  1440. (
  1441. [this](std::size_t id, float opacity)
  1442. {
  1443. currentMenu->getContainer()->setTintColor(Vector4(opacity));
  1444. }
  1445. );
  1446. animator.addAnimation(&menuFadeAnimation);
  1447. // Menu selector animation
  1448. menuSelectorSlideClip.setInterpolator(easeOutCubic<float>);
  1449. menuSelectorSlideAnimation.setClip(&menuSelectorSlideClip);
  1450. menuSelectorSlideAnimation.setAnimateCallback
  1451. (
  1452. [this](std::size_t id, float offset)
  1453. {
  1454. Vector2 translation = menuSelectorImage->getTranslation();
  1455. translation.y = offset;
  1456. menuSelectorImage->setTranslation(translation);
  1457. }
  1458. );
  1459. animator.addAnimation(&menuSelectorSlideAnimation);
  1460. // Menu item select animation
  1461. menuItemSelectClip.setInterpolator(easeOutCubic<Vector4>);
  1462. menuItemSelectAnimation.setClip(&menuItemSelectClip);
  1463. menuItemSelectAnimation.setAnimateCallback
  1464. (
  1465. [this](std::size_t id, const Vector4& color)
  1466. {
  1467. currentMenuItem->getContainer()->setTintColor(color);
  1468. }
  1469. );
  1470. // Menu item deselect animation
  1471. menuItemDeselectClip.setInterpolator(easeOutCubic<Vector4>);
  1472. menuItemDeselectAnimation.setClip(&menuItemDeselectClip);
  1473. menuItemDeselectAnimation.setAnimateCallback
  1474. (
  1475. [this](std::size_t id, const Vector4& color)
  1476. {
  1477. previousMenuItem->getContainer()->setTintColor(color);
  1478. }
  1479. );
  1480. animator.addAnimation(&menuItemSelectAnimation);
  1481. animator.addAnimation(&menuItemDeselectAnimation);
  1482. // Construct fade-in animation clip
  1483. fadeInClip.setInterpolator(easeOutCubic<float>);
  1484. channel = fadeInClip.addChannel(0);
  1485. channel->insertKeyframe(0.0f, 1.0f);
  1486. channel->insertKeyframe(1.0f, 0.0f);
  1487. // Construct fade-out animation clip
  1488. fadeOutClip.setInterpolator(easeOutCubic<float>);
  1489. channel = fadeOutClip.addChannel(0);
  1490. channel->insertKeyframe(0.0f, 0.0f);
  1491. channel->insertKeyframe(1.0f, 1.0f);
  1492. // Setup fade-in animation callbacks
  1493. fadeInAnimation.setAnimateCallback
  1494. (
  1495. [this](std::size_t id, float opacity)
  1496. {
  1497. Vector3 color = Vector3(blackoutImage->getTintColor());
  1498. blackoutImage->setTintColor(Vector4(color, opacity));
  1499. }
  1500. );
  1501. fadeInAnimation.setEndCallback
  1502. (
  1503. [this]()
  1504. {
  1505. blackoutImage->setVisible(false);
  1506. if (fadeInEndCallback != nullptr)
  1507. {
  1508. fadeInEndCallback();
  1509. }
  1510. }
  1511. );
  1512. // Setup fade-out animation callbacks
  1513. fadeOutAnimation.setAnimateCallback
  1514. (
  1515. [this](std::size_t id, float opacity)
  1516. {
  1517. Vector3 color = Vector3(blackoutImage->getTintColor());
  1518. blackoutImage->setTintColor(Vector4(color, opacity));
  1519. }
  1520. );
  1521. fadeOutAnimation.setEndCallback
  1522. (
  1523. [this]()
  1524. {
  1525. blackoutImage->setVisible(false);
  1526. if (fadeOutEndCallback != nullptr)
  1527. {
  1528. fadeOutEndCallback();
  1529. }
  1530. }
  1531. );
  1532. animator.addAnimation(&fadeInAnimation);
  1533. animator.addAnimation(&fadeOutAnimation);
  1534. // Construct camera flash animation clip
  1535. cameraFlashClip.setInterpolator(easeOutQuad<float>);
  1536. channel = cameraFlashClip.addChannel(0);
  1537. channel->insertKeyframe(0.0f, 1.0f);
  1538. channel->insertKeyframe(1.0f, 0.0f);
  1539. // Setup camera flash animation
  1540. float flashDuration = 0.5f;
  1541. cameraFlashAnimation.setSpeed(1.0f / flashDuration);
  1542. cameraFlashAnimation.setLoop(false);
  1543. cameraFlashAnimation.setClip(&cameraFlashClip);
  1544. cameraFlashAnimation.setTimeFrame(cameraFlashClip.getTimeFrame());
  1545. cameraFlashAnimation.setAnimateCallback
  1546. (
  1547. [this](std::size_t id, float opacity)
  1548. {
  1549. cameraFlashImage->setTintColor(Vector4(Vector3(1.0f), opacity));
  1550. }
  1551. );
  1552. cameraFlashAnimation.setStartCallback
  1553. (
  1554. [this]()
  1555. {
  1556. cameraFlashImage->setVisible(true);
  1557. cameraFlashImage->setTintColor(Vector4(1.0f));
  1558. cameraFlashImage->resetTweens();
  1559. }
  1560. );
  1561. cameraFlashAnimation.setEndCallback
  1562. (
  1563. [this]()
  1564. {
  1565. cameraFlashImage->setVisible(false);
  1566. }
  1567. );
  1568. animator.addAnimation(&cameraFlashAnimation);
  1569. // Setup UI scene
  1570. uiScene->addObject(uiBatch);
  1571. uiScene->addObject(&uiCamera);
  1572. // Setup UI camera
  1573. uiCamera.lookAt(Vector3(0), Vector3(0, 0, -1), Vector3(0, 1, 0));
  1574. uiCamera.resetTweens();
  1575. uiCamera.setCompositor(&uiCompositor);
  1576. uiCamera.setCompositeIndex(0);
  1577. uiCamera.setCullingEnabled(false);
  1578. restringUI();
  1579. resizeUI(w, h);
  1580. }
  1581. void Game::setupControls()
  1582. {
  1583. // Get keyboard and mouse
  1584. keyboard = deviceManager->getKeyboards()->front();
  1585. mouse = deviceManager->getMice()->front();
  1586. // Build the master control set
  1587. controls.addControl(&exitControl);
  1588. controls.addControl(&toggleFullscreenControl);
  1589. controls.addControl(&takeScreenshotControl);
  1590. controls.addControl(&menuUpControl);
  1591. controls.addControl(&menuDownControl);
  1592. controls.addControl(&menuLeftControl);
  1593. controls.addControl(&menuRightControl);
  1594. controls.addControl(&menuActivateControl);
  1595. controls.addControl(&menuBackControl);
  1596. controls.addControl(&moveForwardControl);
  1597. controls.addControl(&moveBackControl);
  1598. controls.addControl(&moveLeftControl);
  1599. controls.addControl(&moveRightControl);
  1600. controls.addControl(&zoomInControl);
  1601. controls.addControl(&zoomOutControl);
  1602. controls.addControl(&orbitCCWControl);
  1603. controls.addControl(&orbitCWControl);
  1604. controls.addControl(&adjustCameraControl);
  1605. controls.addControl(&dragCameraControl);
  1606. controls.addControl(&pauseControl);
  1607. controls.addControl(&changeToolControl);
  1608. controls.addControl(&useToolControl);
  1609. controls.addControl(&toggleEditModeControl);
  1610. // Build the system control set
  1611. systemControls.addControl(&exitControl);
  1612. systemControls.addControl(&toggleFullscreenControl);
  1613. systemControls.addControl(&takeScreenshotControl);
  1614. // Build the menu control set
  1615. menuControls.addControl(&menuUpControl);
  1616. menuControls.addControl(&menuDownControl);
  1617. menuControls.addControl(&menuLeftControl);
  1618. menuControls.addControl(&menuRightControl);
  1619. menuControls.addControl(&menuActivateControl);
  1620. menuControls.addControl(&menuBackControl);
  1621. // Build the camera control set
  1622. cameraControls.addControl(&moveForwardControl);
  1623. cameraControls.addControl(&moveBackControl);
  1624. cameraControls.addControl(&moveLeftControl);
  1625. cameraControls.addControl(&moveRightControl);
  1626. cameraControls.addControl(&zoomInControl);
  1627. cameraControls.addControl(&zoomOutControl);
  1628. cameraControls.addControl(&orbitCCWControl);
  1629. cameraControls.addControl(&orbitCWControl);
  1630. cameraControls.addControl(&adjustCameraControl);
  1631. cameraControls.addControl(&dragCameraControl);
  1632. cameraControls.addControl(&pauseControl);
  1633. // Build the tool control set
  1634. toolControls.addControl(&changeToolControl);
  1635. toolControls.addControl(&useToolControl);
  1636. // Build the editor control set
  1637. editorControls.addControl(&toggleEditModeControl);
  1638. // Setup control callbacks
  1639. menuDownControl.setActivatedCallback(std::bind(&Game::selectNextMenuItem, this));
  1640. menuUpControl.setActivatedCallback(std::bind(&Game::selectPreviousMenuItem, this));
  1641. menuActivateControl.setActivatedCallback(std::bind(&Game::activateMenuItem, this));
  1642. menuBackControl.setActivatedCallback(std::bind(&Game::activateLastMenuItem, this));
  1643. pauseControl.setActivatedCallback(std::bind(&Game::togglePause, this));
  1644. exitControl.setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1645. toggleFullscreenControl.setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1646. takeScreenshotControl.setActivatedCallback(std::bind(&Game::queueScreenshot, this));
  1647. // Build map of control names
  1648. controlNameMap["exit"] = &exitControl;
  1649. controlNameMap["toggle-fullscreen"] = &toggleFullscreenControl;
  1650. controlNameMap["take-screenshot"] = &takeScreenshotControl;
  1651. controlNameMap["menu-up"] = &menuUpControl;
  1652. controlNameMap["menu-down"] = &menuDownControl;
  1653. controlNameMap["menu-left"] = &menuLeftControl;
  1654. controlNameMap["menu-right"] = &menuRightControl;
  1655. controlNameMap["menu-activate"] = &menuActivateControl;
  1656. controlNameMap["menu-back"] = &menuBackControl;
  1657. controlNameMap["move-forward"] = &moveForwardControl;
  1658. controlNameMap["move-back"] = &moveBackControl;
  1659. controlNameMap["move-left"] = &moveLeftControl;
  1660. controlNameMap["move-right"] = &moveRightControl;
  1661. controlNameMap["zoom-in"] = &zoomInControl;
  1662. controlNameMap["zoom-out"] = &zoomOutControl;
  1663. controlNameMap["orbit-ccw"] = &orbitCCWControl;
  1664. controlNameMap["orbit-cw"] = &orbitCWControl;
  1665. controlNameMap["adjust-camera"] = &adjustCameraControl;
  1666. controlNameMap["drag-camera"] = &dragCameraControl;
  1667. controlNameMap["pause"] = &pauseControl;
  1668. controlNameMap["change-tool"] = &changeToolControl;
  1669. controlNameMap["use-tool"] = &useToolControl;
  1670. controlNameMap["toggle-edit-mode"] = &toggleEditModeControl;
  1671. // Load control profile
  1672. if (pathExists(controlsPath + controlProfileName + ".csv"))
  1673. {
  1674. loadControlProfile(controlProfileName);
  1675. }
  1676. else
  1677. {
  1678. loadControlProfile("default-keyboard-controls");
  1679. saveControlProfile(controlProfileName);
  1680. }
  1681. // Setup input mapper
  1682. inputMapper = new InputMapper(&eventDispatcher);
  1683. inputMapper->setCallback(std::bind(&Game::inputMapped, this, std::placeholders::_1));
  1684. inputMapper->setControl(nullptr);
  1685. inputMapper->setEnabled(false);
  1686. }
  1687. void Game::setupGameplay()
  1688. {
  1689. // Setup step scheduler
  1690. double maxFrameDuration = 0.25;
  1691. double stepFrequency = 60.0;
  1692. stepScheduler.setMaxFrameDuration(maxFrameDuration);
  1693. stepScheduler.setStepFrequency(stepFrequency);
  1694. timestep = stepScheduler.getStepPeriod();
  1695. // Setup camera rigs
  1696. orbitCam = new OrbitCam();
  1697. orbitCam->attachCamera(&camera);
  1698. freeCam = new FreeCam();
  1699. freeCam->attachCamera(&camera);
  1700. cameraRig = orbitCam;
  1701. }
  1702. void Game::resetSettings()
  1703. {
  1704. // Set default language
  1705. language = "en-us";
  1706. // Set default resolutions
  1707. const Display* display = deviceManager->getDisplays()->front();
  1708. int displayWidth = std::get<0>(display->getDimensions());
  1709. int displayHeight = std::get<1>(display->getDimensions());
  1710. float windowedResolutionRatio = 5.0f / 6.0f;
  1711. windowedResolution = Vector2(displayWidth, displayHeight) * 5.0f / 6.0f;
  1712. windowedResolution.x = static_cast<int>(windowedResolution.x);
  1713. windowedResolution.y = static_cast<int>(windowedResolution.y);
  1714. fullscreenResolution = Vector2(displayWidth, displayHeight);
  1715. // Set default fullscreen mode
  1716. fullscreen = false;
  1717. // Set default vsync mode
  1718. vsync = true;
  1719. // Set default font size
  1720. fontSizePT = 14.0f;
  1721. // Set control profile name
  1722. controlProfileName = "controls";
  1723. }
  1724. void Game::loadSettings()
  1725. {
  1726. // Reset settings to default values
  1727. resetSettings();
  1728. firstRun = false;
  1729. // Load settings table
  1730. try
  1731. {
  1732. settingsTable = resourceManager->load<StringTable>("settings.csv");
  1733. }
  1734. catch (const std::exception& e)
  1735. {
  1736. logger->warning("No user settings found. First run assumed.");
  1737. firstRun = true;
  1738. try
  1739. {
  1740. settingsTable = resourceManager->load<StringTable>("default-settings.csv");
  1741. }
  1742. catch (const std::exception& e)
  1743. {
  1744. logger->error("Failed to load default settings.");
  1745. }
  1746. }
  1747. // Build settings table index
  1748. settingsTableIndex = createIndex(*settingsTable);
  1749. // Read settings from table
  1750. readSetting("language", &language);
  1751. readSetting("windowed-resolution", &windowedResolution);
  1752. readSetting("fullscreen-resolution", &fullscreenResolution);
  1753. readSetting("fullscreen", &fullscreen);
  1754. readSetting("vsync", &vsync);
  1755. readSetting("font-size", &fontSizePT);
  1756. readSetting("control-profile", &controlProfileName);
  1757. }
  1758. void Game::saveSettings()
  1759. {
  1760. }
  1761. void Game::loadStrings()
  1762. {
  1763. // Read strings file
  1764. stringTable = resourceManager->load<StringTable>("strings.csv");
  1765. // Build string table index
  1766. stringTableIndex = createIndex(*stringTable);
  1767. }
  1768. void Game::loadFonts()
  1769. {
  1770. // If the language selection fonts haven't been loaded
  1771. if (languageSelectionFonts.empty())
  1772. {
  1773. // Load one font for each available language
  1774. for (std::size_t i = 0; i < languageCount; ++i)
  1775. {
  1776. // Get language name and font filename for that language
  1777. std::string languageName = getString("language-name", i);
  1778. std::string fontFilename = getString("menu-font-filename", i);
  1779. // Check if language has a name
  1780. if (languageName.empty())
  1781. {
  1782. logger->error("Language #" + std::to_string(i) + " has no name string.");
  1783. languageSelectionFonts.push_back(nullptr);
  1784. continue;
  1785. }
  1786. // Check if language has a font filename
  1787. if (fontFilename.empty())
  1788. {
  1789. logger->error("No font for language #" + std::to_string(i) + ".");
  1790. languageSelectionFonts.push_back(nullptr);
  1791. continue;
  1792. }
  1793. // Load typeface for the font
  1794. Typeface* typeface = resourceManager->load<Typeface>(fontFilename);
  1795. // Create a font at default font size
  1796. Font* font = typeface->createFont(fontSizePX);
  1797. // Build a character set containing only the characters in the language name
  1798. std::set<char32_t> characterSet;
  1799. std::u32string languageNameUTF32 = toUTF32(languageName);
  1800. for (char32_t charcode: languageNameUTF32)
  1801. {
  1802. characterSet.emplace(charcode);
  1803. }
  1804. // Load glyphs for all characters in the character set
  1805. typeface->loadCharset(font, characterSet);
  1806. // Unload the typeface
  1807. resourceManager->unload(fontFilename);
  1808. // Add the font to the language selection fonts
  1809. languageSelectionFonts.push_back(font);
  1810. }
  1811. }
  1812. // Get filenames of fonts
  1813. std::string menuFontFilename = getString("menu-font-filename");
  1814. std::string debugFontFilename = "inconsolata-bold.ttf";
  1815. // Load debugging font
  1816. if (!debugFont)
  1817. {
  1818. // Load debug font typeface
  1819. Typeface* debugTypeface = resourceManager->load<Typeface>(debugFontFilename);
  1820. // Create debug font
  1821. debugFont = debugTypeface->createFont(fontSizePX);
  1822. // Load basic latin characyer set
  1823. debugTypeface->loadCharset(debugFont, UnicodeRange::BASIC_LATIN);
  1824. // Unload debug font typeface
  1825. resourceManager->unload(debugFontFilename);
  1826. }
  1827. // Load menu font typeface
  1828. Typeface* menuTypeface = resourceManager->load<Typeface>(menuFontFilename);
  1829. // Create menu font
  1830. menuFont = menuTypeface->createFont(fontSizePX);
  1831. // Load basic latin character set
  1832. menuTypeface->loadCharset(menuFont, UnicodeRange::BASIC_LATIN);
  1833. // Build character set for all strings in current language
  1834. std::set<char32_t> characterSet;
  1835. for (const StringTableRow& row: *stringTable)
  1836. {
  1837. // Convert to UTF-8 string to UTF-32
  1838. std::u32string string = toUTF32(row[currentLanguageIndex + 2]);
  1839. // Add each character in the string to the charater set
  1840. for (char32_t charcode: string)
  1841. {
  1842. characterSet.emplace(charcode);
  1843. }
  1844. }
  1845. // Load custom character set
  1846. menuTypeface->loadCharset(menuFont, characterSet);
  1847. // Unload menu typeface
  1848. resourceManager->unload(menuFontFilename);
  1849. }
  1850. void Game::loadControlProfile(const std::string& profileName)
  1851. {
  1852. // Load control profile
  1853. std::string controlProfilePath = profileName + ".csv";
  1854. StringTable* controlProfile = resourceManager->load<StringTable>(controlProfilePath);
  1855. for (const StringTableRow& row: *controlProfile)
  1856. {
  1857. // Skip empty rows and comments
  1858. if (row.empty() || row[0].empty() || row[0][0] == '#')
  1859. {
  1860. continue;
  1861. }
  1862. // Get control name
  1863. const std::string& controlName = row[0];
  1864. // Lookup control in control name map
  1865. auto it = controlNameMap.find(controlName);
  1866. if (it == controlNameMap.end())
  1867. {
  1868. logger->warning("Game::loadControlProfile(): Unknown control name \"" + controlName + "\"\n");
  1869. continue;
  1870. }
  1871. // Get pointer to the control
  1872. Control* control = it->second;
  1873. // Determine type of input mapping
  1874. const std::string& deviceType = row[1];
  1875. if (deviceType == "keyboard")
  1876. {
  1877. const std::string& eventType = row[2];
  1878. const std::string& scancodeName = row[3];
  1879. // Get scancode from string
  1880. Scancode scancode = Keyboard::getScancodeFromName(scancodeName.c_str());
  1881. // Map control
  1882. if (scancode != Scancode::UNKNOWN)
  1883. {
  1884. inputRouter->addMapping(KeyMapping(control, keyboard, scancode));
  1885. }
  1886. }
  1887. else if (deviceType == "mouse")
  1888. {
  1889. const std::string& eventType = row[2];
  1890. if (eventType == "motion")
  1891. {
  1892. const std::string& axisName = row[3];
  1893. // Get axis from string
  1894. MouseMotionAxis axis;
  1895. bool negative = (axisName.find('-') != std::string::npos);
  1896. if (axisName.find('x') != std::string::npos)
  1897. {
  1898. axis = (negative) ? MouseMotionAxis::NEGATIVE_X : MouseMotionAxis::POSITIVE_X;
  1899. }
  1900. else if (axisName.find('y') != std::string::npos)
  1901. {
  1902. axis = (negative) ? MouseMotionAxis::NEGATIVE_Y : MouseMotionAxis::POSITIVE_Y;
  1903. }
  1904. else
  1905. {
  1906. logger->warning("Game::loadControlProfile(): Unknown mouse motion axis \"" + axisName + "\"\n");
  1907. continue;
  1908. }
  1909. // Map control
  1910. inputRouter->addMapping(MouseMotionMapping(control, mouse, axis));
  1911. }
  1912. else if (eventType == "wheel")
  1913. {
  1914. const std::string& axisName = row[3];
  1915. // Get axis from string
  1916. MouseWheelAxis axis;
  1917. bool negative = (axisName.find('-') != std::string::npos);
  1918. if (axisName.find('x') != std::string::npos)
  1919. {
  1920. axis = (negative) ? MouseWheelAxis::NEGATIVE_X : MouseWheelAxis::POSITIVE_X;
  1921. }
  1922. else if (axisName.find('y') != std::string::npos)
  1923. {
  1924. axis = (negative) ? MouseWheelAxis::NEGATIVE_Y : MouseWheelAxis::POSITIVE_Y;
  1925. }
  1926. else
  1927. {
  1928. logger->warning("Game::loadControlProfile(): Unknown mouse wheel axis \"" + axisName + "\"\n");
  1929. continue;
  1930. }
  1931. // Map control
  1932. inputRouter->addMapping(MouseWheelMapping(control, mouse, axis));
  1933. }
  1934. else if (eventType == "button")
  1935. {
  1936. const std::string& buttonName = row[3];
  1937. // Get button from string
  1938. int button;
  1939. std::stringstream stream;
  1940. stream << buttonName;
  1941. stream >> button;
  1942. // Map control
  1943. inputRouter->addMapping(MouseButtonMapping(control, mouse, button));
  1944. }
  1945. else
  1946. {
  1947. logger->warning("Game::loadControlProfile(): Unknown mouse event type \"" + eventType + "\"\n");
  1948. continue;
  1949. }
  1950. }
  1951. else if (deviceType == "gamepad")
  1952. {
  1953. const std::string& eventType = row[2];
  1954. if (eventType == "axis")
  1955. {
  1956. std::string axisName = row[3];
  1957. // Determine whether axis is negative or positive
  1958. bool negative = (axisName.find('-') != std::string::npos);
  1959. // Remove sign from axis name
  1960. std::size_t plusPosition = axisName.find('+');
  1961. std::size_t minusPosition = axisName.find('-');
  1962. if (plusPosition != std::string::npos)
  1963. {
  1964. axisName.erase(plusPosition);
  1965. }
  1966. else if (minusPosition != std::string::npos)
  1967. {
  1968. axisName.erase(minusPosition);
  1969. }
  1970. // Get axis from string
  1971. int axis;
  1972. std::stringstream stream;
  1973. stream << axisName;
  1974. stream >> axis;
  1975. // Map control to each gamepad
  1976. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1977. for (Gamepad* gamepad: *gamepads)
  1978. {
  1979. inputRouter->addMapping(GamepadAxisMapping(control, gamepad, axis, negative));
  1980. }
  1981. }
  1982. else if (eventType == "button")
  1983. {
  1984. const std::string& buttonName = row[3];
  1985. // Get button from string
  1986. int button;
  1987. std::stringstream stream;
  1988. stream << buttonName;
  1989. stream >> button;
  1990. // Map control to each gamepad
  1991. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1992. for (Gamepad* gamepad: *gamepads)
  1993. {
  1994. inputRouter->addMapping(GamepadButtonMapping(control, gamepad, button));
  1995. }
  1996. }
  1997. else
  1998. {
  1999. logger->warning("Game::loadControlProfile(): Unknown gamepad event type \"" + eventType + "\"\n");
  2000. continue;
  2001. }
  2002. }
  2003. else
  2004. {
  2005. logger->warning("Game::loadControlProfile(): Unknown input device type \"" + deviceType + "\"\n");
  2006. continue;
  2007. }
  2008. }
  2009. }
  2010. void Game::saveControlProfile(const std::string& profileName)
  2011. {
  2012. // Build control profile string table
  2013. StringTable* table = new StringTable();
  2014. for (auto it = controlNameMap.begin(); it != controlNameMap.end(); ++it)
  2015. {
  2016. // Get control name
  2017. const std::string& controlName = it->first;
  2018. // Get pointer to the control
  2019. Control* control = it->second;
  2020. // Look up list of mappings for the control
  2021. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  2022. if (!mappings)
  2023. {
  2024. continue;
  2025. }
  2026. // For each input mapping
  2027. for (const InputMapping* mapping: *mappings)
  2028. {
  2029. // Add row to the table
  2030. table->push_back(StringTableRow());
  2031. StringTableRow* row = &table->back();
  2032. // Add control name column
  2033. row->push_back(controlName);
  2034. switch (mapping->getType())
  2035. {
  2036. case InputMappingType::KEY:
  2037. {
  2038. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  2039. row->push_back("keyboard");
  2040. row->push_back("key");
  2041. std::string scancodeName = std::string("\"") + std::string(Keyboard::getScancodeName(keyMapping->scancode)) + std::string("\"");
  2042. row->push_back(scancodeName);
  2043. break;
  2044. }
  2045. case InputMappingType::MOUSE_MOTION:
  2046. {
  2047. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  2048. row->push_back("mouse");
  2049. row->push_back("motion");
  2050. std::string axisName;
  2051. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  2052. {
  2053. axisName = "+x";
  2054. }
  2055. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  2056. {
  2057. axisName = "-x";
  2058. }
  2059. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  2060. {
  2061. axisName = "+y";
  2062. }
  2063. else
  2064. {
  2065. axisName = "-y";
  2066. }
  2067. row->push_back(axisName);
  2068. break;
  2069. }
  2070. case InputMappingType::MOUSE_WHEEL:
  2071. {
  2072. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  2073. row->push_back("mouse");
  2074. row->push_back("wheel");
  2075. std::string axisName;
  2076. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  2077. {
  2078. axisName = "+x";
  2079. }
  2080. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  2081. {
  2082. axisName = "-x";
  2083. }
  2084. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  2085. {
  2086. axisName = "+y";
  2087. }
  2088. else
  2089. {
  2090. axisName = "-y";
  2091. }
  2092. row->push_back(axisName);
  2093. break;
  2094. }
  2095. case InputMappingType::MOUSE_BUTTON:
  2096. {
  2097. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  2098. row->push_back("mouse");
  2099. row->push_back("button");
  2100. std::string buttonName;
  2101. std::stringstream stream;
  2102. stream << static_cast<int>(mouseButtonMapping->button);
  2103. stream >> buttonName;
  2104. row->push_back(buttonName);
  2105. break;
  2106. }
  2107. case InputMappingType::GAMEPAD_AXIS:
  2108. {
  2109. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  2110. row->push_back("gamepad");
  2111. row->push_back("axis");
  2112. std::stringstream stream;
  2113. if (gamepadAxisMapping->negative)
  2114. {
  2115. stream << "-";
  2116. }
  2117. else
  2118. {
  2119. stream << "+";
  2120. }
  2121. stream << gamepadAxisMapping->axis;
  2122. std::string axisName;
  2123. stream >> axisName;
  2124. row->push_back(axisName);
  2125. break;
  2126. }
  2127. case InputMappingType::GAMEPAD_BUTTON:
  2128. {
  2129. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  2130. row->push_back("gamepad");
  2131. row->push_back("button");
  2132. std::string buttonName;
  2133. std::stringstream stream;
  2134. stream << static_cast<int>(gamepadButtonMapping->button);
  2135. stream >> buttonName;
  2136. row->push_back(buttonName);
  2137. break;
  2138. }
  2139. default:
  2140. break;
  2141. }
  2142. }
  2143. }
  2144. // Form full path to control profile file
  2145. std::string controlProfilePath = controlsPath + profileName + ".csv";
  2146. // Save control profile
  2147. resourceManager->save<StringTable>(table, controlProfilePath);
  2148. // Free control profile string table
  2149. delete table;
  2150. }
  2151. std::array<std::string, 3> Game::getInputMappingStrings(const InputMapping* mapping)
  2152. {
  2153. std::string deviceString;
  2154. std::string typeString;
  2155. std::string eventString;
  2156. switch (mapping->getType())
  2157. {
  2158. case InputMappingType::KEY:
  2159. {
  2160. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  2161. deviceString = "keyboard";
  2162. typeString = "key";
  2163. eventString = std::string(Keyboard::getScancodeName(keyMapping->scancode));
  2164. break;
  2165. }
  2166. case InputMappingType::MOUSE_MOTION:
  2167. {
  2168. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  2169. deviceString = "mouse";
  2170. eventString = "motion";
  2171. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  2172. {
  2173. eventString = "+x";
  2174. }
  2175. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  2176. {
  2177. eventString = "-x";
  2178. }
  2179. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  2180. {
  2181. eventString = "+y";
  2182. }
  2183. else
  2184. {
  2185. eventString = "-y";
  2186. }
  2187. break;
  2188. }
  2189. case InputMappingType::MOUSE_WHEEL:
  2190. {
  2191. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  2192. deviceString = "mouse";
  2193. typeString = "wheel";
  2194. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  2195. {
  2196. eventString = "+x";
  2197. }
  2198. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  2199. {
  2200. eventString = "-x";
  2201. }
  2202. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  2203. {
  2204. eventString = "+y";
  2205. }
  2206. else
  2207. {
  2208. eventString = "-y";
  2209. }
  2210. break;
  2211. }
  2212. case InputMappingType::MOUSE_BUTTON:
  2213. {
  2214. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  2215. deviceString = "mouse";
  2216. typeString = "button";
  2217. std::stringstream stream;
  2218. stream << static_cast<int>(mouseButtonMapping->button);
  2219. stream >> eventString;
  2220. break;
  2221. }
  2222. case InputMappingType::GAMEPAD_AXIS:
  2223. {
  2224. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  2225. deviceString = "gamepad";
  2226. typeString = "axis";
  2227. std::stringstream stream;
  2228. if (gamepadAxisMapping->negative)
  2229. {
  2230. stream << "-";
  2231. }
  2232. else
  2233. {
  2234. stream << "+";
  2235. }
  2236. stream << gamepadAxisMapping->axis;
  2237. stream >> eventString;
  2238. break;
  2239. }
  2240. case InputMappingType::GAMEPAD_BUTTON:
  2241. {
  2242. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  2243. deviceString = "gamepad";
  2244. typeString = "button";
  2245. std::stringstream stream;
  2246. stream << static_cast<int>(gamepadButtonMapping->button);
  2247. stream >> eventString;
  2248. break;
  2249. }
  2250. default:
  2251. break;
  2252. }
  2253. return {deviceString, typeString, eventString};
  2254. }
  2255. void Game::remapControl(Control* control)
  2256. {
  2257. // Remove previously set input mappings for the control
  2258. inputRouter->removeMappings(control);
  2259. // Start mapping new input
  2260. inputMapper->setControl(control);
  2261. inputMapper->setEnabled(true);
  2262. // Restring UI to show control mappings have been removed.
  2263. restringUI();
  2264. // Disable UI callbacks
  2265. uiRootElement->setCallbacksEnabled(false);
  2266. // Disable menu control callbacks
  2267. menuControls.setCallbacksEnabled(false);
  2268. }
  2269. void Game::resetControls()
  2270. {
  2271. inputRouter->reset();
  2272. loadControlProfile("default-keyboard-controls");
  2273. saveControlProfile(controlProfileName);
  2274. restringUI();
  2275. }
  2276. void Game::resizeUI(int w, int h)
  2277. {
  2278. // Adjust root element dimensions
  2279. uiRootElement->setDimensions(Vector2(w, h));
  2280. uiRootElement->update();
  2281. splashBackgroundImage->setDimensions(Vector2(w, h));
  2282. splashBackgroundImage->setAnchor(Anchor::TOP_LEFT);
  2283. // Resize splash screen image
  2284. splashImage->setAnchor(Anchor::CENTER);
  2285. splashImage->setDimensions(Vector2(splashTexture->getWidth(), splashTexture->getHeight()));
  2286. // Adjust UI camera projection matrix
  2287. uiCamera.setOrthographic(0.0f, w, h, 0.0f, -1.0f, 1.0f);
  2288. uiCamera.resetTweens();
  2289. // Resize camera flash image
  2290. cameraFlashImage->setDimensions(Vector2(w, h));
  2291. cameraFlashImage->setAnchor(Anchor::CENTER);
  2292. // Resize blackout image
  2293. blackoutImage->setDimensions(Vector2(w, h));
  2294. blackoutImage->setAnchor(Anchor::CENTER);
  2295. // Resize language select background image
  2296. languageSelectBGImage->setDimensions(Vector2(w, h));
  2297. languageSelectBGImage->setAnchor(Anchor::CENTER);
  2298. // Resize HUD
  2299. float hudPadding = 20.0f;
  2300. hudContainer->setDimensions(Vector2(w - hudPadding * 2.0f, h - hudPadding * 2.0f));
  2301. hudContainer->setAnchor(Anchor::CENTER);
  2302. // Tool indicator
  2303. Rect toolIndicatorBounds = hudTextureAtlas.getBounds("tool-indicator");
  2304. toolIndicatorBGImage->setDimensions(Vector2(toolIndicatorBounds.getWidth(), toolIndicatorBounds.getHeight()));
  2305. toolIndicatorBGImage->setAnchor(Anchor::TOP_LEFT);
  2306. Rect toolIndicatorIconBounds = hudTextureAtlas.getBounds("tool-indicator-lens");
  2307. toolIndicatorIconImage->setDimensions(Vector2(toolIndicatorIconBounds.getWidth(), toolIndicatorIconBounds.getHeight()));
  2308. toolIndicatorIconImage->setAnchor(Anchor::CENTER);
  2309. // Buttons
  2310. Rect playButtonBounds = hudTextureAtlas.getBounds("button-play");
  2311. Rect fastForwardButtonBounds = hudTextureAtlas.getBounds("button-fast-forward-2x");
  2312. Rect pauseButtonBounds = hudTextureAtlas.getBounds("button-pause");
  2313. Rect buttonBackgroundBounds = hudTextureAtlas.getBounds("button-background");
  2314. Vector2 buttonBGDimensions = Vector2(buttonBackgroundBounds.getWidth(), buttonBackgroundBounds.getHeight());
  2315. float buttonMargin = 10.0f;
  2316. float buttonDepth = 15.0f;
  2317. float buttonContainerWidth = fastForwardButtonBounds.getWidth();
  2318. float buttonContainerHeight = fastForwardButtonBounds.getHeight();
  2319. buttonContainer->setDimensions(Vector2(buttonContainerWidth, buttonContainerHeight));
  2320. buttonContainer->setAnchor(Anchor::TOP_RIGHT);
  2321. playButtonImage->setDimensions(Vector2(playButtonBounds.getWidth(), playButtonBounds.getHeight()));
  2322. playButtonImage->setAnchor(Vector2(0.0f, 0.0f));
  2323. playButtonBGImage->setDimensions(buttonBGDimensions);
  2324. playButtonBGImage->setAnchor(Vector2(0.0f, 1.0f));
  2325. fastForwardButtonImage->setDimensions(Vector2(fastForwardButtonBounds.getWidth(), fastForwardButtonBounds.getHeight()));
  2326. fastForwardButtonImage->setAnchor(Vector2(0.5f, 5.0f));
  2327. fastForwardButtonBGImage->setDimensions(buttonBGDimensions);
  2328. fastForwardButtonBGImage->setAnchor(Vector2(0.5f, 0.5f));
  2329. pauseButtonImage->setDimensions(Vector2(pauseButtonBounds.getWidth(), pauseButtonBounds.getHeight()));
  2330. pauseButtonImage->setAnchor(Vector2(1.0f, 0.0f));
  2331. pauseButtonBGImage->setDimensions(buttonBGDimensions);
  2332. pauseButtonBGImage->setAnchor(Vector2(1.0f, 1.0f));
  2333. // Radial menu
  2334. Rect radialMenuBounds = hudTextureAtlas.getBounds("radial-menu");
  2335. radialMenuContainer->setDimensions(Vector2(w, h));
  2336. radialMenuContainer->setAnchor(Anchor::CENTER);
  2337. radialMenuContainer->setLayerOffset(30);
  2338. radialMenuBackgroundImage->setDimensions(Vector2(w, h));
  2339. radialMenuBackgroundImage->setAnchor(Anchor::CENTER);
  2340. radialMenuBackgroundImage->setLayerOffset(-1);
  2341. //radialMenuImage->setDimensions(Vector2(w * 0.5f, h * 0.5f));
  2342. radialMenuImage->setDimensions(Vector2(radialMenuBounds.getWidth(), radialMenuBounds.getHeight()));
  2343. radialMenuImage->setAnchor(Anchor::CENTER);
  2344. Rect radialMenuSelectorBounds = hudTextureAtlas.getBounds("radial-menu-selector");
  2345. radialMenuSelectorImage->setDimensions(Vector2(radialMenuSelectorBounds.getWidth(), radialMenuSelectorBounds.getHeight()));
  2346. radialMenuSelectorImage->setAnchor(Anchor::CENTER);
  2347. Rect toolIconBrushBounds = hudTextureAtlas.getBounds("tool-icon-brush");
  2348. toolIconBrushImage->setDimensions(Vector2(toolIconBrushBounds.getWidth(), toolIconBrushBounds.getHeight()));
  2349. toolIconBrushImage->setAnchor(Anchor::CENTER);
  2350. Rect toolIconLensBounds = hudTextureAtlas.getBounds("tool-icon-lens");
  2351. toolIconLensImage->setDimensions(Vector2(toolIconLensBounds.getWidth(), toolIconLensBounds.getHeight()));
  2352. toolIconLensImage->setAnchor(Anchor::CENTER);
  2353. Rect toolIconForcepsBounds = hudTextureAtlas.getBounds("tool-icon-forceps");
  2354. toolIconForcepsImage->setDimensions(Vector2(toolIconForcepsBounds.getWidth(), toolIconForcepsBounds.getHeight()));
  2355. toolIconForcepsImage->setAnchor(Anchor::CENTER);
  2356. Rect toolIconSpadeBounds = hudTextureAtlas.getBounds("tool-icon-spade");
  2357. toolIconSpadeImage->setDimensions(Vector2(toolIconSpadeBounds.getWidth(), toolIconSpadeBounds.getHeight()));
  2358. toolIconSpadeImage->setAnchor(Anchor::CENTER);
  2359. Rect toolIconCameraBounds = hudTextureAtlas.getBounds("tool-icon-camera");
  2360. toolIconCameraImage->setDimensions(Vector2(toolIconCameraBounds.getWidth(), toolIconCameraBounds.getHeight()));
  2361. toolIconCameraImage->setAnchor(Anchor::CENTER);
  2362. Rect toolIconMicrochipBounds = hudTextureAtlas.getBounds("tool-icon-microchip");
  2363. toolIconMicrochipImage->setDimensions(Vector2(toolIconMicrochipBounds.getWidth(), toolIconMicrochipBounds.getHeight()));
  2364. toolIconMicrochipImage->setAnchor(Anchor::CENTER);
  2365. Rect toolIconTestTubeBounds = hudTextureAtlas.getBounds("tool-icon-test-tube");
  2366. toolIconTestTubeImage->setDimensions(Vector2(toolIconTestTubeBounds.getWidth(), toolIconTestTubeBounds.getHeight()));
  2367. toolIconTestTubeImage->setAnchor(Anchor::CENTER);
  2368. Rect labelCornerBounds = hudTextureAtlas.getBounds("label-tl");
  2369. Vector2 labelCornerDimensions(labelCornerBounds.getWidth(), labelCornerBounds.getHeight());
  2370. Vector2 antLabelPadding(10.0f, 6.0f);
  2371. antLabelContainer->setDimensions(antLabel->getDimensions() + antLabelPadding * 2.0f);
  2372. antLabelContainer->setTranslation(Vector2(0.0f, (int)(-antPin->getDimensions().y * 0.125f)));
  2373. antLabelTL->setDimensions(labelCornerDimensions);
  2374. antLabelTR->setDimensions(labelCornerDimensions);
  2375. antLabelBL->setDimensions(labelCornerDimensions);
  2376. antLabelBR->setDimensions(labelCornerDimensions);
  2377. 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));
  2378. antLabelCT->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  2379. antLabelCB->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  2380. antLabelCL->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2381. antLabelCR->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2382. antLabelContainer->setAnchor(Vector2(0.5f, 0.5f));
  2383. antLabelTL->setAnchor(Anchor::TOP_LEFT);
  2384. antLabelTR->setAnchor(Anchor::TOP_RIGHT);
  2385. antLabelBL->setAnchor(Anchor::BOTTOM_LEFT);
  2386. antLabelBR->setAnchor(Anchor::BOTTOM_RIGHT);
  2387. antLabelCC->setAnchor(Anchor::CENTER);
  2388. antLabelCT->setAnchor(Vector2(0.5f, 0.0f));
  2389. antLabelCB->setAnchor(Vector2(0.5f, 1.0f));
  2390. antLabelCL->setAnchor(Vector2(0.0f, 0.5f));
  2391. antLabelCR->setAnchor(Vector2(1.0f, 0.5f));
  2392. antLabel->setAnchor(Anchor::CENTER);
  2393. Rect antPinBounds = hudTextureAtlas.getBounds("label-pin");
  2394. antPin->setDimensions(Vector2(antPinBounds.getWidth(), antPinBounds.getHeight()));
  2395. antPin->setAnchor(Vector2(0.5f, 1.0f));
  2396. Rect pinHoleBounds = hudTextureAtlas.getBounds("label-pin-hole");
  2397. antLabelPinHole->setDimensions(Vector2(pinHoleBounds.getWidth(), pinHoleBounds.getHeight()));
  2398. antLabelPinHole->setAnchor(Vector2(0.5f, 0.0f));
  2399. antLabelPinHole->setTranslation(Vector2(0.0f, -antLabelPinHole->getDimensions().y * 0.5f));
  2400. antLabelPinHole->setLayerOffset(2);
  2401. float pinDistance = 20.0f;
  2402. antTag->setAnchor(Anchor::CENTER);
  2403. antTag->setDimensions(Vector2(antLabelContainer->getDimensions().x, antPin->getDimensions().y));
  2404. float cameraGridLineWidth = 2.0f;
  2405. float cameraReticleDiameter = 6.0f;
  2406. cameraGridContainer->setDimensions(Vector2(w, h));
  2407. cameraGridY0Image->setDimensions(Vector2(w, cameraGridLineWidth));
  2408. cameraGridY1Image->setDimensions(Vector2(w, cameraGridLineWidth));
  2409. cameraGridX0Image->setDimensions(Vector2(cameraGridLineWidth, h));
  2410. cameraGridX1Image->setDimensions(Vector2(cameraGridLineWidth, h));
  2411. cameraReticleImage->setDimensions(Vector2(cameraReticleDiameter));
  2412. cameraGridY0Image->setTranslation(Vector2(0));
  2413. cameraGridY1Image->setTranslation(Vector2(0));
  2414. cameraGridX0Image->setTranslation(Vector2(0));
  2415. cameraGridX1Image->setTranslation(Vector2(0));
  2416. cameraReticleImage->setTranslation(Vector2(0));
  2417. Rect menuSelectorBounds = hudTextureAtlas.getBounds("menu-selector");
  2418. menuSelectorImage->setDimensions(Vector2(menuSelectorBounds.getWidth(), menuSelectorBounds.getHeight()));
  2419. UIImage* icons[] =
  2420. {
  2421. toolIconBrushImage,
  2422. nullptr,
  2423. toolIconLensImage,
  2424. nullptr,
  2425. toolIconForcepsImage,
  2426. toolIconMicrochipImage,
  2427. toolIconCameraImage,
  2428. nullptr
  2429. };
  2430. Rect radialMenuIconRingBounds = hudTextureAtlas.getBounds("radial-menu-icon-ring");
  2431. float iconOffset = radialMenuIconRingBounds.getWidth() * 0.5f;
  2432. float sectorAngle = (2.0f * 3.14159264f) / 8.0f;
  2433. for (int i = 0; i < 8; ++i)
  2434. {
  2435. float angle = sectorAngle * static_cast<float>(i - 4);
  2436. Vector2 translation = Vector2(std::cos(angle), std::sin(angle)) * iconOffset;
  2437. translation.x = (int)(translation.x + 0.5f);
  2438. translation.y = (int)(translation.y + 0.5f);
  2439. if (icons[i] != nullptr)
  2440. {
  2441. icons[i]->setTranslation(translation);
  2442. }
  2443. }
  2444. // Main menu size
  2445. float mainMenuWidth = 0.0f;
  2446. float mainMenuHeight = 0.0f;
  2447. float mainMenuSpacing = 0.5f * fontSizePX;
  2448. float mainMenuPadding = fontSizePX * 4.0f;
  2449. for (const MenuItem* item: *mainMenu->getItems())
  2450. {
  2451. mainMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2452. mainMenuHeight += mainMenuSpacing;
  2453. mainMenuWidth = std::max<float>(mainMenuWidth, item->getNameLabel()->getDimensions().x);
  2454. }
  2455. mainMenuHeight -= mainMenuSpacing;
  2456. mainMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2457. mainMenu->resize(mainMenuWidth, mainMenuHeight);
  2458. mainMenu->getContainer()->setTranslation(Vector2(-mainMenuPadding));
  2459. // Settings menu size
  2460. float settingsMenuWidth = 0.0f;
  2461. float settingsMenuHeight = 0.0f;
  2462. float settingsMenuSpacing = 0.5f * fontSizePX;
  2463. float settingsMenuPadding = fontSizePX * 4.0f;
  2464. float settingsMenuValueMargin = fontSizePX * 4.0f;
  2465. for (const MenuItem* item: *settingsMenu->getItems())
  2466. {
  2467. settingsMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2468. settingsMenuHeight += settingsMenuSpacing;
  2469. float itemWidth = item->getNameLabel()->getDimensions().x;
  2470. if (!item->getValueLabel()->getText().empty())
  2471. {
  2472. itemWidth += item->getValueLabel()->getDimensions().x + settingsMenuValueMargin;
  2473. }
  2474. settingsMenuWidth = std::max<float>(settingsMenuWidth, itemWidth);
  2475. }
  2476. settingsMenuHeight -= settingsMenuSpacing;
  2477. settingsMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2478. settingsMenu->resize(settingsMenuWidth, settingsMenuHeight);
  2479. settingsMenu->getContainer()->setTranslation(Vector2(-settingsMenuPadding));
  2480. // Controls menu size
  2481. float controlsMenuWidth = 0.0f;
  2482. float controlsMenuHeight = 0.0f;
  2483. float controlsMenuSpacing = 0.5f * fontSizePX;
  2484. float controlsMenuPadding = fontSizePX * 4.0f;
  2485. float controlsMenuValueMargin = fontSizePX * 4.0f;
  2486. for (const MenuItem* item: *controlsMenu->getItems())
  2487. {
  2488. controlsMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2489. controlsMenuHeight += controlsMenuSpacing;
  2490. float itemWidth = item->getNameLabel()->getDimensions().x;
  2491. if (!item->getValueLabel()->getText().empty())
  2492. {
  2493. itemWidth += item->getValueLabel()->getDimensions().x + controlsMenuValueMargin;
  2494. }
  2495. controlsMenuWidth = std::max<float>(controlsMenuWidth, itemWidth);
  2496. }
  2497. controlsMenuWidth += controlsMenuValueMargin;
  2498. controlsMenuHeight -= controlsMenuSpacing;
  2499. controlsMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2500. controlsMenu->resize(controlsMenuWidth, controlsMenuHeight);
  2501. controlsMenu->getContainer()->setTranslation(Vector2(-controlsMenuPadding));
  2502. // Pause menu size
  2503. float pauseMenuWidth = 0.0f;
  2504. float pauseMenuHeight = 0.0f;
  2505. float pauseMenuSpacing = 0.5f * fontSizePX;
  2506. float pauseMenuPadding = fontSizePX * 4.0f;
  2507. for (const MenuItem* item: *pauseMenu->getItems())
  2508. {
  2509. pauseMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2510. pauseMenuHeight += pauseMenuSpacing;
  2511. pauseMenuWidth = std::max<float>(pauseMenuWidth, item->getNameLabel()->getDimensions().x);
  2512. }
  2513. pauseMenuHeight -= pauseMenuSpacing;
  2514. pauseMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2515. pauseMenu->resize(pauseMenuWidth, pauseMenuHeight);
  2516. pauseMenu->getContainer()->setTranslation(Vector2(-pauseMenuPadding));
  2517. // Language menu size
  2518. float languageMenuWidth = 0.0f;
  2519. float languageMenuHeight = 0.0f;
  2520. float languageMenuSpacing = 0.75f * fontSizePX;
  2521. for (const MenuItem* item: *languageMenu->getItems())
  2522. {
  2523. Font* font = item->getNameLabel()->getFont();
  2524. if (font)
  2525. {
  2526. float lineHeight = font->getMetrics().getAscender() - font->getMetrics().getDescender();
  2527. languageMenuHeight += lineHeight + languageMenuSpacing;
  2528. languageMenuWidth = std::max<float>(languageMenuWidth, item->getNameLabel()->getDimensions().x);
  2529. }
  2530. item->getNameLabel()->setAnchor(Vector2(0.5f, 0.0f));
  2531. }
  2532. languageMenuHeight -= languageMenuSpacing;
  2533. languageMenu->getContainer()->setAnchor(Anchor::CENTER);
  2534. languageMenu->resize(languageMenuWidth, languageMenuHeight);
  2535. }
  2536. void Game::restringUI()
  2537. {
  2538. // Reset fonts
  2539. mainMenu->setFonts(menuFont);
  2540. settingsMenu->setFonts(menuFont);
  2541. controlsMenu->setFonts(menuFont);
  2542. pauseMenu->setFonts(menuFont);
  2543. // Get common strings
  2544. std::string offString = getString("off");
  2545. std::string onString = getString("on");
  2546. std::string backString = getString("back");
  2547. // Main menu strings
  2548. mainMenuContinueItem->setName(getString("continue"));
  2549. mainMenuNewGameItem->setName(getString("new-game"));
  2550. mainMenuColoniesItem->setName(getString("colonies"));
  2551. mainMenuSettingsItem->setName(getString("settings"));
  2552. mainMenuQuitItem->setName(getString("quit"));
  2553. // Settings menu strings
  2554. settingsMenuControlsItem->setName(getString("controls"));
  2555. settingsMenuControlsItem->setValue(getString("ellipsis"));
  2556. settingsMenuFullscreenItem->setName(getString("fullscreen"));
  2557. settingsMenuFullscreenItem->setValue((fullscreen) ? onString : offString);
  2558. settingsMenuVSyncItem->setName(getString("v-sync"));
  2559. settingsMenuVSyncItem->setValue((vsync) ? onString : offString);
  2560. settingsMenuLanguageItem->setName(getString("language"));
  2561. settingsMenuLanguageItem->setValue(getString("language-name"));
  2562. settingsMenuBackItem->setName(backString);
  2563. // Controls menu strings
  2564. restringControlMenuItem(controlsMenuMoveForwardItem, "move-forward");
  2565. restringControlMenuItem(controlsMenuMoveLeftItem, "move-left");
  2566. restringControlMenuItem(controlsMenuMoveBackItem, "move-back");
  2567. restringControlMenuItem(controlsMenuMoveRightItem, "move-right");
  2568. restringControlMenuItem(controlsMenuChangeToolItem, "change-tool");
  2569. restringControlMenuItem(controlsMenuUseToolItem, "use-tool");
  2570. restringControlMenuItem(controlsMenuAdjustCameraItem, "adjust-camera");
  2571. restringControlMenuItem(controlsMenuPauseItem, "pause");
  2572. restringControlMenuItem(controlsMenuToggleFullscreenItem, "toggle-fullscreen");
  2573. restringControlMenuItem(controlsMenuTakeScreenshotItem, "take-screenshot");
  2574. controlsMenuResetToDefaultItem->setName(getString("reset-to-default"));
  2575. controlsMenuBackItem->setName(backString);
  2576. // Pause menu strings
  2577. pauseMenuResumeItem->setName(getString("resume"));
  2578. pauseMenuSettingsItem->setName(getString("settings"));
  2579. pauseMenuMainMenuItem->setName(getString("main-menu"));
  2580. pauseMenuQuitItem->setName(getString("quit"));
  2581. // Language menu strings
  2582. for (std::size_t i = 0; i < languageCount; ++i)
  2583. {
  2584. languageMenuItems[i]->setName(getString("language-name", i));
  2585. }
  2586. // Reset menu tweens
  2587. uiRootElement->update();
  2588. mainMenu->getContainer()->resetTweens();
  2589. settingsMenu->getContainer()->resetTweens();
  2590. controlsMenu->getContainer()->resetTweens();
  2591. pauseMenu->getContainer()->resetTweens();
  2592. languageMenu->getContainer()->resetTweens();
  2593. }
  2594. void Game::restringControlMenuItem(MenuItem* item, const std::string& name)
  2595. {
  2596. item->setName(getString(name));
  2597. Control* control = controlNameMap.find(name)->second;
  2598. std::string value;
  2599. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  2600. if (mappings != nullptr)
  2601. {
  2602. std::size_t i = 0;
  2603. for (const InputMapping* mapping: *mappings)
  2604. {
  2605. std::array<std::string, 3> mappingStrings = getInputMappingStrings(mapping);
  2606. // keyboard-key, mouse-button, gamepad-axis, etc.
  2607. std::string typeName = mappingStrings[0] + "-" + mappingStrings[1];
  2608. std::string type = getString(typeName);
  2609. if (mapping->getType() != InputMappingType::KEY)
  2610. {
  2611. value += type;
  2612. value += " ";
  2613. }
  2614. value += mappingStrings[2];
  2615. if (i < mappings->size() - 1)
  2616. {
  2617. value += ", ";
  2618. }
  2619. ++i;
  2620. }
  2621. }
  2622. item->setValue(value);
  2623. }
  2624. void Game::setTimeOfDay(float time)
  2625. {
  2626. Vector3 midnight = Vector3(0.0f, 1.0f, 0.0f);
  2627. Vector3 sunrise = Vector3(-1.0f, 0.0f, 0.0f);
  2628. Vector3 noon = Vector3(0, -1.0f, 0.0f);
  2629. Vector3 sunset = Vector3(1.0f, 0.0f, 0.0f);
  2630. float angles[4] =
  2631. {
  2632. glm::radians(270.0f), // 00:00
  2633. glm::radians(0.0f), // 06:00
  2634. glm::radians(90.0f), // 12:00
  2635. glm::radians(180.0f) // 18:00
  2636. };
  2637. int index0 = static_cast<int>(fmod(time, 24.0f) / 6.0f);
  2638. int index1 = (index0 + 1) % 4;
  2639. float t = (time - (static_cast<float>(index0) * 6.0f)) / 6.0f;
  2640. Quaternion rotation0 = glm::angleAxis(angles[index0], Vector3(1, 0, 0));
  2641. Quaternion rotation1 = glm::angleAxis(angles[index1], Vector3(1, 0, 0));
  2642. Quaternion rotation = glm::normalize(glm::slerp(rotation0, rotation1, t));
  2643. Vector3 direction = glm::normalize(rotation * Vector3(0, 0, 1));
  2644. sunlight.setDirection(direction);
  2645. Vector3 up = glm::normalize(rotation * Vector3(0, 1, 0));
  2646. sunlightCamera.lookAt(Vector3(0, 0, 0), sunlight.getDirection(), up);
  2647. }
  2648. void Game::queueScreenshot()
  2649. {
  2650. screenshotQueued = true;
  2651. cameraFlashImage->setVisible(false);
  2652. cameraGridContainer->setVisible(false);
  2653. fpsLabel->setVisible(false);
  2654. soundSystem->scrot();
  2655. }
  2656. void Game::screenshot()
  2657. {
  2658. screenshotQueued = false;
  2659. // Read pixel data from framebuffer
  2660. unsigned char* pixels = new unsigned char[w * h * 3];
  2661. glReadBuffer(GL_BACK);
  2662. glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  2663. // Get game title in current language
  2664. std::string title = getString("title");
  2665. // Convert title to lowercase
  2666. std::transform(title.begin(), title.end(), title.begin(), ::tolower);
  2667. // Create screenshot directory if it doesn't exist
  2668. std::string screenshotDirectory = configPath + std::string("screenshots/");
  2669. if (!pathExists(screenshotDirectory))
  2670. {
  2671. createDirectory(screenshotDirectory);
  2672. }
  2673. // Build screenshot file name
  2674. std::string filename = screenshotDirectory + title + "-" + timestamp() + ".png";
  2675. // Write screenshot to file in separate thread
  2676. std::thread screenshotThread(Game::saveScreenshot, filename, w, h, pixels);
  2677. screenshotThread.detach();
  2678. // Play camera flash animation
  2679. cameraFlashAnimation.stop();
  2680. cameraFlashAnimation.rewind();
  2681. cameraFlashAnimation.play();
  2682. // Play camera shutter sound
  2683. // Restore camera UI visibility
  2684. //cameraGridContainer->setVisible(true);
  2685. fpsLabel->setVisible(true);
  2686. // Whiteout screen immediately
  2687. glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
  2688. glClear(GL_COLOR_BUFFER_BIT);
  2689. }
  2690. void Game::inputMapped(const InputMapping& mapping)
  2691. {
  2692. // Skip mouse motion events
  2693. if (mapping.getType() == InputMappingType::MOUSE_MOTION)
  2694. {
  2695. return;
  2696. }
  2697. // Add input mapping to input router
  2698. if (mapping.control != nullptr)
  2699. {
  2700. inputRouter->addMapping(mapping);
  2701. }
  2702. // Disable input mapping generation
  2703. inputMapper->setControl(nullptr);
  2704. inputMapper->setEnabled(false);
  2705. // Restring UI
  2706. restringUI();
  2707. // Schedule callbacks to be enabled in 100ms
  2708. ScheduledFunctionEvent event;
  2709. event.caller = static_cast<void*>(this);
  2710. event.function = [this]()
  2711. {
  2712. // Re-enable UI callbacks
  2713. uiRootElement->setCallbacksEnabled(true);
  2714. // Re-enable menu controls
  2715. menuControls.setCallbacksEnabled(true);
  2716. };
  2717. eventDispatcher.schedule(event, time + 0.1f);
  2718. // Save control profile
  2719. saveControlProfile(controlProfileName);
  2720. }
  2721. void Game::languageSelected()
  2722. {
  2723. // Disable non-system controls
  2724. disableNonSystemControls();
  2725. // Disable UI callbacks
  2726. uiRootElement->setCallbacksEnabled(false);
  2727. // Begin to fade out
  2728. fadeOut(0.5f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &titleState));
  2729. }
  2730. void Game::skipSplash()
  2731. {
  2732. if (StateMachine::getCurrentState() == &splashState)
  2733. {
  2734. StateMachine::changeState(&titleState);
  2735. }
  2736. }
  2737. void Game::togglePause()
  2738. {
  2739. paused = !paused;
  2740. if (paused)
  2741. {
  2742. openMenu(pauseMenu, 0);
  2743. // Enable menu controls and UI callbacks
  2744. uiRootElement->setCallbacksEnabled(true);
  2745. menuControls.setCallbacksEnabled(true);
  2746. }
  2747. else
  2748. {
  2749. closeCurrentMenu();
  2750. // Disable menu controls and UI callbacks
  2751. uiRootElement->setCallbacksEnabled(false);
  2752. menuControls.setCallbacksEnabled(false);
  2753. }
  2754. }
  2755. void Game::continueGame()
  2756. {
  2757. // Disable non-system controls
  2758. disableNonSystemControls();
  2759. // Disable UI callbacks
  2760. uiRootElement->setCallbacksEnabled(false);
  2761. // Start fading out main menu
  2762. menuFadeAnimation.setClip(&menuFadeOutClip);
  2763. menuFadeAnimation.setTimeFrame(menuFadeOutClip.getTimeFrame());
  2764. menuFadeAnimation.rewind();
  2765. menuFadeAnimation.play();
  2766. // Close menu and enter play state after it fades out
  2767. menuFadeAnimation.setEndCallback
  2768. (
  2769. [this]()
  2770. {
  2771. closeCurrentMenu();
  2772. StateMachine::changeState(&playState);
  2773. }
  2774. );
  2775. }
  2776. void Game::newGame()
  2777. {
  2778. // Disable non-system controls
  2779. disableNonSystemControls();
  2780. // Disable UI callbacks
  2781. uiRootElement->setCallbacksEnabled(false);
  2782. // Start fading out main menu
  2783. menuFadeAnimation.setClip(&menuFadeOutClip);
  2784. menuFadeAnimation.setTimeFrame(menuFadeOutClip.getTimeFrame());
  2785. menuFadeAnimation.rewind();
  2786. menuFadeAnimation.play();
  2787. // Close menu and enter play state after it fades out
  2788. menuFadeAnimation.setEndCallback
  2789. (
  2790. [this]()
  2791. {
  2792. closeCurrentMenu();
  2793. }
  2794. );
  2795. // Start to play state
  2796. fadeOut(3.0f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &playState));
  2797. }
  2798. void Game::returnToMainMenu()
  2799. {
  2800. // Disable non-system controls
  2801. disableNonSystemControls();
  2802. // Disable UI callbacks
  2803. uiRootElement->setCallbacksEnabled(false);
  2804. // Close pause menu
  2805. closeCurrentMenu();
  2806. // Fade to title state
  2807. fadeOut(3.0f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &titleState));
  2808. }
  2809. void Game::interpretCommands()
  2810. {
  2811. while (true)
  2812. {
  2813. std::cout << "> " << std::flush;
  2814. std::string line;
  2815. std::getline(std::cin, line);
  2816. try
  2817. {
  2818. auto [commandName, arguments, call] = cli->interpret(line);
  2819. if (call)
  2820. {
  2821. call();
  2822. }
  2823. else
  2824. {
  2825. if (!commandName.empty())
  2826. {
  2827. std::cout << "Unknown command " << commandName << std::endl;
  2828. }
  2829. }
  2830. }
  2831. catch (const std::invalid_argument& e)
  2832. {
  2833. std::string commandName = line.substr(0, line.find(' '));
  2834. auto& helpStrings = cli->help();
  2835. if (auto it = helpStrings.find(commandName); it != helpStrings.end())
  2836. {
  2837. std::cout << "Usage: " << it->second << std::endl;
  2838. }
  2839. else
  2840. {
  2841. std::cout << commandName << ": Invalid arguments" << std::endl;
  2842. }
  2843. }
  2844. }
  2845. }
  2846. void Game::boxSelect(float x, float y, float w, float h)
  2847. {
  2848. boxSelectionContainer->setTranslation(Vector2(x, y));
  2849. boxSelectionContainer->setDimensions(Vector2(w, h));
  2850. boxSelectionImageBackground->setDimensions(Vector2(w, h));
  2851. boxSelectionImageTop->setDimensions(Vector2(w, boxSelectionBorderWidth));
  2852. boxSelectionImageBottom->setDimensions(Vector2(w, boxSelectionBorderWidth));
  2853. boxSelectionImageLeft->setDimensions(Vector2(boxSelectionBorderWidth, h));
  2854. boxSelectionImageRight->setDimensions(Vector2(boxSelectionBorderWidth, h));
  2855. boxSelectionContainer->setVisible(true);
  2856. }
  2857. void Game::fadeIn(float duration, const Vector3& color, std::function<void()> callback)
  2858. {
  2859. if (fadeInAnimation.isPlaying())
  2860. {
  2861. return;
  2862. }
  2863. fadeOutAnimation.stop();
  2864. this->fadeInEndCallback = callback;
  2865. blackoutImage->setTintColor(Vector4(color, 1.0f));
  2866. blackoutImage->setVisible(true);
  2867. fadeInAnimation.setSpeed(1.0f / duration);
  2868. fadeInAnimation.setLoop(false);
  2869. fadeInAnimation.setClip(&fadeInClip);
  2870. fadeInAnimation.setTimeFrame(fadeInClip.getTimeFrame());
  2871. fadeInAnimation.rewind();
  2872. fadeInAnimation.play();
  2873. blackoutImage->resetTweens();
  2874. uiRootElement->update();
  2875. }
  2876. void Game::fadeOut(float duration, const Vector3& color, std::function<void()> callback)
  2877. {
  2878. if (fadeOutAnimation.isPlaying())
  2879. {
  2880. return;
  2881. }
  2882. fadeInAnimation.stop();
  2883. this->fadeOutEndCallback = callback;
  2884. blackoutImage->setVisible(true);
  2885. blackoutImage->setTintColor(Vector4(color, 0.0f));
  2886. fadeOutAnimation.setSpeed(1.0f / duration);
  2887. fadeOutAnimation.setLoop(false);
  2888. fadeOutAnimation.setClip(&fadeOutClip);
  2889. fadeOutAnimation.setTimeFrame(fadeOutClip.getTimeFrame());
  2890. fadeOutAnimation.rewind();
  2891. fadeOutAnimation.play();
  2892. blackoutImage->resetTweens();
  2893. uiRootElement->update();
  2894. }
  2895. void Game::stopFade()
  2896. {
  2897. fadeInAnimation.stop();
  2898. fadeOutAnimation.stop();
  2899. blackoutImage->setVisible(false);
  2900. uiRootElement->update();
  2901. }
  2902. void Game::selectTool(int toolIndex)
  2903. {
  2904. Tool* tools[] =
  2905. {
  2906. brush,
  2907. nullptr,
  2908. lens,
  2909. nullptr,
  2910. forceps,
  2911. nullptr,
  2912. nullptr,
  2913. nullptr
  2914. };
  2915. Tool* nextTool = tools[toolIndex];
  2916. if (nextTool != currentTool)
  2917. {
  2918. if (currentTool)
  2919. {
  2920. currentTool->setActive(false);
  2921. currentTool->update(0.0f);
  2922. }
  2923. currentTool = nextTool;
  2924. if (currentTool)
  2925. {
  2926. currentTool->setActive(true);
  2927. }
  2928. }
  2929. if (1)
  2930. {
  2931. toolIndicatorIconImage->setTextureBounds(toolIndicatorsBounds[toolIndex]);
  2932. toolIndicatorIconImage->setVisible(true);
  2933. }
  2934. else
  2935. {
  2936. toolIndicatorIconImage->setVisible(false);
  2937. }
  2938. }
  2939. EntityID Game::createInstance()
  2940. {
  2941. return entityManager->createEntity();
  2942. }
  2943. EntityID Game::createNamedInstance(const std::string& instanceName)
  2944. {
  2945. EntityID entity = entityManager->createEntity();
  2946. cli->set(instanceName, std::to_string(entity));
  2947. return entity;
  2948. }
  2949. EntityID Game::createInstanceOf(const std::string& templateName)
  2950. {
  2951. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  2952. EntityID entity = entityManager->createEntity();
  2953. entityTemplate->apply(entity, componentManager);
  2954. return entity;
  2955. }
  2956. EntityID Game::createNamedInstanceOf(const std::string& templateName, const std::string& instanceName)
  2957. {
  2958. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  2959. EntityID entity = entityManager->createEntity();
  2960. entityTemplate->apply(entity, componentManager);
  2961. cli->set(instanceName, std::to_string(entity));
  2962. return entity;
  2963. }
  2964. void Game::destroyInstance(EntityID entity)
  2965. {
  2966. entityManager->destroyEntity(entity);
  2967. }
  2968. void Game::addComponent(EntityID entity, ComponentBase* component)
  2969. {
  2970. componentManager->addComponent(entity, component);
  2971. }
  2972. void Game::removeComponent(EntityID entity, ComponentType type)
  2973. {
  2974. ComponentBase* component = componentManager->removeComponent(entity, type);
  2975. delete component;
  2976. }
  2977. void Game::setTranslation(EntityID entity, const Vector3& translation)
  2978. {
  2979. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2980. if (!component)
  2981. {
  2982. return;
  2983. }
  2984. component->transform.translation = translation;
  2985. }
  2986. void Game::setRotation(EntityID entity, const Quaternion& rotation)
  2987. {
  2988. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2989. if (!component)
  2990. {
  2991. return;
  2992. }
  2993. component->transform.rotation = rotation;
  2994. }
  2995. void Game::setScale(EntityID entity, const Vector3& scale)
  2996. {
  2997. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2998. if (!component)
  2999. {
  3000. return;
  3001. }
  3002. component->transform.scale = scale;
  3003. }
  3004. void Game::setTerrainPatchPosition(EntityID entity, const std::tuple<int, int>& position)
  3005. {
  3006. TerrainPatchComponent* component = componentManager->getComponent<TerrainPatchComponent>(entity);
  3007. if (!component)
  3008. {
  3009. return;
  3010. }
  3011. component->position = position;
  3012. }
  3013. void Game::saveScreenshot(const std::string& filename, unsigned int width, unsigned int height, unsigned char* pixels)
  3014. {
  3015. stbi_flip_vertically_on_write(1);
  3016. stbi_write_png(filename.c_str(), width, height, 3, pixels, width * 3);
  3017. delete[] pixels;
  3018. }