scatterSky.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  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. for ( U32 y = 0; y < vertStride; y++ )
  562. {
  563. F32 v = ( (F32)y / (F32)strideMinusOne - 0.5f ) * 2.0f;
  564. for ( U32 x = 0; x < vertStride; x++ )
  565. {
  566. F32 u = ( (F32)x / (F32)strideMinusOne - 0.5f ) * 2.0f;
  567. F32 sx = u;
  568. F32 sy = v;
  569. F32 sz = (mCos( mSqrt( sx*sx + sy*sy ) ) * 1.0f) + zOffset;
  570. //F32 sz = 1.0f;
  571. pVert->point.set( sx, sy, sz );
  572. pVert->point *= vertScale;
  573. pVert->point.normalize();
  574. pVert->point *= 200000.0f;
  575. pVert++;
  576. }
  577. }
  578. mVB.unlock();
  579. // Primitive Buffer...
  580. mPrimBuffer.set( GFX, mPrimCount * 3, mPrimCount, GFXBufferTypeStatic );
  581. U16 *pIdx = NULL;
  582. mPrimBuffer.lock(&pIdx);
  583. U32 curIdx = 0;
  584. for ( U32 y = 0; y < strideMinusOne; y++ )
  585. {
  586. for ( U32 x = 0; x < strideMinusOne; x++ )
  587. {
  588. U32 offset = x + y * vertStride;
  589. pIdx[curIdx] = offset;
  590. curIdx++;
  591. pIdx[curIdx] = offset + 1;
  592. curIdx++;
  593. pIdx[curIdx] = offset + vertStride + 1;
  594. curIdx++;
  595. pIdx[curIdx] = offset;
  596. curIdx++;
  597. pIdx[curIdx] = offset + vertStride + 1;
  598. curIdx++;
  599. pIdx[curIdx] = offset + vertStride;
  600. curIdx++;
  601. }
  602. }
  603. mPrimBuffer.unlock();
  604. }
  605. void ScatterSky::_initMoon()
  606. {
  607. if ( isServerObject() )
  608. return;
  609. if ( mMoonMatInst )
  610. SAFE_DELETE( mMoonMatInst );
  611. if ( mMoonMatName.isNotEmpty() )
  612. mMoonMatInst = MATMGR->createMatInstance( mMoonMatName, MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPCT>() );
  613. }
  614. void ScatterSky::_initCurves()
  615. {
  616. if ( mCurves->getSampleCount() > 0 )
  617. return;
  618. // Takes time of day (0-2) and returns
  619. // the night interpolant (0-1) day/night factor.
  620. // moonlight = 0, sunlight > 0
  621. mCurves[0].clear();
  622. mCurves[0].addPoint( 0.0f, 0.5f );// Sunrise
  623. mCurves[0].addPoint( 0.025f, 1.0f );//
  624. mCurves[0].addPoint( 0.975f, 1.0f );//
  625. mCurves[0].addPoint( 1.0f, 0.5f );//Sunset
  626. mCurves[0].addPoint( 1.02f, 0.0f );//Sunlight ends
  627. mCurves[0].addPoint( 1.98f, 0.0f );//Sunlight begins
  628. mCurves[0].addPoint( 2.0f, 0.5f );// Sunrise
  629. // Takes time of day (0-2) and returns mieScattering factor
  630. // Regulates the size of the sun's disk
  631. mCurves[1].clear();
  632. mCurves[1].addPoint( 0.0f, 0.0006f );
  633. mCurves[1].addPoint( 0.01f, 0.00035f );
  634. mCurves[1].addPoint( 0.03f, 0.00023f );
  635. mCurves[1].addPoint( 0.1f, 0.00022f );
  636. mCurves[1].addPoint( 0.2f, 0.00043f );
  637. mCurves[1].addPoint( 0.3f, 0.00062f );
  638. mCurves[1].addPoint( 0.4f, 0.0008f );
  639. mCurves[1].addPoint( 0.5f, 0.00086f );// High noon
  640. mCurves[1].addPoint( 0.6f, 0.0008f );
  641. mCurves[1].addPoint( 0.7f, 0.00062f );
  642. mCurves[1].addPoint( 0.8f, 0.00043f );
  643. mCurves[1].addPoint( 0.9f, 0.00022f );
  644. mCurves[1].addPoint( 0.97f, 0.00023f );
  645. mCurves[1].addPoint( 0.99f, 0.00035f );
  646. mCurves[1].addPoint( 1.0f, 0.0006f );
  647. mCurves[1].addPoint( 2.0f, 0.0006f );
  648. // Takes time of day and returns brightness
  649. // Controls sunlight and moonlight brightness
  650. mCurves[2].clear();
  651. mCurves[2].addPoint( 0.0f, 0.2f );// Sunrise
  652. mCurves[2].addPoint( 0.1f, 1.0f );
  653. mCurves[2].addPoint( 0.9f, 1.0f );// Sunset
  654. mCurves[2].addPoint( 1.008f, 0.0f );//Adjust end of sun's reflection
  655. mCurves[2].addPoint( 1.02001f, 0.0f );
  656. mCurves[2].addPoint( 1.05f, 0.5f );// Turn brightness up for moonlight
  657. mCurves[2].addPoint( 1.93f, 0.5f );
  658. mCurves[2].addPoint( 1.97999f, 0.0f );// No brightness when sunlight starts
  659. mCurves[2].addPoint( 1.992f, 0.0f );//Adjust start of sun's reflection
  660. mCurves[2].addPoint( 2.0f, 0.2f ); // Sunrise
  661. // Interpolation of day/night color sets
  662. // 0/1 ambient/nightcolor
  663. // 0 = day colors only anytime
  664. // 1 = night colors only anytime
  665. // between 0 and 1 renders both color sets anytime
  666. mCurves[3].clear();
  667. mCurves[3].addPoint( 0.0f, 0.8f );//Sunrise
  668. mCurves[3].addPoint( 0.1f, 0.0f );
  669. mCurves[3].addPoint( 0.99f, 0.0f );
  670. mCurves[3].addPoint( 1.0f, 0.8f );// Sunset
  671. mCurves[3].addPoint( 1.01999f, 1.0f );//
  672. mCurves[3].addPoint( 1.98001f, 1.0f );// Sunlight begins with full night colors
  673. mCurves[3].addPoint( 2.0f, 0.8f ); //Sunrise
  674. // Takes time of day (0-2) and returns smoothing factor
  675. // Interpolates between mMoonTint color and mNightColor
  676. mCurves[4].clear();
  677. mCurves[4].addPoint( 0.0f, 1.0f );
  678. mCurves[4].addPoint( 0.96f, 1.0f );
  679. mCurves[4].addPoint( 1.01999f, 0.5f );
  680. mCurves[4].addPoint( 1.02001f, 0.5f );
  681. mCurves[4].addPoint( 1.08f, 1.0f );
  682. mCurves[4].addPoint( 1.92f, 1.0f );
  683. mCurves[4].addPoint( 1.97999f, 0.5f );
  684. mCurves[4].addPoint( 1.98001f, 0.5f );
  685. mCurves[4].addPoint( 2.0f, 1.0f );
  686. }
  687. void ScatterSky::_updateTimeOfDay( TimeOfDay *timeOfDay, F32 time )
  688. {
  689. setElevation( timeOfDay->getElevationDegrees() );
  690. setAzimuth( timeOfDay->getAzimuthDegrees() );
  691. }
  692. void ScatterSky::_render( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  693. {
  694. if ( overrideMat || (!mShader && !_initShader()) )
  695. return;
  696. GFXTransformSaver saver;
  697. if ( mVB.isNull() || mPrimBuffer.isNull() )
  698. _initVBIB();
  699. GFX->setShader( mShader );
  700. GFX->setShaderConstBuffer( mShaderConsts );
  701. Point4F sphereRadii( mSphereOuterRadius, mSphereOuterRadius * mSphereOuterRadius,
  702. mSphereInnerRadius, mSphereInnerRadius * mSphereInnerRadius );
  703. Point4F scatteringCoeffs( mRayleighScattering * mSkyBrightness, mRayleighScattering4PI,
  704. mMieScattering * mSkyBrightness, mMieScattering4PI );
  705. Point4F invWavelength( 1.0f / mWavelength4[0],
  706. 1.0f / mWavelength4[1],
  707. 1.0f / mWavelength4[2], 1.0f );
  708. Point3F camPos( 0, 0, smViewerHeight );
  709. Point4F miscParams( camPos.z, camPos.z * camPos.z, mScale, mScale / mRayleighScaleDepth );
  710. Frustum frust = state->getFrustum();
  711. frust.setFarDist( smEarthRadius + smAtmosphereRadius );
  712. MatrixF proj( true );
  713. frust.getProjectionMatrix( &proj );
  714. Point3F camPos2 = state->getCameraPosition();
  715. MatrixF xfm(true);
  716. xfm.setPosition(camPos2);//-Point3F( 0, 0, 200000.0f));
  717. GFX->multWorld(xfm);
  718. MatrixF xform(proj);//GFX->getProjectionMatrix());
  719. xform *= GFX->getViewMatrix();
  720. xform *= GFX->getWorldMatrix();
  721. mShaderConsts->setSafe( mModelViewProjSC, xform );
  722. mShaderConsts->setSafe( mMiscSC, miscParams );
  723. mShaderConsts->setSafe( mSphereRadiiSC, sphereRadii );
  724. mShaderConsts->setSafe( mScatteringCoefficientsSC, scatteringCoeffs );
  725. mShaderConsts->setSafe( mCamPosSC, camPos );
  726. mShaderConsts->setSafe( mLightDirSC, mLightDir );
  727. mShaderConsts->setSafe( mSunDirSC, mSunDir );
  728. mShaderConsts->setSafe( mNightColorSC, mNightColor );
  729. mShaderConsts->setSafe( mInverseWavelengthSC, invWavelength );
  730. mShaderConsts->setSafe( mNightInterpolantAndExposureSC, Point2F( mExposure, mNightInterpolant ) );
  731. mShaderConsts->setSafe( mColorizeSC, mColorize*mColorizeAmt );
  732. if ( GFXDevice::getWireframe() )
  733. {
  734. GFXStateBlockDesc desc( mStateBlock->getDesc() );
  735. desc.setFillModeWireframe();
  736. GFX->setStateBlockByDesc( desc );
  737. }
  738. else
  739. GFX->setStateBlock( mStateBlock );
  740. if ( mUseNightCubemap && mNightCubemap )
  741. {
  742. mShaderConsts->setSafe( mUseCubemapSC, 1.0f );
  743. if ( !mNightCubemap->mCubemap )
  744. mNightCubemap->createMap();
  745. GFX->setCubeTexture( 0, mNightCubemap->mCubemap );
  746. }
  747. else
  748. {
  749. GFX->setCubeTexture( 0, NULL );
  750. mShaderConsts->setSafe( mUseCubemapSC, 0.0f );
  751. }
  752. GFX->setPrimitiveBuffer( mPrimBuffer );
  753. GFX->setVertexBuffer( mVB );
  754. GFX->drawIndexedPrimitive( GFXTriangleList, 0, 0, mVertCount, 0, mPrimCount );
  755. }
  756. void ScatterSky::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  757. {
  758. GFXStateBlockDesc desc;
  759. desc.fillMode = GFXFillSolid;
  760. desc.setBlend( false, GFXBlendOne, GFXBlendZero );
  761. desc.setZReadWrite( false, false );
  762. GFXStateBlockRef sb = GFX->GFX->createStateBlock( desc );
  763. GFX->setStateBlock( sb );
  764. PrimBuild::begin( GFXLineStrip, mSkyPoints.size() );
  765. PrimBuild::color3i( 255, 0, 255 );
  766. for ( U32 i = 0; i < mSkyPoints.size(); i++ )
  767. {
  768. Point3F pnt = mSkyPoints[i];
  769. pnt.normalize();
  770. pnt *= 500;
  771. pnt += state->getCameraPosition();
  772. PrimBuild::vertex3fv( pnt );
  773. }
  774. PrimBuild::end();
  775. }
  776. void ScatterSky::_renderMoon( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  777. {
  778. if ( !mMoonMatInst )
  779. return;
  780. Point3F moonlightPosition = state->getCameraPosition() - /*mLight->getDirection()*/ mMoonLightDir * state->getFarPlane() * 0.9f;
  781. F32 dist = (moonlightPosition - state->getCameraPosition()).len();
  782. // worldRadius = screenRadius * dist / worldToScreen
  783. // screenRadius = worldRadius / dist * worldToScreen
  784. //
  785. F32 screenRadius = GFX->getViewport().extent.y * mMoonScale * 0.5f;
  786. F32 worldRadius = screenRadius * dist / state->getWorldToScreenScale().y;
  787. // Calculate Billboard Radius (in world units) to be constant, independent of distance.
  788. // Takes into account distance, viewport size, and specified size in editor
  789. F32 BBRadius = worldRadius;
  790. mMatrixSet->restoreSceneViewProjection();
  791. if ( state->isReflectPass() )
  792. mMatrixSet->setProjection( state->getSceneManager()->getNonClipProjection() );
  793. mMatrixSet->setWorld( MatrixF::Identity );
  794. // Initialize points with basic info
  795. Point3F points[4];
  796. points[0] = Point3F(-BBRadius, 0.0, -BBRadius);
  797. points[1] = Point3F( -BBRadius, 0.0, BBRadius);
  798. points[2] = Point3F( BBRadius, 0.0, BBRadius);
  799. points[3] = Point3F( BBRadius, 0.0, -BBRadius);
  800. static const Point2F sCoords[4] =
  801. {
  802. Point2F( 0.0f, 0.0f ),
  803. Point2F( 0.0f, 1.0f ),
  804. Point2F( 1.0f, 1.0f ),
  805. Point2F( 1.0f, 0.0f )
  806. };
  807. // Get info we need to adjust points
  808. const MatrixF &camView = state->getCameraTransform();
  809. // Finalize points
  810. for(int i = 0; i < 4; i++)
  811. {
  812. // align with camera
  813. camView.mulV(points[i]);
  814. // offset
  815. points[i] += moonlightPosition;
  816. }
  817. // Vertex color.
  818. ColorF moonVertColor( 1.0f, 1.0f, 1.0f, mNightInterpolant );
  819. // Copy points to buffer.
  820. GFXVertexBufferHandle< GFXVertexPCT > vb;
  821. vb.set( GFX, 4, GFXBufferTypeVolatile );
  822. GFXVertexPCT *pVert = vb.lock();
  823. for ( S32 i = 0; i < 4; i++ )
  824. {
  825. pVert->color.set( moonVertColor );
  826. pVert->point.set( points[i] );
  827. pVert->texCoord.set( sCoords[i].x, sCoords[i].y );
  828. pVert++;
  829. }
  830. vb.unlock();
  831. // Setup SceneData struct.
  832. SceneData sgData;
  833. sgData.wireframe = GFXDevice::getWireframe();
  834. sgData.visibility = 1.0f;
  835. // Draw it
  836. while ( mMoonMatInst->setupPass( state, sgData ) )
  837. {
  838. mMoonMatInst->setTransforms( *mMatrixSet, state );
  839. mMoonMatInst->setSceneInfo( state, sgData );
  840. GFX->setVertexBuffer( vb );
  841. GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
  842. }
  843. }
  844. void ScatterSky::_generateSkyPoints()
  845. {
  846. U32 rings=60, segments=20;//rings=160, segments=20;
  847. Point3F tmpPoint( 0, 0, 0 );
  848. // Establish constants used in sphere generation.
  849. F32 deltaRingAngle = ( M_PI_F / (F32)(rings * 2) );
  850. F32 deltaSegAngle = ( 2.0f * M_PI_F / (F32)segments );
  851. // Generate the group of rings for the sphere.
  852. for( int ring = 0; ring < 2; ring++ )
  853. {
  854. F32 r0 = mSin( ring * deltaRingAngle );
  855. F32 y0 = mCos( ring * deltaRingAngle );
  856. // Generate the group of segments for the current ring.
  857. for( int seg = 0; seg < segments + 1 ; seg++ )
  858. {
  859. F32 x0 = r0 * sinf( seg * deltaSegAngle );
  860. F32 z0 = r0 * cosf( seg * deltaSegAngle );
  861. tmpPoint.set( x0, z0, y0 );
  862. tmpPoint.normalizeSafe();
  863. tmpPoint.x *= smEarthRadius + smAtmosphereRadius;
  864. tmpPoint.y *= smEarthRadius + smAtmosphereRadius;
  865. tmpPoint.z *= smEarthRadius + smAtmosphereRadius;
  866. tmpPoint.z -= smEarthRadius;
  867. if ( ring == 1 )
  868. mSkyPoints.push_back( tmpPoint );
  869. }
  870. }
  871. }
  872. void ScatterSky::_interpolateColors()
  873. {
  874. mFogColor.set( 0, 0, 0, 0 );
  875. mAmbientColor.set( 0, 0, 0, 0 );
  876. mSunColor.set( 0, 0, 0, 0 );
  877. _getFogColor( &mFogColor );
  878. _getAmbientColor( &mAmbientColor );
  879. _getSunColor( &mSunColor );
  880. mAmbientColor *= mAmbientScale;
  881. mSunColor *= mSunScale;
  882. mFogColor *= mFogScale;
  883. mMieScattering = (mCurves[1].getVal( mTimeOfDay) * mSunSize ); //Scale the size of the sun's disk
  884. ColorF moonTemp = mMoonTint;
  885. ColorF nightTemp = mNightColor;
  886. moonTemp.interpolate( mNightColor, mMoonTint, mCurves[4].getVal( mTimeOfDay ) );
  887. nightTemp.interpolate( mMoonTint, mNightColor, mCurves[4].getVal( mTimeOfDay ) );
  888. mFogColor.interpolate( mFogColor, mNightFogColor, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  889. mFogColor.alpha = 1.0f;
  890. mAmbientColor.interpolate( mAmbientColor, mNightColor, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  891. mSunColor.interpolate( mSunColor, mMoonTint, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  892. }
  893. void ScatterSky::_getSunColor( ColorF *outColor )
  894. {
  895. PROFILE_SCOPE( ScatterSky_GetSunColor );
  896. U32 count = 0;
  897. ColorF tmpColor( 0, 0, 0 );
  898. VectorF tmpVec( 0, 0, 0 );
  899. tmpVec = mLightDir;
  900. tmpVec.x *= smEarthRadius + smAtmosphereRadius;
  901. tmpVec.y *= smEarthRadius + smAtmosphereRadius;
  902. tmpVec.z *= smEarthRadius + smAtmosphereRadius;
  903. tmpVec.z -= smAtmosphereRadius;
  904. for ( U32 i = 0; i < 10; i++ )
  905. {
  906. _getColor( tmpVec, &tmpColor );
  907. (*outColor) += tmpColor;
  908. tmpVec.x += (smEarthRadius * 0.5f) + (smAtmosphereRadius * 0.5f);
  909. count++;
  910. }
  911. if ( count > 0 )
  912. (*outColor) /= count;
  913. }
  914. void ScatterSky::_getAmbientColor( ColorF *outColor )
  915. {
  916. PROFILE_SCOPE( ScatterSky_GetAmbientColor );
  917. ColorF tmpColor( 0, 0, 0, 0 );
  918. U32 count = 0;
  919. // Disable mieScattering for purposes of calculating the ambient color.
  920. F32 oldMieScattering = mMieScattering;
  921. mMieScattering = 0.0f;
  922. for ( U32 i = 0; i < mSkyPoints.size(); i++ )
  923. {
  924. Point3F pnt( mSkyPoints[i] );
  925. _getColor( pnt, &tmpColor );
  926. (*outColor) += tmpColor;
  927. count++;
  928. }
  929. if ( count > 0 )
  930. (*outColor) /= count;
  931. mMieScattering = oldMieScattering;
  932. }
  933. void ScatterSky::_getFogColor( ColorF *outColor )
  934. {
  935. PROFILE_SCOPE( ScatterSky_GetFogColor );
  936. VectorF scatterPos( 0, 0, 0 );
  937. F32 sunBrightness = mSkyBrightness;
  938. mSkyBrightness *= 0.25f;
  939. F32 yaw = 0, pitch = 0, originalYaw = 0;
  940. VectorF fwd( 0, 1.0f, 0 );
  941. MathUtils::getAnglesFromVector( fwd, yaw, pitch );
  942. originalYaw = yaw;
  943. pitch = mDegToRad( 10.0f );
  944. ColorF tmpColor( 0, 0, 0 );
  945. U32 i = 0;
  946. for ( i = 0; i < 10; i++ )
  947. {
  948. MathUtils::getVectorFromAngles( scatterPos, yaw, pitch );
  949. scatterPos.x *= smEarthRadius + smAtmosphereRadius;
  950. scatterPos.y *= smEarthRadius + smAtmosphereRadius;
  951. scatterPos.z *= smEarthRadius + smAtmosphereRadius;
  952. scatterPos.y -= smEarthRadius;
  953. _getColor( scatterPos, &tmpColor );
  954. (*outColor) += tmpColor;
  955. if ( i <= 5 )
  956. yaw += mDegToRad( 5.0f );
  957. else
  958. {
  959. originalYaw += mDegToRad( -5.0f );
  960. yaw = originalYaw;
  961. }
  962. yaw = mFmod( yaw, M_2PI_F );
  963. }
  964. if ( i > 0 )
  965. (*outColor) /= i;
  966. mSkyBrightness = sunBrightness;
  967. }
  968. F32 ScatterSky::_vernierScale( F32 fCos )
  969. {
  970. F32 x = 1.0 - fCos;
  971. return 0.25f * exp( -0.00287f + x * (0.459f + x * (3.83f + x * ((-6.80f + (x * 5.25f))))) );
  972. }
  973. F32 ScatterSky::_getMiePhase( F32 fCos, F32 fCos2, F32 g, F32 g2)
  974. {
  975. return 1.5f * ((1.0f - g2) / (2.0f + g2)) * (1.0f + fCos2) / mPow(mFabs(1.0f + g2 - 2.0f*g*fCos), 1.5f);
  976. }
  977. F32 ScatterSky::_getRayleighPhase( F32 fCos2 )
  978. {
  979. return 0.75 + 0.75 * fCos2;
  980. }
  981. void ScatterSky::_getColor( const Point3F &pos, ColorF *outColor )
  982. {
  983. PROFILE_SCOPE( ScatterSky_GetColor );
  984. F32 scaleOverScaleDepth = mScale / mRayleighScaleDepth;
  985. F32 rayleighBrightness = mRayleighScattering * mSkyBrightness;
  986. F32 mieBrightness = mMieScattering * mSkyBrightness;
  987. Point3F invWaveLength( 1.0f / mWavelength4[0],
  988. 1.0f / mWavelength4[1],
  989. 1.0f / mWavelength4[2] );
  990. Point3F v3Pos = pos / 6378000.0f;
  991. v3Pos.z += mSphereInnerRadius;
  992. Point3F newCamPos( 0, 0, smViewerHeight );
  993. VectorF v3Ray = v3Pos - newCamPos;
  994. F32 fFar = v3Ray.len();
  995. v3Ray / fFar;
  996. v3Ray.normalizeSafe();
  997. Point3F v3Start = newCamPos;
  998. F32 fDepth = mExp( scaleOverScaleDepth * (mSphereInnerRadius - smViewerHeight ) );
  999. F32 fStartAngle = mDot( v3Ray, v3Start );
  1000. F32 fStartOffset = fDepth * _vernierScale( fStartAngle );
  1001. F32 fSampleLength = fFar / 2.0f;
  1002. F32 fScaledLength = fSampleLength * mScale;
  1003. VectorF v3SampleRay = v3Ray * fSampleLength;
  1004. Point3F v3SamplePoint = v3Start + v3SampleRay * 0.5f;
  1005. Point3F v3FrontColor( 0, 0, 0 );
  1006. for ( U32 i = 0; i < 2; i++ )
  1007. {
  1008. F32 fHeight = v3SamplePoint.len();
  1009. F32 fDepth = mExp( scaleOverScaleDepth * (mSphereInnerRadius - smViewerHeight) );
  1010. F32 fLightAngle = mDot( mLightDir, v3SamplePoint ) / fHeight;
  1011. F32 fCameraAngle = mDot( v3Ray, v3SamplePoint ) / fHeight;
  1012. F32 fScatter = (fStartOffset + fDepth * ( _vernierScale( fLightAngle ) - _vernierScale( fCameraAngle ) ));
  1013. Point3F v3Attenuate( 0, 0, 0 );
  1014. F32 tmp = mExp( -fScatter * (invWaveLength[0] * mRayleighScattering4PI + mMieScattering4PI) );
  1015. v3Attenuate.x = tmp;
  1016. tmp = mExp( -fScatter * (invWaveLength[1] * mRayleighScattering4PI + mMieScattering4PI) );
  1017. v3Attenuate.y = tmp;
  1018. tmp = mExp( -fScatter * (invWaveLength[2] * mRayleighScattering4PI + mMieScattering4PI) );
  1019. v3Attenuate.z = tmp;
  1020. v3FrontColor += v3Attenuate * (fDepth * fScaledLength);
  1021. v3SamplePoint += v3SampleRay;
  1022. }
  1023. Point3F mieColor = v3FrontColor * mieBrightness;
  1024. Point3F rayleighColor = v3FrontColor * (invWaveLength * rayleighBrightness);
  1025. Point3F v3Direction = newCamPos - v3Pos;
  1026. v3Direction.normalize();
  1027. F32 fCos = mDot( mLightDir, v3Direction ) / v3Direction.len();
  1028. F32 fCos2 = fCos * fCos;
  1029. F32 g = -0.991f;
  1030. F32 g2 = g * g;
  1031. F32 miePhase = _getMiePhase( fCos, fCos2, g, g2 );
  1032. Point3F color = rayleighColor + (miePhase * mieColor);
  1033. ColorF tmp( color.x, color.y, color.z, color.y );
  1034. Point3F expColor( 0, 0, 0 );
  1035. expColor.x = 1.0f - exp(-mExposure * color.x);
  1036. expColor.y = 1.0f - exp(-mExposure * color.y);
  1037. expColor.z = 1.0f - exp(-mExposure * color.z);
  1038. tmp.set( expColor.x, expColor.y, expColor.z, 1.0f );
  1039. if ( !tmp.isValidColor() )
  1040. {
  1041. F32 len = expColor.len();
  1042. if ( len > 0 )
  1043. expColor /= len;
  1044. }
  1045. outColor->set( expColor.x, expColor.y, expColor.z, 1.0f );
  1046. }
  1047. // Static protected field set methods
  1048. bool ScatterSky::ptSetElevation( void *object, const char *index, const char *data )
  1049. {
  1050. ScatterSky *sky = static_cast<ScatterSky*>( object );
  1051. F32 val = dAtof( data );
  1052. sky->setElevation( val );
  1053. // we already set the field
  1054. return false;
  1055. }
  1056. bool ScatterSky::ptSetAzimuth( void *object, const char *index, const char *data )
  1057. {
  1058. ScatterSky *sky = static_cast<ScatterSky*>( object );
  1059. F32 val = dAtof( data );
  1060. sky->setAzimuth( val );
  1061. // we already set the field
  1062. return false;
  1063. }
  1064. void ScatterSky::_onSelected()
  1065. {
  1066. #ifdef TORQUE_DEBUG
  1067. // Enable debug rendering on the light.
  1068. if( isClientObject() )
  1069. mLight->enableDebugRendering( true );
  1070. #endif
  1071. Parent::_onSelected();
  1072. }
  1073. void ScatterSky::_onUnselected()
  1074. {
  1075. #ifdef TORQUE_DEBUG
  1076. // Disable debug rendering on the light.
  1077. if( isClientObject() )
  1078. mLight->enableDebugRendering( false );
  1079. #endif
  1080. Parent::_onUnselected();
  1081. }
  1082. // ConsoleMethods
  1083. DefineEngineMethod( ScatterSky, applyChanges, void, (),,
  1084. "Apply a full network update of all fields to all clients."
  1085. )
  1086. {
  1087. object->inspectPostApply();
  1088. }