meshRoad.cpp 64 KB

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