scatterSky.cpp 43 KB

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