scatterSky.cpp 46 KB

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