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

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