sun.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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 "environment/sun.h"
  24. #include "gfx/bitmap/gBitmap.h"
  25. #include "math/mathIO.h"
  26. #include "core/stream/bitStream.h"
  27. #include "console/consoleTypes.h"
  28. #include "console/engineAPI.h"
  29. #include "scene/sceneManager.h"
  30. #include "math/mathUtils.h"
  31. #include "lighting/lightInfo.h"
  32. #include "lighting/lightManager.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "renderInstance/renderPassManager.h"
  35. #include "sim/netConnection.h"
  36. #include "environment/timeOfDay.h"
  37. #include "gfx/gfxTransformSaver.h"
  38. #include "materials/materialManager.h"
  39. #include "materials/baseMatInstance.h"
  40. #include "materials/sceneData.h"
  41. #include "math/util/matrixSet.h"
  42. #include "materials/materialFeatureTypes.h"
  43. IMPLEMENT_CO_NETOBJECT_V1(Sun);
  44. ConsoleDocClass( Sun,
  45. "@brief A global light affecting your entire scene and optionally renders a corona effect.\n\n"
  46. "Sun is both the directional and ambient light for your entire scene.\n\n"
  47. "@ingroup Atmosphere"
  48. );
  49. //-----------------------------------------------------------------------------
  50. Sun::Sun()
  51. {
  52. mNetFlags.set(Ghostable | ScopeAlways);
  53. mTypeMask = EnvironmentObjectType | LightObjectType | StaticObjectType;
  54. mLightColor.set(0.7f, 0.7f, 0.7f);
  55. mLightAmbient.set(1.0f, 1.0f, 1.0f);
  56. mBrightness = 1.0f;
  57. mSunAzimuth = 0.0f;
  58. mSunElevation = 35.0f;
  59. mCastShadows = true;
  60. mStaticRefreshFreq = 250;
  61. mDynamicRefreshFreq = 8;
  62. mAnimateSun = false;
  63. mTotalTime = 0.0f;
  64. mCurrTime = 0.0f;
  65. mStartAzimuth = 0.0f;
  66. mEndAzimuth = 0.0f;
  67. mStartElevation = 0.0f;
  68. mEndElevation = 0.0f;
  69. mLight = LightManager::createLightInfo();
  70. mLight->setType( LightInfo::Vector );
  71. mFlareData = NULL;
  72. mFlareState.clear();
  73. mFlareScale = 1.0f;
  74. mCoronaEnabled = true;
  75. mCoronaScale = 0.5f;
  76. mCoronaTint.set( 1.0f, 1.0f, 1.0f, 1.0f );
  77. mCoronaUseLightColor = true;
  78. mCoronaMatInst = NULL;
  79. INIT_ASSET(CoronaMaterial);
  80. mMatrixSet = reinterpret_cast<MatrixSet *>(dMalloc_aligned(sizeof(MatrixSet), 16));
  81. constructInPlace(mMatrixSet);
  82. mCoronaWorldRadius = 0.0f;
  83. mLightWorldPos = Point3F::Zero;
  84. }
  85. Sun::~Sun()
  86. {
  87. SAFE_DELETE( mLight );
  88. SAFE_DELETE( mCoronaMatInst );
  89. dFree_aligned(mMatrixSet);
  90. }
  91. bool Sun::onAdd()
  92. {
  93. if ( !Parent::onAdd() )
  94. return false;
  95. // Register as listener to TimeOfDay update events
  96. TimeOfDay::getTimeOfDayUpdateSignal().notify( this, &Sun::_updateTimeOfDay );
  97. // Make this thing have a global bounds so that its
  98. // always returned from spatial light queries.
  99. setGlobalBounds();
  100. resetWorldBox();
  101. setRenderTransform( mObjToWorld );
  102. addToScene();
  103. _initCorona();
  104. // Update the light parameters.
  105. _conformLights();
  106. setProcessTick( true );
  107. return true;
  108. }
  109. void Sun::onRemove()
  110. {
  111. TimeOfDay::getTimeOfDayUpdateSignal().remove( this, &Sun::_updateTimeOfDay );
  112. removeFromScene();
  113. Parent::onRemove();
  114. }
  115. void Sun::initPersistFields()
  116. {
  117. docsURL;
  118. addGroup( "Orbit" );
  119. addFieldV( "azimuth", TypeRangedF32, Offset( mSunAzimuth, Sun ), &CommonValidators::PosDegreeRange,
  120. "The horizontal angle of the sun measured clockwise from the positive Y world axis." );
  121. addFieldV( "elevation", TypeRangedF32, Offset( mSunElevation, Sun ), &CommonValidators::DegreeRange,
  122. "The elevation angle of the sun above or below the horizon." );
  123. endGroup( "Orbit" );
  124. // We only add the basic lighting options that all lighting
  125. // systems would use... the specific lighting system options
  126. // are injected at runtime by the lighting system itself.
  127. addGroup( "Lighting" );
  128. addField( "color", TypeColorF, Offset( mLightColor, Sun ),
  129. "Color shading applied to surfaces in direct contact with light source.");
  130. addField( "ambient", TypeColorF, Offset( mLightAmbient, Sun ), "Color shading applied to surfaces not "
  131. "in direct contact with light source, such as in the shadows or interiors.");
  132. addFieldV( "brightness", TypeRangedF32, Offset( mBrightness, Sun ), &CommonValidators::PositiveFloat,
  133. "Adjust the Sun's global contrast/intensity");
  134. addField( "castShadows", TypeBool, Offset( mCastShadows, Sun ),
  135. "Enables/disables shadows cast by objects due to Sun light");
  136. //addField("staticRefreshFreq", TypeS32, Offset(mStaticRefreshFreq, Sun), "static shadow refresh rate (milliseconds)");
  137. //addField("dynamicRefreshFreq", TypeS32, Offset(mDynamicRefreshFreq, Sun), "dynamic shadow refresh rate (milliseconds)");
  138. endGroup( "Lighting" );
  139. addGroup( "Corona" );
  140. addField( "coronaEnabled", TypeBool, Offset( mCoronaEnabled, Sun ),
  141. "Enable or disable rendering of the corona sprite." );
  142. INITPERSISTFIELD_MATERIALASSET(CoronaMaterial, Sun, "Material for the corona sprite.");
  143. addFieldV( "coronaScale", TypeRangedF32, Offset( mCoronaScale, Sun ), &CommonValidators::PositiveFloat,
  144. "Controls size the corona sprite renders, specified as a fractional amount of the screen height." );
  145. addField( "coronaTint", TypeColorF, Offset( mCoronaTint, Sun ),
  146. "Modulates the corona sprite color ( if coronaUseLightColor is false )." );
  147. addField( "coronaUseLightColor", TypeBool, Offset( mCoronaUseLightColor, Sun ),
  148. "Modulate the corona sprite color by the color of the light ( overrides coronaTint )." );
  149. endGroup( "Corona" );
  150. addGroup( "Misc" );
  151. addField( "flareType", TYPEID< LightFlareData >(), Offset( mFlareData, Sun ),
  152. "Datablock for the flare produced by the Sun" );
  153. addFieldV( "flareScale", TypeRangedF32, Offset( mFlareScale, Sun ), &CommonValidators::PositiveFloat,
  154. "Changes the size and intensity of the flare." );
  155. endGroup( "Misc" );
  156. // Now inject any light manager specific fields.
  157. LightManager::initLightFields();
  158. Parent::initPersistFields();
  159. }
  160. void Sun::inspectPostApply()
  161. {
  162. _conformLights();
  163. setMaskBits(UpdateMask);
  164. }
  165. U32 Sun::packUpdate(NetConnection *conn, U32 mask, BitStream *stream )
  166. {
  167. U32 retMask = Parent::packUpdate( conn, mask, stream );
  168. if ( stream->writeFlag( mask & UpdateMask ) )
  169. {
  170. stream->write( mSunAzimuth );
  171. stream->write( mSunElevation );
  172. stream->write( mLightColor );
  173. stream->write( mLightAmbient );
  174. stream->write( mBrightness );
  175. stream->writeFlag( mCastShadows );
  176. stream->write(mStaticRefreshFreq);
  177. stream->write(mDynamicRefreshFreq);
  178. stream->write( mFlareScale );
  179. if ( stream->writeFlag( mFlareData ) )
  180. {
  181. stream->writeRangedU32( mFlareData->getId(),
  182. DataBlockObjectIdFirst,
  183. DataBlockObjectIdLast );
  184. }
  185. stream->writeFlag( mCoronaEnabled );
  186. PACK_ASSET(conn, CoronaMaterial);
  187. stream->write( mCoronaScale );
  188. stream->write( mCoronaTint );
  189. stream->writeFlag( mCoronaUseLightColor );
  190. mLight->packExtended( stream );
  191. }
  192. return retMask;
  193. }
  194. void Sun::unpackUpdate( NetConnection *conn, BitStream *stream )
  195. {
  196. Parent::unpackUpdate( conn, stream );
  197. if ( stream->readFlag() ) // UpdateMask
  198. {
  199. stream->read( &mSunAzimuth );
  200. stream->read( &mSunElevation );
  201. stream->read( &mLightColor );
  202. stream->read( &mLightAmbient );
  203. stream->read( &mBrightness );
  204. mCastShadows = stream->readFlag();
  205. stream->read(&mStaticRefreshFreq);
  206. stream->read(&mDynamicRefreshFreq);
  207. stream->read( &mFlareScale );
  208. if ( stream->readFlag() )
  209. {
  210. SimObjectId id = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  211. LightFlareData *datablock = NULL;
  212. if ( Sim::findObject( id, datablock ) )
  213. mFlareData = datablock;
  214. else
  215. {
  216. conn->setLastError( "Sun::unpackUpdate() - invalid LightFlareData!" );
  217. mFlareData = NULL;
  218. }
  219. }
  220. else
  221. mFlareData = NULL;
  222. mCoronaEnabled = stream->readFlag();
  223. UNPACK_ASSET(conn, CoronaMaterial);
  224. stream->read( &mCoronaScale );
  225. stream->read( &mCoronaTint );
  226. mCoronaUseLightColor = stream->readFlag();
  227. mLight->unpackExtended( stream );
  228. }
  229. if ( isProperlyAdded() )
  230. {
  231. _initCorona();
  232. _conformLights();
  233. }
  234. }
  235. void Sun::submitLights( LightManager *lm, bool staticLighting )
  236. {
  237. // The sun is a special light and needs special registration.
  238. lm->setSpecialLight( LightManager::slSunLightType, mLight );
  239. }
  240. void Sun::advanceTime( F32 timeDelta )
  241. {
  242. if (mAnimateSun)
  243. {
  244. if (mCurrTime >= mTotalTime)
  245. {
  246. mAnimateSun = false;
  247. mCurrTime = 0.0f;
  248. }
  249. else
  250. {
  251. mCurrTime += timeDelta;
  252. F32 fract = mCurrTime / mTotalTime;
  253. F32 inverse = 1.0f - fract;
  254. F32 newAzimuth = mStartAzimuth * inverse + mEndAzimuth * fract;
  255. F32 newElevation = mStartElevation * inverse + mEndElevation * fract;
  256. if (newAzimuth > 360.0f)
  257. newAzimuth -= 360.0f;
  258. if (newElevation > 360.0f)
  259. newElevation -= 360.0f;
  260. setAzimuth(newAzimuth);
  261. setElevation(newElevation);
  262. }
  263. }
  264. }
  265. void Sun::prepRenderImage( SceneRenderState *state )
  266. {
  267. // Only render into diffuse and reflect passes.
  268. if( !state->isDiffusePass() &&
  269. !state->isReflectPass() )
  270. return;
  271. mLightWorldPos = state->getCameraPosition() - state->getFarPlane() * mLight->getDirection() * 0.9f;
  272. F32 dist = ( mLightWorldPos - state->getCameraPosition() ).len();
  273. F32 screenRadius = GFX->getViewport().extent.y * mCoronaScale * 0.5f;
  274. mCoronaWorldRadius = screenRadius * dist / state->getWorldToScreenScale().y;
  275. // Render instance for Corona effect.
  276. if ( mCoronaEnabled && mCoronaMatInst )
  277. {
  278. mMatrixSet->setSceneProjection( GFX->getProjectionMatrix() );
  279. mMatrixSet->setSceneView( GFX->getViewMatrix() );
  280. mMatrixSet->setWorld( GFX->getWorldMatrix() );
  281. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  282. ri->renderDelegate.bind( this, &Sun::_renderCorona );
  283. ri->type = RenderPassManager::RIT_Sky;
  284. // Render after sky objects and before CloudLayer!
  285. ri->defaultKey = 5;
  286. ri->defaultKey2 = 0;
  287. state->getRenderPass()->addInst( ri );
  288. }
  289. // LightFlareData handles rendering flare effects.
  290. if ( mFlareData )
  291. {
  292. mFlareState.fullBrightness = mBrightness;
  293. mFlareState.scale = mFlareScale;
  294. mFlareState.lightInfo = mLight;
  295. mFlareState.worldRadius = mCoronaWorldRadius;
  296. mFlareState.lightMat.identity();
  297. mFlareState.lightMat.setPosition( mLightWorldPos );
  298. mFlareData->prepRender( state, &mFlareState );
  299. }
  300. }
  301. void Sun::setAzimuth( F32 azimuth )
  302. {
  303. mSunAzimuth = azimuth;
  304. _conformLights();
  305. setMaskBits( UpdateMask ); // TODO: Break out the masks to save bandwidth!
  306. }
  307. void Sun::setElevation( F32 elevation )
  308. {
  309. mSunElevation = elevation;
  310. _conformLights();
  311. setMaskBits( UpdateMask ); // TODO: Break out the masks to save some space!
  312. }
  313. void Sun::setColor( const LinearColorF &color )
  314. {
  315. mLightColor = color;
  316. _conformLights();
  317. setMaskBits( UpdateMask ); // TODO: Break out the masks to save some space!
  318. }
  319. void Sun::animate( F32 duration, F32 startAzimuth, F32 endAzimuth, F32 startElevation, F32 endElevation )
  320. {
  321. mAnimateSun = true;
  322. mCurrTime = 0.0f;
  323. mTotalTime = duration;
  324. mStartAzimuth = startAzimuth;
  325. mEndAzimuth = endAzimuth;
  326. mStartElevation = startElevation;
  327. mEndElevation = endElevation;
  328. }
  329. void Sun::_conformLights()
  330. {
  331. // Build the light direction from the azimuth and elevation.
  332. F32 yaw = mDegToRad(mClampF(mSunAzimuth,0,359));
  333. F32 pitch = mDegToRad(mClampF(mSunElevation,-360,+360));
  334. VectorF lightDirection;
  335. MathUtils::getVectorFromAngles(lightDirection, yaw, pitch);
  336. lightDirection.normalize();
  337. mLight->setDirection( -lightDirection );
  338. mLight->setBrightness( mBrightness );
  339. // Now make sure the colors are within range.
  340. mLightColor.clamp();
  341. mLight->setColor( mLightColor );
  342. mLightAmbient.clamp();
  343. mLight->setAmbient( mLightAmbient );
  344. // Optimization... disable shadows if the ambient and
  345. // directional color are the same.
  346. bool castShadows = mLightColor != mLightAmbient && mCastShadows;
  347. mLight->setCastShadows( castShadows );
  348. mLight->setStaticRefreshFreq(mStaticRefreshFreq);
  349. mLight->setDynamicRefreshFreq(mDynamicRefreshFreq);
  350. }
  351. void Sun::_initCorona()
  352. {
  353. if ( isServerObject() )
  354. return;
  355. SAFE_DELETE( mCoronaMatInst );
  356. if (mCoronaMaterialAsset.notNull())
  357. {
  358. FeatureSet features = MATMGR->getDefaultFeatures();
  359. features.removeFeature(MFT_RTLighting);
  360. features.removeFeature(MFT_Visibility);
  361. features.removeFeature(MFT_ReflectionProbes);
  362. features.addFeature(MFT_isBackground);
  363. features.addFeature(MFT_VertLit);
  364. mCoronaMatInst = MATMGR->createMatInstance(mCoronaMaterialAsset->getMaterialDefinitionName(), features, getGFXVertexFormat<GFXVertexPCT>());
  365. GFXStateBlockDesc desc;
  366. desc.setBlend(true);
  367. desc.setAlphaTest(true);
  368. desc.setZReadWrite(true, false);
  369. mCoronaMatInst->addStateBlockDesc(desc);
  370. mCoronaMatInst->init(features, getGFXVertexFormat<GFXVertexPCT>());
  371. }
  372. }
  373. void Sun::_renderCorona( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  374. {
  375. // Calculate Billboard Radius (in world units) to be constant, independent of distance.
  376. // Takes into account distance, viewport size, and specified size in editor
  377. F32 BBRadius = mCoronaWorldRadius;
  378. mMatrixSet->restoreSceneViewProjection();
  379. if ( state->isReflectPass() )
  380. mMatrixSet->setProjection( state->getSceneManager()->getNonClipProjection() );
  381. //mMatrixSet->setWorld( MatrixF::Identity );
  382. // Initialize points with basic info
  383. Point3F points[4];
  384. points[0] = Point3F(-BBRadius, 0.0, -BBRadius);
  385. points[1] = Point3F( -BBRadius, 0.0, BBRadius);
  386. points[2] = Point3F( BBRadius, 0.0, -BBRadius);
  387. points[3] = Point3F(BBRadius, 0.0, BBRadius);
  388. static const Point2F sCoords[4] =
  389. {
  390. Point2F( 0.0f, 0.0f ),
  391. Point2F( 0.0f, 1.0f ),
  392. Point2F( 1.0f, 0.0f ),
  393. Point2F(1.0f, 1.0f)
  394. };
  395. // Get info we need to adjust points
  396. const MatrixF &camView = state->getCameraTransform();
  397. // Finalize points
  398. for(S32 i = 0; i < 4; i++)
  399. {
  400. // align with camera
  401. camView.mulV(points[i]);
  402. // offset
  403. points[i] += mLightWorldPos;
  404. }
  405. LinearColorF vertColor;
  406. if ( mCoronaUseLightColor )
  407. vertColor = mLightColor;
  408. else
  409. vertColor = mCoronaTint;
  410. GFXVertexBufferHandle< GFXVertexPCT > vb;
  411. vb.set( GFX, 4, GFXBufferTypeVolatile );
  412. GFXVertexPCT *pVert = vb.lock();
  413. if(!pVert) return;
  414. for ( S32 i = 0; i < 4; i++ )
  415. {
  416. pVert->color.set( vertColor.toColorI());
  417. pVert->point.set( points[i] );
  418. pVert->texCoord.set( sCoords[i].x, sCoords[i].y );
  419. pVert++;
  420. }
  421. vb.unlock();
  422. // Setup SceneData struct.
  423. SceneData sgData;
  424. sgData.wireframe = GFXDevice::getWireframe();
  425. sgData.visibility = 1.0f;
  426. // Draw it
  427. while ( mCoronaMatInst->setupPass( state, sgData ) )
  428. {
  429. mCoronaMatInst->setTransforms( *mMatrixSet, state );
  430. mCoronaMatInst->setSceneInfo( state, sgData );
  431. GFX->setVertexBuffer( vb );
  432. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  433. }
  434. }
  435. void Sun::_updateTimeOfDay( TimeOfDay *timeOfDay, F32 time )
  436. {
  437. setElevation( timeOfDay->getElevationDegrees() );
  438. setAzimuth( timeOfDay->getAzimuthDegrees() );
  439. }
  440. void Sun::_onSelected()
  441. {
  442. #ifdef TORQUE_DEBUG
  443. // Enable debug rendering on the light.
  444. if( isClientObject() )
  445. mLight->enableDebugRendering( true );
  446. #endif
  447. Parent::_onSelected();
  448. }
  449. void Sun::_onUnselected()
  450. {
  451. #ifdef TORQUE_DEBUG
  452. // Disable debug rendering on the light.
  453. if( isClientObject() )
  454. mLight->enableDebugRendering( false );
  455. #endif
  456. Parent::_onUnselected();
  457. }
  458. DefineEngineMethod(Sun, apply, void, (), , "")
  459. {
  460. object->inspectPostApply();
  461. }
  462. DefineEngineMethod(Sun, animate, void, ( F32 duration, F32 startAzimuth, F32 endAzimuth, F32 startElevation, F32 endElevation ), , "animate( F32 duration, F32 startAzimuth, F32 endAzimuth, F32 startElevation, F32 endElevation )")
  463. {
  464. object->animate(duration, startAzimuth, endAzimuth, startElevation, endElevation);
  465. }