scatterSky.cpp 42 KB

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