meshRoad.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456
  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/meshRoad.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/simPath.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "scene/sceneManager.h"
  31. #include "scene/sgUtil.h"
  32. #include "renderInstance/renderPassManager.h"
  33. #include "T3D/gameBase/gameConnection.h"
  34. #include "core/stream/bitStream.h"
  35. #include "gfx/gfxDrawUtil.h"
  36. #include "gfx/gfxTransformSaver.h"
  37. #include "gfx/primBuilder.h"
  38. #include "gfx/gfxDebugEvent.h"
  39. #include "materials/materialManager.h"
  40. #include "math/mathIO.h"
  41. #include "math/mathUtils.h"
  42. #include "math/util/frustum.h"
  43. #include "gui/3d/guiTSControl.h"
  44. #include "materials/shaderData.h"
  45. #include "gfx/sim/gfxStateBlockData.h"
  46. #include "gfx/sim/debugDraw.h"
  47. #include "collision/concretePolyList.h"
  48. #include "T3D/physics/physicsPlugin.h"
  49. #include "T3D/physics/physicsBody.h"
  50. #include "T3D/physics/physicsCollision.h"
  51. #include "environment/nodeListManager.h"
  52. #define MIN_METERS_PER_SEGMENT 1.0f
  53. #define MIN_NODE_DEPTH 0.25f
  54. #define MAX_NODE_DEPTH 50.0f
  55. #define MIN_NODE_WIDTH 0.25f
  56. #define MAX_NODE_WIDTH 50.0f
  57. static U32 gIdxArray[6][2][3] = {
  58. { { 0, 4, 5 }, { 0, 5, 1 }, }, // Top Face
  59. { { 2, 6, 4 }, { 2, 4, 0 }, }, // Left Face
  60. { { 1, 5, 7 }, { 1, 7, 3 }, }, // Right Face
  61. { { 2, 3, 7 }, { 2, 7, 6 }, }, // Bottom Face
  62. { { 0, 1, 3 }, { 0, 3, 2 }, }, // Front Face
  63. { { 4, 6, 7 }, { 4, 7, 5 }, }, // Back Face
  64. };
  65. static S32 QSORT_CALLBACK compareHitSegments(const void* a,const void* b)
  66. {
  67. const MeshRoadHitSegment *fa = (MeshRoadHitSegment*)a;
  68. const MeshRoadHitSegment *fb = (MeshRoadHitSegment*)b;
  69. return mSign(fb->t - fa->t);
  70. }
  71. //-----------------------------------------------------------------------------
  72. // MeshRoadNodeList Struct
  73. //-----------------------------------------------------------------------------
  74. struct MeshRoadNodeList : public NodeListManager::NodeList
  75. {
  76. Vector<Point3F> mPositions;
  77. Vector<F32> mWidths;
  78. Vector<F32> mDepths;
  79. Vector<VectorF> mNormals;
  80. MeshRoadNodeList() { }
  81. virtual ~MeshRoadNodeList() { }
  82. };
  83. //-----------------------------------------------------------------------------
  84. // MeshRoadNodeEvent Class
  85. //-----------------------------------------------------------------------------
  86. class MeshRoadNodeEvent : public NodeListEvent
  87. {
  88. typedef NodeListEvent Parent;
  89. public:
  90. Vector<Point3F> mPositions;
  91. Vector<F32> mWidths;
  92. Vector<F32> mDepths;
  93. Vector<VectorF> mNormals;
  94. public:
  95. MeshRoadNodeEvent() { mNodeList = NULL; }
  96. virtual ~MeshRoadNodeEvent() { }
  97. virtual void pack(NetConnection*, BitStream*);
  98. virtual void unpack(NetConnection*, BitStream*);
  99. virtual void copyIntoList(NodeListManager::NodeList* copyInto);
  100. virtual void padListToSize();
  101. DECLARE_CONOBJECT(MeshRoadNodeEvent);
  102. };
  103. void MeshRoadNodeEvent::pack(NetConnection* conn, BitStream* stream)
  104. {
  105. Parent::pack( conn, stream );
  106. stream->writeInt( mPositions.size(), 16 );
  107. for (U32 i=0; i<mPositions.size(); ++i)
  108. {
  109. mathWrite( *stream, mPositions[i] );
  110. stream->write( mWidths[i] );
  111. stream->write( mDepths[i] );
  112. mathWrite( *stream, mNormals[i] );
  113. }
  114. }
  115. void MeshRoadNodeEvent::unpack(NetConnection* conn, BitStream* stream)
  116. {
  117. mNodeList = new MeshRoadNodeList();
  118. Parent::unpack( conn, stream );
  119. U32 count = stream->readInt( 16 );
  120. Point3F pos;
  121. F32 width, depth;
  122. VectorF normal;
  123. MeshRoadNodeList* list = static_cast<MeshRoadNodeList*>(mNodeList);
  124. for (U32 i=0; i<count; ++i)
  125. {
  126. mathRead( *stream, &pos );
  127. stream->read( &width );
  128. stream->read( &depth );
  129. mathRead( *stream, &normal );
  130. list->mPositions.push_back( pos );
  131. list->mWidths.push_back( width );
  132. list->mDepths.push_back( depth );
  133. list->mNormals.push_back( normal );
  134. }
  135. list->mTotalValidNodes = count;
  136. // Do we have a complete list?
  137. if (list->mPositions.size() >= mTotalNodes)
  138. list->mListComplete = true;
  139. }
  140. void MeshRoadNodeEvent::copyIntoList(NodeListManager::NodeList* copyInto)
  141. {
  142. MeshRoadNodeList* prevList = dynamic_cast<MeshRoadNodeList*>(copyInto);
  143. MeshRoadNodeList* list = static_cast<MeshRoadNodeList*>(mNodeList);
  144. // Merge our list with the old list.
  145. for (U32 i=mLocalListStart, index=0; i<mLocalListStart+list->mPositions.size(); ++i, ++index)
  146. {
  147. prevList->mPositions[i] = list->mPositions[index];
  148. prevList->mWidths[i] = list->mWidths[index];
  149. prevList->mDepths[i] = list->mDepths[index];
  150. prevList->mNormals[i] = list->mNormals[index];
  151. }
  152. }
  153. void MeshRoadNodeEvent::padListToSize()
  154. {
  155. MeshRoadNodeList* list = static_cast<MeshRoadNodeList*>(mNodeList);
  156. U32 totalValidNodes = list->mTotalValidNodes;
  157. // Pad our list front?
  158. if (mLocalListStart)
  159. {
  160. MeshRoadNodeList* newlist = new MeshRoadNodeList();
  161. newlist->mPositions.increment(mLocalListStart);
  162. newlist->mWidths.increment(mLocalListStart);
  163. newlist->mDepths.increment(mLocalListStart);
  164. newlist->mNormals.increment(mLocalListStart);
  165. newlist->mPositions.merge(list->mPositions);
  166. newlist->mWidths.merge(list->mWidths);
  167. newlist->mDepths.merge(list->mDepths);
  168. newlist->mNormals.merge(list->mNormals);
  169. delete list;
  170. mNodeList = list = newlist;
  171. }
  172. // Pad our list end?
  173. if (list->mPositions.size() < mTotalNodes)
  174. {
  175. U32 delta = mTotalNodes - list->mPositions.size();
  176. list->mPositions.increment(delta);
  177. list->mWidths.increment(delta);
  178. list->mDepths.increment(delta);
  179. list->mNormals.increment(delta);
  180. }
  181. list->mTotalValidNodes = totalValidNodes;
  182. }
  183. IMPLEMENT_CO_NETEVENT_V1(MeshRoadNodeEvent);
  184. ConsoleDocClass( MeshRoadNodeEvent,
  185. "@brief Sends messages to the Mesh Road Editor\n\n"
  186. "Editor use only.\n\n"
  187. "@internal"
  188. );
  189. //-----------------------------------------------------------------------------
  190. // MeshRoadNodeListNotify Class
  191. //-----------------------------------------------------------------------------
  192. class MeshRoadNodeListNotify : public NodeListNotify
  193. {
  194. typedef NodeListNotify Parent;
  195. protected:
  196. SimObjectPtr<MeshRoad> mRoad;
  197. public:
  198. MeshRoadNodeListNotify( MeshRoad* road, U32 listId ) { mRoad = road; mListId = listId; }
  199. virtual ~MeshRoadNodeListNotify() { mRoad = NULL; }
  200. virtual void sendNotification( NodeListManager::NodeList* list );
  201. };
  202. void MeshRoadNodeListNotify::sendNotification( NodeListManager::NodeList* list )
  203. {
  204. if (mRoad.isValid())
  205. {
  206. // Build the road's nodes
  207. MeshRoadNodeList* roadList = dynamic_cast<MeshRoadNodeList*>( list );
  208. if (roadList)
  209. mRoad->buildNodesFromList( roadList );
  210. }
  211. }
  212. //------------------------------------------------------------------------------
  213. // MeshRoadConvex Class
  214. //------------------------------------------------------------------------------
  215. const MatrixF& MeshRoadConvex::getTransform() const
  216. {
  217. return MatrixF::Identity; //mObject->getTransform();
  218. }
  219. Box3F MeshRoadConvex::getBoundingBox() const
  220. {
  221. return box;
  222. }
  223. Box3F MeshRoadConvex::getBoundingBox(const MatrixF& mat, const Point3F& scale) const
  224. {
  225. Box3F newBox = box;
  226. newBox.minExtents.convolve(scale);
  227. newBox.maxExtents.convolve(scale);
  228. mat.mul(newBox);
  229. return newBox;
  230. }
  231. Point3F MeshRoadConvex::support(const VectorF& vec) const
  232. {
  233. F32 bestDot = mDot( verts[0], vec );
  234. const Point3F *bestP = &verts[0];
  235. for(S32 i=1; i<4; i++)
  236. {
  237. F32 newD = mDot(verts[i], vec);
  238. if(newD > bestDot)
  239. {
  240. bestDot = newD;
  241. bestP = &verts[i];
  242. }
  243. }
  244. return *bestP;
  245. }
  246. void MeshRoadConvex::getFeatures(const MatrixF& mat, const VectorF& n, ConvexFeature* cf)
  247. {
  248. cf->material = 0;
  249. cf->object = mObject;
  250. // For a tetrahedron this is pretty easy... first
  251. // convert everything into world space.
  252. Point3F tverts[4];
  253. mat.mulP(verts[0], &tverts[0]);
  254. mat.mulP(verts[1], &tverts[1]);
  255. mat.mulP(verts[2], &tverts[2]);
  256. mat.mulP(verts[3], &tverts[3]);
  257. // Points...
  258. S32 firstVert = cf->mVertexList.size();
  259. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[0];
  260. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[1];
  261. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[2];
  262. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[3];
  263. // Edges...
  264. cf->mEdgeList.increment();
  265. cf->mEdgeList.last().vertex[0] = firstVert+0;
  266. cf->mEdgeList.last().vertex[1] = firstVert+1;
  267. cf->mEdgeList.increment();
  268. cf->mEdgeList.last().vertex[0] = firstVert+1;
  269. cf->mEdgeList.last().vertex[1] = firstVert+2;
  270. cf->mEdgeList.increment();
  271. cf->mEdgeList.last().vertex[0] = firstVert+2;
  272. cf->mEdgeList.last().vertex[1] = firstVert+0;
  273. cf->mEdgeList.increment();
  274. cf->mEdgeList.last().vertex[0] = firstVert+3;
  275. cf->mEdgeList.last().vertex[1] = firstVert+0;
  276. cf->mEdgeList.increment();
  277. cf->mEdgeList.last().vertex[0] = firstVert+3;
  278. cf->mEdgeList.last().vertex[1] = firstVert+1;
  279. cf->mEdgeList.increment();
  280. cf->mEdgeList.last().vertex[0] = firstVert+3;
  281. cf->mEdgeList.last().vertex[1] = firstVert+2;
  282. // Triangles...
  283. cf->mFaceList.increment();
  284. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[0]);
  285. cf->mFaceList.last().vertex[0] = firstVert+2;
  286. cf->mFaceList.last().vertex[1] = firstVert+1;
  287. cf->mFaceList.last().vertex[2] = firstVert+0;
  288. cf->mFaceList.increment();
  289. cf->mFaceList.last().normal = PlaneF(tverts[1], tverts[0], tverts[3]);
  290. cf->mFaceList.last().vertex[0] = firstVert+1;
  291. cf->mFaceList.last().vertex[1] = firstVert+0;
  292. cf->mFaceList.last().vertex[2] = firstVert+3;
  293. cf->mFaceList.increment();
  294. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[3]);
  295. cf->mFaceList.last().vertex[0] = firstVert+2;
  296. cf->mFaceList.last().vertex[1] = firstVert+1;
  297. cf->mFaceList.last().vertex[2] = firstVert+3;
  298. cf->mFaceList.increment();
  299. cf->mFaceList.last().normal = PlaneF(tverts[0], tverts[2], tverts[3]);
  300. cf->mFaceList.last().vertex[0] = firstVert+0;
  301. cf->mFaceList.last().vertex[1] = firstVert+2;
  302. cf->mFaceList.last().vertex[2] = firstVert+3;
  303. }
  304. void MeshRoadConvex::getPolyList( AbstractPolyList* list )
  305. {
  306. // Transform the list into object space and set the pointer to the object
  307. //MatrixF i( mObject->getTransform() );
  308. //Point3F iS( mObject->getScale() );
  309. //list->setTransform(&i, iS);
  310. list->setTransform( &MatrixF::Identity, Point3F::One );
  311. list->setObject(mObject);
  312. // Points...
  313. S32 base = list->addPoint(verts[1]);
  314. list->addPoint(verts[2]);
  315. list->addPoint(verts[0]);
  316. list->addPoint(verts[3]);
  317. // Planes...
  318. list->begin(0,0);
  319. list->vertex(base + 2);
  320. list->vertex(base + 1);
  321. list->vertex(base + 0);
  322. list->plane(base + 2, base + 1, base + 0);
  323. list->end();
  324. list->begin(0,0);
  325. list->vertex(base + 2);
  326. list->vertex(base + 1);
  327. list->vertex(base + 3);
  328. list->plane(base + 2, base + 1, base + 3);
  329. list->end();
  330. list->begin(0,0);
  331. list->vertex(base + 3);
  332. list->vertex(base + 1);
  333. list->vertex(base + 0);
  334. list->plane(base + 3, base + 1, base + 0);
  335. list->end();
  336. list->begin(0,0);
  337. list->vertex(base + 2);
  338. list->vertex(base + 3);
  339. list->vertex(base + 0);
  340. list->plane(base + 2, base + 3, base + 0);
  341. list->end();
  342. }
  343. //------------------------------------------------------------------------------
  344. // MeshRoadSegment Class
  345. //------------------------------------------------------------------------------
  346. MeshRoadSegment::MeshRoadSegment()
  347. {
  348. mPlaneCount = 0;
  349. columns = 0;
  350. rows = 0;
  351. numVerts = 0;
  352. numTriangles = 0;
  353. startVert = 0;
  354. endVert = 0;
  355. startIndex = 0;
  356. endIndex = 0;
  357. slice0 = NULL;
  358. slice1 = NULL;
  359. }
  360. MeshRoadSegment::MeshRoadSegment( MeshRoadSlice *rs0, MeshRoadSlice *rs1, const MatrixF &roadMat )
  361. {
  362. columns = 0;
  363. rows = 0;
  364. numVerts = 0;
  365. numTriangles = 0;
  366. startVert = 0;
  367. endVert = 0;
  368. startIndex = 0;
  369. endIndex = 0;
  370. slice0 = rs0;
  371. slice1 = rs1;
  372. // Calculate the bounding box(s)
  373. worldbounds.minExtents = worldbounds.maxExtents = rs0->p0;
  374. worldbounds.extend( rs0->p2 );
  375. worldbounds.extend( rs0->pb0 );
  376. worldbounds.extend( rs0->pb2 );
  377. worldbounds.extend( rs1->p0 );
  378. worldbounds.extend( rs1->p2 );
  379. worldbounds.extend( rs1->pb0 );
  380. worldbounds.extend( rs1->pb2 );
  381. objectbounds = worldbounds;
  382. roadMat.mul( objectbounds );
  383. // Calculate the planes for this segment
  384. // Will be used for intersection/buoyancy tests
  385. mPlaneCount = 6;
  386. mPlanes[0].set( slice0->pb0, slice0->p0, slice1->p0 ); // left
  387. mPlanes[1].set( slice1->pb2, slice1->p2, slice0->p2 ); // right
  388. mPlanes[2].set( slice0->pb2, slice0->p2, slice0->p0 ); // near
  389. mPlanes[3].set( slice1->p0, slice1->p2, slice1->pb2 ); // far
  390. mPlanes[4].set( slice1->p2, slice1->p0, slice0->p0 ); // top
  391. mPlanes[5].set( slice0->pb0, slice1->pb0, slice1->pb2 ); // bottom
  392. }
  393. void MeshRoadSegment::set( MeshRoadSlice *rs0, MeshRoadSlice *rs1 )
  394. {
  395. columns = 0;
  396. rows = 0;
  397. numVerts = 0;
  398. numTriangles = 0;
  399. startVert = 0;
  400. endVert = 0;
  401. startIndex = 0;
  402. endIndex = 0;
  403. slice0 = rs0;
  404. slice1 = rs1;
  405. }
  406. bool MeshRoadSegment::intersectBox( const Box3F &bounds ) const
  407. {
  408. // This code copied from Frustum class.
  409. Point3F maxPoint;
  410. F32 maxDot;
  411. // Note the planes are ordered left, right, near,
  412. // far, top, bottom for getting early rejections
  413. // from the typical horizontal scene.
  414. for ( S32 i = 0; i < mPlaneCount; i++ )
  415. {
  416. // This is pretty much as optimal as you can
  417. // get for a plane vs AABB test...
  418. //
  419. // 4 comparisons
  420. // 3 multiplies
  421. // 2 adds
  422. // 1 negation
  423. //
  424. // It will early out as soon as it detects the
  425. // bounds is outside one of the planes.
  426. if ( mPlanes[i].x > 0 )
  427. maxPoint.x = bounds.maxExtents.x;
  428. else
  429. maxPoint.x = bounds.minExtents.x;
  430. if ( mPlanes[i].y > 0 )
  431. maxPoint.y = bounds.maxExtents.y;
  432. else
  433. maxPoint.y = bounds.minExtents.y;
  434. if ( mPlanes[i].z > 0 )
  435. maxPoint.z = bounds.maxExtents.z;
  436. else
  437. maxPoint.z = bounds.minExtents.z;
  438. maxDot = mDot( maxPoint, mPlanes[ i ] );
  439. if ( maxDot <= -mPlanes[ i ].d )
  440. return false;
  441. }
  442. return true;
  443. }
  444. bool MeshRoadSegment::containsPoint( const Point3F &pnt ) const
  445. {
  446. // This code from Frustum class.
  447. F32 maxDot;
  448. // Note the planes are ordered left, right, near,
  449. // far, top, bottom for getting early rejections
  450. // from the typical horizontal scene.
  451. for ( S32 i = 0; i < mPlaneCount; i++ )
  452. {
  453. const PlaneF &plane = mPlanes[ i ];
  454. // This is pretty much as optimal as you can
  455. // get for a plane vs point test...
  456. //
  457. // 1 comparison
  458. // 2 multiplies
  459. // 1 adds
  460. //
  461. // It will early out as soon as it detects the
  462. // point is outside one of the planes.
  463. maxDot = mDot( pnt, plane ) + plane.d;
  464. if ( maxDot < 0.0f )
  465. return false;
  466. }
  467. return true;
  468. }
  469. F32 MeshRoadSegment::distanceToSurface(const Point3F &pnt) const
  470. {
  471. return mPlanes[4].distToPlane( pnt );
  472. }
  473. //------------------------------------------------------------------------------
  474. // MeshRoad Class
  475. //------------------------------------------------------------------------------
  476. ConsoleDocClass( MeshRoad,
  477. "@brief A strip of rectangular mesh segments defined by a 3D spline "
  478. "for prototyping road-shaped objects in your scene.\n\n"
  479. "User may control width and depth per node, overall spline shape in three "
  480. "dimensions, and seperate Materials for rendering the top, bottom, and side surfaces.\n\n"
  481. "MeshRoad is not capable of handling intersections, branches, curbs, or other "
  482. "desirable features in a final 'road' asset and is therefore intended for "
  483. "prototyping and experimentation.\n\n"
  484. "Materials assigned to MeshRoad should tile vertically.\n\n"
  485. "@ingroup Terrain"
  486. );
  487. bool MeshRoad::smEditorOpen = false;
  488. bool MeshRoad::smShowBatches = false;
  489. bool MeshRoad::smShowSpline = true;
  490. bool MeshRoad::smShowRoad = true;
  491. bool MeshRoad::smWireframe = true;
  492. SimObjectPtr<SimSet> MeshRoad::smServerMeshRoadSet = NULL;
  493. GFXStateBlockRef MeshRoad::smWireframeSB;
  494. IMPLEMENT_CO_NETOBJECT_V1(MeshRoad);
  495. MeshRoad::MeshRoad()
  496. : mTextureLength( 5.0f ),
  497. mBreakAngle( 3.0f ),
  498. mPhysicsRep( NULL ),
  499. mWidthSubdivisions( 0 )
  500. {
  501. mConvexList = new Convex;
  502. // Setup NetObject.
  503. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  504. mNetFlags.set(Ghostable);
  505. mMatInst[Top] = NULL;
  506. mMatInst[Bottom] = NULL;
  507. mMatInst[Side] = NULL;
  508. }
  509. MeshRoad::~MeshRoad()
  510. {
  511. delete mConvexList;
  512. mConvexList = NULL;
  513. }
  514. void MeshRoad::initPersistFields()
  515. {
  516. addGroup( "MeshRoad" );
  517. addField( "topMaterial", TypeMaterialName, Offset( mMaterialName[Top], MeshRoad ),
  518. "Material for the upper surface of the road." );
  519. addField( "bottomMaterial", TypeMaterialName, Offset( mMaterialName[Bottom], MeshRoad ),
  520. "Material for the bottom surface of the road." );
  521. addField( "sideMaterial", TypeMaterialName, Offset( mMaterialName[Side], MeshRoad ),
  522. "Material for the left, right, front, and back surfaces of the road." );
  523. addField( "textureLength", TypeF32, Offset( mTextureLength, MeshRoad ),
  524. "The length in meters of textures mapped to the MeshRoad." );
  525. addField( "breakAngle", TypeF32, Offset( mBreakAngle, MeshRoad ),
  526. "Angle in degrees - MeshRoad will subdivide the spline if its curve is greater than this threshold." );
  527. addField( "widthSubdivisions", TypeS32, Offset( mWidthSubdivisions, MeshRoad ),
  528. "Subdivide segments widthwise this many times when generating vertices." );
  529. endGroup( "MeshRoad" );
  530. addGroup( "Internal" );
  531. addProtectedField( "Node", TypeString, NULL, &addNodeFromField, &emptyStringProtectedGetFn,
  532. "Do not modify, for internal use." );
  533. endGroup( "Internal" );
  534. Parent::initPersistFields();
  535. }
  536. void MeshRoad::consoleInit()
  537. {
  538. Parent::consoleInit();
  539. Con::addVariable( "$MeshRoad::EditorOpen", TypeBool, &MeshRoad::smEditorOpen, "True if the MeshRoad editor is open, otherwise false.\n"
  540. "@ingroup Editors\n");
  541. Con::addVariable( "$MeshRoad::wireframe", TypeBool, &MeshRoad::smWireframe, "If true, will render the wireframe of the road.\n"
  542. "@ingroup Editors\n");
  543. Con::addVariable( "$MeshRoad::showBatches", TypeBool, &MeshRoad::smShowBatches, "Determines if the debug rendering of the batches cubes is displayed or not.\n"
  544. "@ingroup Editors\n");
  545. Con::addVariable( "$MeshRoad::showSpline", TypeBool, &MeshRoad::smShowSpline, "If true, the spline on which the curvature of this road is based will be rendered.\n"
  546. "@ingroup Editors\n");
  547. Con::addVariable( "$MeshRoad::showRoad", TypeBool, &MeshRoad::smShowRoad, "If true, the road will be rendered. When in the editor, roads are always rendered regardless of this flag.\n"
  548. "@ingroup Editors\n");
  549. }
  550. bool MeshRoad::addNodeFromField( void *object, const char *index, const char *data )
  551. {
  552. MeshRoad *pObj = static_cast<MeshRoad*>(object);
  553. //if ( !pObj->isProperlyAdded() )
  554. //{
  555. F32 width, depth;
  556. Point3F pos, normal;
  557. U32 result = dSscanf( data, "%g %g %g %g %g %g %g %g", &pos.x, &pos.y, &pos.z, &width, &depth, &normal.x, &normal.y, &normal.z );
  558. if ( result == 8 )
  559. pObj->_addNode( pos, width, depth, normal );
  560. //}
  561. return false;
  562. }
  563. bool MeshRoad::onAdd()
  564. {
  565. if ( !Parent::onAdd() )
  566. return false;
  567. // Reset the World Box.
  568. //setGlobalBounds();
  569. resetWorldBox();
  570. // Set the Render Transform.
  571. setRenderTransform(mObjToWorld);
  572. // Add to ServerMeshRoadSet
  573. if ( isServerObject() )
  574. {
  575. getServerSet()->addObject( this );
  576. }
  577. if ( isClientObject() )
  578. _initMaterial();
  579. // Generate the Vert/Index buffers and everything else.
  580. _regenerate();
  581. // Add to Scene.
  582. addToScene();
  583. return true;
  584. }
  585. void MeshRoad::onRemove()
  586. {
  587. SAFE_DELETE( mPhysicsRep );
  588. mConvexList->nukeList();
  589. for ( U32 i = 0; i < SurfaceCount; i++ )
  590. {
  591. SAFE_DELETE( mMatInst[i] );
  592. }
  593. removeFromScene();
  594. Parent::onRemove();
  595. }
  596. void MeshRoad::inspectPostApply()
  597. {
  598. // Set Parent.
  599. Parent::inspectPostApply();
  600. //if ( mMetersPerSegment < MIN_METERS_PER_SEGMENT )
  601. // mMetersPerSegment = MIN_METERS_PER_SEGMENT;
  602. setMaskBits(MeshRoadMask);
  603. }
  604. void MeshRoad::onStaticModified( const char* slotName, const char*newValue )
  605. {
  606. Parent::onStaticModified( slotName, newValue );
  607. if ( dStricmp( slotName, "breakAngle" ) == 0 )
  608. {
  609. setMaskBits( RegenMask );
  610. }
  611. }
  612. void MeshRoad::writeFields( Stream &stream, U32 tabStop )
  613. {
  614. Parent::writeFields( stream, tabStop );
  615. // Now write all nodes
  616. stream.write(2, "\r\n");
  617. for ( U32 i = 0; i < mNodes.size(); i++ )
  618. {
  619. const MeshRoadNode &node = mNodes[i];
  620. stream.writeTabs(tabStop);
  621. char buffer[1024];
  622. dMemset( buffer, 0, 1024 );
  623. dSprintf( buffer, 1024, "Node = \"%g %g %g %g %g %g %g %g\";", node.point.x, node.point.y, node.point.z, node.width, node.depth, node.normal.x, node.normal.y, node.normal.z );
  624. stream.writeLine( (const U8*)buffer );
  625. }
  626. }
  627. bool MeshRoad::writeField( StringTableEntry fieldname, const char *value )
  628. {
  629. if ( fieldname == StringTable->insert("Node") )
  630. return false;
  631. return Parent::writeField( fieldname, value );
  632. }
  633. void MeshRoad::onEditorEnable()
  634. {
  635. }
  636. void MeshRoad::onEditorDisable()
  637. {
  638. }
  639. SimSet* MeshRoad::getServerSet()
  640. {
  641. if ( !smServerMeshRoadSet )
  642. {
  643. smServerMeshRoadSet = new SimSet();
  644. smServerMeshRoadSet->registerObject( "ServerMeshRoadSet" );
  645. Sim::getRootGroup()->addObject( smServerMeshRoadSet );
  646. }
  647. return smServerMeshRoadSet;
  648. }
  649. void MeshRoad::prepRenderImage( SceneRenderState* state )
  650. {
  651. if ( mNodes.size() <= 1 )
  652. return;
  653. RenderPassManager *renderPass = state->getRenderPass();
  654. // Normal Road RenderInstance
  655. // Always rendered when the editor is not open
  656. // otherwise obey the smShowRoad flag
  657. if ( smShowRoad || !smEditorOpen )
  658. {
  659. MeshRenderInst coreRI;
  660. coreRI.clear();
  661. coreRI.objectToWorld = &MatrixF::Identity;
  662. coreRI.worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  663. coreRI.projection = renderPass->allocSharedXform(RenderPassManager::Projection);
  664. coreRI.type = RenderPassManager::RIT_Mesh;
  665. BaseMatInstance *matInst;
  666. for ( U32 i = 0; i < SurfaceCount; i++ )
  667. {
  668. matInst = state->getOverrideMaterial( mMatInst[i] );
  669. if ( !matInst )
  670. continue;
  671. // Get the lights if we haven't already.
  672. if ( matInst->isForwardLit() && !coreRI.lights[0] )
  673. {
  674. LightQuery query;
  675. query.init( getWorldSphere() );
  676. query.getLights( coreRI.lights, 8 );
  677. }
  678. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  679. *ri = coreRI;
  680. // Currently rendering whole road, fix to cull and batch
  681. // per segment.
  682. // Set the correct material for rendering.
  683. ri->matInst = matInst;
  684. ri->vertBuff = &mVB[i];
  685. ri->primBuff = &mPB[i];
  686. ri->prim = renderPass->allocPrim();
  687. ri->prim->type = GFXTriangleList;
  688. ri->prim->minIndex = 0;
  689. ri->prim->startIndex = 0;
  690. ri->prim->numPrimitives = mTriangleCount[i];
  691. ri->prim->startVertex = 0;
  692. ri->prim->numVertices = mVertCount[i];
  693. // We sort by the material then vertex buffer.
  694. ri->defaultKey = matInst->getStateHint();
  695. ri->defaultKey2 = (uintptr_t)ri->vertBuff; // Not 64bit safe!
  696. renderPass->addInst( ri );
  697. }
  698. }
  699. // Debug RenderInstance
  700. // Only when editor is open.
  701. if ( smEditorOpen )
  702. {
  703. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  704. ri->renderDelegate.bind( this, &MeshRoad::_debugRender );
  705. ri->type = RenderPassManager::RIT_Editor;
  706. state->getRenderPass()->addInst( ri );
  707. }
  708. }
  709. void MeshRoad::_initMaterial()
  710. {
  711. for ( U32 i = 0; i < SurfaceCount; i++ )
  712. {
  713. if ( mMatInst[i] )
  714. SAFE_DELETE( mMatInst[i] );
  715. if ( mMaterial[i] )
  716. mMatInst[i] = mMaterial[i]->createMatInstance();
  717. else
  718. mMatInst[i] = MATMGR->createMatInstance( "WarningMaterial" );
  719. mMatInst[i]->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTT>() );
  720. }
  721. }
  722. void MeshRoad::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* )
  723. {
  724. //MeshRoadConvex convex;
  725. //buildConvex( Box3F(true), convex );
  726. //convex.render();
  727. //GFXDrawUtil *drawer = GFX->getDrawUtil();
  728. //GFX->setStateBlock( smStateBlock );
  729. return;
  730. /*
  731. U32 convexCount = mDebugConvex.size();
  732. PrimBuild::begin( GFXTriangleList, convexCount * 12 );
  733. PrimBuild::color4i( 0, 0, 255, 155 );
  734. for ( U32 i = 0; i < convexCount; i++ )
  735. {
  736. MeshRoadConvex *convex = mDebugConvex[i];
  737. Point3F a = convex->verts[0];
  738. Point3F b = convex->verts[1];
  739. Point3F c = convex->verts[2];
  740. Point3F p = convex->verts[3];
  741. //mObjToWorld.mulP(a);
  742. //mObjToWorld.mulP(b);
  743. //mObjToWorld.mulP(c);
  744. //mObjToWorld.mulP(p);
  745. PrimBuild::vertex3fv( c );
  746. PrimBuild::vertex3fv( b );
  747. PrimBuild::vertex3fv( a );
  748. PrimBuild::vertex3fv( b );
  749. PrimBuild::vertex3fv( a );
  750. PrimBuild::vertex3fv( p );
  751. PrimBuild::vertex3fv( c );
  752. PrimBuild::vertex3fv( b );
  753. PrimBuild::vertex3fv( p );
  754. PrimBuild::vertex3fv( a );
  755. PrimBuild::vertex3fv( c );
  756. PrimBuild::vertex3fv( p );
  757. }
  758. PrimBuild::end();
  759. for ( U32 i = 0; i < mSegments.size(); i++ )
  760. {
  761. ///GFX->getDrawUtil()->drawWireBox( mSegments[i].worldbounds, ColorI(255,0,0,255) );
  762. }
  763. GFX->enterDebugEvent( ColorI( 255, 0, 0 ), "DecalRoad_debugRender" );
  764. GFXTransformSaver saver;
  765. GFX->setStateBlock( smStateBlock );
  766. Point3F size(1,1,1);
  767. ColorI color( 255, 0, 0, 255 );
  768. if ( smShowBatches )
  769. {
  770. for ( U32 i = 0; i < mBatches.size(); i++ )
  771. {
  772. const Box3F &box = mBatches[i].bounds;
  773. Point3F center;
  774. box.getCenter( &center );
  775. GFX->getDrawUtil()->drawWireCube( ( box.maxExtents - box.minExtents ) * 0.5f, center, ColorI(255,100,100,255) );
  776. }
  777. }
  778. GFX->leaveDebugEvent();
  779. */
  780. }
  781. U32 MeshRoad::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  782. {
  783. U32 retMask = Parent::packUpdate(con, mask, stream);
  784. if ( stream->writeFlag( mask & MeshRoadMask ) )
  785. {
  786. // Write Object Transform.
  787. stream->writeAffineTransform( mObjToWorld );
  788. // Write Materials
  789. stream->write( mMaterialName[0] );
  790. stream->write( mMaterialName[1] );
  791. stream->write( mMaterialName[2] );
  792. stream->write( mTextureLength );
  793. stream->write( mBreakAngle );
  794. stream->write( mWidthSubdivisions );
  795. }
  796. if ( stream->writeFlag( mask & NodeMask ) )
  797. {
  798. const U32 nodeByteSize = 32; // Based on sending all of a node's parameters
  799. // Test if we can fit all of our nodes within the current stream.
  800. // We make sure we leave 100 bytes still free in the stream for whatever
  801. // may follow us.
  802. S32 allowedBytes = stream->getWriteByteSize() - 100;
  803. if ( stream->writeFlag( (nodeByteSize * mNodes.size()) < allowedBytes ) )
  804. {
  805. // All nodes should fit, so send them out now.
  806. stream->writeInt( mNodes.size(), 16 );
  807. for ( U32 i = 0; i < mNodes.size(); i++ )
  808. {
  809. mathWrite( *stream, mNodes[i].point );
  810. stream->write( mNodes[i].width );
  811. stream->write( mNodes[i].depth );
  812. mathWrite( *stream, mNodes[i].normal );
  813. }
  814. }
  815. else
  816. {
  817. // There isn't enough space left in the stream for all of the
  818. // nodes. Batch them up into NetEvents.
  819. U32 id = gServerNodeListManager->nextListId();
  820. U32 count = 0;
  821. U32 index = 0;
  822. while (count < mNodes.size())
  823. {
  824. count += NodeListManager::smMaximumNodesPerEvent;
  825. if (count > mNodes.size())
  826. {
  827. count = mNodes.size();
  828. }
  829. MeshRoadNodeEvent* event = new MeshRoadNodeEvent();
  830. event->mId = id;
  831. event->mTotalNodes = mNodes.size();
  832. event->mLocalListStart = index;
  833. for (; index<count; ++index)
  834. {
  835. event->mPositions.push_back( mNodes[index].point );
  836. event->mWidths.push_back( mNodes[index].width );
  837. event->mDepths.push_back( mNodes[index].depth );
  838. event->mNormals.push_back( mNodes[index].normal );
  839. }
  840. con->postNetEvent( event );
  841. }
  842. stream->write( id );
  843. }
  844. }
  845. stream->writeFlag( mask & RegenMask );
  846. // Were done ...
  847. return retMask;
  848. }
  849. void MeshRoad::unpackUpdate(NetConnection * con, BitStream * stream)
  850. {
  851. // Unpack Parent.
  852. Parent::unpackUpdate(con, stream);
  853. // MeshRoadMask
  854. if(stream->readFlag())
  855. {
  856. MatrixF ObjectMatrix;
  857. stream->readAffineTransform(&ObjectMatrix);
  858. Parent::setTransform(ObjectMatrix);
  859. // Read Materials...
  860. Material *pMat = NULL;
  861. for ( U32 i = 0; i < SurfaceCount; i++ )
  862. {
  863. stream->read( &mMaterialName[i] );
  864. if ( !Sim::findObject( mMaterialName[i], pMat ) )
  865. Con::printf( "DecalRoad::unpackUpdate, failed to find Material of name %s", mMaterialName[i].c_str() );
  866. else
  867. mMaterial[i] = pMat;
  868. }
  869. if ( isProperlyAdded() )
  870. _initMaterial();
  871. stream->read( &mTextureLength );
  872. stream->read( &mBreakAngle );
  873. stream->read( &mWidthSubdivisions );
  874. }
  875. // NodeMask
  876. if ( stream->readFlag() )
  877. {
  878. if (stream->readFlag())
  879. {
  880. // Nodes have been passed in this update
  881. U32 count = stream->readInt( 16 );
  882. mNodes.clear();
  883. Point3F pos, normal;
  884. F32 width, depth;
  885. for ( U32 i = 0; i < count; i++ )
  886. {
  887. mathRead( *stream, &pos );
  888. stream->read( &width );
  889. stream->read( &depth );
  890. mathRead( *stream, &normal );
  891. _addNode( pos, width, depth, normal );
  892. }
  893. }
  894. else
  895. {
  896. // Nodes will arrive as events
  897. U32 id;
  898. stream->read( &id );
  899. // Check if the road's nodes made it here before we did.
  900. NodeListManager::NodeList* list = NULL;
  901. if ( gClientNodeListManager->findListById( id, &list, true) )
  902. {
  903. // Work with the completed list
  904. MeshRoadNodeList* roadList = dynamic_cast<MeshRoadNodeList*>( list );
  905. if (roadList)
  906. buildNodesFromList( roadList );
  907. delete list;
  908. }
  909. else
  910. {
  911. // Nodes have not yet arrived, so register our interest in the list
  912. MeshRoadNodeListNotify* notify = new MeshRoadNodeListNotify( this, id );
  913. gClientNodeListManager->registerNotification( notify );
  914. }
  915. }
  916. }
  917. if ( stream->readFlag() && isProperlyAdded() )
  918. _regenerate();
  919. }
  920. void MeshRoad::setTransform( const MatrixF &mat )
  921. {
  922. for ( U32 i = 0; i < mNodes.size(); i++ )
  923. {
  924. mWorldToObj.mulP( mNodes[i].point );
  925. mat.mulP( mNodes[i].point );
  926. }
  927. Parent::setTransform( mat );
  928. if ( mPhysicsRep )
  929. mPhysicsRep->setTransform( mat );
  930. // Regenerate and update the client
  931. _regenerate();
  932. setMaskBits( NodeMask | RegenMask );
  933. }
  934. void MeshRoad::setScale( const VectorF &scale )
  935. {
  936. // We ignore scale requests from the editor
  937. // right now.
  938. //Parent::setScale( scale );
  939. }
  940. void MeshRoad::buildConvex(const Box3F& box, Convex* convex)
  941. {
  942. if ( mSlices.size() < 2 )
  943. return;
  944. mConvexList->collectGarbage();
  945. mDebugConvex.clear();
  946. Box3F realBox = box;
  947. mWorldToObj.mul(realBox);
  948. realBox.minExtents.convolveInverse(mObjScale);
  949. realBox.maxExtents.convolveInverse(mObjScale);
  950. if (realBox.isOverlapped(getObjBox()) == false)
  951. return;
  952. U32 segmentCount = mSegments.size();
  953. // Create convex(s) for each segment
  954. for ( U32 i = 0; i < segmentCount; i++ )
  955. {
  956. const MeshRoadSegment &segment = mSegments[i];
  957. // Is this segment overlapped?
  958. if ( !segment.getWorldBounds().isOverlapped( box ) )
  959. continue;
  960. // Each segment has 6 faces
  961. for ( U32 j = 0; j < 6; j++ )
  962. {
  963. // Only first segment has front face
  964. if ( j == 4 && i != 0 )
  965. continue;
  966. // Only last segment has back face
  967. if ( j == 5 && i != segmentCount-1 )
  968. continue;
  969. // Each face has 2 convex(s)
  970. for ( U32 k = 0; k < 2; k++ )
  971. {
  972. // See if this convex exists in the working set already...
  973. Convex* cc = 0;
  974. CollisionWorkingList& wl = convex->getWorkingList();
  975. for ( CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext )
  976. {
  977. if ( itr->mConvex->getType() == MeshRoadConvexType )
  978. {
  979. MeshRoadConvex *pConvex = static_cast<MeshRoadConvex*>(itr->mConvex);
  980. if ( pConvex->pRoad == this &&
  981. pConvex->segmentId == i &&
  982. pConvex->faceId == j &&
  983. pConvex->triangleId == k )
  984. {
  985. cc = itr->mConvex;
  986. break;
  987. }
  988. }
  989. }
  990. if (cc)
  991. continue;
  992. // Get the triangle...
  993. U32 idx0 = gIdxArray[j][k][0];
  994. U32 idx1 = gIdxArray[j][k][1];
  995. U32 idx2 = gIdxArray[j][k][2];
  996. Point3F a = segment[idx0];
  997. Point3F b = segment[idx1];
  998. Point3F c = segment[idx2];
  999. // Transform the result into object space!
  1000. //mWorldToObj.mulP( a );
  1001. //mWorldToObj.mulP( b );
  1002. //mWorldToObj.mulP( c );
  1003. PlaneF p( c, b, a );
  1004. Point3F peak = ((a + b + c) / 3.0f) + (p * 0.15f);
  1005. // Set up the convex...
  1006. MeshRoadConvex *cp = new MeshRoadConvex();
  1007. mConvexList->registerObject( cp );
  1008. convex->addToWorkingList( cp );
  1009. cp->mObject = this;
  1010. cp->pRoad = this;
  1011. cp->segmentId = i;
  1012. cp->faceId = j;
  1013. cp->triangleId = k;
  1014. cp->normal = p;
  1015. cp->verts[0] = c;
  1016. cp->verts[1] = b;
  1017. cp->verts[2] = a;
  1018. cp->verts[3] = peak;
  1019. // Update the bounding box.
  1020. Box3F &bounds = cp->box;
  1021. bounds.minExtents.set( F32_MAX, F32_MAX, F32_MAX );
  1022. bounds.maxExtents.set( -F32_MAX, -F32_MAX, -F32_MAX );
  1023. bounds.minExtents.setMin( a );
  1024. bounds.minExtents.setMin( b );
  1025. bounds.minExtents.setMin( c );
  1026. bounds.minExtents.setMin( peak );
  1027. bounds.maxExtents.setMax( a );
  1028. bounds.maxExtents.setMax( b );
  1029. bounds.maxExtents.setMax( c );
  1030. bounds.maxExtents.setMax( peak );
  1031. mDebugConvex.push_back(cp);
  1032. }
  1033. }
  1034. }
  1035. }
  1036. bool MeshRoad::buildPolyList( PolyListContext, AbstractPolyList* polyList, const Box3F &box, const SphereF & )
  1037. {
  1038. if ( mSlices.size() < 2 )
  1039. return false;
  1040. polyList->setTransform( &MatrixF::Identity, Point3F::One );
  1041. polyList->setObject(this);
  1042. // JCF: optimize this to not always add everything.
  1043. return buildSegmentPolyList( polyList, 0, mSegments.size() - 1, true, true );
  1044. }
  1045. bool MeshRoad::buildSegmentPolyList( AbstractPolyList* polyList, U32 startSegIdx, U32 endSegIdx, bool capFront, bool capEnd )
  1046. {
  1047. if ( mSlices.size() < 2 )
  1048. return false;
  1049. // Add verts
  1050. for ( U32 i = startSegIdx; i <= endSegIdx; i++ )
  1051. {
  1052. const MeshRoadSegment &seg = mSegments[i];
  1053. if ( i == startSegIdx )
  1054. {
  1055. polyList->addPoint( seg.slice0->p0 );
  1056. polyList->addPoint( seg.slice0->p2 );
  1057. polyList->addPoint( seg.slice0->pb0 );
  1058. polyList->addPoint( seg.slice0->pb2 );
  1059. }
  1060. polyList->addPoint( seg.slice1->p0 );
  1061. polyList->addPoint( seg.slice1->p2 );
  1062. polyList->addPoint( seg.slice1->pb0 );
  1063. polyList->addPoint( seg.slice1->pb2 );
  1064. }
  1065. // Temporaries to hold indices for the corner points of a quad.
  1066. S32 p00, p01, p11, p10;
  1067. S32 pb00, pb01, pb11, pb10;
  1068. U32 offset = 0;
  1069. DebugDrawer *ddraw = NULL;//DebugDrawer::get();
  1070. ClippedPolyList *cpolyList = dynamic_cast<ClippedPolyList*>(polyList);
  1071. MatrixF mat;
  1072. Point3F scale;
  1073. if ( cpolyList )
  1074. cpolyList->getTransform( &mat, &scale );
  1075. for ( U32 i = startSegIdx; i <= endSegIdx; i++ )
  1076. {
  1077. p00 = offset;
  1078. p10 = offset + 1;
  1079. pb00 = offset + 2;
  1080. pb10 = offset + 3;
  1081. p01 = offset + 4;
  1082. p11 = offset + 5;
  1083. pb01 = offset + 6;
  1084. pb11 = offset + 7;
  1085. // Top Face
  1086. polyList->begin( 0,0 );
  1087. polyList->vertex( p00 );
  1088. polyList->vertex( p01 );
  1089. polyList->vertex( p11 );
  1090. polyList->plane( p00, p01, p11 );
  1091. polyList->end();
  1092. if ( ddraw && cpolyList )
  1093. {
  1094. Point3F v0 = cpolyList->mVertexList[p00].point;
  1095. mat.mulP( v0 );
  1096. Point3F v1 = cpolyList->mVertexList[p01].point;
  1097. mat.mulP( v1 );
  1098. Point3F v2 = cpolyList->mVertexList[p11].point;
  1099. mat.mulP( v2 );
  1100. ddraw->drawTri( v0, v1, v2 );
  1101. ddraw->setLastZTest( false );
  1102. ddraw->setLastTTL( 0 );
  1103. }
  1104. polyList->begin( 0,0 );
  1105. polyList->vertex( p00 );
  1106. polyList->vertex( p11 );
  1107. polyList->vertex( p10 );
  1108. polyList->plane( p00, p11, p10 );
  1109. polyList->end();
  1110. if ( ddraw && cpolyList )
  1111. {
  1112. ddraw->drawTri( cpolyList->mVertexList[p00].point, cpolyList->mVertexList[p11].point, cpolyList->mVertexList[p10].point );
  1113. ddraw->setLastTTL( 0 );
  1114. }
  1115. // Left Face
  1116. polyList->begin( 0,0 );
  1117. polyList->vertex( pb00 );
  1118. polyList->vertex( pb01 );
  1119. polyList->vertex( p01 );
  1120. polyList->plane( pb00, pb01, p01 );
  1121. polyList->end();
  1122. polyList->begin( 0,0 );
  1123. polyList->vertex( pb00 );
  1124. polyList->vertex( p01 );
  1125. polyList->vertex( p00 );
  1126. polyList->plane( pb00, p01, p00 );
  1127. polyList->end();
  1128. // Right Face
  1129. polyList->begin( 0,0 );
  1130. polyList->vertex( p10 );
  1131. polyList->vertex( p11 );
  1132. polyList->vertex( pb11 );
  1133. polyList->plane( p10, p11, pb11 );
  1134. polyList->end();
  1135. polyList->begin( 0,0 );
  1136. polyList->vertex( p10 );
  1137. polyList->vertex( pb11 );
  1138. polyList->vertex( pb10 );
  1139. polyList->plane( p10, pb11, pb10 );
  1140. polyList->end();
  1141. // Bottom Face
  1142. polyList->begin( 0,0 );
  1143. polyList->vertex( pb00 );
  1144. polyList->vertex( pb10 );
  1145. polyList->vertex( pb11 );
  1146. polyList->plane( pb00, pb10, pb11 );
  1147. polyList->end();
  1148. polyList->begin( 0,0 );
  1149. polyList->vertex( pb00 );
  1150. polyList->vertex( pb11 );
  1151. polyList->vertex( pb01 );
  1152. polyList->plane( pb00, pb11, pb01 );
  1153. polyList->end();
  1154. // Front Face
  1155. if ( i == startSegIdx && capFront )
  1156. {
  1157. polyList->begin( 0,0 );
  1158. polyList->vertex( p00 );
  1159. polyList->vertex( p10 );
  1160. polyList->vertex( pb10 );
  1161. polyList->plane( p00, p10, pb10 );
  1162. polyList->end();
  1163. polyList->begin( 0,0 );
  1164. polyList->vertex( p00 );
  1165. polyList->vertex( pb10 );
  1166. polyList->vertex( pb00 );
  1167. polyList->plane( p00, pb10, pb00 );
  1168. polyList->end();
  1169. }
  1170. // Back Face
  1171. if ( i == endSegIdx && capEnd )
  1172. {
  1173. polyList->begin( 0,0 );
  1174. polyList->vertex( p01 );
  1175. polyList->vertex( pb01 );
  1176. polyList->vertex( pb11 );
  1177. polyList->plane( p01, pb01, pb11 );
  1178. polyList->end();
  1179. polyList->begin( 0,0 );
  1180. polyList->vertex( p01 );
  1181. polyList->vertex( pb11 );
  1182. polyList->vertex( p11 );
  1183. polyList->plane( p01, pb11, p11 );
  1184. polyList->end();
  1185. }
  1186. offset += 4;
  1187. }
  1188. return true;
  1189. }
  1190. bool MeshRoad::castRay( const Point3F &s, const Point3F &e, RayInfo *info )
  1191. {
  1192. Point3F start = s;
  1193. Point3F end = e;
  1194. mObjToWorld.mulP(start);
  1195. mObjToWorld.mulP(end);
  1196. F32 out = 1.0f; // The output fraction/percentage along the line defined by s and e
  1197. VectorF norm(0.0f, 0.0f, 0.0f); // The normal of the face intersected
  1198. Vector<MeshRoadHitSegment> hitSegments;
  1199. for ( U32 i = 0; i < mSegments.size(); i++ )
  1200. {
  1201. const MeshRoadSegment &segment = mSegments[i];
  1202. F32 t;
  1203. VectorF n;
  1204. if ( segment.getWorldBounds().collideLine( start, end, &t, &n ) )
  1205. {
  1206. hitSegments.increment();
  1207. hitSegments.last().t = t;
  1208. hitSegments.last().idx = i;
  1209. }
  1210. }
  1211. dQsort( hitSegments.address(), hitSegments.size(), sizeof(MeshRoadHitSegment), compareHitSegments );
  1212. U32 idx0, idx1, idx2;
  1213. F32 t;
  1214. for ( U32 i = 0; i < hitSegments.size(); i++ )
  1215. {
  1216. U32 segIdx = hitSegments[i].idx;
  1217. const MeshRoadSegment &segment = mSegments[segIdx];
  1218. // Each segment has 6 faces
  1219. for ( U32 j = 0; j < 6; j++ )
  1220. {
  1221. if ( j == 4 && segIdx != 0 )
  1222. continue;
  1223. if ( j == 5 && segIdx != mSegments.size() - 1 )
  1224. continue;
  1225. // Each face has 2 triangles
  1226. for ( U32 k = 0; k < 2; k++ )
  1227. {
  1228. idx0 = gIdxArray[j][k][0];
  1229. idx1 = gIdxArray[j][k][1];
  1230. idx2 = gIdxArray[j][k][2];
  1231. const Point3F &v0 = segment[idx0];
  1232. const Point3F &v1 = segment[idx1];
  1233. const Point3F &v2 = segment[idx2];
  1234. if ( !MathUtils::mLineTriangleCollide( start, end,
  1235. v2, v1, v0,
  1236. NULL,
  1237. &t ) )
  1238. continue;
  1239. if ( t >= 0.0f && t < 1.0f && t < out )
  1240. {
  1241. out = t;
  1242. norm = PlaneF( v0, v1, v2 );
  1243. }
  1244. }
  1245. }
  1246. if (out >= 0.0f && out < 1.0f)
  1247. break;
  1248. }
  1249. if (out >= 0.0f && out < 1.0f)
  1250. {
  1251. info->t = out;
  1252. info->normal = norm;
  1253. info->point.interpolate(start, end, out);
  1254. info->face = -1;
  1255. info->object = this;
  1256. info->material = this->mMatInst[0];
  1257. return true;
  1258. }
  1259. return false;
  1260. }
  1261. bool MeshRoad::collideBox(const Point3F &start, const Point3F &end, RayInfo* info)
  1262. {
  1263. Con::warnf( "MeshRoad::collideBox() - not yet implemented!" );
  1264. return Parent::collideBox( start, end, info );
  1265. }
  1266. void MeshRoad::_regenerate()
  1267. {
  1268. if ( mNodes.size() == 0 )
  1269. return;
  1270. const Point3F &nodePt = mNodes.first().point;
  1271. MatrixF mat( true );
  1272. mat.setPosition( nodePt );
  1273. Parent::setTransform( mat );
  1274. _generateSlices();
  1275. // Make sure we are in the correct bins given our world box.
  1276. if( getSceneManager() != NULL )
  1277. getSceneManager()->notifyObjectDirty( this );
  1278. }
  1279. void MeshRoad::_generateSlices()
  1280. {
  1281. if ( mNodes.size() < 2 )
  1282. return;
  1283. // Create the spline, initialized with the MeshRoadNode(s)
  1284. U32 nodeCount = mNodes.size();
  1285. MeshRoadSplineNode *splineNodes = new MeshRoadSplineNode[nodeCount];
  1286. for ( U32 i = 0; i < nodeCount; i++ )
  1287. {
  1288. MeshRoadSplineNode &splineNode = splineNodes[i];
  1289. const MeshRoadNode &node = mNodes[i];
  1290. splineNode.x = node.point.x;
  1291. splineNode.y = node.point.y;
  1292. splineNode.z = node.point.z;
  1293. splineNode.width = node.width;
  1294. splineNode.depth = node.depth;
  1295. splineNode.normal = node.normal;
  1296. }
  1297. CatmullRom<MeshRoadSplineNode> spline;
  1298. spline.initialize( nodeCount, splineNodes );
  1299. delete [] splineNodes;
  1300. mSlices.clear();
  1301. VectorF lastBreakVector(0,0,0);
  1302. MeshRoadSlice slice;
  1303. MeshRoadSplineNode lastBreakNode;
  1304. lastBreakNode = spline.evaluate(0.0f);
  1305. for ( U32 i = 1; i < mNodes.size(); i++ )
  1306. {
  1307. F32 t1 = spline.getTime(i);
  1308. F32 t0 = spline.getTime(i-1);
  1309. F32 segLength = spline.arcLength( t0, t1 );
  1310. U32 numSegments = mCeil( segLength / MIN_METERS_PER_SEGMENT );
  1311. numSegments = getMax( numSegments, (U32)1 );
  1312. F32 tstep = ( t1 - t0 ) / numSegments;
  1313. U32 startIdx = 0;
  1314. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  1315. for ( U32 j = startIdx; j < endIdx; j++ )
  1316. {
  1317. F32 t = t0 + tstep * j;
  1318. MeshRoadSplineNode splineNode = spline.evaluate(t);
  1319. VectorF toNodeVec = splineNode.getPosition() - lastBreakNode.getPosition();
  1320. toNodeVec.normalizeSafe();
  1321. if ( lastBreakVector.isZero() )
  1322. lastBreakVector = toNodeVec;
  1323. F32 angle = mRadToDeg( mAcos( mDot( toNodeVec, lastBreakVector ) ) );
  1324. if ( j == startIdx ||
  1325. ( j == endIdx - 1 && i == mNodes.size() - 1 ) ||
  1326. angle > mBreakAngle )
  1327. {
  1328. // Push back a spline node
  1329. slice.p1.set( splineNode.x, splineNode.y, splineNode.z );
  1330. slice.width = splineNode.width;
  1331. slice.depth = splineNode.depth;
  1332. slice.normal = splineNode.normal;
  1333. slice.normal.normalize();
  1334. slice.parentNodeIdx = i-1;
  1335. slice.t = t;
  1336. mSlices.push_back( slice );
  1337. lastBreakVector = splineNode.getPosition() - lastBreakNode.getPosition();
  1338. lastBreakVector.normalizeSafe();
  1339. lastBreakNode = splineNode;
  1340. }
  1341. }
  1342. }
  1343. //
  1344. // Calculate uvec, fvec, and rvec for all slices
  1345. //
  1346. MatrixF mat(true);
  1347. for ( U32 i = 0; i < mSlices.size(); i++ )
  1348. {
  1349. calcSliceTransform( i, mat );
  1350. mat.getColumn( 0, &mSlices[i].rvec );
  1351. mat.getColumn( 1, &mSlices[i].fvec );
  1352. mat.getColumn( 2, &mSlices[i].uvec );
  1353. }
  1354. //
  1355. // Calculate p0/p2/pb0/pb2 for all slices
  1356. //
  1357. for ( U32 i = 0; i < mSlices.size(); i++ )
  1358. {
  1359. MeshRoadSlice *slice = &mSlices[i];
  1360. slice->p0 = slice->p1 - slice->rvec * slice->width * 0.5f;
  1361. slice->p2 = slice->p1 + slice->rvec * slice->width * 0.5f;
  1362. slice->pb0 = slice->p0 - slice->uvec * slice->depth;
  1363. slice->pb2 = slice->p2 - slice->uvec * slice->depth;
  1364. }
  1365. // Generate the object/world bounds
  1366. Box3F box;
  1367. for ( U32 i = 0; i < mSlices.size(); i++ )
  1368. {
  1369. const MeshRoadSlice &slice = mSlices[i];
  1370. if ( i == 0 )
  1371. {
  1372. box.minExtents = slice.p0;
  1373. box.maxExtents = slice.p2;
  1374. box.extend( slice.pb0 );
  1375. box.extend( slice.pb2 );
  1376. }
  1377. else
  1378. {
  1379. box.extend( slice.p0 );
  1380. box.extend( slice.p2 );
  1381. box.extend( slice.pb0 );
  1382. box.extend( slice.pb2 );
  1383. }
  1384. }
  1385. mWorldBox = box;
  1386. resetObjectBox();
  1387. _generateSegments();
  1388. }
  1389. void MeshRoad::_generateSegments()
  1390. {
  1391. SAFE_DELETE( mPhysicsRep );
  1392. mSegments.clear();
  1393. for ( U32 i = 0; i < mSlices.size() - 1; i++ )
  1394. {
  1395. MeshRoadSegment seg( &mSlices[i], &mSlices[i+1], getWorldTransform() );
  1396. mSegments.push_back( seg );
  1397. }
  1398. if ( isClientObject() )
  1399. _generateVerts();
  1400. if ( PHYSICSMGR )
  1401. {
  1402. ConcretePolyList polylist;
  1403. if ( buildPolyList( PLC_Collision, &polylist, getWorldBox(), getWorldSphere() ) )
  1404. {
  1405. polylist.triangulate();
  1406. PhysicsCollision *colShape = PHYSICSMGR->createCollision();
  1407. colShape->addTriangleMesh( polylist.mVertexList.address(),
  1408. polylist.mVertexList.size(),
  1409. polylist.mIndexList.address(),
  1410. polylist.mIndexList.size() / 3,
  1411. MatrixF::Identity );
  1412. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  1413. mPhysicsRep = PHYSICSMGR->createBody();
  1414. mPhysicsRep->init( colShape, 0, 0, this, world );
  1415. }
  1416. }
  1417. }
  1418. void MeshRoad::_generateVerts()
  1419. {
  1420. const U32 widthDivisions = getMax( 0, mWidthSubdivisions );
  1421. const F32 divisionStep = 1.0f / (F32)( widthDivisions + 1 );
  1422. const U32 sliceCount = mSlices.size();
  1423. const U32 segmentCount = mSegments.size();
  1424. mVertCount[Top] = ( 2 + widthDivisions ) * sliceCount;
  1425. mTriangleCount[Top] = segmentCount * 2 * ( widthDivisions + 1 );
  1426. mVertCount[Bottom] = sliceCount * 2;
  1427. mTriangleCount[Bottom] = segmentCount * 2;
  1428. mVertCount[Side] = sliceCount * 4;
  1429. mTriangleCount[Side] = segmentCount * 4 + 4;
  1430. // Calculate TexCoords for Slices
  1431. F32 texCoordV = 0.0f;
  1432. mSlices[0].texCoordV = 0.0f;
  1433. for ( U32 i = 1; i < sliceCount; i++ )
  1434. {
  1435. MeshRoadSlice &slice = mSlices[i];
  1436. MeshRoadSlice &prevSlice = mSlices[i-1];
  1437. // Increment the textCoordV for the next slice.
  1438. F32 len = ( slice.p1 - prevSlice.p1 ).len();
  1439. texCoordV += len / mTextureLength;
  1440. slice.texCoordV = texCoordV;
  1441. }
  1442. // Make Vertex Buffers
  1443. GFXVertexPNTT *pVert = NULL;
  1444. U32 vertCounter = 0;
  1445. // Top Buffers...
  1446. mVB[Top].set( GFX, mVertCount[Top], GFXBufferTypeStatic );
  1447. pVert = mVB[Top].lock();
  1448. vertCounter = 0;
  1449. for ( U32 i = 0; i < sliceCount; i++ )
  1450. {
  1451. MeshRoadSlice &slice = mSlices[i];
  1452. pVert->point = slice.p0;
  1453. pVert->normal = slice.uvec;
  1454. pVert->tangent = slice.fvec;
  1455. pVert->texCoord.set(1,slice.texCoordV);
  1456. pVert++;
  1457. vertCounter++;
  1458. for ( U32 j = 0; j < widthDivisions; j++ )
  1459. {
  1460. const F32 t = divisionStep * (F32)( j + 1 );
  1461. pVert->point.interpolate( slice.p0, slice.p2, t );
  1462. pVert->normal = slice.uvec;
  1463. pVert->tangent = slice.fvec;
  1464. pVert->texCoord.set( 1.0f - t, slice.texCoordV );
  1465. pVert++;
  1466. vertCounter++;
  1467. }
  1468. pVert->point = slice.p2;
  1469. pVert->normal = slice.uvec;
  1470. pVert->tangent = slice.fvec;
  1471. pVert->texCoord.set( 0, slice.texCoordV );
  1472. pVert++;
  1473. vertCounter++;
  1474. }
  1475. AssertFatal( vertCounter == mVertCount[Top], "MeshRoad, wrote incorrect number of verts in mVB[Top]!" );
  1476. mVB[Top].unlock();
  1477. // Bottom Buffer...
  1478. mVB[Bottom].set( GFX, mVertCount[Bottom], GFXBufferTypeStatic );
  1479. pVert = mVB[Bottom].lock();
  1480. vertCounter = 0;
  1481. for ( U32 i = 0; i < sliceCount; i++ )
  1482. {
  1483. MeshRoadSlice &slice = mSlices[i];
  1484. pVert->point = slice.pb2;
  1485. pVert->normal = -slice.uvec;
  1486. pVert->tangent = slice.fvec;
  1487. pVert->texCoord.set(0,slice.texCoordV);
  1488. pVert++;
  1489. vertCounter++;
  1490. pVert->point = slice.pb0;
  1491. pVert->normal = -slice.uvec;
  1492. pVert->tangent = slice.fvec;
  1493. pVert->texCoord.set(1,slice.texCoordV);
  1494. pVert++;
  1495. vertCounter++;
  1496. }
  1497. AssertFatal( vertCounter == mVertCount[Bottom], "MeshRoad, wrote incorrect number of verts in mVB[Bottom]!" );
  1498. mVB[Bottom].unlock();
  1499. // Side Buffers...
  1500. mVB[Side].set( GFX, mVertCount[Side], GFXBufferTypeStatic );
  1501. pVert = mVB[Side].lock();
  1502. vertCounter = 0;
  1503. for ( U32 i = 0; i < sliceCount; i++ )
  1504. {
  1505. MeshRoadSlice &slice = mSlices[i];
  1506. pVert->point = slice.p0;
  1507. pVert->normal = -slice.rvec;
  1508. pVert->tangent = slice.fvec;
  1509. pVert->texCoord.set(1,slice.texCoordV);
  1510. pVert++;
  1511. vertCounter++;
  1512. pVert->point = slice.p2;
  1513. pVert->normal = slice.rvec;
  1514. pVert->tangent = slice.fvec;
  1515. pVert->texCoord.set(1,slice.texCoordV);
  1516. pVert++;
  1517. vertCounter++;
  1518. pVert->point = slice.pb0;
  1519. pVert->normal = -slice.rvec;
  1520. pVert->tangent = slice.fvec;
  1521. pVert->texCoord.set(0,slice.texCoordV);
  1522. pVert++;
  1523. vertCounter++;
  1524. pVert->point = slice.pb2;
  1525. pVert->normal = slice.rvec;
  1526. pVert->tangent = slice.fvec;
  1527. pVert->texCoord.set(0,slice.texCoordV);
  1528. pVert++;
  1529. vertCounter++;
  1530. }
  1531. AssertFatal( vertCounter == mVertCount[Side], "MeshRoad, wrote incorrect number of verts in mVB[Side]!" );
  1532. mVB[Side].unlock();
  1533. // Make Primitive Buffers
  1534. U32 p00, p01, p11, p10;
  1535. U32 pb00, pb01, pb11, pb10;
  1536. U32 offset = 0;
  1537. U16 *pIdx = NULL;
  1538. U32 curIdx = 0;
  1539. // Top Primitive Buffer
  1540. mPB[Top].set( GFX, mTriangleCount[Top] * 3, mTriangleCount[Top], GFXBufferTypeStatic );
  1541. mPB[Top].lock(&pIdx);
  1542. curIdx = 0;
  1543. offset = 0;
  1544. const U32 rowStride = 2 + widthDivisions;
  1545. for ( U32 i = 0; i < mSegments.size(); i++ )
  1546. {
  1547. for ( U32 j = 0; j < widthDivisions + 1; j++ )
  1548. {
  1549. p00 = offset;
  1550. p10 = offset + 1;
  1551. p01 = offset + rowStride;
  1552. p11 = offset + rowStride + 1;
  1553. pIdx[curIdx] = p00;
  1554. curIdx++;
  1555. pIdx[curIdx] = p01;
  1556. curIdx++;
  1557. pIdx[curIdx] = p11;
  1558. curIdx++;
  1559. pIdx[curIdx] = p00;
  1560. curIdx++;
  1561. pIdx[curIdx] = p11;
  1562. curIdx++;
  1563. pIdx[curIdx] = p10;
  1564. curIdx++;
  1565. offset += 1;
  1566. }
  1567. offset += 1;
  1568. }
  1569. AssertFatal( curIdx == mTriangleCount[Top] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Top]!" );
  1570. mPB[Top].unlock();
  1571. // Bottom Primitive Buffer
  1572. mPB[Bottom].set( GFX, mTriangleCount[Bottom] * 3, mTriangleCount[Bottom], GFXBufferTypeStatic );
  1573. mPB[Bottom].lock(&pIdx);
  1574. curIdx = 0;
  1575. offset = 0;
  1576. for ( U32 i = 0; i < mSegments.size(); i++ )
  1577. {
  1578. p00 = offset;
  1579. p10 = offset + 1;
  1580. p01 = offset + 2;
  1581. p11 = offset + 3;
  1582. pIdx[curIdx] = p00;
  1583. curIdx++;
  1584. pIdx[curIdx] = p01;
  1585. curIdx++;
  1586. pIdx[curIdx] = p11;
  1587. curIdx++;
  1588. pIdx[curIdx] = p00;
  1589. curIdx++;
  1590. pIdx[curIdx] = p11;
  1591. curIdx++;
  1592. pIdx[curIdx] = p10;
  1593. curIdx++;
  1594. offset += 2;
  1595. }
  1596. AssertFatal( curIdx == mTriangleCount[Bottom] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Bottom]!" );
  1597. mPB[Bottom].unlock();
  1598. // Side Primitive Buffer
  1599. mPB[Side].set( GFX, mTriangleCount[Side] * 3, mTriangleCount[Side], GFXBufferTypeStatic );
  1600. mPB[Side].lock(&pIdx);
  1601. curIdx = 0;
  1602. offset = 0;
  1603. for ( U32 i = 0; i < mSegments.size(); i++ )
  1604. {
  1605. p00 = offset;
  1606. p10 = offset + 1;
  1607. pb00 = offset + 2;
  1608. pb10 = offset + 3;
  1609. p01 = offset + 4;
  1610. p11 = offset + 5;
  1611. pb01 = offset + 6;
  1612. pb11 = offset + 7;
  1613. // Left Side
  1614. pIdx[curIdx] = pb00;
  1615. curIdx++;
  1616. pIdx[curIdx] = pb01;
  1617. curIdx++;
  1618. pIdx[curIdx] = p01;
  1619. curIdx++;
  1620. pIdx[curIdx] = pb00;
  1621. curIdx++;
  1622. pIdx[curIdx] = p01;
  1623. curIdx++;
  1624. pIdx[curIdx] = p00;
  1625. curIdx++;
  1626. // Right Side
  1627. pIdx[curIdx] = p10;
  1628. curIdx++;
  1629. pIdx[curIdx] = p11;
  1630. curIdx++;
  1631. pIdx[curIdx] = pb11;
  1632. curIdx++;
  1633. pIdx[curIdx] = p10;
  1634. curIdx++;
  1635. pIdx[curIdx] = pb11;
  1636. curIdx++;
  1637. pIdx[curIdx] = pb10;
  1638. curIdx++;
  1639. offset += 4;
  1640. }
  1641. // Cap the front and back ends
  1642. pIdx[curIdx++] = 0;
  1643. pIdx[curIdx++] = 1;
  1644. pIdx[curIdx++] = 3;
  1645. pIdx[curIdx++] = 0;
  1646. pIdx[curIdx++] = 3;
  1647. pIdx[curIdx++] = 2;
  1648. pIdx[curIdx++] = offset + 0;
  1649. pIdx[curIdx++] = offset + 3;
  1650. pIdx[curIdx++] = offset + 1;
  1651. pIdx[curIdx++] = offset + 0;
  1652. pIdx[curIdx++] = offset + 2;
  1653. pIdx[curIdx++] = offset + 3;
  1654. AssertFatal( curIdx == mTriangleCount[Side] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Side]!" );
  1655. mPB[Side].unlock();
  1656. }
  1657. const MeshRoadNode& MeshRoad::getNode( U32 idx )
  1658. {
  1659. return mNodes[idx];
  1660. }
  1661. VectorF MeshRoad::getNodeNormal( U32 idx )
  1662. {
  1663. if ( mNodes.size() - 1 < idx )
  1664. return VectorF::Zero;
  1665. return mNodes[idx].normal;
  1666. }
  1667. void MeshRoad::setNodeNormal( U32 idx, const VectorF &normal )
  1668. {
  1669. if ( mNodes.size() - 1 < idx )
  1670. return;
  1671. mNodes[idx].normal = normal;
  1672. regenerate();
  1673. setMaskBits( NodeMask | RegenMask );
  1674. }
  1675. Point3F MeshRoad::getNodePosition( U32 idx )
  1676. {
  1677. if ( mNodes.size() - 1 < idx )
  1678. return Point3F::Zero;
  1679. return mNodes[idx].point;
  1680. }
  1681. void MeshRoad::setNodePosition( U32 idx, const Point3F &pos )
  1682. {
  1683. if ( mNodes.size() - 1 < idx )
  1684. return;
  1685. mNodes[idx].point = pos;
  1686. regenerate();
  1687. setMaskBits( NodeMask | RegenMask );
  1688. }
  1689. U32 MeshRoad::addNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal )
  1690. {
  1691. U32 idx = _addNode( pos, width, depth, normal );
  1692. regenerate();
  1693. setMaskBits( NodeMask | RegenMask );
  1694. return idx;
  1695. }
  1696. void MeshRoad::buildNodesFromList( MeshRoadNodeList* list )
  1697. {
  1698. mNodes.clear();
  1699. for (U32 i=0; i<list->mPositions.size(); ++i)
  1700. {
  1701. _addNode( list->mPositions[i], list->mWidths[i], list->mDepths[i], list->mNormals[i] );
  1702. }
  1703. _regenerate();
  1704. }
  1705. U32 MeshRoad::insertNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1706. {
  1707. U32 ret = _insertNode( pos, width, depth, normal, idx );
  1708. regenerate();
  1709. setMaskBits( NodeMask | RegenMask );
  1710. return ret;
  1711. }
  1712. void MeshRoad::setNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1713. {
  1714. if ( mNodes.size() - 1 < idx )
  1715. return;
  1716. MeshRoadNode &node = mNodes[idx];
  1717. node.point = pos;
  1718. node.width = width;
  1719. node.depth = depth;
  1720. node.normal = normal;
  1721. regenerate();
  1722. setMaskBits( NodeMask | RegenMask );
  1723. }
  1724. void MeshRoad::setNodeWidth( U32 idx, F32 meters )
  1725. {
  1726. meters = mClampF( meters, MIN_NODE_WIDTH, MAX_NODE_WIDTH );
  1727. if ( mNodes.size() - 1 < idx )
  1728. return;
  1729. mNodes[idx].width = meters;
  1730. _regenerate();
  1731. setMaskBits( RegenMask | NodeMask );
  1732. }
  1733. F32 MeshRoad::getNodeWidth( U32 idx )
  1734. {
  1735. if ( mNodes.size() - 1 < idx )
  1736. return -1.0f;
  1737. return mNodes[idx].width;
  1738. }
  1739. void MeshRoad::setNodeDepth( U32 idx, F32 meters )
  1740. {
  1741. meters = mClampF( meters, MIN_NODE_DEPTH, MAX_NODE_DEPTH );
  1742. if ( mNodes.size() - 1 < idx )
  1743. return;
  1744. mNodes[idx].depth = meters;
  1745. _regenerate();
  1746. setMaskBits( MeshRoadMask | RegenMask | NodeMask );
  1747. }
  1748. F32 MeshRoad::getNodeDepth( U32 idx )
  1749. {
  1750. if ( mNodes.size() - 1 < idx )
  1751. return -1.0f;
  1752. return mNodes[idx].depth;
  1753. }
  1754. MatrixF MeshRoad::getNodeTransform( U32 idx )
  1755. {
  1756. MatrixF mat(true);
  1757. if ( mNodes.size() - 1 < idx )
  1758. return mat;
  1759. bool hasNext = idx + 1 < mNodes.size();
  1760. bool hasPrev = (S32)idx - 1 > 0;
  1761. const MeshRoadNode &node = mNodes[idx];
  1762. VectorF fvec( 0, 1, 0 );
  1763. if ( hasNext )
  1764. {
  1765. fvec = mNodes[idx+1].point - node.point;
  1766. fvec.normalizeSafe();
  1767. }
  1768. else if ( hasPrev )
  1769. {
  1770. fvec = node.point - mNodes[idx-1].point;
  1771. fvec.normalizeSafe();
  1772. }
  1773. else
  1774. fvec = mPerp( node.normal );
  1775. if ( fvec.isZero() )
  1776. fvec = mPerp( node.normal );
  1777. F32 dot = mDot( fvec, node.normal );
  1778. if ( dot < -0.9f || dot > 0.9f )
  1779. fvec = mPerp( node.normal );
  1780. VectorF rvec = mCross( fvec, node.normal );
  1781. if ( rvec.isZero() )
  1782. rvec = mPerp( fvec );
  1783. rvec.normalize();
  1784. fvec = mCross( node.normal, rvec );
  1785. fvec.normalize();
  1786. mat.setColumn( 0, rvec );
  1787. mat.setColumn( 1, fvec );
  1788. mat.setColumn( 2, node.normal );
  1789. mat.setColumn( 3, node.point );
  1790. AssertFatal( m_matF_determinant( mat ) != 0.0f, "no inverse!");
  1791. return mat;
  1792. }
  1793. void MeshRoad::calcSliceTransform( U32 idx, MatrixF &mat )
  1794. {
  1795. if ( mSlices.size() - 1 < idx )
  1796. return;
  1797. bool hasNext = idx + 1 < mSlices.size();
  1798. bool hasPrev = (S32)idx - 1 >= 0;
  1799. const MeshRoadSlice &slice = mSlices[idx];
  1800. VectorF fvec( 0, 1, 0 );
  1801. if ( hasNext )
  1802. {
  1803. fvec = mSlices[idx+1].p1 - slice.p1;
  1804. fvec.normalizeSafe();
  1805. }
  1806. else if ( hasPrev )
  1807. {
  1808. fvec = slice.p1 - mSlices[idx-1].p1;
  1809. fvec.normalizeSafe();
  1810. }
  1811. else
  1812. fvec = mPerp( slice.normal );
  1813. if ( fvec.isZero() )
  1814. fvec = mPerp( slice.normal );
  1815. F32 dot = mDot( fvec, slice.normal );
  1816. if ( dot < -0.9f || dot > 0.9f )
  1817. fvec = mPerp( slice.normal );
  1818. VectorF rvec = mCross( fvec, slice.normal );
  1819. if ( rvec.isZero() )
  1820. rvec = mPerp( fvec );
  1821. rvec.normalize();
  1822. fvec = mCross( slice.normal, rvec );
  1823. fvec.normalize();
  1824. mat.setColumn( 0, rvec );
  1825. mat.setColumn( 1, fvec );
  1826. mat.setColumn( 2, slice.normal );
  1827. mat.setColumn( 3, slice.p1 );
  1828. AssertFatal( m_matF_determinant( mat ) != 0.0f, "no inverse!");
  1829. }
  1830. F32 MeshRoad::getRoadLength() const
  1831. {
  1832. F32 length = 0.0f;
  1833. for ( U32 i = 0; i < mSegments.size(); i++ )
  1834. {
  1835. length += mSegments[i].length();
  1836. }
  1837. return length;
  1838. }
  1839. void MeshRoad::deleteNode( U32 idx )
  1840. {
  1841. if ( mNodes.size() - 1 < idx )
  1842. return;
  1843. mNodes.erase(idx);
  1844. _regenerate();
  1845. setMaskBits( RegenMask | NodeMask );
  1846. }
  1847. U32 MeshRoad::_addNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal )
  1848. {
  1849. mNodes.increment();
  1850. MeshRoadNode &node = mNodes.last();
  1851. node.point = pos;
  1852. node.width = width;
  1853. node.depth = depth;
  1854. node.normal = normal;
  1855. setMaskBits( NodeMask | RegenMask );
  1856. return mNodes.size() - 1;
  1857. }
  1858. U32 MeshRoad::_insertNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1859. {
  1860. U32 ret;
  1861. MeshRoadNode *node;
  1862. if ( idx == U32_MAX )
  1863. {
  1864. mNodes.increment();
  1865. node = &mNodes.last();
  1866. ret = mNodes.size() - 1;
  1867. }
  1868. else
  1869. {
  1870. mNodes.insert( idx );
  1871. node = &mNodes[idx];
  1872. ret = idx;
  1873. }
  1874. node->point = pos;
  1875. node->depth = depth;
  1876. node->width = width;
  1877. node->normal = normal;
  1878. return ret;
  1879. }
  1880. bool MeshRoad::collideRay( const Point3F &origin, const Point3F &direction, U32 *nodeIdx, Point3F *collisionPnt )
  1881. {
  1882. Point3F p0 = origin;
  1883. Point3F p1 = origin + direction * 2000.0f;
  1884. // If the line segment does not collide with the MeshRoad's world box,
  1885. // it definitely does not collide with any part of the river.
  1886. if ( !getWorldBox().collideLine( p0, p1 ) )
  1887. return false;
  1888. if ( mSlices.size() < 2 )
  1889. return false;
  1890. MathUtils::Quad quad;
  1891. MathUtils::Ray ray;
  1892. F32 t;
  1893. // Check each road segment (formed by a pair of slices) for collision
  1894. // with the line segment.
  1895. for ( U32 i = 0; i < mSlices.size() - 1; i++ )
  1896. {
  1897. const MeshRoadSlice &slice0 = mSlices[i];
  1898. const MeshRoadSlice &slice1 = mSlices[i+1];
  1899. // For simplicities sake we will only test for collision between the
  1900. // line segment and the Top face of the river segment.
  1901. // Clockwise starting with the leftmost/closest point.
  1902. quad.p00 = slice0.p0;
  1903. quad.p01 = slice1.p0;
  1904. quad.p11 = slice1.p2;
  1905. quad.p10 = slice0.p2;
  1906. ray.origin = origin;
  1907. ray.direction = direction;
  1908. if ( MathUtils::mRayQuadCollide( quad, ray, NULL, &t ) )
  1909. {
  1910. if ( nodeIdx )
  1911. *nodeIdx = slice0.parentNodeIdx;
  1912. if ( collisionPnt )
  1913. *collisionPnt = ray.origin + ray.direction * t;
  1914. return true;
  1915. }
  1916. }
  1917. return false;
  1918. }
  1919. void MeshRoad::regenerate()
  1920. {
  1921. _regenerate();
  1922. setMaskBits( RegenMask );
  1923. }
  1924. //-------------------------------------------------------------------------
  1925. // Console Methods
  1926. //-------------------------------------------------------------------------
  1927. DefineEngineMethod( MeshRoad, setNodeDepth, void, ( S32 idx, F32 meters ),,
  1928. "Intended as a helper to developers and editor scripts.\n"
  1929. "Sets the depth in meters of a particular node."
  1930. )
  1931. {
  1932. object->setNodeDepth( idx, meters );
  1933. }
  1934. DefineEngineMethod( MeshRoad, regenerate, void, (),,
  1935. "Intended as a helper to developers and editor scripts.\n"
  1936. "Force MeshRoad to recreate its geometry."
  1937. )
  1938. {
  1939. object->regenerate();
  1940. }
  1941. DefineEngineMethod( MeshRoad, postApply, void, (),,
  1942. "Intended as a helper to developers and editor scripts.\n"
  1943. "Force trigger an inspectPostApply. This will transmit "
  1944. "material and other fields ( not including nodes ) to client objects."
  1945. )
  1946. {
  1947. object->inspectPostApply();
  1948. }