scatterSky.cpp 46 KB

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