sky.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. /*
  2. * Copyright 2017 Stanislav Pidhorskyi. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. /*
  6. * This example demonstrates:
  7. * - Usage of Perez sky model [1] to render a dynamic sky.
  8. * - Rendering a mesh with a lightmap, shading of which is driven by the same parameters as the sky.
  9. *
  10. * Typically, the sky is rendered using cubemaps or other environment maps.
  11. * This approach can provide a high-quality sky, but the downside is that the
  12. * image is static. To achieve daytime changes in sky appearance, there is a need
  13. * in a dynamic model.
  14. *
  15. * Perez "An All-Weather Model for Sky Luminance Distribution" is a simple,
  16. * but good enough model which is, in essence, a function that
  17. * interpolates a sky color. As input, it requires several turbidity
  18. * coefficients, a color at zenith and direction to the sun.
  19. * Turbidity coefficients are taken from [2], which are computed using more
  20. * complex physically based models. Color at zenith depends on daytime and can
  21. * vary depending on many factors.
  22. *
  23. * In the code below, there are two tables that contain sky and sun luminance
  24. * which were computed using code from [3]. Luminance in those tables
  25. * represents actual scale of light energy that comes from sun compared to
  26. * the sky.
  27. *
  28. * The sky is driven by luminance of the sky, while the material of the
  29. * landscape is driven by both, the luminance of the sky and the sun. The
  30. * lightening model is very simple and consists of two parts: directional
  31. * light and hemisphere light. The first is used for the sun while the second
  32. * is used for the sky. Additionally, the second part is modulated by a
  33. * lightmap to achieve ambient occlusion effect.
  34. *
  35. * References
  36. * ==========
  37. *
  38. * [1] R. Perez, R. Seals, and J. Michalsky."An All-Weather Model for Sky Luminance Distribution".
  39. * Solar Energy, Volume 50, Number 3 (March 1993), pp. 235–245.
  40. *
  41. * [2] A. J. Preetham, Peter Shirley, and Brian Smits. "A Practical Analytic Model for Daylight",
  42. * Proceedings of the 26th Annual Conference on Computer Graphics and Interactive Techniques,
  43. * 1999, pp. 91–100.
  44. * https://www.cs.utah.edu/~shirley/papers/sunsky/sunsky.pdf
  45. *
  46. * [3] E. Lengyel, Game Engine Gems, Volume One. Jones & Bartlett Learning, 2010. pp. 219 - 234
  47. *
  48. */
  49. #include "common.h"
  50. #include "bgfx_utils.h"
  51. #include "imgui/imgui.h"
  52. #include "camera.h"
  53. #include "bounds.h"
  54. #include <map>
  55. namespace
  56. {
  57. // Represents color. Color-space depends on context.
  58. // In the code below, used to represent color in XYZ, and RGB color-space
  59. typedef bx::Vec3 Color;
  60. // HDTV rec. 709 matrix.
  61. static float M_XYZ2RGB[] =
  62. {
  63. 3.240479f, -0.969256f, 0.055648f,
  64. -1.53715f, 1.875991f, -0.204043f,
  65. -0.49853f, 0.041556f, 1.057311f,
  66. };
  67. // Converts color repesentation from CIE XYZ to RGB color-space.
  68. Color xyzToRgb(const Color& xyz)
  69. {
  70. Color rgb;
  71. rgb.x = M_XYZ2RGB[0] * xyz.x + M_XYZ2RGB[3] * xyz.y + M_XYZ2RGB[6] * xyz.z;
  72. rgb.y = M_XYZ2RGB[1] * xyz.x + M_XYZ2RGB[4] * xyz.y + M_XYZ2RGB[7] * xyz.z;
  73. rgb.z = M_XYZ2RGB[2] * xyz.x + M_XYZ2RGB[5] * xyz.y + M_XYZ2RGB[8] * xyz.z;
  74. return rgb;
  75. };
  76. // Precomputed luminance of sunlight in XYZ colorspace.
  77. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model.
  78. // This table is used for piecewise linear interpolation. Transitions from and to 0.0 at sunset and sunrise are highly inaccurate
  79. static std::map<float, Color> sunLuminanceXYZTable = {
  80. { 5.0f, { 0.000000f, 0.000000f, 0.000000f } },
  81. { 7.0f, { 12.703322f, 12.989393f, 9.100411f } },
  82. { 8.0f, { 13.202644f, 13.597814f, 11.524929f } },
  83. { 9.0f, { 13.192974f, 13.597458f, 12.264488f } },
  84. { 10.0f, { 13.132943f, 13.535914f, 12.560032f } },
  85. { 11.0f, { 13.088722f, 13.489535f, 12.692996f } },
  86. { 12.0f, { 13.067827f, 13.467483f, 12.745179f } },
  87. { 13.0f, { 13.069653f, 13.469413f, 12.740822f } },
  88. { 14.0f, { 13.094319f, 13.495428f, 12.678066f } },
  89. { 15.0f, { 13.142133f, 13.545483f, 12.526785f } },
  90. { 16.0f, { 13.201734f, 13.606017f, 12.188001f } },
  91. { 17.0f, { 13.182774f, 13.572725f, 11.311157f } },
  92. { 18.0f, { 12.448635f, 12.672520f, 8.267771f } },
  93. { 20.0f, { 0.000000f, 0.000000f, 0.000000f } },
  94. };
  95. // Precomputed luminance of sky in the zenith point in XYZ colorspace.
  96. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model.
  97. // This table is used for piecewise linear interpolation. Day/night transitions are highly inaccurate.
  98. // The scale of luminance change in Day/night transitions is not preserved.
  99. // Luminance at night was increased to eliminate need the of HDR render.
  100. static std::map<float, Color> skyLuminanceXYZTable = {
  101. { 0.0f, { 0.308f, 0.308f, 0.411f } },
  102. { 1.0f, { 0.308f, 0.308f, 0.410f } },
  103. { 2.0f, { 0.301f, 0.301f, 0.402f } },
  104. { 3.0f, { 0.287f, 0.287f, 0.382f } },
  105. { 4.0f, { 0.258f, 0.258f, 0.344f } },
  106. { 5.0f, { 0.258f, 0.258f, 0.344f } },
  107. { 7.0f, { 0.962851f, 1.000000f, 1.747835f } },
  108. { 8.0f, { 0.967787f, 1.000000f, 1.776762f } },
  109. { 9.0f, { 0.970173f, 1.000000f, 1.788413f } },
  110. { 10.0f, { 0.971431f, 1.000000f, 1.794102f } },
  111. { 11.0f, { 0.972099f, 1.000000f, 1.797096f } },
  112. { 12.0f, { 0.972385f, 1.000000f, 1.798389f } },
  113. { 13.0f, { 0.972361f, 1.000000f, 1.798278f } },
  114. { 14.0f, { 0.972020f, 1.000000f, 1.796740f } },
  115. { 15.0f, { 0.971275f, 1.000000f, 1.793407f } },
  116. { 16.0f, { 0.969885f, 1.000000f, 1.787078f } },
  117. { 17.0f, { 0.967216f, 1.000000f, 1.773758f } },
  118. { 18.0f, { 0.961668f, 1.000000f, 1.739891f } },
  119. { 20.0f, { 0.264f, 0.264f, 0.352f } },
  120. { 21.0f, { 0.264f, 0.264f, 0.352f } },
  121. { 22.0f, { 0.290f, 0.290f, 0.386f } },
  122. { 23.0f, { 0.303f, 0.303f, 0.404f } },
  123. };
  124. // Turbidity tables. Taken from:
  125. // A. J. Preetham, P. Shirley, and B. Smits. A Practical Analytic Model for Daylight. SIGGRAPH ’99
  126. // Coefficients correspond to xyY colorspace.
  127. static Color ABCDE[] =
  128. {
  129. { -0.2592f, -0.2608f, -1.4630f },
  130. { 0.0008f, 0.0092f, 0.4275f },
  131. { 0.2125f, 0.2102f, 5.3251f },
  132. { -0.8989f, -1.6537f, -2.5771f },
  133. { 0.0452f, 0.0529f, 0.3703f },
  134. };
  135. static Color ABCDE_t[] =
  136. {
  137. { -0.0193f, -0.0167f, 0.1787f },
  138. { -0.0665f, -0.0950f, -0.3554f },
  139. { -0.0004f, -0.0079f, -0.0227f },
  140. { -0.0641f, -0.0441f, 0.1206f },
  141. { -0.0033f, -0.0109f, -0.0670f },
  142. };
  143. // Performs piecewise linear interpolation of a Color parameter.
  144. class DynamicValueController
  145. {
  146. typedef Color ValueType;
  147. typedef std::map<float, ValueType> KeyMap;
  148. public:
  149. DynamicValueController()
  150. {
  151. }
  152. ~DynamicValueController()
  153. {
  154. }
  155. void SetMap(const KeyMap& keymap)
  156. {
  157. m_keyMap = keymap;
  158. }
  159. ValueType GetValue(float time) const
  160. {
  161. typename KeyMap::const_iterator itUpper = m_keyMap.upper_bound(time + 1e-6f);
  162. typename KeyMap::const_iterator itLower = itUpper;
  163. --itLower;
  164. if (itLower == m_keyMap.end())
  165. {
  166. return itUpper->second;
  167. }
  168. if (itUpper == m_keyMap.end())
  169. {
  170. return itLower->second;
  171. }
  172. float lowerTime = itLower->first;
  173. const ValueType& lowerVal = itLower->second;
  174. float upperTime = itUpper->first;
  175. const ValueType& upperVal = itUpper->second;
  176. if (lowerTime == upperTime)
  177. {
  178. return lowerVal;
  179. }
  180. return interpolate(lowerTime, lowerVal, upperTime, upperVal, time);
  181. };
  182. void Clear()
  183. {
  184. m_keyMap.clear();
  185. };
  186. private:
  187. ValueType interpolate(float lowerTime, const ValueType& lowerVal, float upperTime, const ValueType& upperVal, float time) const
  188. {
  189. const float tt = (time - lowerTime) / (upperTime - lowerTime);
  190. const ValueType result = bx::lerp(lowerVal, upperVal, tt);
  191. return result;
  192. };
  193. KeyMap m_keyMap;
  194. };
  195. // Controls sun position according to time, month, and observer's latitude.
  196. // Sun position computation based on Earth's orbital elements: https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
  197. class SunController
  198. {
  199. public:
  200. enum Month : int
  201. {
  202. January = 0,
  203. February,
  204. March,
  205. April,
  206. May,
  207. June,
  208. July,
  209. August,
  210. September,
  211. October,
  212. November,
  213. December
  214. };
  215. SunController()
  216. : m_latitude(50.0f)
  217. , m_month(June)
  218. , m_eclipticObliquity(bx::toRad(23.4f) )
  219. , m_delta(0.0f)
  220. {
  221. m_northDir = { 1.0f, 0.0f, 0.0f };
  222. m_sunDir = { 0.0f, -1.0f, 0.0f };
  223. m_upDir = { 0.0f, 1.0f, 0.0f };
  224. }
  225. void Update(float _time)
  226. {
  227. CalculateSunOrbit();
  228. UpdateSunPosition(_time - 12.0f);
  229. }
  230. bx::Vec3 m_northDir;
  231. bx::Vec3 m_sunDir;
  232. bx::Vec3 m_upDir;
  233. float m_latitude;
  234. Month m_month;
  235. private:
  236. void CalculateSunOrbit()
  237. {
  238. float day = 30.0f * m_month + 15.0f;
  239. float lambda = 280.46f + 0.9856474f * day;
  240. lambda = bx::toRad(lambda);
  241. m_delta = bx::asin(bx::sin(m_eclipticObliquity) * bx::sin(lambda) );
  242. }
  243. void UpdateSunPosition(float _hour)
  244. {
  245. const float latitude = bx::toRad(m_latitude);
  246. const float hh = _hour * bx::kPi / 12.0f;
  247. const float azimuth = bx::atan2(
  248. bx::sin(hh)
  249. , bx::cos(hh) * bx::sin(latitude) - bx::tan(m_delta) * bx::cos(latitude)
  250. );
  251. const float altitude = bx::asin(
  252. bx::sin(latitude) * bx::sin(m_delta) + bx::cos(latitude) * bx::cos(m_delta) * bx::cos(hh)
  253. );
  254. const bx::Quaternion rot0 = bx::rotateAxis(m_upDir, -azimuth);
  255. const bx::Vec3 dir = bx::mul(m_northDir, rot0);
  256. const bx::Vec3 uxd = bx::cross(m_upDir, dir);
  257. const bx::Quaternion rot1 = bx::rotateAxis(uxd, altitude);
  258. m_sunDir = bx::mul(dir, rot1);
  259. }
  260. float m_eclipticObliquity;
  261. float m_delta;
  262. };
  263. struct ScreenPosVertex
  264. {
  265. float m_x;
  266. float m_y;
  267. static void init()
  268. {
  269. ms_decl
  270. .begin()
  271. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  272. .end();
  273. }
  274. static bgfx::VertexDecl ms_decl;
  275. };
  276. bgfx::VertexDecl ScreenPosVertex::ms_decl;
  277. // Renders a screen-space grid of triangles.
  278. // Because of performance reasons, and because sky color is smooth, sky color is computed in vertex shader.
  279. // 32x32 is a reasonable size for the grid to have smooth enough colors.
  280. struct ProceduralSky
  281. {
  282. void init(int verticalCount, int horizontalCount)
  283. {
  284. // Create vertex stream declaration.
  285. ScreenPosVertex::init();
  286. m_skyProgram = loadProgram("vs_sky", "fs_sky");
  287. m_skyProgram_colorBandingFix = loadProgram("vs_sky", "fs_sky_color_banding_fix");
  288. m_preventBanding = true;
  289. bx::AllocatorI* allocator = entry::getAllocator();
  290. ScreenPosVertex* vertices = (ScreenPosVertex*)BX_ALLOC(allocator
  291. , verticalCount * horizontalCount * sizeof(ScreenPosVertex)
  292. );
  293. for (int i = 0; i < verticalCount; i++)
  294. {
  295. for (int j = 0; j < horizontalCount; j++)
  296. {
  297. ScreenPosVertex& v = vertices[i * verticalCount + j];
  298. v.m_x = float(j) / (horizontalCount - 1) * 2.0f - 1.0f;
  299. v.m_y = float(i) / (verticalCount - 1) * 2.0f - 1.0f;
  300. }
  301. }
  302. uint16_t* indices = (uint16_t*)BX_ALLOC(allocator
  303. , (verticalCount - 1) * (horizontalCount - 1) * 6 * sizeof(uint16_t)
  304. );
  305. int k = 0;
  306. for (int i = 0; i < verticalCount - 1; i++)
  307. {
  308. for (int j = 0; j < horizontalCount - 1; j++)
  309. {
  310. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 0));
  311. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0));
  312. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1));
  313. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0));
  314. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 1));
  315. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1));
  316. }
  317. }
  318. m_vbh = bgfx::createVertexBuffer(bgfx::copy(vertices, sizeof(ScreenPosVertex) * verticalCount * horizontalCount), ScreenPosVertex::ms_decl);
  319. m_ibh = bgfx::createIndexBuffer(bgfx::copy(indices, sizeof(uint16_t) * k));
  320. BX_FREE(allocator, indices);
  321. BX_FREE(allocator, vertices);
  322. }
  323. void shutdown()
  324. {
  325. bgfx::destroy(m_ibh);
  326. bgfx::destroy(m_vbh);
  327. bgfx::destroy(m_skyProgram);
  328. bgfx::destroy(m_skyProgram_colorBandingFix);
  329. }
  330. void draw()
  331. {
  332. bgfx::setState(BGFX_STATE_WRITE_RGB | BGFX_STATE_DEPTH_TEST_EQUAL);
  333. bgfx::setIndexBuffer(m_ibh);
  334. bgfx::setVertexBuffer(0, m_vbh);
  335. bgfx::submit(0, m_preventBanding ? m_skyProgram_colorBandingFix : m_skyProgram);
  336. }
  337. bgfx::VertexBufferHandle m_vbh;
  338. bgfx::IndexBufferHandle m_ibh;
  339. bgfx::ProgramHandle m_skyProgram;
  340. bgfx::ProgramHandle m_skyProgram_colorBandingFix;
  341. bool m_preventBanding;
  342. };
  343. class ExampleProceduralSky : public entry::AppI
  344. {
  345. public:
  346. ExampleProceduralSky(const char* _name, const char* _description)
  347. : entry::AppI(_name, _description)
  348. {
  349. }
  350. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  351. {
  352. Args args(_argc, _argv);
  353. m_width = _width;
  354. m_height = _height;
  355. m_debug = BGFX_DEBUG_NONE;
  356. m_reset = BGFX_RESET_VSYNC;
  357. bgfx::Init init;
  358. init.type = args.m_type;
  359. init.vendorId = args.m_pciId;
  360. init.resolution.width = m_width;
  361. init.resolution.height = m_height;
  362. init.resolution.reset = m_reset;
  363. bgfx::init(init);
  364. // Enable m_debug text.
  365. bgfx::setDebug(m_debug);
  366. // Set view 0 clear state.
  367. bgfx::setViewClear(0
  368. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  369. , 0x000000ff
  370. , 1.0f
  371. , 0
  372. );
  373. m_sunLuminanceXYZ.SetMap(sunLuminanceXYZTable);
  374. m_skyLuminanceXYZ.SetMap(skyLuminanceXYZTable);
  375. m_mesh = meshLoad("meshes/test_scene.bin");
  376. m_lightmapTexture = loadTexture("textures/lightmap.ktx");
  377. // Imgui.
  378. imguiCreate();
  379. m_timeOffset = bx::getHPCounter();
  380. m_time = 0.0f;
  381. m_timeScale = 1.0f;
  382. s_texLightmap = bgfx::createUniform("s_texLightmap", bgfx::UniformType::Sampler);
  383. u_sunLuminance = bgfx::createUniform("u_sunLuminance", bgfx::UniformType::Vec4);
  384. u_skyLuminanceXYZ = bgfx::createUniform("u_skyLuminanceXYZ", bgfx::UniformType::Vec4);
  385. u_skyLuminance = bgfx::createUniform("u_skyLuminance", bgfx::UniformType::Vec4);
  386. u_sunDirection = bgfx::createUniform("u_sunDirection", bgfx::UniformType::Vec4);
  387. u_parameters = bgfx::createUniform("u_parameters", bgfx::UniformType::Vec4);
  388. u_perezCoeff = bgfx::createUniform("u_perezCoeff", bgfx::UniformType::Vec4, 5);
  389. m_landscapeProgram = loadProgram("vs_sky_landscape", "fs_sky_landscape");
  390. m_sky.init(32, 32);
  391. m_sun.Update(0);
  392. cameraCreate();
  393. cameraSetPosition({ 5.0f, 3.0, 0.0f });
  394. cameraSetVerticalAngle(bx::kPi / 8.0f);
  395. cameraSetHorizontalAngle(-bx::kPi / 3.0f);
  396. m_turbidity = 2.15f;
  397. }
  398. virtual int shutdown() override
  399. {
  400. // Cleanup.
  401. cameraDestroy();
  402. imguiDestroy();
  403. meshUnload(m_mesh);
  404. m_sky.shutdown();
  405. bgfx::destroy(s_texLightmap);
  406. bgfx::destroy(u_sunLuminance);
  407. bgfx::destroy(u_skyLuminanceXYZ);
  408. bgfx::destroy(u_skyLuminance);
  409. bgfx::destroy(u_sunDirection);
  410. bgfx::destroy(u_parameters);
  411. bgfx::destroy(u_perezCoeff);
  412. bgfx::destroy(m_lightmapTexture);
  413. bgfx::destroy(m_landscapeProgram);
  414. bgfx::frame();
  415. // Shutdown bgfx.
  416. bgfx::shutdown();
  417. return 0;
  418. }
  419. void imgui(float _width)
  420. {
  421. ImGui::Begin("ProceduralSky");
  422. ImGui::SetWindowSize(ImVec2(_width, 200.0f) );
  423. ImGui::SliderFloat("Time scale", &m_timeScale, 0.0f, 1.0f);
  424. ImGui::SliderFloat("Time", &m_time, 0.0f, 24.0f);
  425. ImGui::SliderFloat("Latitude", &m_sun.m_latitude, -90.0f, 90.0f);
  426. ImGui::SliderFloat("Turbidity", &m_turbidity, 1.9f, 10.0f);
  427. ImGui::Checkbox("Prevent color banding", &m_sky.m_preventBanding);
  428. const char* items[] =
  429. {
  430. "January",
  431. "February",
  432. "March",
  433. "April",
  434. "May",
  435. "June",
  436. "July",
  437. "August",
  438. "September",
  439. "October",
  440. "November",
  441. "December"
  442. };
  443. ImGui::Combo("Month", (int*)&m_sun.m_month, items, 12);
  444. ImGui::End();
  445. }
  446. bool update() override
  447. {
  448. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  449. {
  450. int64_t now = bx::getHPCounter();
  451. static int64_t last = now;
  452. const int64_t frameTime = now - last;
  453. last = now;
  454. const double freq = double(bx::getHPFrequency());
  455. const float deltaTime = float(frameTime / freq);
  456. m_time += m_timeScale * deltaTime;
  457. m_time = bx::mod(m_time, 24.0f);
  458. m_sun.Update(m_time);
  459. imguiBeginFrame(m_mouseState.m_mx
  460. , m_mouseState.m_my
  461. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  462. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  463. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  464. , m_mouseState.m_mz
  465. , uint16_t(m_width)
  466. , uint16_t(m_height)
  467. );
  468. showExampleDialog(this);
  469. ImGui::SetNextWindowPos(
  470. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  471. , ImGuiCond_FirstUseEver
  472. );
  473. imgui(m_width / 5.0f - 10.0f);
  474. imguiEndFrame();
  475. if (!ImGui::MouseOverArea())
  476. {
  477. // Update camera.
  478. cameraUpdate(deltaTime, m_mouseState);
  479. }
  480. // Set view 0 default viewport.
  481. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height));
  482. float view[16];
  483. cameraGetViewMtx(view);
  484. float proj[16];
  485. bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 2000.0f, bgfx::getCaps()->homogeneousDepth);
  486. bgfx::setViewTransform(0, view, proj);
  487. Color sunLuminanceXYZ = m_sunLuminanceXYZ.GetValue(m_time);
  488. Color sunLuminanceRGB = xyzToRgb(sunLuminanceXYZ);
  489. Color skyLuminanceXYZ = m_skyLuminanceXYZ.GetValue(m_time);
  490. Color skyLuminanceRGB = xyzToRgb(skyLuminanceXYZ);
  491. bgfx::setUniform(u_sunLuminance, &sunLuminanceRGB.x);
  492. bgfx::setUniform(u_skyLuminanceXYZ, &skyLuminanceXYZ.x);
  493. bgfx::setUniform(u_skyLuminance, &skyLuminanceRGB.x);
  494. bgfx::setUniform(u_sunDirection, &m_sun.m_sunDir.x);
  495. float exposition[4] = { 0.02f, 3.0f, 0.1f, m_time };
  496. bgfx::setUniform(u_parameters, exposition);
  497. float perezCoeff[4 * 5];
  498. computePerezCoeff(m_turbidity, perezCoeff);
  499. bgfx::setUniform(u_perezCoeff, perezCoeff, 5);
  500. bgfx::setTexture(0, s_texLightmap, m_lightmapTexture);
  501. meshSubmit(m_mesh, 0, m_landscapeProgram, NULL);
  502. m_sky.draw();
  503. bgfx::frame();
  504. return true;
  505. }
  506. return false;
  507. }
  508. void computePerezCoeff(float _turbidity, float* _outPerezCoeff)
  509. {
  510. const bx::Vec3 turbidity = { _turbidity, _turbidity, _turbidity };
  511. for (uint32_t ii = 0; ii < 5; ++ii)
  512. {
  513. const bx::Vec3 tmp = bx::mad(ABCDE_t[ii], turbidity, ABCDE[ii]);
  514. float* out = _outPerezCoeff + 4 * ii;
  515. bx::store(out, tmp);
  516. out[3] = 0.0f;
  517. }
  518. }
  519. bgfx::ProgramHandle m_landscapeProgram;
  520. bgfx::UniformHandle s_texLightmap;
  521. bgfx::TextureHandle m_lightmapTexture;
  522. bgfx::UniformHandle u_sunLuminance;
  523. bgfx::UniformHandle u_skyLuminanceXYZ;
  524. bgfx::UniformHandle u_skyLuminance;
  525. bgfx::UniformHandle u_sunDirection;
  526. bgfx::UniformHandle u_parameters;
  527. bgfx::UniformHandle u_perezCoeff;
  528. ProceduralSky m_sky;
  529. SunController m_sun;
  530. DynamicValueController m_sunLuminanceXYZ;
  531. DynamicValueController m_skyLuminanceXYZ;
  532. uint32_t m_width;
  533. uint32_t m_height;
  534. uint32_t m_debug;
  535. uint32_t m_reset;
  536. Mesh* m_mesh;
  537. entry::MouseState m_mouseState;
  538. float m_time;
  539. float m_timeScale;
  540. int64_t m_timeOffset;
  541. float m_turbidity;
  542. };
  543. } // namespace
  544. ENTRY_IMPLEMENT_MAIN(ExampleProceduralSky, "36-sky", "Perez dynamic sky model.");