decalRoad.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  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/decalRoad.h"
  24. #include "console/consoleTypes.h"
  25. #include "console/engineAPI.h"
  26. #include "util/catmullRom.h"
  27. #include "math/util/quadTransforms.h"
  28. #include "scene/sceneRenderState.h"
  29. #include "scene/sceneManager.h"
  30. #include "core/stream/bitStream.h"
  31. #include "gfx/gfxDrawUtil.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "math/mathIO.h"
  34. #include "math/mathUtils.h"
  35. #include "terrain/terrData.h"
  36. #include "materials/materialDefinition.h"
  37. #include "materials/materialManager.h"
  38. #include "materials/baseMatInstance.h"
  39. #include "environment/nodeListManager.h"
  40. #include "lighting/lightQuery.h"
  41. extern F32 gDecalBias;
  42. extern bool gEditingMission;
  43. //-----------------------------------------------------------------------------
  44. // DecalRoadNodeList Struct
  45. //-----------------------------------------------------------------------------
  46. struct DecalRoadNodeList : public NodeListManager::NodeList
  47. {
  48. Vector<Point3F> mPositions;
  49. Vector<F32> mWidths;
  50. DecalRoadNodeList() { }
  51. virtual ~DecalRoadNodeList() { }
  52. };
  53. //-----------------------------------------------------------------------------
  54. // DecalRoadNodeEvent Class
  55. //-----------------------------------------------------------------------------
  56. class DecalRoadNodeEvent : public NodeListEvent
  57. {
  58. typedef NodeListEvent Parent;
  59. public:
  60. Vector<Point3F> mPositions;
  61. Vector<F32> mWidths;
  62. public:
  63. DecalRoadNodeEvent() { mNodeList = NULL; }
  64. virtual ~DecalRoadNodeEvent() { }
  65. virtual void pack(NetConnection*, BitStream*);
  66. virtual void unpack(NetConnection*, BitStream*);
  67. virtual void copyIntoList(NodeListManager::NodeList* copyInto);
  68. virtual void padListToSize();
  69. DECLARE_CONOBJECT(DecalRoadNodeEvent);
  70. };
  71. void DecalRoadNodeEvent::pack(NetConnection* conn, BitStream* stream)
  72. {
  73. Parent::pack( conn, stream );
  74. stream->writeInt( mPositions.size(), 16 );
  75. for (U32 i=0; i<mPositions.size(); ++i)
  76. {
  77. mathWrite( *stream, mPositions[i] );
  78. stream->write( mWidths[i] );
  79. }
  80. }
  81. void DecalRoadNodeEvent::unpack(NetConnection* conn, BitStream* stream)
  82. {
  83. mNodeList = new DecalRoadNodeList();
  84. Parent::unpack( conn, stream );
  85. U32 count = stream->readInt( 16 );
  86. Point3F pos;
  87. F32 width;
  88. DecalRoadNodeList* list = static_cast<DecalRoadNodeList*>(mNodeList);
  89. for (U32 i=0; i<count; ++i)
  90. {
  91. mathRead( *stream, &pos );
  92. stream->read( &width );
  93. list->mPositions.push_back( pos );
  94. list->mWidths.push_back( width );
  95. }
  96. list->mTotalValidNodes = count;
  97. // Do we have a complete list?
  98. if (list->mPositions.size() >= mTotalNodes)
  99. list->mListComplete = true;
  100. }
  101. void DecalRoadNodeEvent::copyIntoList(NodeListManager::NodeList* copyInto)
  102. {
  103. DecalRoadNodeList* prevList = static_cast<DecalRoadNodeList*>(copyInto);
  104. DecalRoadNodeList* list = static_cast<DecalRoadNodeList*>(mNodeList);
  105. // Merge our list with the old list.
  106. for (U32 i=mLocalListStart, index=0; i<mLocalListStart+list->mPositions.size(); ++i, ++index)
  107. {
  108. prevList->mPositions[i] = list->mPositions[index];
  109. prevList->mWidths[i] = list->mWidths[index];
  110. }
  111. }
  112. void DecalRoadNodeEvent::padListToSize()
  113. {
  114. DecalRoadNodeList* list = static_cast<DecalRoadNodeList*>(mNodeList);
  115. U32 totalValidNodes = list->mTotalValidNodes;
  116. // Pad our list front?
  117. if (mLocalListStart)
  118. {
  119. DecalRoadNodeList* newlist = new DecalRoadNodeList();
  120. newlist->mPositions.increment(mLocalListStart);
  121. newlist->mWidths.increment(mLocalListStart);
  122. newlist->mPositions.merge(list->mPositions);
  123. newlist->mWidths.merge(list->mWidths);
  124. delete list;
  125. mNodeList = list = newlist;
  126. }
  127. // Pad our list end?
  128. if (list->mPositions.size() < mTotalNodes)
  129. {
  130. U32 delta = mTotalNodes - list->mPositions.size();
  131. list->mPositions.increment(delta);
  132. list->mWidths.increment(delta);
  133. }
  134. list->mTotalValidNodes = totalValidNodes;
  135. }
  136. IMPLEMENT_CO_NETEVENT_V1(DecalRoadNodeEvent);
  137. ConsoleDocClass( DecalRoadNodeEvent,
  138. "@brief Sends messages to the Decal Road Editor\n\n"
  139. "Editor use only.\n\n"
  140. "@internal"
  141. );
  142. //-----------------------------------------------------------------------------
  143. // DecalRoadNodeListNotify Class
  144. //-----------------------------------------------------------------------------
  145. class DecalRoadNodeListNotify : public NodeListNotify
  146. {
  147. typedef NodeListNotify Parent;
  148. protected:
  149. SimObjectPtr<DecalRoad> mRoad;
  150. public:
  151. DecalRoadNodeListNotify( DecalRoad* road, U32 listId ) { mRoad = road; mListId = listId; }
  152. virtual ~DecalRoadNodeListNotify() { mRoad = NULL; }
  153. virtual void sendNotification( NodeListManager::NodeList* list );
  154. };
  155. void DecalRoadNodeListNotify::sendNotification( NodeListManager::NodeList* list )
  156. {
  157. if (mRoad.isValid())
  158. {
  159. // Build the road's nodes
  160. DecalRoadNodeList* roadList = dynamic_cast<DecalRoadNodeList*>( list );
  161. if (roadList)
  162. mRoad->buildNodesFromList( roadList );
  163. }
  164. }
  165. //-----------------------------------------------------------------------------
  166. // DecalRoadUpdateEvent Class
  167. //-----------------------------------------------------------------------------
  168. void DecalRoadUpdateEvent::process( SimObject *object )
  169. {
  170. DecalRoad *road = dynamic_cast<DecalRoad*>( object );
  171. AssertFatal( road, "DecalRoadRegenEvent::process - wasn't a DecalRoad" );
  172. // Inform clients to perform the update.
  173. road->setMaskBits( mMask );
  174. if ( !road->isProperlyAdded() )
  175. return;
  176. // Perform the server side update.
  177. if ( mMask & DecalRoad::TerrainChangedMask )
  178. {
  179. road->_generateEdges();
  180. }
  181. if ( mMask & DecalRoad::GenEdgesMask )
  182. {
  183. // Server has already done this.
  184. //road->_generateEdges();
  185. }
  186. if ( mMask & DecalRoad::ReClipMask )
  187. {
  188. // Server does not need to capture verts.
  189. road->_captureVerts();
  190. }
  191. }
  192. //------------------------------------------------------------------------------
  193. // Class: DecalRoad
  194. //------------------------------------------------------------------------------
  195. ConsoleDocClass( DecalRoad,
  196. "@brief A strip shaped decal defined by spine nodes which clips against Terrain objects.\n\n"
  197. "DecalRoad is for representing a road or path ( or other inventive things ) across "
  198. "a TerrainBlock. It renders as a decal and is therefore only for features that do "
  199. "not need geometric depth.\n\n"
  200. "The Material assigned to DecalRoad should tile vertically.\n\n"
  201. "@ingroup Terrain"
  202. );
  203. // Init Statics
  204. // Static ConsoleVars for toggling debug rendering
  205. bool DecalRoad::smEditorOpen = false;
  206. bool DecalRoad::smWireframe = true;
  207. bool DecalRoad::smShowBatches = false;
  208. bool DecalRoad::smDiscardAll = false;
  209. bool DecalRoad::smShowSpline = true;
  210. bool DecalRoad::smShowRoad = true;
  211. S32 DecalRoad::smUpdateDelay = 500;
  212. SimObjectPtr<SimSet> DecalRoad::smServerDecalRoadSet = NULL;
  213. // Constructors
  214. DecalRoad::DecalRoad()
  215. : mBreakAngle( 3.0f ),
  216. mSegmentsPerBatch( 10 ),
  217. mTextureLength( 5.0f ),
  218. mRenderPriority( 10 ),
  219. mLoadRenderData( true ),
  220. mMaterial( NULL ),
  221. mMatInst( NULL ),
  222. mTriangleCount(0),
  223. mVertCount(0),
  224. mUpdateEventId( -1 ),
  225. mLastEvent(NULL),
  226. mTerrainUpdateRect( Box3F::Invalid )
  227. {
  228. // Setup NetObject.
  229. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  230. mNetFlags.set(Ghostable);
  231. }
  232. DecalRoad::~DecalRoad()
  233. {
  234. }
  235. IMPLEMENT_CO_NETOBJECT_V1(DecalRoad);
  236. // ConsoleObject
  237. void DecalRoad::initPersistFields()
  238. {
  239. addGroup( "DecalRoad" );
  240. addField( "material", TypeMaterialName, Offset( mMaterialName, DecalRoad ), "Material used for rendering." );
  241. addProtectedField( "textureLength", TypeF32, Offset( mTextureLength, DecalRoad ), &DecalRoad::ptSetTextureLength, &defaultProtectedGetFn,
  242. "The length in meters of textures mapped to the DecalRoad" );
  243. addProtectedField( "breakAngle", TypeF32, Offset( mBreakAngle, DecalRoad ), &DecalRoad::ptSetBreakAngle, &defaultProtectedGetFn,
  244. "Angle in degrees - DecalRoad will subdivided the spline if its curve is greater than this threshold." );
  245. addField( "renderPriority", TypeS32, Offset( mRenderPriority, DecalRoad ),
  246. "DecalRoad(s) are rendered in descending renderPriority order." );
  247. endGroup( "DecalRoad" );
  248. addGroup( "Internal" );
  249. addProtectedField( "node", TypeString, NULL, &addNodeFromField, &emptyStringProtectedGetFn,
  250. "Do not modify, for internal use." );
  251. endGroup( "Internal" );
  252. Parent::initPersistFields();
  253. }
  254. void DecalRoad::consoleInit()
  255. {
  256. Parent::consoleInit();
  257. // Vars for debug rendering while the RoadEditor is open, only used if smEditorOpen is true.
  258. Con::addVariable( "$DecalRoad::EditorOpen", TypeBool, &DecalRoad::smEditorOpen, "For use by the Decal Editor.\n\n"
  259. "@ingroup Editors\n" );
  260. Con::addVariable( "$DecalRoad::wireframe", TypeBool, &DecalRoad::smWireframe, "For use by the Decal Editor.\n\n"
  261. "@ingroup Editors\n" );
  262. Con::addVariable( "$DecalRoad::showBatches", TypeBool, &DecalRoad::smShowBatches, "For use by the Decal Editor.\n\n"
  263. "@ingroup Editors\n" );
  264. Con::addVariable( "$DecalRoad::discardAll", TypeBool, &DecalRoad::smDiscardAll, "For use by the Decal Editor.\n\n"
  265. "@ingroup Editors\n");
  266. Con::addVariable( "$DecalRoad::showSpline", TypeBool, &DecalRoad::smShowSpline, "For use by the Decal Editor.\n\n"
  267. "@ingroup Editors\n" );
  268. Con::addVariable( "$DecalRoad::showRoad", TypeBool, &DecalRoad::smShowRoad, "For use by the Decal Editor.\n\n"
  269. "@ingroup Editors\n" );
  270. Con::addVariable( "$DecalRoad::updateDelay", TypeS32, &DecalRoad::smUpdateDelay, "For use by the Decal Editor.\n\n"
  271. "@ingroup Editors\n" );
  272. }
  273. // SimObject
  274. bool DecalRoad::onAdd()
  275. {
  276. if ( !Parent::onAdd() )
  277. return false;
  278. // DecalRoad is at position zero when created,
  279. // it sets its own position to the first node inside
  280. // _generateEdges but until it has at least one node
  281. // it will be at 0,0,0.
  282. MatrixF mat(true);
  283. Parent::setTransform( mat );
  284. // The client side calculates bounds based on clipped geometry. It would
  285. // be wasteful for the server to do this so the server uses global bounds.
  286. if ( isServerObject() )
  287. {
  288. setGlobalBounds();
  289. resetWorldBox();
  290. }
  291. // Set the Render Transform.
  292. setRenderTransform(mObjToWorld);
  293. // Add to Scene.
  294. addToScene();
  295. if ( isServerObject() )
  296. getServerSet()->addObject( this );
  297. //
  298. TerrainBlock::smUpdateSignal.notify( this, &DecalRoad::_onTerrainChanged );
  299. //
  300. if ( isClientObject() )
  301. _initMaterial();
  302. _generateEdges();
  303. _captureVerts();
  304. return true;
  305. }
  306. void DecalRoad::onRemove()
  307. {
  308. SAFE_DELETE( mMatInst );
  309. TerrainBlock::smUpdateSignal.remove( this, &DecalRoad::_onTerrainChanged );
  310. removeFromScene();
  311. Parent::onRemove();
  312. }
  313. void DecalRoad::inspectPostApply()
  314. {
  315. Parent::inspectPostApply();
  316. setMaskBits( DecalRoadMask );
  317. }
  318. void DecalRoad::onStaticModified( const char* slotName, const char*newValue )
  319. {
  320. Parent::onStaticModified( slotName, newValue );
  321. /*
  322. if ( isProperlyAdded() &&
  323. dStricmp( slotName, "material" ) == 0 )
  324. {
  325. setMaskBits( DecalRoadMask );
  326. }
  327. */
  328. if ( dStricmp( slotName, "renderPriority" ) == 0 )
  329. {
  330. mRenderPriority = getMax( dAtoi(newValue), (S32)1 );
  331. }
  332. }
  333. SimSet* DecalRoad::getServerSet()
  334. {
  335. if ( !smServerDecalRoadSet )
  336. {
  337. smServerDecalRoadSet = new SimSet();
  338. smServerDecalRoadSet->registerObject( "ServerDecalRoadSet" );
  339. Sim::getRootGroup()->addObject( smServerDecalRoadSet );
  340. }
  341. return smServerDecalRoadSet;
  342. }
  343. void DecalRoad::writeFields( Stream &stream, U32 tabStop )
  344. {
  345. Parent::writeFields( stream, tabStop );
  346. // Now write all nodes
  347. stream.write(2, "\r\n");
  348. for ( U32 i = 0; i < mNodes.size(); i++ )
  349. {
  350. const RoadNode &node = mNodes[i];
  351. stream.writeTabs(tabStop);
  352. char buffer[1024];
  353. dMemset( buffer, 0, 1024 );
  354. dSprintf( buffer, 1024, "Node = \"%f %f %f %f\";", node.point.x, node.point.y, node.point.z, node.width );
  355. stream.writeLine( (const U8*)buffer );
  356. }
  357. }
  358. bool DecalRoad::writeField( StringTableEntry fieldname, const char *value )
  359. {
  360. if ( fieldname == StringTable->insert("node") )
  361. return false;
  362. return Parent::writeField( fieldname, value );
  363. }
  364. void DecalRoad::onEditorEnable()
  365. {
  366. }
  367. void DecalRoad::onEditorDisable()
  368. {
  369. }
  370. // NetObject
  371. U32 DecalRoad::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  372. {
  373. // Pack Parent.
  374. U32 retMask = Parent::packUpdate(con, mask, stream);
  375. if ( stream->writeFlag( mask & DecalRoadMask ) )
  376. {
  377. // Write Texture Name.
  378. stream->write( mMaterialName );
  379. stream->write( mBreakAngle );
  380. stream->write( mSegmentsPerBatch );
  381. stream->write( mTextureLength );
  382. stream->write( mRenderPriority );
  383. }
  384. if ( stream->writeFlag( mask & NodeMask ) )
  385. {
  386. //stream->writeInt( mNodes.size(), 16 );
  387. //for ( U32 i = 0; i < mNodes.size(); i++ )
  388. //{
  389. // mathWrite( *stream, mNodes[i].point );
  390. // stream->write( mNodes[i].width );
  391. //}
  392. const U32 nodeByteSize = 16; // Based on sending all of a node's parameters
  393. // Test if we can fit all of our nodes within the current stream.
  394. // We make sure we leave 100 bytes still free in the stream for whatever
  395. // may follow us.
  396. S32 allowedBytes = stream->getWriteByteSize() - 100;
  397. if ( stream->writeFlag( (nodeByteSize * mNodes.size()) < allowedBytes ) )
  398. {
  399. // All nodes should fit, so send them out now.
  400. stream->writeInt( mNodes.size(), 16 );
  401. for ( U32 i = 0; i < mNodes.size(); i++ )
  402. {
  403. mathWrite( *stream, mNodes[i].point );
  404. stream->write( mNodes[i].width );
  405. }
  406. }
  407. else
  408. {
  409. // There isn't enough space left in the stream for all of the
  410. // nodes. Batch them up into NetEvents.
  411. U32 id = gServerNodeListManager->nextListId();
  412. U32 count = 0;
  413. U32 index = 0;
  414. while (count < mNodes.size())
  415. {
  416. count += NodeListManager::smMaximumNodesPerEvent;
  417. if (count > mNodes.size())
  418. {
  419. count = mNodes.size();
  420. }
  421. DecalRoadNodeEvent* event = new DecalRoadNodeEvent();
  422. event->mId = id;
  423. event->mTotalNodes = mNodes.size();
  424. event->mLocalListStart = index;
  425. for (; index<count; ++index)
  426. {
  427. event->mPositions.push_back( mNodes[index].point );
  428. event->mWidths.push_back( mNodes[index].width );
  429. }
  430. con->postNetEvent( event );
  431. }
  432. stream->write( id );
  433. }
  434. }
  435. stream->writeFlag( mask & GenEdgesMask );
  436. stream->writeFlag( mask & ReClipMask );
  437. stream->writeFlag( mask & TerrainChangedMask );
  438. // Were done ...
  439. return retMask;
  440. }
  441. void DecalRoad::unpackUpdate( NetConnection *con, BitStream *stream )
  442. {
  443. // Unpack Parent.
  444. Parent::unpackUpdate( con, stream );
  445. // DecalRoadMask
  446. if ( stream->readFlag() )
  447. {
  448. String matName;
  449. stream->read( &matName );
  450. if ( matName != mMaterialName )
  451. {
  452. mMaterialName = matName;
  453. Material *pMat = NULL;
  454. if ( !Sim::findObject( mMaterialName, pMat ) )
  455. {
  456. Con::printf( "DecalRoad::unpackUpdate, failed to find Material of name %s!", mMaterialName.c_str() );
  457. }
  458. else
  459. {
  460. mMaterial = pMat;
  461. if ( isProperlyAdded() )
  462. _initMaterial();
  463. }
  464. }
  465. stream->read( &mBreakAngle );
  466. stream->read( &mSegmentsPerBatch );
  467. stream->read( &mTextureLength );
  468. stream->read( &mRenderPriority );
  469. }
  470. // NodeMask
  471. if ( stream->readFlag() )
  472. {
  473. //U32 count = stream->readInt( 16 );
  474. //mNodes.clear();
  475. //Point3F pos;
  476. //F32 width;
  477. //for ( U32 i = 0; i < count; i++ )
  478. //{
  479. // mathRead( *stream, &pos );
  480. // stream->read( &width );
  481. // _addNode( pos, width );
  482. //}
  483. if (stream->readFlag())
  484. {
  485. // Nodes have been passed in this update
  486. U32 count = stream->readInt( 16 );
  487. mNodes.clear();
  488. Point3F pos;
  489. F32 width;
  490. for ( U32 i = 0; i < count; i++ )
  491. {
  492. mathRead( *stream, &pos );
  493. stream->read( &width );
  494. _addNode( pos, width );
  495. }
  496. }
  497. else
  498. {
  499. // Nodes will arrive as events
  500. U32 id;
  501. stream->read( &id );
  502. // Check if the road's nodes made it here before we did.
  503. NodeListManager::NodeList* list = NULL;
  504. if ( gClientNodeListManager->findListById( id, &list, true) )
  505. {
  506. // Work with the completed list
  507. DecalRoadNodeList* roadList = dynamic_cast<DecalRoadNodeList*>( list );
  508. if (roadList)
  509. buildNodesFromList( roadList );
  510. delete list;
  511. }
  512. else
  513. {
  514. // Nodes have not yet arrived, so register our interest in the list
  515. DecalRoadNodeListNotify* notify = new DecalRoadNodeListNotify( this, id );
  516. gClientNodeListManager->registerNotification( notify );
  517. }
  518. }
  519. }
  520. // GenEdgesMask
  521. if ( stream->readFlag() && isProperlyAdded() )
  522. _generateEdges();
  523. // ReClipMask
  524. if ( stream->readFlag() && isProperlyAdded() )
  525. _captureVerts();
  526. // TerrainChangedMask
  527. if ( stream->readFlag() )
  528. {
  529. if ( isProperlyAdded() )
  530. {
  531. if ( mTerrainUpdateRect.isOverlapped( getWorldBox() ) )
  532. {
  533. _generateEdges();
  534. _captureVerts();
  535. // Clear out the mTerrainUpdateRect since we have updated its
  536. // region and we now need to store future terrain changes
  537. // in it.
  538. mTerrainUpdateRect = Box3F::Invalid;
  539. }
  540. }
  541. }
  542. }
  543. void DecalRoad::prepRenderImage( SceneRenderState* state )
  544. {
  545. PROFILE_SCOPE( DecalRoad_prepRenderImage );
  546. if ( mNodes.size() <= 1 ||
  547. mBatches.size() == 0 ||
  548. !mMatInst ||
  549. state->isShadowPass() )
  550. return;
  551. // If we don't have a material instance after the override then
  552. // we can skip rendering all together.
  553. BaseMatInstance *matInst = state->getOverrideMaterial( mMatInst );
  554. if ( !matInst )
  555. return;
  556. RenderPassManager *renderPass = state->getRenderPass();
  557. // Debug RenderInstance
  558. // Only when editor is open.
  559. if ( smEditorOpen )
  560. {
  561. ObjectRenderInst *ri = renderPass->allocInst<ObjectRenderInst>();
  562. ri->type = RenderPassManager::RIT_Editor;
  563. ri->renderDelegate.bind( this, &DecalRoad::_debugRender );
  564. state->getRenderPass()->addInst( ri );
  565. }
  566. // Normal Road RenderInstance
  567. // Always rendered when the editor is not open
  568. // otherwise obey the smShowRoad flag
  569. if ( !smShowRoad && smEditorOpen )
  570. return;
  571. const Frustum &frustum = state->getCameraFrustum();
  572. MeshRenderInst coreRI;
  573. coreRI.clear();
  574. coreRI.objectToWorld = &MatrixF::Identity;
  575. coreRI.worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  576. MatrixF *tempMat = renderPass->allocUniqueXform( MatrixF( true ) );
  577. MathUtils::getZBiasProjectionMatrix( gDecalBias, frustum, tempMat );
  578. coreRI.projection = tempMat;
  579. coreRI.type = RenderPassManager::RIT_DecalRoad;
  580. coreRI.vertBuff = &mVB;
  581. coreRI.primBuff = &mPB;
  582. coreRI.matInst = matInst;
  583. // Make it the sort distance the max distance so that
  584. // it renders after all the other opaque geometry in
  585. // the deferred bin.
  586. coreRI.sortDistSq = F32_MAX;
  587. // If we need lights then set them up.
  588. if ( matInst->isForwardLit() )
  589. {
  590. LightQuery query;
  591. query.init( getWorldSphere() );
  592. query.getLights( coreRI.lights, 8 );
  593. }
  594. U32 startBatchIdx = -1;
  595. U32 endBatchIdx = 0;
  596. for ( U32 i = 0; i < mBatches.size(); i++ )
  597. {
  598. const RoadBatch &batch = mBatches[i];
  599. const bool isVisible = !frustum.isCulled( batch.bounds );
  600. if ( isVisible )
  601. {
  602. // If this is the start of a set of batches.
  603. if ( startBatchIdx == -1 )
  604. endBatchIdx = startBatchIdx = i;
  605. // Else we're extending the end batch index.
  606. else
  607. ++endBatchIdx;
  608. // If this isn't the last batch then continue.
  609. if ( i < mBatches.size()-1 )
  610. continue;
  611. }
  612. // We we still don't have a start batch, so skip.
  613. if ( startBatchIdx == -1 )
  614. continue;
  615. // Render this set of batches.
  616. const RoadBatch &startBatch = mBatches[startBatchIdx];
  617. const RoadBatch &endBatch = mBatches[endBatchIdx];
  618. U32 startVert = startBatch.startVert;
  619. U32 startIdx = startBatch.startIndex;
  620. U32 vertCount = endBatch.endVert - startVert;
  621. U32 idxCount = ( endBatch.endIndex - startIdx ) + 1;
  622. U32 triangleCount = idxCount / 3;
  623. AssertFatal( startVert + vertCount <= mVertCount, "DecalRoad, bad draw call!" );
  624. AssertFatal( startIdx + triangleCount < mTriangleCount * 3, "DecalRoad, bad draw call!" );
  625. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  626. *ri = coreRI;
  627. ri->prim = renderPass->allocPrim();
  628. ri->prim->type = GFXTriangleList;
  629. ri->prim->minIndex = 0;
  630. ri->prim->startIndex = startIdx;
  631. ri->prim->numPrimitives = triangleCount;
  632. ri->prim->startVertex = 0;
  633. ri->prim->numVertices = endBatch.endVert + 1;
  634. // For sorting we first sort by render priority
  635. // and then by objectId.
  636. //
  637. // Since a road can submit more than one render instance, we want all
  638. // draw calls for a single road to occur consecutively, since they
  639. // could use the same vertex buffer.
  640. ri->defaultKey = mRenderPriority << 0 | mId << 16;
  641. ri->defaultKey2 = 0;
  642. renderPass->addInst( ri );
  643. // Reset the batching.
  644. startBatchIdx = -1;
  645. }
  646. }
  647. void DecalRoad::setTransform( const MatrixF &mat )
  648. {
  649. // We ignore transform requests from the editor
  650. // right now.
  651. }
  652. void DecalRoad::setScale( const VectorF &scale )
  653. {
  654. // We ignore scale requests from the editor
  655. // right now.
  656. }
  657. // DecalRoad Public Methods
  658. bool DecalRoad::getClosestNode( const Point3F &pos, U32 &idx )
  659. {
  660. F32 closestDist = F32_MAX;
  661. for ( U32 i = 0; i < mNodes.size(); i++ )
  662. {
  663. F32 dist = ( mNodes[i].point - pos ).len();
  664. if ( dist < closestDist )
  665. {
  666. closestDist = dist;
  667. idx = i;
  668. }
  669. }
  670. return closestDist != F32_MAX;
  671. }
  672. bool DecalRoad::containsPoint( const Point3F &worldPos, U32 *nodeIdx ) const
  673. {
  674. // This is just for making selections in the editor, we use the
  675. // client-side road because it has the proper edge's.
  676. if ( isServerObject() && getClientObject() )
  677. return ((DecalRoad*)getClientObject())->containsPoint( worldPos, nodeIdx );
  678. // If point isn't in the world box,
  679. // it's definitely not in the road.
  680. //if ( !getWorldBox().isContained( worldPos ) )
  681. // return false;
  682. if ( mEdges.size() < 2 )
  683. return false;
  684. Point2F testPt( worldPos.x,
  685. worldPos.y );
  686. Point2F poly[4];
  687. // Look through all edges, does the polygon
  688. // formed from adjacent edge's contain the worldPos?
  689. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  690. {
  691. const RoadEdge &edge0 = mEdges[i];
  692. const RoadEdge &edge1 = mEdges[i+1];
  693. poly[0].set( edge0.p0.x, edge0.p0.y );
  694. poly[1].set( edge0.p2.x, edge0.p2.y );
  695. poly[2].set( edge1.p2.x, edge1.p2.y );
  696. poly[3].set( edge1.p0.x, edge1.p0.y );
  697. if ( MathUtils::pointInPolygon( poly, 4, testPt ) )
  698. {
  699. if ( nodeIdx )
  700. *nodeIdx = edge0.parentNodeIdx;
  701. return true;
  702. }
  703. }
  704. return false;
  705. }
  706. bool DecalRoad::castray( const Point3F &start, const Point3F &end ) const
  707. {
  708. // We just cast against the object box for the editor.
  709. return mWorldBox.collideLine( start, end );
  710. }
  711. Point3F DecalRoad::getNodePosition( U32 idx )
  712. {
  713. if ( mNodes.size() - 1 < idx )
  714. return Point3F();
  715. return mNodes[idx].point;
  716. }
  717. void DecalRoad::setNodePosition( U32 idx, const Point3F &pos )
  718. {
  719. if ( mNodes.size() - 1 < idx )
  720. return;
  721. mNodes[idx].point = pos;
  722. _generateEdges();
  723. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  724. }
  725. U32 DecalRoad::addNode( const Point3F &pos, F32 width )
  726. {
  727. U32 idx = _addNode( pos, width );
  728. _generateEdges();
  729. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  730. return idx;
  731. }
  732. U32 DecalRoad::insertNode(const Point3F &pos, const F32 &width, const U32 &idx)
  733. {
  734. U32 ret = _insertNode( pos, width, idx );
  735. _generateEdges();
  736. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  737. return ret;
  738. }
  739. void DecalRoad::setNodeWidth( U32 idx, F32 width )
  740. {
  741. if ( mNodes.size() - 1 < idx )
  742. return;
  743. mNodes[idx].width = width;
  744. _generateEdges();
  745. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  746. }
  747. F32 DecalRoad::getNodeWidth( U32 idx )
  748. {
  749. if ( mNodes.size() - 1 < idx )
  750. return -1.0f;
  751. return mNodes[idx].width;
  752. }
  753. void DecalRoad::deleteNode( U32 idx )
  754. {
  755. if ( mNodes.size() - 1 < idx )
  756. return;
  757. mNodes.erase(idx);
  758. _generateEdges();
  759. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  760. }
  761. void DecalRoad::buildNodesFromList( DecalRoadNodeList* list )
  762. {
  763. mNodes.clear();
  764. for (U32 i=0; i<list->mPositions.size(); ++i)
  765. {
  766. _addNode( list->mPositions[i], list->mWidths[i] );
  767. }
  768. _generateEdges();
  769. _captureVerts();
  770. }
  771. void DecalRoad::setTextureLength( F32 meters )
  772. {
  773. meters = getMax( meters, 0.1f );
  774. if ( mTextureLength == meters )
  775. return;
  776. mTextureLength = meters;
  777. _generateEdges();
  778. scheduleUpdate( DecalRoadMask | ReClipMask );
  779. }
  780. void DecalRoad::setBreakAngle( F32 degrees )
  781. {
  782. //meters = getMax( meters, MIN_METERS_PER_SEGMENT );
  783. //if ( mBreakAngle == meters )
  784. // return;
  785. mBreakAngle = degrees;
  786. _generateEdges();
  787. scheduleUpdate( DecalRoadMask | GenEdgesMask | ReClipMask );
  788. }
  789. void DecalRoad::scheduleUpdate( U32 updateMask )
  790. {
  791. scheduleUpdate( updateMask, smUpdateDelay, true );
  792. }
  793. void DecalRoad::scheduleUpdate( U32 updateMask, U32 delayMs, bool restartTimer )
  794. {
  795. if ( Sim::isEventPending( mUpdateEventId ) )
  796. {
  797. if ( !restartTimer )
  798. {
  799. mLastEvent->mMask |= updateMask;
  800. return;
  801. }
  802. else
  803. {
  804. Sim::cancelEvent( mUpdateEventId );
  805. }
  806. }
  807. mLastEvent = new DecalRoadUpdateEvent( updateMask, delayMs );
  808. mUpdateEventId = Sim::postEvent( this, mLastEvent, Sim::getCurrentTime() + delayMs );
  809. }
  810. void DecalRoad::regenerate()
  811. {
  812. _generateEdges();
  813. _captureVerts();
  814. setMaskBits( NodeMask | GenEdgesMask | ReClipMask );
  815. }
  816. bool DecalRoad::addNodeFromField( void *object, const char *index, const char *data )
  817. {
  818. DecalRoad *pObj = static_cast<DecalRoad*>(object);
  819. F32 x,y,z,width;
  820. U32 result = dSscanf( data, "%f %f %f %f", &x, &y, &z, &width );
  821. if ( result == 4 )
  822. pObj->_addNode( Point3F(x,y,z), width );
  823. return false;
  824. }
  825. // Internal Helper Methods
  826. void DecalRoad::_initMaterial()
  827. {
  828. SAFE_DELETE( mMatInst );
  829. if ( mMaterial )
  830. mMatInst = mMaterial->createMatInstance();
  831. else
  832. mMatInst = MATMGR->createMatInstance( "WarningMaterial" );
  833. GFXStateBlockDesc desc;
  834. desc.setZReadWrite( true, false );
  835. mMatInst->addStateBlockDesc( desc );
  836. mMatInst->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTBT>() );
  837. }
  838. void DecalRoad::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* )
  839. {
  840. //if ( mStateBlock.isNull() )
  841. // return;
  842. GFX->enterDebugEvent( ColorI( 255, 0, 0 ), "DecalRoad_debugRender" );
  843. GFXTransformSaver saver;
  844. //GFX->setStateBlock( mStateBlock );
  845. Point3F size(1,1,1);
  846. ColorI color( 255, 0, 0, 255 );
  847. GFXStateBlockDesc desc;
  848. desc.setZReadWrite( true, false );
  849. desc.setBlend( true );
  850. desc.fillMode = GFXFillWireframe;
  851. if ( smShowBatches )
  852. {
  853. for ( U32 i = 0; i < mBatches.size(); i++ )
  854. {
  855. const Box3F &box = mBatches[i].bounds;
  856. GFX->getDrawUtil()->drawCube( desc, box, ColorI(255,100,100,255) );
  857. }
  858. }
  859. //GFX->leaveDebugEvent();
  860. }
  861. void DecalRoad::_generateEdges()
  862. {
  863. PROFILE_SCOPE( DecalRoad_generateEdges );
  864. //Con::warnf( "%s - generateEdges", isServerObject() ? "server" : "client" );
  865. if ( mNodes.size() > 0 )
  866. {
  867. // Set our object position to the first node.
  868. const Point3F &nodePt = mNodes.first().point;
  869. MatrixF mat( true );
  870. mat.setPosition( nodePt );
  871. Parent::setTransform( mat );
  872. // The server object has global bounds, which Parent::setTransform
  873. // messes up so we must reset it.
  874. if ( isServerObject() )
  875. {
  876. mObjBox.minExtents.set(-1e10, -1e10, -1e10);
  877. mObjBox.maxExtents.set( 1e10, 1e10, 1e10);
  878. }
  879. }
  880. if ( mNodes.size() < 2 )
  881. return;
  882. // Ensure nodes are above the terrain height at their xy position
  883. for ( U32 i = 0; i < mNodes.size(); i++ )
  884. {
  885. _getTerrainHeight( mNodes[i].point );
  886. }
  887. // Now start generating edges...
  888. U32 nodeCount = mNodes.size();
  889. Point3F *positions = new Point3F[nodeCount];
  890. for ( U32 i = 0; i < nodeCount; i++ )
  891. {
  892. const RoadNode &node = mNodes[i];
  893. positions[i].set( node.point.x, node.point.y, node.width );
  894. }
  895. CatmullRom<Point3F> spline;
  896. spline.initialize( nodeCount, positions );
  897. delete [] positions;
  898. mEdges.clear();
  899. Point3F lastBreakVector(0,0,0);
  900. RoadEdge slice;
  901. Point3F lastBreakNode;
  902. lastBreakNode = spline.evaluate(0.0f);
  903. for ( U32 i = 1; i < mNodes.size(); i++ )
  904. {
  905. F32 t1 = spline.getTime(i);
  906. F32 t0 = spline.getTime(i-1);
  907. F32 segLength = spline.arcLength( t0, t1 );
  908. U32 numSegments = mCeil( segLength / MIN_METERS_PER_SEGMENT );
  909. numSegments = getMax( numSegments, (U32)1 );
  910. F32 tstep = ( t1 - t0 ) / numSegments;
  911. U32 startIdx = 0;
  912. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  913. for ( U32 j = startIdx; j < endIdx; j++ )
  914. {
  915. F32 t = t0 + tstep * j;
  916. Point3F splineNode = spline.evaluate(t);
  917. F32 width = splineNode.z;
  918. _getTerrainHeight( splineNode );
  919. Point3F toNodeVec = splineNode - lastBreakNode;
  920. toNodeVec.normalizeSafe();
  921. if ( lastBreakVector.isZero() )
  922. lastBreakVector = toNodeVec;
  923. F32 angle = mRadToDeg( mAcos( mDot( toNodeVec, lastBreakVector ) ) );
  924. if ( j == startIdx ||
  925. ( j == endIdx - 1 && i == mNodes.size() - 1 ) ||
  926. angle > mBreakAngle )
  927. {
  928. // Push back a spline node
  929. //slice.p1.set( splineNode.x, splineNode.y, 0.0f );
  930. //_getTerrainHeight( slice.p1 );
  931. slice.p1 = splineNode;
  932. slice.uvec.set(0,0,1);
  933. slice.width = width;
  934. slice.parentNodeIdx = i-1;
  935. mEdges.push_back( slice );
  936. lastBreakVector = splineNode - lastBreakNode;
  937. lastBreakVector.normalizeSafe();
  938. lastBreakNode = splineNode;
  939. }
  940. }
  941. }
  942. /*
  943. for ( U32 i = 1; i < nodeCount; i++ )
  944. {
  945. F32 t0 = spline.getTime( i-1 );
  946. F32 t1 = spline.getTime( i );
  947. F32 segLength = spline.arcLength( t0, t1 );
  948. U32 numSegments = mCeil( segLength / mBreakAngle );
  949. numSegments = getMax( numSegments, (U32)1 );
  950. F32 tstep = ( t1 - t0 ) / numSegments;
  951. AssertFatal( numSegments > 0, "DecalRoad::_generateEdges, got zero segments!" );
  952. U32 startIdx = 0;
  953. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  954. for ( U32 j = startIdx; j < endIdx; j++ )
  955. {
  956. F32 t = t0 + tstep * j;
  957. Point3F val = spline.evaluate(t);
  958. RoadEdge edge;
  959. edge.p1.set( val.x, val.y, 0.0f );
  960. _getTerrainHeight( val.x, val.y, edge.p1.z );
  961. edge.uvec.set(0,0,1);
  962. edge.width = val.z;
  963. edge.parentNodeIdx = i-1;
  964. mEdges.push_back( edge );
  965. }
  966. }
  967. */
  968. //
  969. // Calculate fvec and rvec for all edges
  970. //
  971. RoadEdge *edge = NULL;
  972. RoadEdge *nextEdge = NULL;
  973. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  974. {
  975. edge = &mEdges[i];
  976. nextEdge = &mEdges[i+1];
  977. edge->fvec = nextEdge->p1 - edge->p1;
  978. edge->fvec.normalize();
  979. edge->rvec = mCross( edge->fvec, edge->uvec );
  980. edge->rvec.normalize();
  981. }
  982. // Must do the last edge outside the loop
  983. RoadEdge *lastEdge = &mEdges[mEdges.size()-1];
  984. RoadEdge *prevEdge = &mEdges[mEdges.size()-2];
  985. lastEdge->fvec = prevEdge->fvec;
  986. lastEdge->rvec = prevEdge->rvec;
  987. //
  988. // Calculate p0/p2 for all edges
  989. //
  990. for ( U32 i = 0; i < mEdges.size(); i++ )
  991. {
  992. edge = &mEdges[i];
  993. edge->p0 = edge->p1 - edge->rvec * edge->width * 0.5f;
  994. edge->p2 = edge->p1 + edge->rvec * edge->width * 0.5f;
  995. _getTerrainHeight( edge->p0 );
  996. _getTerrainHeight( edge->p2 );
  997. }
  998. }
  999. void DecalRoad::_captureVerts()
  1000. {
  1001. PROFILE_SCOPE( DecalRoad_captureVerts );
  1002. //Con::warnf( "%s - captureVerts", isServerObject() ? "server" : "client" );
  1003. if ( isServerObject() )
  1004. {
  1005. //Con::errorf( "DecalRoad::_captureVerts - called on the server side!" );
  1006. return;
  1007. }
  1008. if ( mEdges.size() == 0 )
  1009. return;
  1010. //
  1011. // Construct ClippedPolyList objects for each pair
  1012. // of roadEdges.
  1013. // Use them to capture Terrain verts.
  1014. //
  1015. SphereF sphere;
  1016. RoadEdge *edge = NULL;
  1017. RoadEdge *nextEdge = NULL;
  1018. mTriangleCount = 0;
  1019. mVertCount = 0;
  1020. Vector<ClippedPolyList> clipperList;
  1021. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  1022. {
  1023. Box3F box;
  1024. edge = &mEdges[i];
  1025. nextEdge = &mEdges[i+1];
  1026. box.minExtents = edge->p1;
  1027. box.maxExtents = edge->p1;
  1028. box.extend( edge->p0 );
  1029. box.extend( edge->p2 );
  1030. box.extend( nextEdge->p0 );
  1031. box.extend( nextEdge->p1 );
  1032. box.extend( nextEdge->p2 );
  1033. box.minExtents.z -= 5.0f;
  1034. box.maxExtents.z += 5.0f;
  1035. sphere.center = ( nextEdge->p1 + edge->p1 ) * 0.5f;
  1036. sphere.radius = 100.0f; // NOTE: no idea how to calculate this
  1037. ClippedPolyList clipper;
  1038. clipper.mNormal.set(0.0f, 0.0f, 0.0f);
  1039. VectorF n;
  1040. PlaneF plane0, plane1;
  1041. // Construct Back Plane
  1042. n = edge->p2 - edge->p0;
  1043. n.normalize();
  1044. n = mCross( n, edge->uvec );
  1045. plane0.set( edge->p0, n );
  1046. clipper.mPlaneList.push_back( plane0 );
  1047. // Construct Front Plane
  1048. n = nextEdge->p2 - nextEdge->p0;
  1049. n.normalize();
  1050. n = -mCross( edge->uvec, n );
  1051. plane1.set( nextEdge->p0, -n );
  1052. //clipper.mPlaneList.push_back( plane1 );
  1053. // Test if / where the planes intersect.
  1054. bool discardLeft = false;
  1055. bool discardRight = false;
  1056. Point3F iPos;
  1057. VectorF iDir;
  1058. if ( plane0.intersect( plane1, iPos, iDir ) )
  1059. {
  1060. Point2F iPos2F( iPos.x, iPos.y );
  1061. Point2F cPos2F( edge->p1.x, edge->p1.y );
  1062. Point2F rVec2F( edge->rvec.x, edge->rvec.y );
  1063. Point2F iVec2F = iPos2F - cPos2F;
  1064. F32 iLen = iVec2F.len();
  1065. iVec2F.normalize();
  1066. if ( iLen < edge->width * 0.5f )
  1067. {
  1068. F32 dot = mDot( rVec2F, iVec2F );
  1069. // The clipping planes intersected on the right side,
  1070. // discard the right side clipping plane.
  1071. if ( dot > 0.0f )
  1072. discardRight = true;
  1073. // The clipping planes intersected on the left side,
  1074. // discard the left side clipping plane.
  1075. else
  1076. discardLeft = true;
  1077. }
  1078. }
  1079. // Left Plane
  1080. if ( !discardLeft )
  1081. {
  1082. n = ( nextEdge->p0 - edge->p0 );
  1083. n.normalize();
  1084. n = mCross( edge->uvec, n );
  1085. clipper.mPlaneList.push_back( PlaneF(edge->p0, n) );
  1086. }
  1087. else
  1088. {
  1089. nextEdge->p0 = edge->p0;
  1090. }
  1091. // Right Plane
  1092. if ( !discardRight )
  1093. {
  1094. n = ( nextEdge->p2 - edge->p2 );
  1095. n.normalize();
  1096. n = -mCross( n, edge->uvec );
  1097. clipper.mPlaneList.push_back( PlaneF(edge->p2, -n) );
  1098. }
  1099. else
  1100. {
  1101. nextEdge->p2 = edge->p2;
  1102. }
  1103. n = nextEdge->p2 - nextEdge->p0;
  1104. n.normalize();
  1105. n = -mCross( edge->uvec, n );
  1106. plane1.set( nextEdge->p0, -n );
  1107. clipper.mPlaneList.push_back( plane1 );
  1108. // We have constructed the clipping planes,
  1109. // now grab/clip the terrain geometry
  1110. getContainer()->buildPolyList( PLC_Decal, box, TerrainObjectType, &clipper );
  1111. clipper.cullUnusedVerts();
  1112. clipper.triangulate();
  1113. clipper.generateNormals();
  1114. // If we got something, add it to the ClippedPolyList Vector
  1115. if ( !clipper.isEmpty() && !( smDiscardAll && ( discardRight || discardLeft ) ) )
  1116. {
  1117. clipperList.push_back( clipper );
  1118. mVertCount += clipper.mVertexList.size();
  1119. mTriangleCount += clipper.mPolyList.size();
  1120. }
  1121. }
  1122. //
  1123. // Set the roadEdge height to be flush with terrain
  1124. // This is not really necessary but makes the debug spline rendering better.
  1125. //
  1126. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  1127. {
  1128. edge = &mEdges[i];
  1129. _getTerrainHeight( edge->p0.x, edge->p0.y, edge->p0.z );
  1130. _getTerrainHeight( edge->p2.x, edge->p2.y, edge->p2.z );
  1131. }
  1132. //
  1133. // Allocate the RoadBatch(s)
  1134. //
  1135. // If we captured no verts, then we can return here without
  1136. // allocating any RoadBatches or the Vert/Index Buffers.
  1137. // PreprenderImage will not allocate a render instance while
  1138. // mBatches.size() is zero.
  1139. U32 numClippers = clipperList.size();
  1140. if ( numClippers == 0 )
  1141. return;
  1142. mBatches.clear();
  1143. // Allocate the VertexBuffer and PrimitiveBuffer
  1144. mVB.set( GFX, mVertCount, GFXBufferTypeStatic );
  1145. mPB.set( GFX, mTriangleCount * 3, 0, GFXBufferTypeStatic );
  1146. // Lock the VertexBuffer
  1147. GFXVertexPNTBT *vertPtr = mVB.lock();
  1148. if(!vertPtr) return;
  1149. U32 vertIdx = 0;
  1150. //
  1151. // Fill the VertexBuffer and vertex data for the RoadBatches
  1152. // Loop through the ClippedPolyList Vector
  1153. //
  1154. RoadBatch *batch = NULL;
  1155. F32 texStart = 0.0f;
  1156. F32 texEnd;
  1157. for ( U32 i = 0; i < clipperList.size(); i++ )
  1158. {
  1159. ClippedPolyList *clipper = &clipperList[i];
  1160. edge = &mEdges[i];
  1161. nextEdge = &mEdges[i+1];
  1162. VectorF segFvec = nextEdge->p1 - edge->p1;
  1163. F32 segLen = segFvec.len();
  1164. segFvec.normalize();
  1165. F32 texLen = segLen / mTextureLength;
  1166. texEnd = texStart + texLen;
  1167. BiQuadToSqr quadToSquare( Point2F( edge->p0.x, edge->p0.y ),
  1168. Point2F( edge->p2.x, edge->p2.y ),
  1169. Point2F( nextEdge->p2.x, nextEdge->p2.y ),
  1170. Point2F( nextEdge->p0.x, nextEdge->p0.y ) );
  1171. //
  1172. if ( i % mSegmentsPerBatch == 0 )
  1173. {
  1174. mBatches.increment();
  1175. batch = &mBatches.last();
  1176. batch->bounds.minExtents = clipper->mVertexList[0].point;
  1177. batch->bounds.maxExtents = clipper->mVertexList[0].point;
  1178. batch->startVert = vertIdx;
  1179. }
  1180. // Loop through each ClippedPolyList
  1181. for ( U32 j = 0; j < clipper->mVertexList.size(); j++ )
  1182. {
  1183. // Add each vert to the VertexBuffer
  1184. Point3F pos = clipper->mVertexList[j].point;
  1185. vertPtr[vertIdx].point = pos;
  1186. vertPtr[vertIdx].normal = clipper->mNormalList[j];
  1187. Point2F uv = quadToSquare.transform( Point2F(pos.x,pos.y) );
  1188. vertPtr[vertIdx].texCoord.x = uv.x;
  1189. vertPtr[vertIdx].texCoord.y = -(( texEnd - texStart ) * uv.y + texStart);
  1190. vertPtr[vertIdx].tangent = mCross( segFvec, clipper->mNormalList[j] );
  1191. vertPtr[vertIdx].binormal = segFvec;
  1192. vertIdx++;
  1193. // Expand the RoadBatch bounds to contain this vertex
  1194. batch->bounds.extend( pos );
  1195. }
  1196. batch->endVert = vertIdx - 1;
  1197. texStart = texEnd;
  1198. }
  1199. // Unlock the VertexBuffer, we are done filling it.
  1200. mVB.unlock();
  1201. // Lock the PrimitiveBuffer
  1202. U16 *idxBuff;
  1203. mPB.lock(&idxBuff);
  1204. U32 curIdx = 0;
  1205. U16 vertOffset = 0;
  1206. batch = NULL;
  1207. S32 batchIdx = -1;
  1208. // Fill the PrimitiveBuffer
  1209. // Loop through each ClippedPolyList in the Vector
  1210. for ( U32 i = 0; i < clipperList.size(); i++ )
  1211. {
  1212. ClippedPolyList *clipper = &clipperList[i];
  1213. if ( i % mSegmentsPerBatch == 0 )
  1214. {
  1215. batchIdx++;
  1216. batch = &mBatches[batchIdx];
  1217. batch->startIndex = curIdx;
  1218. }
  1219. for ( U32 j = 0; j < clipper->mPolyList.size(); j++ )
  1220. {
  1221. // Write indices for each Poly
  1222. ClippedPolyList::Poly *poly = &clipper->mPolyList[j];
  1223. AssertFatal( poly->vertexCount == 3, "Got non-triangle poly!" );
  1224. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart] + vertOffset;
  1225. curIdx++;
  1226. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart + 1] + vertOffset;
  1227. curIdx++;
  1228. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart + 2] + vertOffset;
  1229. curIdx++;
  1230. }
  1231. batch->endIndex = curIdx - 1;
  1232. vertOffset += clipper->mVertexList.size();
  1233. }
  1234. // Unlock the PrimitiveBuffer, we are done filling it.
  1235. mPB.unlock();
  1236. // Generate the object/world bounds
  1237. // Is the union of all batch bounding boxes.
  1238. Box3F box;
  1239. for ( U32 i = 0; i < mBatches.size(); i++ )
  1240. {
  1241. batch = &mBatches[i];
  1242. if ( i == 0 )
  1243. box = batch->bounds;
  1244. else
  1245. box.intersect( batch->bounds );
  1246. }
  1247. mWorldBox = box;
  1248. resetObjectBox();
  1249. // Make sure we are in the correct bins given our world box.
  1250. if( getSceneManager() != NULL )
  1251. getSceneManager()->notifyObjectDirty( this );
  1252. }
  1253. U32 DecalRoad::_addNode( const Point3F &pos, F32 width )
  1254. {
  1255. mNodes.increment();
  1256. RoadNode &node = mNodes.last();
  1257. node.point = pos;
  1258. node.width = width;
  1259. return mNodes.size() - 1;
  1260. }
  1261. U32 DecalRoad::_insertNode( const Point3F &pos, const F32 &width, const U32 &idx )
  1262. {
  1263. U32 ret;
  1264. RoadNode *node;
  1265. if ( idx == U32_MAX )
  1266. {
  1267. mNodes.increment();
  1268. node = &mNodes.last();
  1269. ret = mNodes.size() - 1;
  1270. }
  1271. else
  1272. {
  1273. mNodes.insert( idx );
  1274. node = &mNodes[idx];
  1275. ret = idx;
  1276. }
  1277. node->point = pos;
  1278. //node->t = -1.0f;
  1279. //node->rot.identity();
  1280. node->width = width;
  1281. return ret;
  1282. }
  1283. bool DecalRoad::_getTerrainHeight( Point3F &pos )
  1284. {
  1285. return _getTerrainHeight( pos.x, pos.y, pos.z );
  1286. }
  1287. bool DecalRoad::_getTerrainHeight( const Point2F &pos, F32 &height )
  1288. {
  1289. return _getTerrainHeight( pos.x, pos.y, height );
  1290. }
  1291. bool DecalRoad::_getTerrainHeight( const F32 &x, const F32 &y, F32 &height )
  1292. {
  1293. Point3F startPnt( x, y, 10000.0f );
  1294. Point3F endPnt( x, y, -10000.0f );
  1295. RayInfo ri;
  1296. bool hit;
  1297. hit = getContainer()->castRay(startPnt, endPnt, TerrainObjectType, &ri);
  1298. if ( hit )
  1299. height = ri.point.z;
  1300. return hit;
  1301. }
  1302. void DecalRoad::_onTerrainChanged( U32 type, TerrainBlock* tblock, const Point2I &min, const Point2I &max )
  1303. {
  1304. // The client side object just stores the area that has changed
  1305. // and waits for the (delayed) update event from the server
  1306. // to actually perform the update.
  1307. if ( isClientObject() && tblock->isClientObject() )
  1308. {
  1309. // Convert the min and max into world space.
  1310. const F32 size = tblock->getSquareSize();
  1311. const Point3F pos = tblock->getPosition();
  1312. // TODO: I don't think this works right with tiling!
  1313. Box3F dirty( F32( min.x * size ) + pos.x, F32( min.y * size ) + pos.y, -F32_MAX,
  1314. F32( max.x * size ) + pos.x, F32( max.y * size ) + pos.y, F32_MAX );
  1315. if ( !mTerrainUpdateRect.isValidBox() )
  1316. mTerrainUpdateRect = dirty;
  1317. else
  1318. mTerrainUpdateRect.intersect( dirty );
  1319. }
  1320. // The server object only updates edges (doesn't clip to geometry)
  1321. // and schedules an update to be sent to the client.
  1322. else if ( isServerObject() && tblock->isServerObject() )
  1323. {
  1324. //_generateEdges();
  1325. scheduleUpdate( TerrainChangedMask );
  1326. }
  1327. }
  1328. // Static protected field set methods
  1329. bool DecalRoad::ptSetBreakAngle( void *object, const char *index, const char *data )
  1330. {
  1331. DecalRoad *road = static_cast<DecalRoad*>( object );
  1332. F32 val = dAtof( data );
  1333. road->setBreakAngle( val );
  1334. // we already set the field
  1335. return false;
  1336. }
  1337. bool DecalRoad::ptSetTextureLength( void *object, const char *index, const char *data )
  1338. {
  1339. DecalRoad *road = static_cast<DecalRoad*>( object );
  1340. F32 val = dAtof( data );
  1341. road->setTextureLength( val );
  1342. // we already set the field
  1343. return false;
  1344. }
  1345. // ConsoleMethods
  1346. DefineEngineMethod( DecalRoad, regenerate, void, (),,
  1347. "Intended as a helper to developers and editor scripts.\n"
  1348. "Force DecalRoad to update it's spline and reclip geometry."
  1349. )
  1350. {
  1351. object->regenerate();
  1352. }
  1353. DefineEngineMethod( DecalRoad, postApply, void, (),,
  1354. "Intended as a helper to developers and editor scripts.\n"
  1355. "Force trigger an inspectPostApply. This will transmit "
  1356. "the material and other fields ( not including nodes ) "
  1357. "to client objects."
  1358. )
  1359. {
  1360. object->inspectPostApply();
  1361. }