scatterSky.cpp 43 KB

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