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

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