Photons.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. //
  2. // Copyright (c) 2017, THUNDERBEAST GAMES LLC All rights reserved
  3. // Copyright (c) 2015 Dmitry Sovetov
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Core/StringUtils.h>
  24. #include "EmbreeScene.h"
  25. #include "SceneBaker.h"
  26. #include "Photons.h"
  27. #include "BakeMesh.h"
  28. namespace AtomicGlow
  29. {
  30. PhotonMap::PhotonMap(BakeMesh* bakeMesh, int width, int height) :
  31. bakeMesh_(bakeMesh),
  32. width_(width),
  33. height_(height)
  34. {
  35. if (width_ > 0 && height_ > 0)
  36. {
  37. photons_ = new Photon[width_ * height_];
  38. for (int i = 0; i < width_ * height_; i++)
  39. {
  40. photons_[i].Reset();
  41. }
  42. }
  43. }
  44. PhotonMap::~PhotonMap()
  45. {
  46. }
  47. void PhotonMap::SavePng(const String& filename) const
  48. {
  49. Image image(bakeMesh_->GetContext());
  50. image.SetSize(width_, height_, 3);
  51. image.Clear(Color::BLACK);
  52. for( int y = 0; y < height_; y++ )
  53. {
  54. for( int x = 0; x < width_; x++ )
  55. {
  56. const Photon& photon = photons_[y * width_ + x];
  57. int count;
  58. Color gathered = Color::BLACK;
  59. for (count = 0; count < PHOTON_TRI_MAX; count++)
  60. {
  61. if (photon.tris_[count] == PHOTON_TRI_INVALID)
  62. break;
  63. gathered += photon.gathered_[count];
  64. }
  65. if (!count)
  66. continue;
  67. gathered.r_ *= (1.0f / float(count));
  68. gathered.g_ *= (1.0f / float(count));
  69. gathered.b_ *= (1.0f / float(count));
  70. gathered.a_ *= (1.0f / float(count));
  71. image.SetPixel(x, y, gathered);
  72. }
  73. }
  74. image.SavePNG(filename);
  75. }
  76. void PhotonMap::Gather(int radius )
  77. {
  78. for( int y = 0; y < height_; y++ )
  79. {
  80. for( int x = 0; x < width_; x++ )
  81. {
  82. Photon& photon = photons_[y * width_ + x];
  83. for (int i = 0; i < PHOTON_TRI_MAX; i++)
  84. {
  85. if (photon.tris_[i] == PHOTON_TRI_INVALID)
  86. break;
  87. photon.gathered_[i] = Gather(photon.tris_[i], x, y, radius);
  88. }
  89. }
  90. }
  91. /*
  92. if (true)
  93. {
  94. String filename = ToString("/Users/jenge/Temp/PhotonMap%i.png", bakeMesh_->GetGeomID());
  95. SavePng(filename);
  96. }
  97. */
  98. }
  99. Color PhotonMap::Gather( int triIndex, int x, int y, int radius ) const
  100. {
  101. Color color = Color::BLACK;
  102. int photons = 0;
  103. for( int j = y - radius; j <= y + radius; j++ )
  104. {
  105. for( int i = x - radius; i <= x + radius; i++ )
  106. {
  107. if( i < 0 || j < 0 || i >= width_ || j >= height_ )
  108. {
  109. continue;
  110. }
  111. const Photon& photon = photons_[j * width_ + i];
  112. int idx = photon.MapTriIndex(triIndex);
  113. if (idx == PHOTON_TRI_INVALID)
  114. {
  115. continue;
  116. }
  117. float distance = sqrtf( static_cast<float>( (x - i) * (x - i) + (y - j) * (y - j) ) );
  118. if( distance > radius ) {
  119. continue;
  120. }
  121. if (photon.photons_[idx])
  122. {
  123. color += photon.color_[idx];
  124. photons += photon.photons_[idx];
  125. }
  126. }
  127. }
  128. if( photons == 0 )
  129. {
  130. return Color::BLACK;
  131. }
  132. float divisor = 1.0f / static_cast<float>( photons );
  133. color.r_ *= divisor;
  134. color.g_ *= divisor;
  135. color.b_ *= divisor;
  136. color.a_ *= divisor;
  137. return color;
  138. }
  139. Photons::Photons( SceneBaker* sceneBaker, int passCount, int maxDepth, float energyThreshold, float maxDistance )
  140. : sceneBaker_( SharedPtr<SceneBaker>(sceneBaker) ),
  141. passCount_( passCount ),
  142. maxDepth_( maxDepth ),
  143. energyThreshold_( energyThreshold ),
  144. maxDistance_( maxDistance ),
  145. photonCount_( 0 )
  146. {
  147. }
  148. int Photons::Emit( const Vector<SharedPtr<BakeLight>>& bakeLights )
  149. {
  150. // TODO: depending on performance, photon emission may need to be threaded
  151. for( int j = 0; j < passCount_; j++ )
  152. {
  153. Vector<SharedPtr<BakeLight>>::ConstIterator itr = bakeLights.Begin();
  154. while (itr != bakeLights.End())
  155. {
  156. BakeLight* bakeLight = *itr;
  157. if( !bakeLight->GetPhotonEmitter() )
  158. {
  159. itr++;
  160. continue;
  161. }
  162. EmitPhotons( bakeLight );
  163. itr++;
  164. }
  165. }
  166. return photonCount_;
  167. }
  168. void Photons::EmitPhotons( const BakeLight* light )
  169. {
  170. PhotonEmitter* emitter = light->GetPhotonEmitter();
  171. Vector3 direction;
  172. Vector3 position;
  173. for( int i = 0, n = emitter->GetPhotonCount(); i < n; i++ )
  174. {
  175. // Emit photon
  176. emitter->Emit( sceneBaker_, position, direction );
  177. // Calculate light cutoff
  178. float cut = 1.0f;
  179. if( const LightCutoff* cutoff = light->GetCutoffModel() )
  180. {
  181. cut = cutoff->GetCutoffForDirection( direction );
  182. }
  183. if( cut <= 0.0f )
  184. {
  185. continue;
  186. }
  187. Trace( light->GetAttenuationModel(), position, direction, light->GetColor() * light->GetIntensity() * cut, 0 );
  188. }
  189. }
  190. void Photons::Trace(const LightAttenuation* attenuation, const Vector3& position, const Vector3& direction, const Color& color, int depth , unsigned lastGeomID, unsigned lastPrimID)
  191. {
  192. // Maximum depth or energy threshold exceeded
  193. if( depth > maxDepth_ || color.Luma() < energyThreshold_ )
  194. {
  195. return;
  196. }
  197. // clean this mess up
  198. RTCScene scene = sceneBaker_->GetEmbreeScene()->GetRTCScene();
  199. float maxDist = attenuation ? maxDistance_ : LIGHT_LARGE_DISTANCE;
  200. lightRay_.SetupRay(position, direction, .001f, maxDist);
  201. RTCRay& ray = lightRay_.rtcRay_;
  202. rtcIntersect(scene, ray);
  203. // The photon didn't hit anything
  204. if (ray.geomID == RTC_INVALID_GEOMETRY_ID)
  205. {
  206. return;
  207. }
  208. // self hit
  209. if (ray.geomID == lastGeomID && ray.primID == lastPrimID)
  210. {
  211. return;
  212. }
  213. Vector3 hitPosition = position + (direction * ray.tfar);
  214. Vector3 hitNormal(ray.Ng[0], ray.Ng[1], ray.Ng[2]);
  215. hitNormal.Normalize();
  216. // energy attenuation after a photon has passed the traced segment
  217. float att = 1.0f;
  218. if( attenuation )
  219. {
  220. att = attenuation->Calculate( (position - hitPosition).Length() );
  221. }
  222. // energy after reflection
  223. float influence = LightInfluence::GetLambert( direction, hitNormal ) * att;
  224. if (influence <= 0.0f)
  225. {
  226. return;
  227. }
  228. BakeMesh* bakeMesh = sceneBaker_->GetEmbreeScene()->GetBakeMesh(ray.geomID);
  229. Color hitColor;
  230. Vector3 bary(ray.u, ray.v, 1.0f-ray.u-ray.v);
  231. // TODO: alpha mask support?
  232. if (!bakeMesh || !bakeMesh->GetUV0Color(ray.primID, bary, hitColor))
  233. {
  234. return;
  235. }
  236. // final photon color
  237. hitColor.r_ *= (color.r_ * influence);
  238. hitColor.g_ *= (color.g_ * influence);
  239. hitColor.b_ *= (color.b_ * influence);
  240. Vector2 st;
  241. bakeMesh->GetST(ray.primID, 1, bary, st);
  242. // store photon energy
  243. Store( bakeMesh->GetPhotonMap(), (int) ray.primID, hitColor, st );
  244. // keep tracing
  245. Vector3 dir;
  246. Vector3::GetRandomHemisphereDirection(dir, hitNormal);
  247. Trace( attenuation, hitPosition, dir, hitColor, depth + 1, ray.geomID, ray.primID );
  248. }
  249. void Photons::Store(PhotonMap* photonmap, int triIdx, const Color& color, const Vector2& uv )
  250. {
  251. if( !photonmap ) {
  252. return;
  253. }
  254. if (!photonmap->AddPhoton(triIdx, uv, color))
  255. {
  256. return;
  257. }
  258. photonCount_++;
  259. }
  260. }