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

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