decalRoad.cpp 48 KB

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