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

462 lines
13 KiB

  1. /*
  2. * Copyright (C) 2021 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/states/loading.hpp"
  20. #include "application.hpp"
  21. #include "astro/illuminance.hpp"
  22. #include "color/color.hpp"
  23. #include "entity/components/atmosphere.hpp"
  24. #include "entity/components/blackbody.hpp"
  25. #include "entity/components/celestial-body.hpp"
  26. #include "entity/components/orbit.hpp"
  27. #include "entity/components/terrain.hpp"
  28. #include "entity/components/transform.hpp"
  29. #include "entity/systems/astronomy.hpp"
  30. #include "entity/systems/orbit.hpp"
  31. #include "entity/commands.hpp"
  32. #include "entity/archetype.hpp"
  33. #include "game/states/nuptial-flight.hpp"
  34. #include "game/states/splash.hpp"
  35. #include "game/states/forage.hpp"
  36. #include "game/controls.hpp"
  37. #include "geom/spherical.hpp"
  38. #include "gl/drawing-mode.hpp"
  39. #include "gl/vertex-array.hpp"
  40. #include "gl/vertex-attribute-type.hpp"
  41. #include "gl/vertex-buffer.hpp"
  42. #include "physics/light/photometry.hpp"
  43. #include "physics/orbit/orbit.hpp"
  44. #include "renderer/material.hpp"
  45. #include "renderer/model.hpp"
  46. #include "renderer/passes/shadow-map-pass.hpp"
  47. #include "renderer/vertex-attributes.hpp"
  48. #include "resources/resource-manager.hpp"
  49. #include "scene/ambient-light.hpp"
  50. #include "scene/directional-light.hpp"
  51. #include "utility/timestamp.hpp"
  52. namespace game {
  53. namespace state {
  54. namespace loading {
  55. /// Loads control profile and calibrates gamepads
  56. static void load_controls(game::context* ctx);
  57. /// Creates the universe and solar system.
  58. static void cosmogenesis(game::context* ctx);
  59. /// Creates a sun.
  60. static void heliogenesis(game::context* ctx);
  61. /// Creates a planet.
  62. static void planetogenesis(game::context* ctx);
  63. /// Creates a moon.
  64. static void selenogenesis(game::context* ctx);
  65. /// Creates fixed stars.
  66. static void extrasolar_heliogenesis(game::context* ctx);
  67. /// Creates an ant colony
  68. static void colonigenesis(game::context* ctx);
  69. void enter(game::context* ctx)
  70. {
  71. // Load controls
  72. ctx->logger->push_task("Loading controls");
  73. try
  74. {
  75. load_controls(ctx);
  76. }
  77. catch (...)
  78. {
  79. ctx->logger->pop_task(EXIT_FAILURE);
  80. }
  81. ctx->logger->pop_task(EXIT_SUCCESS);
  82. // Create universe
  83. ctx->logger->push_task("Creating the universe");
  84. try
  85. {
  86. cosmogenesis(ctx);
  87. }
  88. catch (...)
  89. {
  90. ctx->logger->pop_task(EXIT_FAILURE);
  91. throw;
  92. }
  93. ctx->logger->pop_task(EXIT_SUCCESS);
  94. // Determine next game state
  95. application::state next_state;
  96. if (ctx->option_quick_start.has_value())
  97. {
  98. next_state.name = "forage";
  99. next_state.enter = std::bind(game::state::forage::enter, ctx);
  100. next_state.exit = std::bind(game::state::forage::exit, ctx);
  101. }
  102. else
  103. {
  104. next_state.name = "splash";
  105. next_state.enter = std::bind(game::state::splash::enter, ctx);
  106. next_state.exit = std::bind(game::state::splash::exit, ctx);
  107. }
  108. // Queue next game state
  109. ctx->app->queue_state(next_state);
  110. }
  111. void exit(game::context* ctx)
  112. {}
  113. void load_controls(game::context* ctx)
  114. {
  115. // If a control profile is set in the config file
  116. if (ctx->config->contains("control_profile"))
  117. {
  118. // Load control profile
  119. json* profile = ctx->resource_manager->load<json>((*ctx->config)["control_profile"].get<std::string>());
  120. // Apply control profile
  121. if (profile)
  122. {
  123. game::apply_control_profile(ctx, *profile);
  124. }
  125. }
  126. // Calibrate gamepads
  127. for (input::gamepad* gamepad: ctx->app->get_gamepads())
  128. {
  129. ctx->logger->push_task("Loading calibration for gamepad " + gamepad->get_guid());
  130. json* calibration = game::load_gamepad_calibration(ctx, gamepad);
  131. if (!calibration)
  132. {
  133. ctx->logger->pop_task(EXIT_FAILURE);
  134. ctx->logger->push_task("Generating default calibration for gamepad " + gamepad->get_guid());
  135. json default_calibration = game::default_gamepad_calibration();
  136. apply_gamepad_calibration(gamepad, default_calibration);
  137. if (!save_gamepad_calibration(ctx, gamepad, default_calibration))
  138. ctx->logger->pop_task(EXIT_FAILURE);
  139. else
  140. ctx->logger->pop_task(EXIT_SUCCESS);
  141. }
  142. else
  143. {
  144. ctx->logger->pop_task(EXIT_SUCCESS);
  145. apply_gamepad_calibration(gamepad, *calibration);
  146. }
  147. }
  148. // Toggle fullscreen
  149. ctx->controls["toggle_fullscreen"]->set_activated_callback
  150. (
  151. [ctx]()
  152. {
  153. bool fullscreen = !ctx->app->is_fullscreen();
  154. ctx->app->set_fullscreen(fullscreen);
  155. if (!fullscreen)
  156. {
  157. int2 resolution;
  158. resolution.x = (*ctx->config)["windowed_resolution"][0].get<int>();
  159. resolution.y = (*ctx->config)["windowed_resolution"][1].get<int>();
  160. ctx->app->resize_window(resolution.x, resolution.y);
  161. }
  162. (*ctx->config)["fullscreen"] = fullscreen;
  163. }
  164. );
  165. // Screenshot
  166. ctx->controls["screenshot"]->set_activated_callback
  167. (
  168. [ctx]()
  169. {
  170. std::string path = ctx->screenshots_path + "antkeeper-" + timestamp() + ".png";
  171. ctx->app->save_frame(path);
  172. }
  173. );
  174. // Menu back
  175. ctx->controls["menu_back"]->set_activated_callback
  176. (
  177. std::bind(&application::close, ctx->app, 0)
  178. );
  179. // Set activation threshold for menu navigation controls to mitigate drifting gamepad axes
  180. const float menu_activation_threshold = 0.1f;
  181. ctx->controls["menu_up"]->set_activation_threshold(menu_activation_threshold);
  182. ctx->controls["menu_down"]->set_activation_threshold(menu_activation_threshold);
  183. ctx->controls["menu_left"]->set_activation_threshold(menu_activation_threshold);
  184. ctx->controls["menu_right"]->set_activation_threshold(menu_activation_threshold);
  185. }
  186. void cosmogenesis(game::context* ctx)
  187. {
  188. // Init time
  189. const double time = 0.0;
  190. ctx->astronomy_system->set_universal_time(time);
  191. ctx->orbit_system->set_universal_time(time);
  192. // Create sun
  193. ctx->logger->push_task("Creating the sun");
  194. try
  195. {
  196. heliogenesis(ctx);
  197. }
  198. catch (...)
  199. {
  200. ctx->logger->pop_task(EXIT_FAILURE);
  201. throw;
  202. }
  203. ctx->logger->pop_task(EXIT_SUCCESS);
  204. // Create planet
  205. ctx->logger->push_task("Creating the planet");
  206. try
  207. {
  208. planetogenesis(ctx);
  209. }
  210. catch (...)
  211. {
  212. ctx->logger->pop_task(EXIT_FAILURE);
  213. throw;
  214. }
  215. ctx->logger->pop_task(EXIT_SUCCESS);
  216. // Create moon
  217. ctx->logger->push_task("Creating the moon");
  218. try
  219. {
  220. selenogenesis(ctx);
  221. }
  222. catch (...)
  223. {
  224. ctx->logger->pop_task(EXIT_FAILURE);
  225. throw;
  226. }
  227. ctx->logger->pop_task(EXIT_SUCCESS);
  228. // Create fixed stars
  229. ctx->logger->push_task("Creating fixed stars");
  230. try
  231. {
  232. extrasolar_heliogenesis(ctx);
  233. }
  234. catch (...)
  235. {
  236. ctx->logger->pop_task(EXIT_FAILURE);
  237. throw;
  238. }
  239. ctx->logger->pop_task(EXIT_SUCCESS);
  240. // Create ant colony
  241. ctx->logger->push_task("Creating ant colony");
  242. try
  243. {
  244. colonigenesis(ctx);
  245. }
  246. catch (...)
  247. {
  248. ctx->logger->pop_task(EXIT_FAILURE);
  249. throw;
  250. }
  251. ctx->logger->pop_task(EXIT_SUCCESS);
  252. }
  253. void heliogenesis(game::context* ctx)
  254. {
  255. // Create solar entity
  256. entity::archetype* sun_archetype = ctx->resource_manager->load<entity::archetype>("sun.ent");
  257. entity::id sun_eid = sun_archetype->create(*ctx->entity_registry);
  258. ctx->entities["sun"] = sun_eid;
  259. // Create direct sun light scene object
  260. scene::directional_light* sun_direct = new scene::directional_light();
  261. // Create ambient sun light scene object
  262. scene::ambient_light* sun_ambient = new scene::ambient_light();
  263. sun_ambient->set_color({1, 1, 1});
  264. sun_ambient->set_intensity(0.0f);
  265. sun_ambient->update_tweens();
  266. // Add sun light scene objects to surface scene
  267. ctx->surface_scene->add_object(sun_direct);
  268. ctx->surface_scene->add_object(sun_ambient);
  269. // Pass direct sun light scene object to shadow map pass and astronomy system
  270. ctx->surface_shadow_map_pass->set_light(sun_direct);
  271. ctx->astronomy_system->set_sun_light(sun_direct);
  272. }
  273. void planetogenesis(game::context* ctx)
  274. {
  275. // Create planetary entity
  276. entity::archetype* planet_archetype = ctx->resource_manager->load<entity::archetype>("planet.ent");
  277. entity::id planet_eid = planet_archetype->create(*ctx->entity_registry);
  278. ctx->entities["planet"] = planet_eid;
  279. // Assign planetary terrain component
  280. entity::component::terrain terrain;
  281. terrain.elevation = [](double, double) -> double
  282. {
  283. //return math::random<double>(0.0, 1.0);
  284. return 0.0;
  285. };
  286. terrain.max_lod = 0;
  287. terrain.patch_material = nullptr;
  288. ctx->entity_registry->assign<entity::component::terrain>(planet_eid, terrain);
  289. // Pass planet to astronomy system as reference body
  290. ctx->astronomy_system->set_reference_body(planet_eid);
  291. // Load sky model
  292. ctx->surface_sky_pass->set_sky_model(ctx->resource_manager->load<model>("sky-dome.mdl"));
  293. }
  294. void selenogenesis(game::context* ctx)
  295. {
  296. // Create lunar entity
  297. entity::id moon_eid = ctx->entity_registry->create();
  298. ctx->entities["moon"] = moon_eid;
  299. // Pass moon model to sky pass
  300. ctx->surface_sky_pass->set_moon_model(ctx->resource_manager->load<model>("moon.mdl"));
  301. }
  302. void extrasolar_heliogenesis(game::context* ctx)
  303. {
  304. // Load star catalog
  305. string_table* star_catalog = ctx->resource_manager->load<string_table>("stars.csv");
  306. // Allocate star catalog vertex data
  307. std::size_t star_count = 0;
  308. if (star_catalog->size() > 0)
  309. star_count = star_catalog->size() - 1;
  310. std::size_t star_vertex_size = 7;
  311. std::size_t star_vertex_stride = star_vertex_size * sizeof(float);
  312. float* star_vertex_data = new float[star_count * star_vertex_size];
  313. float* star_vertex = star_vertex_data;
  314. // Build star catalog vertex data
  315. for (std::size_t i = 1; i < star_catalog->size(); ++i)
  316. {
  317. const string_table_row& catalog_row = (*star_catalog)[i];
  318. double ra = 0.0;
  319. double dec = 0.0;
  320. double vmag = 0.0;
  321. double bv_color = 0.0;
  322. // Parse star catalog entry
  323. try
  324. {
  325. ra = std::stod(catalog_row[1]);
  326. dec = std::stod(catalog_row[2]);
  327. vmag = std::stod(catalog_row[3]);
  328. bv_color = std::stod(catalog_row[4]);
  329. }
  330. catch (const std::exception& e)
  331. {
  332. continue;
  333. }
  334. // Convert right ascension and declination from degrees to radians
  335. ra = math::wrap_radians(math::radians(ra));
  336. dec = math::wrap_radians(math::radians(dec));
  337. // Transform spherical equatorial coordinates to rectangular equatorial coordinates
  338. double3 position_bci = geom::spherical::to_cartesian(double3{1.0, dec, ra});
  339. // Transform coordinates from equatorial space to inertial space
  340. physics::frame<double> bci_to_inertial = physics::orbit::inertial::to_bci({0, 0, 0}, 0.0, math::radians(23.4393)).inverse();
  341. double3 position_inertial = bci_to_inertial * position_bci;
  342. // Convert color index to color temperature
  343. double cct = color::index::bv_to_cct(bv_color);
  344. // Calculate XYZ color from color temperature
  345. double3 color_xyz = color::cct::to_xyz(cct);
  346. // Transform XYZ color to ACEScg colorspace
  347. double3 color_acescg = color::xyz::to_acescg(color_xyz);
  348. // Convert apparent magnitude to irradiance (W/m^2)
  349. double vmag_irradiance = std::pow(10.0, 0.4 * (-vmag - 19.0 + 0.4));
  350. // Convert irradiance to illuminance
  351. double vmag_illuminance = vmag_irradiance * (683.0 * 0.14);
  352. // Scale color by illuminance
  353. double3 scaled_color = color_acescg * vmag_illuminance;
  354. // Build vertex
  355. *(star_vertex++) = static_cast<float>(position_inertial.x);
  356. *(star_vertex++) = static_cast<float>(position_inertial.y);
  357. *(star_vertex++) = static_cast<float>(position_inertial.z);
  358. *(star_vertex++) = static_cast<float>(scaled_color.x);
  359. *(star_vertex++) = static_cast<float>(scaled_color.y);
  360. *(star_vertex++) = static_cast<float>(scaled_color.z);
  361. *(star_vertex++) = static_cast<float>(vmag);
  362. }
  363. // Unload star catalog
  364. ctx->resource_manager->unload("stars.csv");
  365. // Allocate stars model
  366. model* stars_model = new model();
  367. // Resize model VBO and upload vertex data
  368. gl::vertex_buffer* vbo = stars_model->get_vertex_buffer();
  369. vbo->resize(star_count * star_vertex_stride, star_vertex_data);
  370. // Free star catalog vertex data
  371. delete[] star_vertex_data;
  372. // Bind vertex attributes to model VAO
  373. gl::vertex_array* vao = stars_model->get_vertex_array();
  374. std::size_t vao_offset = 0;
  375. vao->bind_attribute(VERTEX_POSITION_LOCATION, *vbo, 3, gl::vertex_attribute_type::float_32, star_vertex_stride, 0);
  376. vao_offset += 3;
  377. vao->bind_attribute(VERTEX_COLOR_LOCATION, *vbo, 4, gl::vertex_attribute_type::float_32, star_vertex_stride, sizeof(float) * vao_offset);
  378. // Load star material
  379. material* star_material = ctx->resource_manager->load<material>("fixed-star.mtl");
  380. // Create model group
  381. model_group* stars_model_group = stars_model->add_group("stars");
  382. stars_model_group->set_material(star_material);
  383. stars_model_group->set_drawing_mode(gl::drawing_mode::points);
  384. stars_model_group->set_start_index(0);
  385. stars_model_group->set_index_count(star_count);
  386. // Pass stars model to sky pass
  387. ctx->surface_sky_pass->set_stars_model(stars_model);
  388. }
  389. void colonigenesis(game::context* ctx)
  390. {}
  391. } // namespace loading
  392. } // namespace state
  393. } // namespace game