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

497 lines
14 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::id planet_eid = ctx->entity_registry->create();
  277. ctx->entities["planet"] = planet_eid;
  278. // Assign planetary celestial body component
  279. entity::component::celestial_body body;
  280. body.radius = 6.3781e6;
  281. body.axial_tilt = math::radians(23.4393);
  282. body.axial_rotation = math::radians(280.46061837504);
  283. body.angular_frequency = math::radians(360.9856122880876128);
  284. ctx->entity_registry->assign<entity::component::celestial_body>(planet_eid, body);
  285. // Assign planetary orbit component
  286. entity::component::orbit orbit;
  287. orbit.elements.a = 1.496e+11;
  288. orbit.elements.e = 0.01671123;
  289. orbit.elements.i = math::radians(-0.00001531);
  290. orbit.elements.raan = math::radians(0.0);
  291. const double longitude_periapsis = math::radians(102.93768193);
  292. orbit.elements.w = longitude_periapsis - orbit.elements.raan;
  293. orbit.elements.ta = math::radians(100.46457166) - longitude_periapsis;
  294. ctx->entity_registry->assign<entity::component::orbit>(planet_eid, orbit);
  295. // Assign planetary terrain component
  296. entity::component::terrain terrain;
  297. terrain.elevation = [](double, double) -> double
  298. {
  299. //return math::random<double>(0.0, 1.0);
  300. return 0.0;
  301. };
  302. terrain.max_lod = 0;
  303. terrain.patch_material = nullptr;
  304. ctx->entity_registry->assign<entity::component::terrain>(planet_eid, terrain);
  305. // Assign planetary atmosphere component
  306. entity::component::atmosphere atmosphere;
  307. atmosphere.exosphere_altitude = 65e3;
  308. atmosphere.index_of_refraction = 1.000293;
  309. atmosphere.rayleigh_density = 2.545e25;
  310. atmosphere.rayleigh_scale_height = 8000.0;
  311. atmosphere.mie_density = 14.8875;
  312. atmosphere.mie_scale_height = 1200.0;
  313. atmosphere.mie_anisotropy = 0.8;
  314. ctx->entity_registry->assign<entity::component::atmosphere>(planet_eid, atmosphere);
  315. // Assign planetary transform component
  316. entity::component::transform transform;
  317. transform.local = math::identity_transform<float>;
  318. transform.warp = true;
  319. ctx->entity_registry->assign<entity::component::transform>(planet_eid, transform);
  320. // Pass planet to astronomy system as reference body
  321. ctx->astronomy_system->set_reference_body(planet_eid);
  322. // Load sky model
  323. ctx->surface_sky_pass->set_sky_model(ctx->resource_manager->load<model>("sky-dome.mdl"));
  324. }
  325. void selenogenesis(game::context* ctx)
  326. {
  327. // Create lunar entity
  328. entity::id moon_eid = ctx->entity_registry->create();
  329. ctx->entities["moon"] = moon_eid;
  330. // Pass moon model to sky pass
  331. ctx->surface_sky_pass->set_moon_model(ctx->resource_manager->load<model>("moon.mdl"));
  332. }
  333. void extrasolar_heliogenesis(game::context* ctx)
  334. {
  335. // Load star catalog
  336. string_table* star_catalog = ctx->resource_manager->load<string_table>("stars.csv");
  337. // Allocate star catalog vertex data
  338. std::size_t star_count = 0;
  339. if (star_catalog->size() > 0)
  340. star_count = star_catalog->size() - 1;
  341. std::size_t star_vertex_size = 7;
  342. std::size_t star_vertex_stride = star_vertex_size * sizeof(float);
  343. float* star_vertex_data = new float[star_count * star_vertex_size];
  344. float* star_vertex = star_vertex_data;
  345. // Build star catalog vertex data
  346. for (std::size_t i = 1; i < star_catalog->size(); ++i)
  347. {
  348. const string_table_row& catalog_row = (*star_catalog)[i];
  349. double ra = 0.0;
  350. double dec = 0.0;
  351. double vmag = 0.0;
  352. double bv_color = 0.0;
  353. // Parse star catalog entry
  354. try
  355. {
  356. ra = std::stod(catalog_row[1]);
  357. dec = std::stod(catalog_row[2]);
  358. vmag = std::stod(catalog_row[3]);
  359. bv_color = std::stod(catalog_row[4]);
  360. }
  361. catch (const std::exception& e)
  362. {
  363. continue;
  364. }
  365. // Convert right ascension and declination from degrees to radians
  366. ra = math::wrap_radians(math::radians(ra));
  367. dec = math::wrap_radians(math::radians(dec));
  368. // Transform spherical equatorial coordinates to rectangular equatorial coordinates
  369. double3 position_bci = geom::spherical::to_cartesian(double3{1.0, dec, ra});
  370. // Transform coordinates from equatorial space to inertial space
  371. physics::frame<double> bci_to_inertial = physics::orbit::inertial::to_bci({0, 0, 0}, 0.0, math::radians(23.4393)).inverse();
  372. double3 position_inertial = bci_to_inertial * position_bci;
  373. // Convert color index to color temperature
  374. double cct = color::index::bv_to_cct(bv_color);
  375. // Calculate XYZ color from color temperature
  376. double3 color_xyz = color::cct::to_xyz(cct);
  377. // Transform XYZ color to ACEScg colorspace
  378. double3 color_acescg = color::xyz::to_acescg(color_xyz);
  379. // Convert apparent magnitude to irradiance (W/m^2)
  380. double vmag_irradiance = std::pow(10.0, 0.4 * (-vmag - 19.0 + 0.4));
  381. // Convert irradiance to illuminance
  382. double vmag_illuminance = vmag_irradiance * (683.0 * 0.14);
  383. // Scale color by illuminance
  384. double3 scaled_color = color_acescg * vmag_illuminance;
  385. // Build vertex
  386. *(star_vertex++) = static_cast<float>(position_inertial.x);
  387. *(star_vertex++) = static_cast<float>(position_inertial.y);
  388. *(star_vertex++) = static_cast<float>(position_inertial.z);
  389. *(star_vertex++) = static_cast<float>(scaled_color.x);
  390. *(star_vertex++) = static_cast<float>(scaled_color.y);
  391. *(star_vertex++) = static_cast<float>(scaled_color.z);
  392. *(star_vertex++) = static_cast<float>(vmag);
  393. }
  394. // Unload star catalog
  395. ctx->resource_manager->unload("stars.csv");
  396. // Allocate stars model
  397. model* stars_model = new model();
  398. // Resize model VBO and upload vertex data
  399. gl::vertex_buffer* vbo = stars_model->get_vertex_buffer();
  400. vbo->resize(star_count * star_vertex_stride, star_vertex_data);
  401. // Free star catalog vertex data
  402. delete[] star_vertex_data;
  403. // Bind vertex attributes to model VAO
  404. gl::vertex_array* vao = stars_model->get_vertex_array();
  405. std::size_t vao_offset = 0;
  406. vao->bind_attribute(VERTEX_POSITION_LOCATION, *vbo, 3, gl::vertex_attribute_type::float_32, star_vertex_stride, 0);
  407. vao_offset += 3;
  408. vao->bind_attribute(VERTEX_COLOR_LOCATION, *vbo, 4, gl::vertex_attribute_type::float_32, star_vertex_stride, sizeof(float) * vao_offset);
  409. // Load star material
  410. material* star_material = ctx->resource_manager->load<material>("fixed-star.mtl");
  411. // Create model group
  412. model_group* stars_model_group = stars_model->add_group("stars");
  413. stars_model_group->set_material(star_material);
  414. stars_model_group->set_drawing_mode(gl::drawing_mode::points);
  415. stars_model_group->set_start_index(0);
  416. stars_model_group->set_index_count(star_count);
  417. // Pass stars model to sky pass
  418. ctx->surface_sky_pass->set_stars_model(stars_model);
  419. }
  420. void colonigenesis(game::context* ctx)
  421. {}
  422. } // namespace loading
  423. } // namespace state
  424. } // namespace game