ProcSky.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. //
  2. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Graphics/Graphics.h"
  25. #include "../Graphics/GraphicsEvents.h"
  26. #include "../Graphics/View.h"
  27. #include "../Scene/Scene.h"
  28. #include "../Graphics/Camera.h"
  29. #include "../Scene/SceneEvents.h"
  30. #include "../Graphics/Light.h"
  31. #include "../Resource/ResourceCache.h"
  32. #include "../Graphics/Technique.h"
  33. #include "../Environment/ProcSky.h"
  34. #include "../Graphics/Renderer.h"
  35. #if defined(_MSC_VER)
  36. #include "stdint.h"
  37. #endif
  38. #if defined(EMSCRIPTEN) || defined(ATOMIC_PLATFORM_LINUX)
  39. #include <stdint.h>
  40. #endif
  41. namespace Atomic
  42. {
  43. extern const char* GEOMETRY_CATEGORY;
  44. float ProcSky::timeOfDay_ = 0.0f;
  45. ProcSky::ProcSky(Context* context) :
  46. Drawable(context, DRAWABLE_GEOMETRY),
  47. geometry_(new Geometry(context)),
  48. vertexBuffer_(new VertexBuffer(context_)),
  49. indexBuffer_(new IndexBuffer(context_)),
  50. autoUpdate_(false),
  51. dayTime_(0.0f),
  52. lastDayTimeUpdate_(-1.0f),
  53. shadowFade_(1.0f),
  54. customWorldTransform_(Matrix3x4::IDENTITY),
  55. initialized_(false),
  56. flipped_(false)
  57. {
  58. }
  59. ProcSky::~ProcSky()
  60. {
  61. }
  62. void ProcSky::RegisterObject(Context* context)
  63. {
  64. context->RegisterFactory<ProcSky>(GEOMETRY_CATEGORY);
  65. ATOMIC_COPY_BASE_ATTRIBUTES(Drawable);
  66. }
  67. void ProcSky::UpdateBatches(const FrameInfo& frame)
  68. {
  69. if (!initialized_)
  70. Initialize();
  71. distance_ = 0.0f;
  72. // Follow only the camera rotation, not position
  73. Matrix3x4 customView(Vector3::ZERO, frame.camera_->GetNode()->GetWorldRotation().Inverse(), Vector3::ONE);
  74. customWorldTransform_ = customView * node_->GetWorldTransform();
  75. for (unsigned i = 0; i < batches_.Size(); ++i)
  76. {
  77. batches_[i].worldTransform_ = &customWorldTransform_;
  78. batches_[i].numWorldTransforms_ = 1;
  79. batches_[i].distance_ = 0.0f;
  80. }
  81. }
  82. void ProcSky::UpdateGeometry(const FrameInfo& frame)
  83. {
  84. if (!initialized_)
  85. Initialize();
  86. if ( indexBuffer_->IsDataLost())
  87. UpdateIndexBuffer();
  88. UpdateVertexBuffer(frame);
  89. }
  90. UpdateGeometryType ProcSky::GetUpdateGeometryType()
  91. {
  92. // updates vertex buffer per frame
  93. return UPDATE_MAIN_THREAD;
  94. }
  95. void ProcSky::OnWorldBoundingBoxUpdate()
  96. {
  97. // The skybox is supposed to be visible everywhere, so set a humongous bounding box
  98. worldBoundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE);
  99. }
  100. void ProcSky::OnNodeSet(Node* node)
  101. {
  102. Drawable::OnNodeSet(node);
  103. if (node && node->GetScene())
  104. {
  105. SubscribeToEvent(node->GetScene(), E_SCENEUPDATE, ATOMIC_HANDLER(ProcSky, HandleSceneUpdate));
  106. SubscribeToEvent(E_BEGINVIEWUPDATE, ATOMIC_HANDLER(ProcSky, HandleBeginViewUpdate));
  107. }
  108. }
  109. void ProcSky::HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData)
  110. {
  111. #ifdef ATOMIC_OPENGL
  112. flipped_ = false;
  113. View* view = static_cast<View*>(eventData[BeginViewUpdate::P_VIEW].GetPtr());
  114. if (view && view->GetRenderTarget())
  115. flipped_ = true;
  116. #endif
  117. }
  118. void ProcSky::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  119. {
  120. using namespace SceneUpdate;
  121. if (!initialized_)
  122. Initialize();
  123. float timeStep = eventData[P_TIMESTEP].GetFloat();
  124. if (autoUpdate_)
  125. {
  126. dayTime_ += timeStep * .1f;
  127. SetDayTime(dayTime_);
  128. }
  129. }
  130. float ProcSky::SetDayTime(float time)
  131. {
  132. if (!initialized_)
  133. Initialize();
  134. sunAngle_ = (time+0.5f) * M_PI;
  135. int degrees = int(sunAngle_ * M_RADTODEG);
  136. degrees %= 360;
  137. timeOfDay_ = ((degrees + 90) % 360) / 15.0f;
  138. if (degrees >= 150 || degrees <= 15)
  139. {
  140. // fade out
  141. if (shadowFade_ < 0.0f || shadowFade_ != 1.0f)
  142. {
  143. if (autoUpdate_)
  144. {
  145. shadowFade_ += .05f;
  146. if (shadowFade_ > 1.0f)
  147. shadowFade_ = 1.0f;
  148. }
  149. else
  150. {
  151. shadowFade_ = 1.0f;
  152. }
  153. sunlight_->SetShadowIntensity(shadowFade_);
  154. if (!sunlight_->GetCastShadows())
  155. sunlight_->SetCastShadows(true);
  156. }
  157. else
  158. {
  159. if (sunlight_->GetCastShadows())
  160. sunlight_->SetCastShadows(false);
  161. }
  162. }
  163. else
  164. {
  165. // fade in
  166. if (shadowFade_ < 0.0f || shadowFade_ != 0.0f)
  167. {
  168. if (autoUpdate_)
  169. {
  170. shadowFade_ -= .05f;
  171. if (shadowFade_ < 0.0f)
  172. shadowFade_ = 0.0f;
  173. }
  174. else
  175. {
  176. shadowFade_ = 0.0f;
  177. }
  178. sunlight_->SetShadowIntensity(shadowFade_);
  179. if (!sunlight_->GetCastShadows())
  180. sunlight_->SetCastShadows(true);
  181. }
  182. else
  183. {
  184. if (!sunlight_->GetCastShadows())
  185. sunlight_->SetCastShadows(true);
  186. }
  187. }
  188. Quaternion rot(degrees, Vector3::RIGHT);
  189. node_->SetRotation(rot);
  190. float daylight = cosf( time * M_PI ) * 0.8f + 0.4f;
  191. if( daylight > 1.0f )
  192. daylight = 1.0f;
  193. if( daylight < 0.0f )
  194. daylight = 0.0f;
  195. daylight = sqrtf( daylight );
  196. float dawnGlow = sinf( time * M_PI * 1.0f );
  197. int glowX = dawnGlow > 0.0f ? 0 : 7;
  198. dawnGlow = Atomic::Max( 0.0f, fabs( dawnGlow * dawnGlow * dawnGlow ) * 1.1f - 0.1f );
  199. Color top = Color(0,0,0,1).Lerp(topColor_, daylight);
  200. Color horiz = Color(.1,.1,.1,1).Lerp(horizColor_, daylight);
  201. uint8_t skytex[32 * 8 * 4 ];
  202. uint8_t* p;
  203. // bottom row is black
  204. p = &skytex[31*8*4];
  205. for( uint32_t x = 0; x < 8; x++ )
  206. {
  207. *p++ = 0;
  208. *p++ = 0;
  209. *p++ = 0;
  210. *p++ = 255;
  211. }
  212. p = skytex;
  213. for( uint32_t z = 0; z < 31; z++ )
  214. {
  215. for( uint32_t x = 0; x < 8; x++ )
  216. {
  217. float xGlow = Atomic::Max( 0, -abs((int)x-glowX) + 5 ) / 5.0f;
  218. float hGlow = z/31.0f;
  219. float glow = (dawnGlow * hGlow * hGlow * sqrtf( xGlow ));
  220. Color baseColor = top.Lerp(horiz, Atomic::Min( 1.0f, float (z*11) / 255.0f));
  221. baseColor = baseColor.Lerp(lerpColor_, glow );
  222. // pic a color from the mid - horizon (this is cheesy!)
  223. if (z == 28 && x == 4)
  224. {
  225. fogColor_ = baseColor;
  226. zone_->SetFogColor(fogColor_);
  227. Color sunColor (.3f, .2f, .1f);
  228. sunColor += fogColor_;
  229. sunlight_->SetColor(sunColor);
  230. Color ambient = sunColor * .75f;
  231. if (ambient.r_ < .25f)
  232. ambient.r_ = .25f;
  233. if (ambient.g_ < .25f)
  234. ambient.g_ = .25f;
  235. if (ambient.b_ < .25f)
  236. ambient.b_ = .25f;
  237. zone_->SetAmbientColor(ambient);
  238. }
  239. unsigned r = Clamp(((int)(baseColor.r_ * 255.0f)), 0, 255);
  240. unsigned g = Clamp(((int)(baseColor.g_ * 255.0f)), 0, 255);
  241. unsigned b = Clamp(((int)(baseColor.b_ * 255.0f)), 0, 255);
  242. *p++ = (uint8_t) r;
  243. *p++ = (uint8_t) g;
  244. *p++ = (uint8_t) b;
  245. *p++ = 255;
  246. }
  247. }
  248. //if (fabs(lastDayTimeUpdate_ - dayTime_) > .005f)
  249. {
  250. skyTexture_->SetData(0,0,0,8,32,skytex);
  251. lastDayTimeUpdate_ = dayTime_;
  252. }
  253. return Atomic::Max( 4.0f/15.0f, daylight );
  254. }
  255. void ProcSky::UpdateIndexBuffer()
  256. {
  257. unsigned short* dest = (unsigned short*)indexBuffer_->Lock(0, 6, true);
  258. *dest++ = 2; *dest++ = 1; *dest++ = 0;
  259. *dest++ = 0; *dest++ = 3; *dest++ = 2;
  260. indexBuffer_->Unlock();
  261. indexBuffer_->ClearDataLost();
  262. }
  263. void ProcSky::UpdateVertexBuffer(const FrameInfo &frame)
  264. {
  265. float* vdest = (float*)vertexBuffer_->Lock(0, 4, true);
  266. const Frustum& frustum = frame.camera_->GetFrustum();
  267. // Upper left corner
  268. Vector3 n;
  269. Vector3 planes[4];
  270. planes[0] = frustum.planes_[PLANE_LEFT].normal_;
  271. planes[1] = frustum.planes_[PLANE_RIGHT].normal_;
  272. planes[2] = frustum.planes_[PLANE_UP].normal_;
  273. planes[3] = frustum.planes_[PLANE_DOWN].normal_;
  274. float top = 1.0f;
  275. float bottom = -1.0f;
  276. #ifdef ATOMIC_OPENGL
  277. if (flipped_)
  278. {
  279. top = -1.0f;
  280. bottom = 1.0f;
  281. }
  282. #endif
  283. // 0 2
  284. n = planes[0].CrossProduct(planes[2]);
  285. *vdest++ = -1.0f;
  286. *vdest++ = top;
  287. *vdest++ = 1.0f;
  288. *vdest++ = n.x_;
  289. *vdest++ = -n.y_;
  290. *vdest++ = n.z_ ;
  291. // Lower left corner
  292. // 3 0
  293. n = planes[3].CrossProduct(planes[0]);
  294. *vdest++ = -1.0f;
  295. *vdest++ = bottom;
  296. *vdest++ = 1.0f;
  297. *vdest++ = n.x_;
  298. *vdest++ = -n.y_;
  299. *vdest++ = n.z_;
  300. // Lower right corner
  301. // 1 3
  302. n = planes[1].CrossProduct(planes[3]);
  303. *vdest++ = 1.0f;
  304. *vdest++ = bottom;
  305. *vdest++ = 1.0f;
  306. *vdest++ = n.x_;
  307. *vdest++ = -n.y_;
  308. *vdest++ = n.z_;
  309. // Upper right corner
  310. // 2 1
  311. n = planes[2].CrossProduct(planes[1]);
  312. *vdest++ = 1.0f;
  313. *vdest++ = top;
  314. *vdest++ = 1.0f;
  315. *vdest++ = n.x_;
  316. *vdest++ = -n.y_;
  317. *vdest++ = n.z_;
  318. vertexBuffer_->Unlock();
  319. vertexBuffer_->ClearDataLost();
  320. }
  321. void ProcSky::Initialize()
  322. {
  323. initialized_ = true;
  324. topColor_.b_ = float(0x76) / 255.0f;
  325. topColor_.g_ = float(0x4a) / 255.0f;
  326. topColor_.r_ = float(0x1f) / 255.0f;
  327. topColor_.a_ = 1.0f;
  328. horizColor_.b_ = float(0xca) / 255.0f;
  329. horizColor_.g_ = float(0x9b) / 255.0f;
  330. horizColor_.r_ = float(0x65) / 255.0f;
  331. horizColor_.a_ = 1.0f;
  332. lerpColor_.b_ = float(0x16) / 255.0f;
  333. lerpColor_.g_ = float(0x40) / 255.0f;
  334. lerpColor_.r_ = float(0x9b) / 255.0f;
  335. lerpColor_.a_ = 1.0f;
  336. sunlight_ = node_->CreateComponent<Light>();
  337. sunlight_->SetLightType(LIGHT_DIRECTIONAL);
  338. sunlight_->SetCastShadows(true);
  339. sunlight_->SetShadowBias(BiasParameters(0.0001f, 0.5f));
  340. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  341. #if ANDROID
  342. sunlight_->SetShadowCascade(CascadeParameters(50.0f, 0.0f, 0.0f, 0.0f, 0.8f));
  343. #else
  344. sunlight_->SetShadowCascade(CascadeParameters(30.0f, 60.0f, 120.0f, 200.0f, 0.8f));
  345. #endif
  346. ResourceCache* cache = GetSubsystem<ResourceCache>();
  347. skyMaterial_ = cache->GetResource<Material>("Materials/ProcSky.xml");
  348. geometry_->SetVertexBuffer(0, vertexBuffer_);
  349. geometry_->SetIndexBuffer(indexBuffer_);
  350. indexBuffer_->SetSize( 6, false);
  351. UpdateIndexBuffer();
  352. // updated per frame
  353. vertexBuffer_->SetSize(4, MASK_POSITION | MASK_NORMAL , true);
  354. batches_.Resize(1);
  355. batches_[0].geometry_ = geometry_;
  356. batches_[0].geometryType_ = GEOM_STATIC_NOINSTANCING;
  357. batches_[0].worldTransform_ = &customWorldTransform_;
  358. batches_[0].material_ = skyMaterial_;
  359. batches_[0].geometry_->SetDrawRange(TRIANGLE_LIST, 0, 6, false);
  360. skyTexture_ = new Texture2D(context_);
  361. skyMaterial_->SetTexture(TU_DIFFUSE , skyTexture_);
  362. skyTexture_->SetMipsToSkip(QUALITY_LOW, 0); // No quality reduction
  363. skyTexture_->SetNumLevels(1); // No mipmaps
  364. skyTexture_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  365. skyTexture_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  366. int width = 8;
  367. int height = 32;
  368. skyTexture_->SetSize(width, height, Graphics::GetRGBAFormat(), TEXTURE_DYNAMIC);
  369. SharedArrayPtr<unsigned char> emptyBitmap(new unsigned char[width * height * 4]);
  370. memset(emptyBitmap.Get(), 0, width * height * 4);
  371. skyTexture_->SetData(0, 0, 0, width, height, emptyBitmap.Get());
  372. PODVector<Component*> components;
  373. node_->GetScene()->GetComponents(components, Zone::GetTypeStatic(), true);
  374. zone_ = (Zone*)components[0];
  375. }
  376. void ProcSky::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  377. {
  378. // Do not record a raycast result for a skybox, as it would block all other results
  379. }
  380. }