groundPlane.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/groundPlane.h"
  28. #include "renderInstance/renderPassManager.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "materials/sceneData.h"
  31. #include "materials/materialDefinition.h"
  32. #include "materials/materialManager.h"
  33. #include "materials/baseMatInstance.h"
  34. #include "math/util/frustum.h"
  35. #include "math/mPlane.h"
  36. #include "console/consoleTypes.h"
  37. #include "console/engineAPI.h"
  38. #include "core/stream/bitStream.h"
  39. #include "collision/boxConvex.h"
  40. #include "collision/abstractPolyList.h"
  41. #include "T3D/physics/physicsPlugin.h"
  42. #include "T3D/physics/physicsBody.h"
  43. #include "T3D/physics/physicsCollision.h"
  44. #ifdef TORQUE_AFX_ENABLED
  45. #include "afx/ce/afxZodiacMgr.h"
  46. #endif
  47. /// Minimum square size allowed. This is a cheap way to limit the amount
  48. /// of geometry possibly generated by the GroundPlane (vertex buffers have a
  49. /// limit, too). Dynamically clipping extents into range is a problem since the
  50. /// location of the horizon depends on the camera orientation. Just shifting
  51. /// squareSize as needed also doesn't work as that causes different geometry to
  52. /// be generated depending on the viewpoint and orientation which affects the
  53. /// texturing.
  54. static const F32 sMIN_SQUARE_SIZE = 16;
  55. IMPLEMENT_CO_NETOBJECT_V1( GroundPlane );
  56. ConsoleDocClass( GroundPlane,
  57. "@brief An infinite plane extending in all direction.\n\n"
  58. "%GroundPlane is useful for setting up simple testing scenes, or it can be "
  59. "placed under an existing scene to keep objects from falling into 'nothing'.\n\n"
  60. "%GroundPlane may not be moved or rotated, it is always at the world origin.\n\n"
  61. "@ingroup Terrain"
  62. );
  63. GroundPlane::GroundPlane()
  64. : mSquareSize( 128.0f ),
  65. mScaleU( 1.0f ),
  66. mScaleV( 1.0f ),
  67. mMaterial( NULL ),
  68. mMaterialInst(NULL),
  69. mPhysicsRep( NULL ),
  70. mMin( 0.0f, 0.0f ),
  71. mMax( 0.0f, 0.0f )
  72. {
  73. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  74. mNetFlags.set( Ghostable | ScopeAlways );
  75. mConvexList = new Convex;
  76. mTypeMask |= TerrainLikeObjectType;
  77. INIT_ASSET(Material);
  78. }
  79. GroundPlane::~GroundPlane()
  80. {
  81. mMaterial = nullptr;
  82. if(mMaterialInst)
  83. SAFE_DELETE(mMaterialInst);
  84. mConvexList->nukeList();
  85. SAFE_DELETE( mConvexList );
  86. }
  87. void GroundPlane::initPersistFields()
  88. {
  89. docsURL;
  90. addGroup( "Plane" );
  91. addField( "squareSize", TypeF32, Offset( mSquareSize, GroundPlane ), "Square size in meters to which %GroundPlane subdivides its geometry." );
  92. addField( "scaleU", TypeF32, Offset( mScaleU, GroundPlane ), "Scale of texture repeat in the U direction." );
  93. addField( "scaleV", TypeF32, Offset( mScaleV, GroundPlane ), "Scale of texture repeat in the V direction." );
  94. INITPERSISTFIELD_MATERIALASSET(Material, GroundPlane, "The material used to render the ground plane.");
  95. endGroup( "Plane" );
  96. Parent::initPersistFields();
  97. removeField( "scale" );
  98. removeField( "position" );
  99. removeField( "rotation" );
  100. }
  101. bool GroundPlane::onAdd()
  102. {
  103. if( !Parent::onAdd() )
  104. return false;
  105. if( isClientObject() )
  106. _updateMaterial();
  107. if( mSquareSize < sMIN_SQUARE_SIZE )
  108. {
  109. Con::errorf( "GroundPlane - squareSize below threshold; re-setting to %.02f", sMIN_SQUARE_SIZE );
  110. mSquareSize = sMIN_SQUARE_SIZE;
  111. }
  112. Parent::setScale( VectorF( 1.0f, 1.0f, 1.0f ) );
  113. Parent::setTransform( MatrixF::Identity );
  114. setGlobalBounds();
  115. resetWorldBox();
  116. addToScene();
  117. if ( PHYSICSMGR )
  118. {
  119. PhysicsCollision *colShape = PHYSICSMGR->createCollision();
  120. colShape->addPlane( PlaneF( Point3F::Zero, Point3F( 0, 0, 1 ) ) );
  121. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  122. mPhysicsRep = PHYSICSMGR->createBody();
  123. mPhysicsRep->init( colShape, 0, 0, this, world );
  124. }
  125. return true;
  126. }
  127. void GroundPlane::onRemove()
  128. {
  129. if (!mMaterialAsset.isNull())
  130. AssetDatabase.releaseAsset(mMaterialAsset.getAssetId());
  131. //SAFE_DELETE(mMaterialInst);
  132. SAFE_DELETE( mPhysicsRep );
  133. removeFromScene();
  134. Parent::onRemove();
  135. }
  136. void GroundPlane::inspectPostApply()
  137. {
  138. Parent::inspectPostApply();
  139. setMaskBits( U32( -1 ) );
  140. if( mSquareSize < sMIN_SQUARE_SIZE )
  141. {
  142. Con::errorf( "GroundPlane - squareSize below threshold; re-setting to %.02f", sMIN_SQUARE_SIZE );
  143. mSquareSize = sMIN_SQUARE_SIZE;
  144. }
  145. setScale( VectorF( 1.0f, 1.0f, 1.0f ) );
  146. }
  147. void GroundPlane::setTransform( const MatrixF &mat )
  148. {
  149. // Ignore.
  150. }
  151. void GroundPlane::setScale( const Point3F& scale )
  152. {
  153. // Ignore.
  154. }
  155. U32 GroundPlane::packUpdate( NetConnection* connection, U32 mask, BitStream* stream )
  156. {
  157. U32 retMask = Parent::packUpdate( connection, mask, stream );
  158. stream->write( mSquareSize );
  159. stream->write( mScaleU );
  160. stream->write( mScaleV );
  161. PACK_ASSET(connection, Material);
  162. return retMask;
  163. }
  164. void GroundPlane::unpackUpdate( NetConnection* connection, BitStream* stream )
  165. {
  166. Parent::unpackUpdate( connection, stream );
  167. stream->read( &mSquareSize );
  168. stream->read( &mScaleU );
  169. stream->read( &mScaleV );
  170. UNPACK_ASSET(connection, Material);
  171. // If we're added then something possibly changed in
  172. // the editor... do an update of the material and the
  173. // geometry.
  174. if ( isProperlyAdded() )
  175. {
  176. _updateMaterial();
  177. mVertexBuffer = NULL;
  178. }
  179. }
  180. void GroundPlane::_updateMaterial()
  181. {
  182. if (mMaterialAsset.notNull())
  183. {
  184. if (mMaterialInst && String(mMaterialAsset->getMaterialDefinitionName()).equal(mMaterialInst->getMaterial()->getName(), String::NoCase))
  185. return;
  186. SAFE_DELETE(mMaterialInst);
  187. mMaterialInst = MATMGR->createMatInstance(mMaterialAsset->getMaterialDefinitionName(), getGFXVertexFormat< VertexType >());
  188. if (!mMaterialInst)
  189. Con::errorf("GroundPlane::_updateMaterial - no Material called '%s'", mMaterialAsset->getMaterialDefinitionName());
  190. }
  191. }
  192. bool GroundPlane::castRay( const Point3F& start, const Point3F& end, RayInfo* info )
  193. {
  194. PlaneF plane( Point3F( 0.0f, 0.0f, 0.0f ), Point3F( 0.0f, 0.0f, 1.0f ) );
  195. F32 t = plane.intersect( start, end );
  196. if( t >= 0.0 && t <= 1.0 )
  197. {
  198. info->t = t;
  199. info->setContactPoint( start, end );
  200. info->normal.set( 0, 0, 1 );
  201. info->material = mMaterialInst;
  202. info->object = this;
  203. info->distance = 0;
  204. info->faceDot = 0;
  205. info->texCoord.set( 0, 0 );
  206. return true;
  207. }
  208. return false;
  209. }
  210. void GroundPlane::buildConvex( const Box3F& box, Convex* convex )
  211. {
  212. mConvexList->collectGarbage();
  213. Box3F planeBox = getPlaneBox();
  214. if ( !box.isOverlapped( planeBox ) )
  215. return;
  216. // See if we already have a convex in the working set.
  217. BoxConvex *boxConvex = NULL;
  218. CollisionWorkingList &wl = convex->getWorkingList();
  219. CollisionWorkingList *itr = wl.wLink.mNext;
  220. for ( ; itr != &wl; itr = itr->wLink.mNext )
  221. {
  222. if ( itr->mConvex->getType() == BoxConvexType &&
  223. itr->mConvex->getObject() == this )
  224. {
  225. boxConvex = (BoxConvex*)itr->mConvex;
  226. break;
  227. }
  228. }
  229. if ( !boxConvex )
  230. {
  231. boxConvex = new BoxConvex;
  232. mConvexList->registerObject( boxConvex );
  233. boxConvex->init( this );
  234. convex->addToWorkingList( boxConvex );
  235. }
  236. // Update our convex to best match the queried box
  237. if ( boxConvex )
  238. {
  239. Point3F queryCenter = box.getCenter();
  240. boxConvex->mCenter = Point3F( queryCenter.x, queryCenter.y, -GROUND_PLANE_BOX_HEIGHT_HALF );
  241. boxConvex->mSize = Point3F( box.getExtents().x,
  242. box.getExtents().y,
  243. GROUND_PLANE_BOX_HEIGHT_HALF );
  244. }
  245. }
  246. bool GroundPlane::buildPolyList( PolyListContext context, AbstractPolyList* polyList, const Box3F& box, const SphereF& )
  247. {
  248. polyList->setObject( this );
  249. polyList->setTransform( &MatrixF::Identity, Point3F( 1.0f, 1.0f, 1.0f ) );
  250. if(context == PLC_Navigation)
  251. {
  252. F32 z = getPosition().z;
  253. Point3F
  254. p0(box.minExtents.x, box.maxExtents.y, z),
  255. p1(box.maxExtents.x, box.maxExtents.y, z),
  256. p2(box.maxExtents.x, box.minExtents.y, z),
  257. p3(box.minExtents.x, box.minExtents.y, z);
  258. // Add vertices to poly list.
  259. U32 v0 = polyList->addPoint(p0);
  260. polyList->addPoint(p1);
  261. polyList->addPoint(p2);
  262. polyList->addPoint(p3);
  263. // Add plane between first three vertices.
  264. polyList->begin(0, 0);
  265. polyList->vertex(v0);
  266. polyList->vertex(v0+1);
  267. polyList->vertex(v0+2);
  268. polyList->plane(v0, v0+1, v0+2);
  269. polyList->end();
  270. // Add plane between last three vertices.
  271. polyList->begin(0, 1);
  272. polyList->vertex(v0+2);
  273. polyList->vertex(v0+3);
  274. polyList->vertex(v0);
  275. polyList->plane(v0+2, v0+3, v0);
  276. polyList->end();
  277. return true;
  278. }
  279. Box3F planeBox = getPlaneBox();
  280. polyList->addBox( planeBox, mMaterialInst );
  281. return true;
  282. }
  283. void GroundPlane::prepRenderImage( SceneRenderState* state )
  284. {
  285. PROFILE_SCOPE( GroundPlane_prepRenderImage );
  286. // TODO: Should we skip rendering the ground plane into
  287. // the shadows? Its not like you can ever get under it.
  288. if ( !mMaterial )
  289. return;
  290. // If we don't have a material instance after the override then
  291. // we can skip rendering all together.
  292. BaseMatInstance *matInst = state->getOverrideMaterial(mMaterialInst);
  293. if ( !matInst )
  294. return;
  295. PROFILE_SCOPE( GroundPlane_prepRender );
  296. // Update the geometry.
  297. createGeometry( state->getCullingFrustum() );
  298. if( mVertexBuffer.isNull() )
  299. return;
  300. #ifdef TORQUE_AFX_ENABLED
  301. afxZodiacMgr::renderGroundPlaneZodiacs(state, this);
  302. #endif
  303. // Add a render instance.
  304. RenderPassManager* pass = state->getRenderPass();
  305. MeshRenderInst* ri = pass->allocInst< MeshRenderInst >();
  306. ri->type = RenderPassManager::RIT_Mesh;
  307. ri->vertBuff = &mVertexBuffer;
  308. ri->primBuff = &mPrimitiveBuffer;
  309. ri->prim = &mPrimitive;
  310. ri->matInst = matInst;
  311. ri->objectToWorld = pass->allocUniqueXform( MatrixF::Identity );
  312. ri->worldToCamera = pass->allocSharedXform( RenderPassManager::View );
  313. ri->projection = pass->allocSharedXform( RenderPassManager::Projection );
  314. ri->visibility = 1.0f;
  315. ri->translucentSort = matInst->getMaterial()->isTranslucent();
  316. ri->defaultKey = matInst->getStateHint();
  317. if( ri->translucentSort )
  318. ri->type = RenderPassManager::RIT_Translucent;
  319. // If we need lights then set them up.
  320. if ( matInst->isForwardLit() )
  321. {
  322. LightQuery query;
  323. query.init( getWorldSphere() );
  324. query.getLights( ri->lights, 8 );
  325. }
  326. pass->addInst( ri );
  327. }
  328. /// Generate a subset of the ground plane matching the given frustum.
  329. void GroundPlane::createGeometry( const Frustum& frustum )
  330. {
  331. PROFILE_SCOPE( GroundPlane_createGeometry );
  332. enum { MAX_WIDTH = 256, MAX_HEIGHT = 256 };
  333. // Project the frustum onto the XY grid.
  334. Point2F min;
  335. Point2F max;
  336. projectFrustum( frustum, mSquareSize, min, max );
  337. // Early out if the grid projection hasn't changed.
  338. if( mVertexBuffer.isValid() &&
  339. min == mMin &&
  340. max == mMax )
  341. return;
  342. mMin = min;
  343. mMax = max;
  344. // Determine the grid extents and allocate the buffers.
  345. // Adjust square size permanently if with the given frustum,
  346. // we end up producing more than a certain limit of geometry.
  347. // This is to prevent this code from causing trouble with
  348. // long viewing distances.
  349. // This only affects the client object, of course, and thus
  350. // has no permanent effect.
  351. U32 width = mCeil( ( max.x - min.x ) / mSquareSize );
  352. if( width > MAX_WIDTH )
  353. {
  354. mSquareSize = mCeil( ( max.x - min.x ) / MAX_WIDTH );
  355. width = MAX_WIDTH;
  356. }
  357. else if( !width )
  358. width = 1;
  359. U32 height = mCeil( ( max.y - min.y ) / mSquareSize );
  360. if( height > MAX_HEIGHT )
  361. {
  362. mSquareSize = mCeil( ( max.y - min.y ) / MAX_HEIGHT );
  363. height = MAX_HEIGHT;
  364. }
  365. else if( !height )
  366. height = 1;
  367. const U32 numVertices = ( width + 1 ) * ( height + 1 );
  368. const U32 numTriangles = width * height * 2;
  369. // Only reallocate if the buffers are too small.
  370. if ( mVertexBuffer.isNull() || numVertices > mVertexBuffer->mNumVerts )
  371. {
  372. mVertexBuffer.set( GFX, numVertices, GFXBufferTypeDynamic );
  373. }
  374. if ( mPrimitiveBuffer.isNull() || numTriangles > mPrimitiveBuffer->mPrimitiveCount )
  375. {
  376. mPrimitiveBuffer.set( GFX, numTriangles*3, numTriangles, GFXBufferTypeDynamic );
  377. }
  378. // Generate the grid.
  379. generateGrid( width, height, mSquareSize, min, max, mVertexBuffer, mPrimitiveBuffer );
  380. // Set up GFX primitive.
  381. mPrimitive.type = GFXTriangleList;
  382. mPrimitive.numPrimitives = numTriangles;
  383. mPrimitive.numVertices = numVertices;
  384. }
  385. /// Project the given frustum onto the ground plane and return the XY bounds in world space.
  386. void GroundPlane::projectFrustum( const Frustum& frustum, F32 squareSize, Point2F& outMin, Point2F& outMax )
  387. {
  388. // Get the frustum's min and max XY coordinates.
  389. const Box3F bounds = frustum.getBounds();
  390. Point2F minPt( bounds.minExtents.x, bounds.minExtents.y );
  391. Point2F maxPt( bounds.maxExtents.x, bounds.maxExtents.y );
  392. // Round the min and max coordinates so they align on the grid.
  393. minPt.x -= mFmod( minPt.x, squareSize );
  394. minPt.y -= mFmod( minPt.y, squareSize );
  395. F32 maxDeltaX = mFmod( maxPt.x, squareSize );
  396. F32 maxDeltaY = mFmod( maxPt.y, squareSize );
  397. if( maxDeltaX != 0.0f )
  398. maxPt.x += ( squareSize - maxDeltaX );
  399. if( maxDeltaY != 0.0f )
  400. maxPt.y += ( squareSize - maxDeltaY );
  401. // Add a safezone, so we don't touch the clipping planes.
  402. minPt.x -= squareSize; minPt.y -= squareSize;
  403. maxPt.x += squareSize; maxPt.y += squareSize;
  404. outMin = minPt;
  405. outMax = maxPt;
  406. }
  407. /// Generate a triangulated grid spanning the given bounds into the given buffers.
  408. void GroundPlane::generateGrid( U32 width, U32 height, F32 squareSize,
  409. const Point2F& min, const Point2F& max,
  410. GFXVertexBufferHandle< VertexType >& outVertices,
  411. GFXPrimitiveBufferHandle& outPrimitives )
  412. {
  413. // Generate the vertices.
  414. VertexType* vertices = outVertices.lock();
  415. for( F32 y = min.y; y <= max.y; y += squareSize )
  416. for( F32 x = min.x; x <= max.x; x += squareSize )
  417. {
  418. vertices->point.x = x;
  419. vertices->point.y = y;
  420. vertices->point.z = 0.0;
  421. vertices->texCoord.x = ( x / squareSize ) * mScaleU;
  422. vertices->texCoord.y = ( y / squareSize ) * -mScaleV;
  423. vertices->normal.x = 0.0f;
  424. vertices->normal.y = 0.0f;
  425. vertices->normal.z = 1.0f;
  426. vertices->tangent.x = 1.0f;
  427. vertices->tangent.y = 0.0f;
  428. vertices->tangent.z = 0.0f;
  429. vertices->binormal.x = 0.0f;
  430. vertices->binormal.y = 1.0f;
  431. vertices->binormal.z = 0.0f;
  432. vertices++;
  433. }
  434. outVertices.unlock();
  435. // Generate the indices.
  436. U16* indices;
  437. outPrimitives.lock( &indices );
  438. U16 corner1 = 0;
  439. U16 corner2 = 1;
  440. U16 corner3 = width + 1;
  441. U16 corner4 = width + 2;
  442. for( U32 y = 0; y < height; ++ y )
  443. {
  444. for( U32 x = 0; x < width; ++ x )
  445. {
  446. indices[ 0 ] = corner3;
  447. indices[ 1 ] = corner2;
  448. indices[ 2 ] = corner1;
  449. indices += 3;
  450. indices[ 0 ] = corner3;
  451. indices[ 1 ] = corner4;
  452. indices[ 2 ] = corner2;
  453. indices += 3;
  454. corner1 ++;
  455. corner2 ++;
  456. corner3 ++;
  457. corner4 ++;
  458. }
  459. corner1 ++;
  460. corner2 ++;
  461. corner3 ++;
  462. corner4 ++;
  463. }
  464. outPrimitives.unlock();
  465. }
  466. void GroundPlane::getUtilizedAssets(Vector<StringTableEntry>* usedAssetsList)
  467. {
  468. if (!mMaterialAsset.isNull() && mMaterialAsset->getAssetId() != MaterialAsset::smNoMaterialAssetFallback)
  469. usedAssetsList->push_back_unique(mMaterialAsset->getAssetId());
  470. }
  471. DefineEngineMethod( GroundPlane, postApply, void, (),,
  472. "Intended as a helper to developers and editor scripts.\n"
  473. "Force trigger an inspectPostApply. This will transmit "
  474. "material and other fields to client objects."
  475. )
  476. {
  477. object->inspectPostApply();
  478. }