sun.cpp 16 KB

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