scatterSky.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "scatterSky.h"
  24. #include "core/stream/bitStream.h"
  25. #include "console/consoleTypes.h"
  26. #include "console/engineAPI.h"
  27. #include "sim/netConnection.h"
  28. #include "math/util/sphereMesh.h"
  29. #include "math/mathUtils.h"
  30. #include "math/util/matrixSet.h"
  31. #include "scene/sceneRenderState.h"
  32. #include "lighting/lightInfo.h"
  33. #include "gfx/sim/gfxStateBlockData.h"
  34. #include "gfx/gfxTransformSaver.h"
  35. #include "gfx/gfxDrawUtil.h"
  36. #include "gfx/sim/cubemapData.h"
  37. #include "materials/shaderData.h"
  38. #include "materials/materialManager.h"
  39. #include "materials/baseMatInstance.h"
  40. #include "materials/sceneData.h"
  41. #include "environment/timeOfDay.h"
  42. ConsoleDocClass( ScatterSky,
  43. "@brief Represents both the sun and sky for scenes with a dynamic time of day.\n\n"
  44. "%ScatterSky renders as a dome shaped mesh which is camera relative and always overhead. "
  45. "It is intended to be part of the background of your scene and renders before all "
  46. "other objects types.\n\n"
  47. "%ScatterSky is designed for outdoor scenes which need to transition fluidly "
  48. "between radically different times of day. It will respond to time changes "
  49. "originating from a TimeOfDay object or the elevation field can be directly "
  50. "adjusted.\n\n"
  51. "During day, %ScatterSky uses atmosphereic sunlight scattering "
  52. "aproximations to generate a sky gradient and sun corona. It also calculates "
  53. "the fog color, ambient color, and sun color, which are used for scene "
  54. "lighting. This is user controlled by fields within the ScatterSky group.\n\n"
  55. "During night, %ScatterSky supports can transition to a night sky cubemap and "
  56. "moon sprite. The user can control this and night time colors used for scene "
  57. "lighting with fields within the Night group.\n\n"
  58. "A scene with a ScatterSky should not have any other sky or sun objects "
  59. "as it already fulfills both roles.\n\n"
  60. "%ScatterSky is intended to be used with CloudLayer and TimeOfDay as part of "
  61. "a scene with dynamic lighting. Having a %ScatterSky without a changing "
  62. "time of day would unnecessarily give up artistic control compared and fillrate "
  63. "compared to a SkyBox + Sun setup.\n\n"
  64. "@ingroup Atmosphere"
  65. );
  66. IMPLEMENT_CO_NETOBJECT_V1(ScatterSky);
  67. const F32 ScatterSky::smEarthRadius = (6378.0f * 1000.0f);
  68. const F32 ScatterSky::smAtmosphereRadius = 200000.0f;
  69. const F32 ScatterSky::smViewerHeight = 1.0f;
  70. GFXImplementVertexFormat( ScatterSkyVertex )
  71. {
  72. addElement( "POSITION", GFXDeclType_Float3 );
  73. addElement( "NORMAL", GFXDeclType_Float3 );
  74. addElement( "COLOR", GFXDeclType_Color );
  75. }
  76. ScatterSky::ScatterSky()
  77. {
  78. mPrimCount = 0;
  79. mVertCount = 0;
  80. // Rayleigh scattering constant.
  81. mRayleighScattering = 0.0035f;
  82. mRayleighScattering4PI = mRayleighScattering * 4.0f * M_PI_F;
  83. // Mie scattering constant.
  84. mMieScattering = 0.0045f;
  85. mMieScattering4PI = mMieScattering * 4.0f * M_PI_F;
  86. // Overall scatter scalar.
  87. mSkyBrightness = 25.0f;
  88. // The Mie phase asymmetry factor.
  89. mMiePhaseAssymetry = -0.75f;
  90. mSphereInnerRadius = 1.0f;
  91. mSphereOuterRadius = 1.0f * 1.025f;
  92. mScale = 1.0f / (mSphereOuterRadius - mSphereInnerRadius);
  93. // 650 nm for red
  94. // 570 nm for green
  95. // 475 nm for blue
  96. mWavelength.set( 0.650f, 0.570f, 0.475f, 0 );
  97. mWavelength4[0] = mPow(mWavelength[0], 4.0f);
  98. mWavelength4[1] = mPow(mWavelength[1], 4.0f);
  99. mWavelength4[2] = mPow(mWavelength[2], 4.0f);
  100. mRayleighScaleDepth = 0.25f;
  101. mMieScaleDepth = 0.1f;
  102. mAmbientColor.set( 0, 0, 0, 1.0f );
  103. mAmbientScale.set( 1.0f, 1.0f, 1.0f, 1.0f );
  104. mSunColor.set( 0, 0, 0, 1.0f );
  105. mSunScale = ColorF::WHITE;
  106. mFogColor.set( 0, 0, 0, 1.0f );
  107. mFogScale = ColorF::WHITE;
  108. mExposure = 1.0f;
  109. mNightInterpolant = 0;
  110. mShader = NULL;
  111. mTimeOfDay = 0;
  112. mSunAzimuth = 0.0f;
  113. mSunElevation = 35.0f;
  114. mMoonAzimuth = 0.0f;
  115. mMoonElevation = 45.0f;
  116. mBrightness = 1.0f;
  117. mCastShadows = true;
  118. mDirty = true;
  119. mLight = LightManager::createLightInfo();
  120. mLight->setType( LightInfo::Vector );
  121. mFlareData = NULL;
  122. mFlareState.clear();
  123. mFlareScale = 1.0f;
  124. mMoonEnabled = true;
  125. mMoonScale = 0.2f;
  126. mMoonTint.set( 0.192157f, 0.192157f, 0.192157f, 1.0f );
  127. MathUtils::getVectorFromAngles( mMoonLightDir, 0.0f, 45.0f );
  128. mMoonLightDir.normalize();
  129. mMoonLightDir = -mMoonLightDir;
  130. mNightCubemap = NULL;
  131. mNightColor.set( 0.0196078f, 0.0117647f, 0.109804f, 1.0f );
  132. mNightFogColor = mNightColor;
  133. mUseNightCubemap = false;
  134. mSunSize = 1.0f;
  135. mMoonMatInst = NULL;
  136. mNetFlags.set( Ghostable | ScopeAlways );
  137. mTypeMask |= EnvironmentObjectType | LightObjectType | StaticObjectType;
  138. _generateSkyPoints();
  139. mMatrixSet = reinterpret_cast<MatrixSet *>(dMalloc_aligned(sizeof(MatrixSet), 16));
  140. constructInPlace(mMatrixSet);
  141. mColorizeAmt = 0;
  142. mColorize.set(0,0,0);
  143. }
  144. ScatterSky::~ScatterSky()
  145. {
  146. SAFE_DELETE( mLight );
  147. SAFE_DELETE( mMoonMatInst );
  148. dFree_aligned(mMatrixSet);
  149. }
  150. bool ScatterSky::onAdd()
  151. {
  152. PROFILE_SCOPE(ScatterSky_onAdd);
  153. // onNewDatablock for the server is called here
  154. // for the client it is called in unpackUpdate
  155. if ( !Parent::onAdd() )
  156. return false;
  157. if ( isClientObject() )
  158. TimeOfDay::getTimeOfDayUpdateSignal().notify( this, &ScatterSky::_updateTimeOfDay );
  159. setGlobalBounds();
  160. resetWorldBox();
  161. addToScene();
  162. if ( isClientObject() )
  163. {
  164. _initMoon();
  165. Sim::findObject( mNightCubemapName, mNightCubemap );
  166. }
  167. return true;
  168. }
  169. void ScatterSky::onRemove()
  170. {
  171. removeFromScene();
  172. if ( isClientObject() )
  173. TimeOfDay::getTimeOfDayUpdateSignal().remove( this, &ScatterSky::_updateTimeOfDay );
  174. Parent::onRemove();
  175. }
  176. void ScatterSky::_conformLights()
  177. {
  178. _initCurves();
  179. F32 val = mCurves[0].getVal( mTimeOfDay );
  180. mNightInterpolant = 1.0f - val;
  181. VectorF lightDirection;
  182. F32 brightness;
  183. // Build the light direction from the azimuth and elevation.
  184. F32 yaw = mDegToRad(mClampF(mSunAzimuth,0,359));
  185. F32 pitch = mDegToRad(mClampF(mSunElevation,-360,+360));
  186. MathUtils::getVectorFromAngles(lightDirection, yaw, pitch);
  187. lightDirection.normalize();
  188. mSunDir = -lightDirection;
  189. yaw = mDegToRad(mClampF(mMoonAzimuth,0,359));
  190. pitch = mDegToRad(mClampF(mMoonElevation,-360,+360));
  191. MathUtils::getVectorFromAngles( mMoonLightDir, yaw, pitch );
  192. mMoonLightDir.normalize();
  193. mMoonLightDir = -mMoonLightDir;
  194. brightness = mCurves[2].getVal( mTimeOfDay );
  195. if ( mNightInterpolant >= 1.0f )
  196. lightDirection = -mMoonLightDir;
  197. mLight->setDirection( -lightDirection );
  198. mLight->setBrightness( brightness * mBrightness );
  199. mLightDir = lightDirection;
  200. // Have to do interpolation
  201. // after the light direction is set
  202. // otherwise the sun color will be invalid.
  203. _interpolateColors();
  204. mLight->setAmbient( mAmbientColor );
  205. mLight->setColor( mSunColor );
  206. mLight->setCastShadows( mCastShadows );
  207. FogData fog = getSceneManager()->getFogData();
  208. fog.color = mFogColor;
  209. getSceneManager()->setFogData( fog );
  210. }
  211. void ScatterSky::submitLights( LightManager *lm, bool staticLighting )
  212. {
  213. if ( mDirty )
  214. {
  215. _conformLights();
  216. mDirty = false;
  217. }
  218. // The sun is a special light and needs special registration.
  219. lm->setSpecialLight( LightManager::slSunLightType, mLight );
  220. }
  221. void ScatterSky::setAzimuth( F32 azimuth )
  222. {
  223. mSunAzimuth = azimuth;
  224. mDirty = true;
  225. setMaskBits( TimeMask );
  226. }
  227. void ScatterSky::setElevation( F32 elevation )
  228. {
  229. mSunElevation = elevation;
  230. while( elevation < 0 )
  231. elevation += 360.0f;
  232. while( elevation >= 360.0f )
  233. elevation -= 360.0f;
  234. mTimeOfDay = elevation / 180.0f;
  235. mDirty = true;
  236. setMaskBits( TimeMask );
  237. }
  238. void ScatterSky::inspectPostApply()
  239. {
  240. mDirty = true;
  241. setMaskBits( 0xFFFFFFFF );
  242. }
  243. void ScatterSky::initPersistFields()
  244. {
  245. addGroup( "ScatterSky",
  246. "Only azimuth and elevation are networked fields. To trigger a full update of all other fields use the applyChanges ConsoleMethod." );
  247. addField( "skyBrightness", TypeF32, Offset( mSkyBrightness, ScatterSky ),
  248. "Global brightness and intensity applied to the sky and objects in the level." );
  249. addField( "sunSize", TypeF32, Offset( mSunSize, ScatterSky ),
  250. "Affects the size of the sun's disk." );
  251. addField( "colorizeAmount", TypeF32, Offset( mColorizeAmt, ScatterSky ),
  252. "Controls how much the the alpha component of colorize brigthens the sky. Setting to 0 returns default behavior." );
  253. addField( "colorize", TypeColorF, Offset( mColorize, ScatterSky ),
  254. "Tints the sky the color specified, the alpha controls the brigthness. The brightness is multipled by the value of colorizeAmt." );
  255. addField( "rayleighScattering", TypeF32, Offset( mRayleighScattering, ScatterSky ),
  256. "Controls how blue the atmosphere is during the day." );
  257. addField( "sunScale", TypeColorF, Offset( mSunScale, ScatterSky ),
  258. "Modulates the directional color of sunlight." );
  259. addField( "ambientScale", TypeColorF, Offset( mAmbientScale, ScatterSky ),
  260. "Modulates the ambient color of sunlight." );
  261. addField( "fogScale", TypeColorF, Offset( mFogScale, ScatterSky ),
  262. "Modulates the fog color. Note that this overrides the LevelInfo.fogColor "
  263. "property, so you should not use LevelInfo.fogColor if the level contains "
  264. "a ScatterSky object." );
  265. addField( "exposure", TypeF32, Offset( mExposure, ScatterSky ),
  266. "Controls the contrast of the sky and sun during daytime." );
  267. endGroup( "ScatterSky" );
  268. addGroup( "Orbit" );
  269. addProtectedField( "azimuth", TypeF32, Offset( mSunAzimuth, ScatterSky ), &ScatterSky::ptSetAzimuth, &defaultProtectedGetFn,
  270. "The horizontal angle of the sun measured clockwise from the positive Y world axis. This field is networked." );
  271. addProtectedField( "elevation", TypeF32, Offset( mSunElevation, ScatterSky ), &ScatterSky::ptSetElevation, &defaultProtectedGetFn,
  272. "The elevation angle of the sun above or below the horizon. This field is networked." );
  273. addField( "moonAzimuth", TypeF32, Offset( mMoonAzimuth, ScatterSky ),
  274. "The horizontal angle of the moon measured clockwise from the positive Y world axis. This is not animated by time or networked." );
  275. addField( "moonElevation", TypeF32, Offset( mMoonElevation, ScatterSky ),
  276. "The elevation angle of the moon above or below the horizon. This is not animated by time or networked." );
  277. endGroup( "Orbit" );
  278. // We only add the basic lighting options that all lighting
  279. // systems would use... the specific lighting system options
  280. // are injected at runtime by the lighting system itself.
  281. addGroup( "Lighting" );
  282. addField( "castShadows", TypeBool, Offset( mCastShadows, ScatterSky ),
  283. "Enables/disables shadows cast by objects due to ScatterSky light." );
  284. addField( "brightness", TypeF32, Offset( mBrightness, ScatterSky ),
  285. "The brightness of the ScatterSky's light object." );
  286. endGroup( "Lighting" );
  287. addGroup( "Misc" );
  288. addField( "flareType", TYPEID< LightFlareData >(), Offset( mFlareData, ScatterSky ),
  289. "Datablock for the flare produced by the ScatterSky." );
  290. addField( "flareScale", TypeF32, Offset( mFlareScale, ScatterSky ),
  291. "Changes the size and intensity of the flare." );
  292. endGroup( "Misc" );
  293. addGroup( "Night" );
  294. addField( "nightColor", TypeColorF, Offset( mNightColor, ScatterSky ),
  295. "The ambient color during night. Also used for the sky color if useNightCubemap is false." );
  296. addField( "nightFogColor", TypeColorF, Offset( mNightFogColor, ScatterSky ),
  297. "The fog color during night." );
  298. addField( "moonEnabled", TypeBool, Offset( mMoonEnabled, ScatterSky ),
  299. "Enable or disable rendering of the moon sprite during night." );
  300. addField( "moonMat", TypeMaterialName, Offset( mMoonMatName, ScatterSky ),
  301. "Material for the moon sprite." );
  302. addField( "moonScale", TypeF32, Offset( mMoonScale, ScatterSky ),
  303. "Controls size the moon sprite renders, specified as a fractional amount of the screen height." );
  304. addField( "moonLightColor", TypeColorF, Offset( mMoonTint, ScatterSky ),
  305. "Color of light cast by the directional light during night." );
  306. addField( "useNightCubemap", TypeBool, Offset( mUseNightCubemap, ScatterSky ),
  307. "Transition to the nightCubemap during night. If false we use nightColor." );
  308. addField( "nightCubemap", TypeCubemapName, Offset( mNightCubemapName, ScatterSky ),
  309. "Cubemap visible during night." );
  310. endGroup( "Night" );
  311. // Now inject any light manager specific fields.
  312. LightManager::initLightFields();
  313. Parent::initPersistFields();
  314. }
  315. U32 ScatterSky::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  316. {
  317. U32 retMask = Parent::packUpdate(con, mask, stream);
  318. if ( stream->writeFlag( mask & TimeMask ) )
  319. {
  320. stream->write( mSunAzimuth );
  321. stream->write( mSunElevation );
  322. }
  323. if ( stream->writeFlag( mask & UpdateMask ) )
  324. {
  325. stream->write( mRayleighScattering );
  326. mRayleighScattering4PI = mRayleighScattering * 4.0f * M_PI_F;
  327. stream->write( mRayleighScattering4PI );
  328. stream->write( mMieScattering );
  329. mMieScattering4PI = mMieScattering * 4.0f * M_PI_F;
  330. stream->write( mMieScattering4PI );
  331. stream->write( mSunSize );
  332. stream->write( mSkyBrightness );
  333. stream->write( mMiePhaseAssymetry );
  334. stream->write( mSphereInnerRadius );
  335. stream->write( mSphereOuterRadius );
  336. stream->write( mScale );
  337. stream->write( mWavelength );
  338. stream->write( mWavelength4[0] );
  339. stream->write( mWavelength4[1] );
  340. stream->write( mWavelength4[2] );
  341. stream->write( mRayleighScaleDepth );
  342. stream->write( mMieScaleDepth );
  343. stream->write( mNightColor );
  344. stream->write( mNightFogColor );
  345. stream->write( mAmbientScale );
  346. stream->write( mSunScale );
  347. stream->write( mFogScale );
  348. stream->write( mColorizeAmt );
  349. stream->write( mColorize );
  350. stream->write( mExposure );
  351. stream->write( mBrightness );
  352. stream->writeFlag( mCastShadows );
  353. stream->write( mFlareScale );
  354. if ( stream->writeFlag( mFlareData ) )
  355. {
  356. stream->writeRangedU32( mFlareData->getId(),
  357. DataBlockObjectIdFirst,
  358. DataBlockObjectIdLast );
  359. }
  360. stream->writeFlag( mMoonEnabled );
  361. stream->write( mMoonMatName );
  362. stream->write( mMoonScale );
  363. stream->write( mMoonTint );
  364. stream->writeFlag( mUseNightCubemap );
  365. stream->write( mNightCubemapName );
  366. stream->write( mMoonAzimuth );
  367. stream->write( mMoonElevation );
  368. mLight->packExtended( stream );
  369. }
  370. return retMask;
  371. }
  372. void ScatterSky::unpackUpdate(NetConnection *con, BitStream *stream)
  373. {
  374. Parent::unpackUpdate(con, stream);
  375. if ( stream->readFlag() ) // TimeMask
  376. {
  377. F32 temp = 0;
  378. stream->read( &temp );
  379. setAzimuth( temp );
  380. stream->read( &temp );
  381. setElevation( temp );
  382. }
  383. if ( stream->readFlag() ) // UpdateMask
  384. {
  385. stream->read( &mRayleighScattering );
  386. stream->read( &mRayleighScattering4PI );
  387. stream->read( &mMieScattering );
  388. stream->read( &mMieScattering4PI );
  389. stream->read( &mSunSize );
  390. stream->read( &mSkyBrightness );
  391. stream->read( &mMiePhaseAssymetry );
  392. stream->read( &mSphereInnerRadius );
  393. stream->read( &mSphereOuterRadius );
  394. stream->read( &mScale );
  395. ColorF tmpColor( 0, 0, 0 );
  396. stream->read( &tmpColor );
  397. stream->read( &mWavelength4[0] );
  398. stream->read( &mWavelength4[1] );
  399. stream->read( &mWavelength4[2] );
  400. stream->read( &mRayleighScaleDepth );
  401. stream->read( &mMieScaleDepth );
  402. stream->read( &mNightColor );
  403. stream->read( &mNightFogColor );
  404. stream->read( &mAmbientScale );
  405. stream->read( &mSunScale );
  406. stream->read( &mFogScale );
  407. F32 colorizeAmt;
  408. stream->read( &colorizeAmt );
  409. if(mColorizeAmt != colorizeAmt) {
  410. mColorizeAmt = colorizeAmt;
  411. mShader = NULL; //forces shader refresh
  412. }
  413. stream->read( &mColorize );
  414. if ( tmpColor != mWavelength )
  415. {
  416. mWavelength = tmpColor;
  417. mWavelength4[0] = mPow(mWavelength[0], 4.0f);
  418. mWavelength4[1] = mPow(mWavelength[1], 4.0f);
  419. mWavelength4[2] = mPow(mWavelength[2], 4.0f);
  420. }
  421. stream->read( &mExposure );
  422. stream->read( &mBrightness );
  423. mCastShadows = stream->readFlag();
  424. stream->read( &mFlareScale );
  425. if ( stream->readFlag() )
  426. {
  427. SimObjectId id = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  428. LightFlareData *datablock = NULL;
  429. if ( Sim::findObject( id, datablock ) )
  430. mFlareData = datablock;
  431. else
  432. {
  433. con->setLastError( "ScatterSky::unpackUpdate() - invalid LightFlareData!" );
  434. mFlareData = NULL;
  435. }
  436. }
  437. else
  438. mFlareData = NULL;
  439. mMoonEnabled = stream->readFlag();
  440. stream->read( &mMoonMatName );
  441. stream->read( &mMoonScale );
  442. stream->read( &mMoonTint );
  443. mUseNightCubemap = stream->readFlag();
  444. stream->read( &mNightCubemapName );
  445. stream->read( &mMoonAzimuth );
  446. stream->read( &mMoonElevation );
  447. mLight->unpackExtended( stream );
  448. if ( isProperlyAdded() )
  449. {
  450. mDirty = true;
  451. _initMoon();
  452. Sim::findObject( mNightCubemapName, mNightCubemap );
  453. }
  454. }
  455. }
  456. void ScatterSky::prepRenderImage( SceneRenderState *state )
  457. {
  458. // Only render into diffuse and reflect passes.
  459. if( !state->isDiffusePass() &&
  460. !state->isReflectPass() )
  461. return;
  462. // Regular sky render instance.
  463. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  464. ri->renderDelegate.bind( this, &ScatterSky::_render );
  465. ri->type = RenderPassManager::RIT_Sky;
  466. ri->defaultKey = 10;
  467. ri->defaultKey2 = 0;
  468. state->getRenderPass()->addInst( ri );
  469. // Debug render instance.
  470. /*
  471. if ( Con::getBoolVariable( "$ScatterSky::debug", false ) )
  472. {
  473. ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  474. ri->renderDelegate.bind( this, &ScatterSky::_debugRender );
  475. ri->type = RenderPassManager::RIT_Editor;
  476. state->getRenderPass()->addInst( ri );
  477. }
  478. */
  479. // Light flare effect render instance.
  480. if ( mFlareData && mNightInterpolant != 1.0f )
  481. {
  482. mFlareState.fullBrightness = mBrightness;
  483. mFlareState.scale = mFlareScale;
  484. mFlareState.lightInfo = mLight;
  485. Point3F lightPos = state->getCameraPosition() - state->getFarPlane() * mLight->getDirection() * 0.9f;
  486. mFlareState.lightMat.identity();
  487. mFlareState.lightMat.setPosition( lightPos );
  488. mFlareData->prepRender( state, &mFlareState );
  489. }
  490. // Render instances for Night effects.
  491. if ( mNightInterpolant <= 0.0f )
  492. return;
  493. // Render instance for Moon sprite.
  494. if ( mMoonEnabled && mMoonMatInst )
  495. {
  496. mMatrixSet->setSceneView(GFX->getWorldMatrix());
  497. mMatrixSet->setSceneProjection(GFX->getProjectionMatrix());
  498. mMatrixSet->setWorld(GFX->getWorldMatrix());
  499. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  500. ri->renderDelegate.bind( this, &ScatterSky::_renderMoon );
  501. ri->type = RenderPassManager::RIT_Sky;
  502. // Render after sky objects and before CloudLayer!
  503. ri->defaultKey = 5;
  504. ri->defaultKey2 = 0;
  505. state->getRenderPass()->addInst( ri );
  506. }
  507. }
  508. bool ScatterSky::_initShader()
  509. {
  510. ShaderData *shaderData;
  511. if ( !Sim::findObject( "ScatterSkyShaderData", shaderData ) )
  512. {
  513. Con::warnf( "ScatterSky::_initShader - failed to locate shader ScatterSkyShaderData!" );
  514. return false;
  515. }
  516. Vector<GFXShaderMacro> macros;
  517. if ( mColorizeAmt )
  518. macros.push_back( GFXShaderMacro( "USE_COLORIZE" ) );
  519. mShader = shaderData->getShader( macros );
  520. if ( !mShader )
  521. return false;
  522. if ( mStateBlock.isNull() )
  523. {
  524. GFXStateBlockData *data = NULL;
  525. if ( !Sim::findObject( "ScatterSkySBData", data ) )
  526. Con::warnf( "ScatterSky::_initShader - failed to locate ScatterSkySBData!" );
  527. else
  528. mStateBlock = GFX->createStateBlock( data->getState() );
  529. }
  530. if ( !mStateBlock )
  531. return false;
  532. mShaderConsts = mShader->allocConstBuffer();
  533. mModelViewProjSC = mShader->getShaderConstHandle( "$modelView" );
  534. // Camera height, cam height squared, scale and scale over depth.
  535. mMiscSC = mShader->getShaderConstHandle( "$misc" );
  536. // Inner and out radius, and inner and outer radius squared.
  537. mSphereRadiiSC = mShader->getShaderConstHandle( "$sphereRadii" );
  538. // Rayleigh sun brightness, mie sun brightness and 4 * PI * coefficients.
  539. mScatteringCoefficientsSC = mShader->getShaderConstHandle( "$scatteringCoeffs" );
  540. mCamPosSC = mShader->getShaderConstHandle( "$camPos" );
  541. mLightDirSC = mShader->getShaderConstHandle( "$lightDir" );
  542. mSunDirSC = mShader->getShaderConstHandle( "$sunDir" );
  543. mNightColorSC = mShader->getShaderConstHandle( "$nightColor" );
  544. mInverseWavelengthSC = mShader->getShaderConstHandle( "$invWaveLength" );
  545. mNightInterpolantAndExposureSC = mShader->getShaderConstHandle( "$nightInterpAndExposure" );
  546. mUseCubemapSC = mShader->getShaderConstHandle( "$useCubemap" );
  547. mColorizeSC = mShader->getShaderConstHandle( "$colorize" );
  548. return true;
  549. }
  550. void ScatterSky::_initVBIB()
  551. {
  552. // Vertex Buffer...
  553. U32 vertStride = 50;
  554. U32 strideMinusOne = vertStride - 1;
  555. mVertCount = vertStride * vertStride;
  556. mPrimCount = strideMinusOne * strideMinusOne * 2;
  557. Point3F vertScale( 16.0f, 16.0f, 4.0f );
  558. F32 zOffset = -( mCos( mSqrt( 1.0f ) ) + 0.01f );
  559. mVB.set( GFX, mVertCount, GFXBufferTypeStatic );
  560. ScatterSkyVertex *pVert = mVB.lock();
  561. if(!pVert) return;
  562. for ( U32 y = 0; y < vertStride; y++ )
  563. {
  564. F32 v = ( (F32)y / (F32)strideMinusOne - 0.5f ) * 2.0f;
  565. for ( U32 x = 0; x < vertStride; x++ )
  566. {
  567. F32 u = ( (F32)x / (F32)strideMinusOne - 0.5f ) * 2.0f;
  568. F32 sx = u;
  569. F32 sy = v;
  570. F32 sz = (mCos( mSqrt( sx*sx + sy*sy ) ) * 1.0f) + zOffset;
  571. //F32 sz = 1.0f;
  572. pVert->point.set( sx, sy, sz );
  573. pVert->point *= vertScale;
  574. pVert->point.normalize();
  575. pVert->point *= 200000.0f;
  576. pVert++;
  577. }
  578. }
  579. mVB.unlock();
  580. // Primitive Buffer...
  581. mPrimBuffer.set( GFX, mPrimCount * 3, mPrimCount, GFXBufferTypeStatic );
  582. U16 *pIdx = NULL;
  583. mPrimBuffer.lock(&pIdx);
  584. U32 curIdx = 0;
  585. for ( U32 y = 0; y < strideMinusOne; y++ )
  586. {
  587. for ( U32 x = 0; x < strideMinusOne; x++ )
  588. {
  589. U32 offset = x + y * vertStride;
  590. pIdx[curIdx] = offset;
  591. curIdx++;
  592. pIdx[curIdx] = offset + 1;
  593. curIdx++;
  594. pIdx[curIdx] = offset + vertStride + 1;
  595. curIdx++;
  596. pIdx[curIdx] = offset;
  597. curIdx++;
  598. pIdx[curIdx] = offset + vertStride + 1;
  599. curIdx++;
  600. pIdx[curIdx] = offset + vertStride;
  601. curIdx++;
  602. }
  603. }
  604. mPrimBuffer.unlock();
  605. }
  606. void ScatterSky::_initMoon()
  607. {
  608. if ( isServerObject() )
  609. return;
  610. if ( mMoonMatInst )
  611. SAFE_DELETE( mMoonMatInst );
  612. if ( mMoonMatName.isNotEmpty() )
  613. mMoonMatInst = MATMGR->createMatInstance( mMoonMatName, MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPCT>() );
  614. }
  615. void ScatterSky::_initCurves()
  616. {
  617. if ( mCurves->getSampleCount() > 0 )
  618. return;
  619. // Takes time of day (0-2) and returns
  620. // the night interpolant (0-1) day/night factor.
  621. // moonlight = 0, sunlight > 0
  622. mCurves[0].clear();
  623. mCurves[0].addPoint( 0.0f, 0.5f );// Sunrise
  624. mCurves[0].addPoint( 0.025f, 1.0f );//
  625. mCurves[0].addPoint( 0.975f, 1.0f );//
  626. mCurves[0].addPoint( 1.0f, 0.5f );//Sunset
  627. mCurves[0].addPoint( 1.02f, 0.0f );//Sunlight ends
  628. mCurves[0].addPoint( 1.98f, 0.0f );//Sunlight begins
  629. mCurves[0].addPoint( 2.0f, 0.5f );// Sunrise
  630. // Takes time of day (0-2) and returns mieScattering factor
  631. // Regulates the size of the sun's disk
  632. mCurves[1].clear();
  633. mCurves[1].addPoint( 0.0f, 0.0006f );
  634. mCurves[1].addPoint( 0.01f, 0.00035f );
  635. mCurves[1].addPoint( 0.03f, 0.00023f );
  636. mCurves[1].addPoint( 0.1f, 0.00022f );
  637. mCurves[1].addPoint( 0.2f, 0.00043f );
  638. mCurves[1].addPoint( 0.3f, 0.00062f );
  639. mCurves[1].addPoint( 0.4f, 0.0008f );
  640. mCurves[1].addPoint( 0.5f, 0.00086f );// High noon
  641. mCurves[1].addPoint( 0.6f, 0.0008f );
  642. mCurves[1].addPoint( 0.7f, 0.00062f );
  643. mCurves[1].addPoint( 0.8f, 0.00043f );
  644. mCurves[1].addPoint( 0.9f, 0.00022f );
  645. mCurves[1].addPoint( 0.97f, 0.00023f );
  646. mCurves[1].addPoint( 0.99f, 0.00035f );
  647. mCurves[1].addPoint( 1.0f, 0.0006f );
  648. mCurves[1].addPoint( 2.0f, 0.0006f );
  649. // Takes time of day and returns brightness
  650. // Controls sunlight and moonlight brightness
  651. mCurves[2].clear();
  652. mCurves[2].addPoint( 0.0f, 0.2f );// Sunrise
  653. mCurves[2].addPoint( 0.1f, 1.0f );
  654. mCurves[2].addPoint( 0.9f, 1.0f );// Sunset
  655. mCurves[2].addPoint( 1.008f, 0.0f );//Adjust end of sun's reflection
  656. mCurves[2].addPoint( 1.02001f, 0.0f );
  657. mCurves[2].addPoint( 1.05f, 0.5f );// Turn brightness up for moonlight
  658. mCurves[2].addPoint( 1.93f, 0.5f );
  659. mCurves[2].addPoint( 1.97999f, 0.0f );// No brightness when sunlight starts
  660. mCurves[2].addPoint( 1.992f, 0.0f );//Adjust start of sun's reflection
  661. mCurves[2].addPoint( 2.0f, 0.2f ); // Sunrise
  662. // Interpolation of day/night color sets
  663. // 0/1 ambient/nightcolor
  664. // 0 = day colors only anytime
  665. // 1 = night colors only anytime
  666. // between 0 and 1 renders both color sets anytime
  667. mCurves[3].clear();
  668. mCurves[3].addPoint( 0.0f, 0.8f );//Sunrise
  669. mCurves[3].addPoint( 0.1f, 0.0f );
  670. mCurves[3].addPoint( 0.99f, 0.0f );
  671. mCurves[3].addPoint( 1.0f, 0.8f );// Sunset
  672. mCurves[3].addPoint( 1.01999f, 1.0f );//
  673. mCurves[3].addPoint( 1.98001f, 1.0f );// Sunlight begins with full night colors
  674. mCurves[3].addPoint( 2.0f, 0.8f ); //Sunrise
  675. // Takes time of day (0-2) and returns smoothing factor
  676. // Interpolates between mMoonTint color and mNightColor
  677. mCurves[4].clear();
  678. mCurves[4].addPoint( 0.0f, 1.0f );
  679. mCurves[4].addPoint( 0.96f, 1.0f );
  680. mCurves[4].addPoint( 1.01999f, 0.5f );
  681. mCurves[4].addPoint( 1.02001f, 0.5f );
  682. mCurves[4].addPoint( 1.08f, 1.0f );
  683. mCurves[4].addPoint( 1.92f, 1.0f );
  684. mCurves[4].addPoint( 1.97999f, 0.5f );
  685. mCurves[4].addPoint( 1.98001f, 0.5f );
  686. mCurves[4].addPoint( 2.0f, 1.0f );
  687. }
  688. void ScatterSky::_updateTimeOfDay( TimeOfDay *timeOfDay, F32 time )
  689. {
  690. setElevation( timeOfDay->getElevationDegrees() );
  691. setAzimuth( timeOfDay->getAzimuthDegrees() );
  692. }
  693. void ScatterSky::_render( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  694. {
  695. if ( overrideMat || (!mShader && !_initShader()) )
  696. return;
  697. GFXTransformSaver saver;
  698. if ( mVB.isNull() || mPrimBuffer.isNull() )
  699. _initVBIB();
  700. GFX->setShader( mShader );
  701. GFX->setShaderConstBuffer( mShaderConsts );
  702. Point4F sphereRadii( mSphereOuterRadius, mSphereOuterRadius * mSphereOuterRadius,
  703. mSphereInnerRadius, mSphereInnerRadius * mSphereInnerRadius );
  704. Point4F scatteringCoeffs( mRayleighScattering * mSkyBrightness, mRayleighScattering4PI,
  705. mMieScattering * mSkyBrightness, mMieScattering4PI );
  706. Point4F invWavelength( 1.0f / mWavelength4[0],
  707. 1.0f / mWavelength4[1],
  708. 1.0f / mWavelength4[2], 1.0f );
  709. Point3F camPos( 0, 0, smViewerHeight );
  710. Point4F miscParams( camPos.z, camPos.z * camPos.z, mScale, mScale / mRayleighScaleDepth );
  711. Frustum frust = state->getCameraFrustum();
  712. frust.setFarDist( smEarthRadius + smAtmosphereRadius );
  713. MatrixF proj( true );
  714. frust.getProjectionMatrix( &proj );
  715. Point3F camPos2 = state->getCameraPosition();
  716. MatrixF xfm(true);
  717. xfm.setPosition(camPos2);//-Point3F( 0, 0, 200000.0f));
  718. GFX->multWorld(xfm);
  719. MatrixF xform(proj);//GFX->getProjectionMatrix());
  720. xform *= GFX->getViewMatrix();
  721. xform *= GFX->getWorldMatrix();
  722. mShaderConsts->setSafe( mModelViewProjSC, xform );
  723. mShaderConsts->setSafe( mMiscSC, miscParams );
  724. mShaderConsts->setSafe( mSphereRadiiSC, sphereRadii );
  725. mShaderConsts->setSafe( mScatteringCoefficientsSC, scatteringCoeffs );
  726. mShaderConsts->setSafe( mCamPosSC, camPos );
  727. mShaderConsts->setSafe( mLightDirSC, mLightDir );
  728. mShaderConsts->setSafe( mSunDirSC, mSunDir );
  729. mShaderConsts->setSafe( mNightColorSC, mNightColor );
  730. mShaderConsts->setSafe( mInverseWavelengthSC, invWavelength );
  731. mShaderConsts->setSafe( mNightInterpolantAndExposureSC, Point2F( mExposure, mNightInterpolant ) );
  732. mShaderConsts->setSafe( mColorizeSC, mColorize*mColorizeAmt );
  733. if ( GFXDevice::getWireframe() )
  734. {
  735. GFXStateBlockDesc desc( mStateBlock->getDesc() );
  736. desc.setFillModeWireframe();
  737. GFX->setStateBlockByDesc( desc );
  738. }
  739. else
  740. GFX->setStateBlock( mStateBlock );
  741. if ( mUseNightCubemap && mNightCubemap )
  742. {
  743. mShaderConsts->setSafe( mUseCubemapSC, 1.0f );
  744. if ( !mNightCubemap->mCubemap )
  745. mNightCubemap->createMap();
  746. GFX->setCubeTexture( 0, mNightCubemap->mCubemap );
  747. }
  748. else
  749. {
  750. GFX->setCubeTexture( 0, NULL );
  751. mShaderConsts->setSafe( mUseCubemapSC, 0.0f );
  752. }
  753. GFX->setPrimitiveBuffer( mPrimBuffer );
  754. GFX->setVertexBuffer( mVB );
  755. GFX->drawIndexedPrimitive( GFXTriangleList, 0, 0, mVertCount, 0, mPrimCount );
  756. }
  757. void ScatterSky::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  758. {
  759. GFXStateBlockDesc desc;
  760. desc.fillMode = GFXFillSolid;
  761. desc.setBlend( false, GFXBlendOne, GFXBlendZero );
  762. desc.setZReadWrite( false, false );
  763. GFXStateBlockRef sb = GFX->GFX->createStateBlock( desc );
  764. GFX->setStateBlock( sb );
  765. PrimBuild::begin( GFXLineStrip, mSkyPoints.size() );
  766. PrimBuild::color3i( 255, 0, 255 );
  767. for ( U32 i = 0; i < mSkyPoints.size(); i++ )
  768. {
  769. Point3F pnt = mSkyPoints[i];
  770. pnt.normalize();
  771. pnt *= 500;
  772. pnt += state->getCameraPosition();
  773. PrimBuild::vertex3fv( pnt );
  774. }
  775. PrimBuild::end();
  776. }
  777. void ScatterSky::_renderMoon( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  778. {
  779. if ( !mMoonMatInst )
  780. return;
  781. Point3F moonlightPosition = state->getCameraPosition() - /*mLight->getDirection()*/ mMoonLightDir * state->getFarPlane() * 0.9f;
  782. F32 dist = (moonlightPosition - state->getCameraPosition()).len();
  783. // worldRadius = screenRadius * dist / worldToScreen
  784. // screenRadius = worldRadius / dist * worldToScreen
  785. //
  786. F32 screenRadius = GFX->getViewport().extent.y * mMoonScale * 0.5f;
  787. F32 worldRadius = screenRadius * dist / state->getWorldToScreenScale().y;
  788. // Calculate Billboard Radius (in world units) to be constant, independent of distance.
  789. // Takes into account distance, viewport size, and specified size in editor
  790. F32 BBRadius = worldRadius;
  791. mMatrixSet->restoreSceneViewProjection();
  792. if ( state->isReflectPass() )
  793. mMatrixSet->setProjection( state->getSceneManager()->getNonClipProjection() );
  794. mMatrixSet->setWorld( MatrixF::Identity );
  795. // Initialize points with basic info
  796. Point3F points[4];
  797. points[0] = Point3F(-BBRadius, 0.0, -BBRadius);
  798. points[1] = Point3F( -BBRadius, 0.0, BBRadius);
  799. points[2] = Point3F( BBRadius, 0.0, BBRadius);
  800. points[3] = Point3F( BBRadius, 0.0, -BBRadius);
  801. static const Point2F sCoords[4] =
  802. {
  803. Point2F( 0.0f, 0.0f ),
  804. Point2F( 0.0f, 1.0f ),
  805. Point2F( 1.0f, 1.0f ),
  806. Point2F( 1.0f, 0.0f )
  807. };
  808. // Get info we need to adjust points
  809. const MatrixF &camView = state->getCameraTransform();
  810. // Finalize points
  811. for(S32 i = 0; i < 4; i++)
  812. {
  813. // align with camera
  814. camView.mulV(points[i]);
  815. // offset
  816. points[i] += moonlightPosition;
  817. }
  818. // Vertex color.
  819. ColorF moonVertColor( 1.0f, 1.0f, 1.0f, mNightInterpolant );
  820. // Copy points to buffer.
  821. GFXVertexBufferHandle< GFXVertexPCT > vb;
  822. vb.set( GFX, 4, GFXBufferTypeVolatile );
  823. GFXVertexPCT *pVert = vb.lock();
  824. if(!pVert) return;
  825. for ( S32 i = 0; i < 4; i++ )
  826. {
  827. pVert->color.set( moonVertColor );
  828. pVert->point.set( points[i] );
  829. pVert->texCoord.set( sCoords[i].x, sCoords[i].y );
  830. pVert++;
  831. }
  832. vb.unlock();
  833. // Setup SceneData struct.
  834. SceneData sgData;
  835. sgData.wireframe = GFXDevice::getWireframe();
  836. sgData.visibility = 1.0f;
  837. // Draw it
  838. while ( mMoonMatInst->setupPass( state, sgData ) )
  839. {
  840. mMoonMatInst->setTransforms( *mMatrixSet, state );
  841. mMoonMatInst->setSceneInfo( state, sgData );
  842. GFX->setVertexBuffer( vb );
  843. GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
  844. }
  845. }
  846. void ScatterSky::_generateSkyPoints()
  847. {
  848. U32 rings=60, segments=20;//rings=160, segments=20;
  849. Point3F tmpPoint( 0, 0, 0 );
  850. // Establish constants used in sphere generation.
  851. F32 deltaRingAngle = ( M_PI_F / (F32)(rings * 2) );
  852. F32 deltaSegAngle = ( 2.0f * M_PI_F / (F32)segments );
  853. // Generate the group of rings for the sphere.
  854. for( S32 ring = 0; ring < 2; ring++ )
  855. {
  856. F32 r0 = mSin( ring * deltaRingAngle );
  857. F32 y0 = mCos( ring * deltaRingAngle );
  858. // Generate the group of segments for the current ring.
  859. for( S32 seg = 0; seg < segments + 1 ; seg++ )
  860. {
  861. F32 x0 = r0 * sinf( seg * deltaSegAngle );
  862. F32 z0 = r0 * cosf( seg * deltaSegAngle );
  863. tmpPoint.set( x0, z0, y0 );
  864. tmpPoint.normalizeSafe();
  865. tmpPoint.x *= smEarthRadius + smAtmosphereRadius;
  866. tmpPoint.y *= smEarthRadius + smAtmosphereRadius;
  867. tmpPoint.z *= smEarthRadius + smAtmosphereRadius;
  868. tmpPoint.z -= smEarthRadius;
  869. if ( ring == 1 )
  870. mSkyPoints.push_back( tmpPoint );
  871. }
  872. }
  873. }
  874. void ScatterSky::_interpolateColors()
  875. {
  876. mFogColor.set( 0, 0, 0, 0 );
  877. mAmbientColor.set( 0, 0, 0, 0 );
  878. mSunColor.set( 0, 0, 0, 0 );
  879. _getFogColor( &mFogColor );
  880. _getAmbientColor( &mAmbientColor );
  881. _getSunColor( &mSunColor );
  882. mAmbientColor *= mAmbientScale;
  883. mSunColor *= mSunScale;
  884. mFogColor *= mFogScale;
  885. mMieScattering = (mCurves[1].getVal( mTimeOfDay) * mSunSize ); //Scale the size of the sun's disk
  886. ColorF moonTemp = mMoonTint;
  887. ColorF nightTemp = mNightColor;
  888. moonTemp.interpolate( mNightColor, mMoonTint, mCurves[4].getVal( mTimeOfDay ) );
  889. nightTemp.interpolate( mMoonTint, mNightColor, mCurves[4].getVal( mTimeOfDay ) );
  890. mFogColor.interpolate( mFogColor, mNightFogColor, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  891. mFogColor.alpha = 1.0f;
  892. mAmbientColor.interpolate( mAmbientColor, mNightColor, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  893. mSunColor.interpolate( mSunColor, mMoonTint, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  894. }
  895. void ScatterSky::_getSunColor( ColorF *outColor )
  896. {
  897. PROFILE_SCOPE( ScatterSky_GetSunColor );
  898. U32 count = 0;
  899. ColorF tmpColor( 0, 0, 0 );
  900. VectorF tmpVec( 0, 0, 0 );
  901. tmpVec = mLightDir;
  902. tmpVec.x *= smEarthRadius + smAtmosphereRadius;
  903. tmpVec.y *= smEarthRadius + smAtmosphereRadius;
  904. tmpVec.z *= smEarthRadius + smAtmosphereRadius;
  905. tmpVec.z -= smAtmosphereRadius;
  906. for ( U32 i = 0; i < 10; i++ )
  907. {
  908. _getColor( tmpVec, &tmpColor );
  909. (*outColor) += tmpColor;
  910. tmpVec.x += (smEarthRadius * 0.5f) + (smAtmosphereRadius * 0.5f);
  911. count++;
  912. }
  913. if ( count > 0 )
  914. (*outColor) /= count;
  915. }
  916. void ScatterSky::_getAmbientColor( ColorF *outColor )
  917. {
  918. PROFILE_SCOPE( ScatterSky_GetAmbientColor );
  919. ColorF tmpColor( 0, 0, 0, 0 );
  920. U32 count = 0;
  921. // Disable mieScattering for purposes of calculating the ambient color.
  922. F32 oldMieScattering = mMieScattering;
  923. mMieScattering = 0.0f;
  924. for ( U32 i = 0; i < mSkyPoints.size(); i++ )
  925. {
  926. Point3F pnt( mSkyPoints[i] );
  927. _getColor( pnt, &tmpColor );
  928. (*outColor) += tmpColor;
  929. count++;
  930. }
  931. if ( count > 0 )
  932. (*outColor) /= count;
  933. mMieScattering = oldMieScattering;
  934. }
  935. void ScatterSky::_getFogColor( ColorF *outColor )
  936. {
  937. PROFILE_SCOPE( ScatterSky_GetFogColor );
  938. VectorF scatterPos( 0, 0, 0 );
  939. F32 sunBrightness = mSkyBrightness;
  940. mSkyBrightness *= 0.25f;
  941. F32 yaw = 0, pitch = 0, originalYaw = 0;
  942. VectorF fwd( 0, 1.0f, 0 );
  943. MathUtils::getAnglesFromVector( fwd, yaw, pitch );
  944. originalYaw = yaw;
  945. pitch = mDegToRad( 10.0f );
  946. ColorF tmpColor( 0, 0, 0 );
  947. U32 i = 0;
  948. for ( i = 0; i < 10; i++ )
  949. {
  950. MathUtils::getVectorFromAngles( scatterPos, yaw, pitch );
  951. scatterPos.x *= smEarthRadius + smAtmosphereRadius;
  952. scatterPos.y *= smEarthRadius + smAtmosphereRadius;
  953. scatterPos.z *= smEarthRadius + smAtmosphereRadius;
  954. scatterPos.y -= smEarthRadius;
  955. _getColor( scatterPos, &tmpColor );
  956. (*outColor) += tmpColor;
  957. if ( i <= 5 )
  958. yaw += mDegToRad( 5.0f );
  959. else
  960. {
  961. originalYaw += mDegToRad( -5.0f );
  962. yaw = originalYaw;
  963. }
  964. yaw = mFmod( yaw, M_2PI_F );
  965. }
  966. if ( i > 0 )
  967. (*outColor) /= i;
  968. mSkyBrightness = sunBrightness;
  969. }
  970. F32 ScatterSky::_vernierScale( F32 fCos )
  971. {
  972. F32 x = 1.0 - fCos;
  973. return 0.25f * exp( -0.00287f + x * (0.459f + x * (3.83f + x * ((-6.80f + (x * 5.25f))))) );
  974. }
  975. F32 ScatterSky::_getMiePhase( F32 fCos, F32 fCos2, F32 g, F32 g2)
  976. {
  977. return 1.5f * ((1.0f - g2) / (2.0f + g2)) * (1.0f + fCos2) / mPow(mFabs(1.0f + g2 - 2.0f*g*fCos), 1.5f);
  978. }
  979. F32 ScatterSky::_getRayleighPhase( F32 fCos2 )
  980. {
  981. return 0.75 + 0.75 * fCos2;
  982. }
  983. void ScatterSky::_getColor( const Point3F &pos, ColorF *outColor )
  984. {
  985. PROFILE_SCOPE( ScatterSky_GetColor );
  986. F32 scaleOverScaleDepth = mScale / mRayleighScaleDepth;
  987. F32 rayleighBrightness = mRayleighScattering * mSkyBrightness;
  988. F32 mieBrightness = mMieScattering * mSkyBrightness;
  989. Point3F invWaveLength( 1.0f / mWavelength4[0],
  990. 1.0f / mWavelength4[1],
  991. 1.0f / mWavelength4[2] );
  992. Point3F v3Pos = pos / 6378000.0f;
  993. v3Pos.z += mSphereInnerRadius;
  994. Point3F newCamPos( 0, 0, smViewerHeight );
  995. VectorF v3Ray = v3Pos - newCamPos;
  996. F32 fFar = v3Ray.len();
  997. v3Ray / fFar;
  998. v3Ray.normalizeSafe();
  999. Point3F v3Start = newCamPos;
  1000. F32 fDepth = mExp( scaleOverScaleDepth * (mSphereInnerRadius - smViewerHeight ) );
  1001. F32 fStartAngle = mDot( v3Ray, v3Start );
  1002. F32 fStartOffset = fDepth * _vernierScale( fStartAngle );
  1003. F32 fSampleLength = fFar / 2.0f;
  1004. F32 fScaledLength = fSampleLength * mScale;
  1005. VectorF v3SampleRay = v3Ray * fSampleLength;
  1006. Point3F v3SamplePoint = v3Start + v3SampleRay * 0.5f;
  1007. Point3F v3FrontColor( 0, 0, 0 );
  1008. for ( U32 i = 0; i < 2; i++ )
  1009. {
  1010. F32 fHeight = v3SamplePoint.len();
  1011. F32 fDepth = mExp( scaleOverScaleDepth * (mSphereInnerRadius - smViewerHeight) );
  1012. F32 fLightAngle = mDot( mLightDir, v3SamplePoint ) / fHeight;
  1013. F32 fCameraAngle = mDot( v3Ray, v3SamplePoint ) / fHeight;
  1014. F32 fScatter = (fStartOffset + fDepth * ( _vernierScale( fLightAngle ) - _vernierScale( fCameraAngle ) ));
  1015. Point3F v3Attenuate( 0, 0, 0 );
  1016. F32 tmp = mExp( -fScatter * (invWaveLength[0] * mRayleighScattering4PI + mMieScattering4PI) );
  1017. v3Attenuate.x = tmp;
  1018. tmp = mExp( -fScatter * (invWaveLength[1] * mRayleighScattering4PI + mMieScattering4PI) );
  1019. v3Attenuate.y = tmp;
  1020. tmp = mExp( -fScatter * (invWaveLength[2] * mRayleighScattering4PI + mMieScattering4PI) );
  1021. v3Attenuate.z = tmp;
  1022. v3FrontColor += v3Attenuate * (fDepth * fScaledLength);
  1023. v3SamplePoint += v3SampleRay;
  1024. }
  1025. Point3F mieColor = v3FrontColor * mieBrightness;
  1026. Point3F rayleighColor = v3FrontColor * (invWaveLength * rayleighBrightness);
  1027. Point3F v3Direction = newCamPos - v3Pos;
  1028. v3Direction.normalize();
  1029. F32 fCos = mDot( mLightDir, v3Direction ) / v3Direction.len();
  1030. F32 fCos2 = fCos * fCos;
  1031. F32 g = -0.991f;
  1032. F32 g2 = g * g;
  1033. F32 miePhase = _getMiePhase( fCos, fCos2, g, g2 );
  1034. Point3F color = rayleighColor + (miePhase * mieColor);
  1035. ColorF tmp( color.x, color.y, color.z, color.y );
  1036. Point3F expColor( 0, 0, 0 );
  1037. expColor.x = 1.0f - exp(-mExposure * color.x);
  1038. expColor.y = 1.0f - exp(-mExposure * color.y);
  1039. expColor.z = 1.0f - exp(-mExposure * color.z);
  1040. tmp.set( expColor.x, expColor.y, expColor.z, 1.0f );
  1041. if ( !tmp.isValidColor() )
  1042. {
  1043. F32 len = expColor.len();
  1044. if ( len > 0 )
  1045. expColor /= len;
  1046. }
  1047. outColor->set( expColor.x, expColor.y, expColor.z, 1.0f );
  1048. }
  1049. // Static protected field set methods
  1050. bool ScatterSky::ptSetElevation( void *object, const char *index, const char *data )
  1051. {
  1052. ScatterSky *sky = static_cast<ScatterSky*>( object );
  1053. F32 val = dAtof( data );
  1054. sky->setElevation( val );
  1055. // we already set the field
  1056. return false;
  1057. }
  1058. bool ScatterSky::ptSetAzimuth( void *object, const char *index, const char *data )
  1059. {
  1060. ScatterSky *sky = static_cast<ScatterSky*>( object );
  1061. F32 val = dAtof( data );
  1062. sky->setAzimuth( val );
  1063. // we already set the field
  1064. return false;
  1065. }
  1066. void ScatterSky::_onSelected()
  1067. {
  1068. #ifdef TORQUE_DEBUG
  1069. // Enable debug rendering on the light.
  1070. if( isClientObject() )
  1071. mLight->enableDebugRendering( true );
  1072. #endif
  1073. Parent::_onSelected();
  1074. }
  1075. void ScatterSky::_onUnselected()
  1076. {
  1077. #ifdef TORQUE_DEBUG
  1078. // Disable debug rendering on the light.
  1079. if( isClientObject() )
  1080. mLight->enableDebugRendering( false );
  1081. #endif
  1082. Parent::_onUnselected();
  1083. }
  1084. // ConsoleMethods
  1085. DefineEngineMethod( ScatterSky, applyChanges, void, (),,
  1086. "Apply a full network update of all fields to all clients."
  1087. )
  1088. {
  1089. object->inspectPostApply();
  1090. }