sun.cpp 17 KB

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