navMesh.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2014 Daniel Buckmaster
  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 "navMesh.h"
  23. #include "navContext.h"
  24. #include <DetourDebugDraw.h>
  25. #include <RecastDebugDraw.h>
  26. #include "math/mathUtils.h"
  27. #include "math/mRandom.h"
  28. #include "console/consoleTypes.h"
  29. #include "console/engineAPI.h"
  30. #include "console/typeValidators.h"
  31. #include "scene/sceneRenderState.h"
  32. #include "gfx/gfxDrawUtil.h"
  33. #include "renderInstance/renderPassManager.h"
  34. #include "gfx/primBuilder.h"
  35. #include "core/stream/bitStream.h"
  36. #include "math/mathIO.h"
  37. #include "core/fileio.h"
  38. extern bool gEditingMission;
  39. IMPLEMENT_CO_NETOBJECT_V1(NavMesh);
  40. const U32 NavMesh::mMaxVertsPerPoly = 3;
  41. SimObjectPtr<SimSet> NavMesh::smServerSet = NULL;
  42. ImplementEnumType(NavMeshWaterMethod,
  43. "The method used to include water surfaces in the NavMesh.\n")
  44. { NavMesh::Ignore, "Ignore", "Ignore all water surfaces.\n" },
  45. { NavMesh::Solid, "Solid", "Treat water surfaces as solid and walkable.\n" },
  46. { NavMesh::Impassable, "Impassable", "Treat water as an impassable obstacle.\n" },
  47. EndImplementEnumType;
  48. SimSet *NavMesh::getServerSet()
  49. {
  50. if(!smServerSet)
  51. {
  52. SimSet *set = NULL;
  53. if(Sim::findObject("ServerNavMeshSet", set))
  54. smServerSet = set;
  55. else
  56. {
  57. smServerSet = new SimSet();
  58. smServerSet->registerObject("ServerNavMeshSet");
  59. Sim::getRootGroup()->addObject(smServerSet);
  60. }
  61. }
  62. return smServerSet;
  63. }
  64. SimObjectPtr<EventManager> NavMesh::smEventManager = NULL;
  65. EventManager *NavMesh::getEventManager()
  66. {
  67. if(!smEventManager)
  68. {
  69. smEventManager = new EventManager();
  70. smEventManager->registerObject("NavEventManager");
  71. Sim::getRootGroup()->addObject(smEventManager);
  72. smEventManager->setMessageQueue("NavEventManagerQueue");
  73. smEventManager->registerEvent("NavMeshCreated");
  74. smEventManager->registerEvent("NavMeshRemoved");
  75. smEventManager->registerEvent("NavMeshStartUpdate");
  76. smEventManager->registerEvent("NavMeshUpdate");
  77. smEventManager->registerEvent("NavMeshTileUpdate");
  78. smEventManager->registerEvent("NavMeshUpdateBox");
  79. smEventManager->registerEvent("NavMeshObstacleAdded");
  80. smEventManager->registerEvent("NavMeshObstacleRemoved");
  81. }
  82. return smEventManager;
  83. }
  84. DefineConsoleFunction(getNavMeshEventManager, S32, (),,
  85. "@brief Get the EventManager object for all NavMesh updates.")
  86. {
  87. return NavMesh::getEventManager()->getId();
  88. }
  89. DefineConsoleFunction(NavMeshUpdateAll, void, (S32 objid, bool remove), (0, false),
  90. "@brief Update all NavMesh tiles that intersect the given object's world box.")
  91. {
  92. SceneObject *obj;
  93. if(!Sim::findObject(objid, obj))
  94. return;
  95. if(remove)
  96. obj->disableCollision();
  97. SimSet *set = NavMesh::getServerSet();
  98. for(U32 i = 0; i < set->size(); i++)
  99. {
  100. NavMesh *m = dynamic_cast<NavMesh*>(set->at(i));
  101. if (m)
  102. {
  103. m->cancelBuild();
  104. m->buildTiles(obj->getWorldBox());
  105. }
  106. }
  107. if(remove)
  108. obj->enableCollision();
  109. }
  110. DefineConsoleFunction(NavMeshUpdateOne, void, (S32 meshid, S32 objid, bool remove), (0, 0, false),
  111. "@brief Update all tiles in a given NavMesh that intersect the given object's world box.")
  112. {
  113. NavMesh *mesh;
  114. SceneObject *obj;
  115. if(!Sim::findObject(meshid, mesh))
  116. {
  117. Con::errorf("NavMeshUpdateOne: cannot find NavMesh %d", meshid);
  118. return;
  119. }
  120. if(!Sim::findObject(objid, obj))
  121. {
  122. Con::errorf("NavMeshUpdateOne: cannot find SceneObject %d", objid);
  123. return;
  124. }
  125. if(remove)
  126. obj->disableCollision();
  127. mesh->buildTiles(obj->getWorldBox());
  128. if(remove)
  129. obj->enableCollision();
  130. }
  131. NavMesh::NavMesh()
  132. {
  133. mTypeMask |= StaticShapeObjectType | MarkerObjectType;
  134. mFileName = StringTable->insert("");
  135. mNetFlags.clear(Ghostable);
  136. mSaveIntermediates = false;
  137. nm = NULL;
  138. ctx = NULL;
  139. mWaterMethod = Ignore;
  140. dMemset(&cfg, 0, sizeof(cfg));
  141. mCellSize = mCellHeight = 0.2f;
  142. mWalkableHeight = 2.0f;
  143. mWalkableClimb = 0.3f;
  144. mWalkableRadius = 0.5f;
  145. mWalkableSlope = 40.0f;
  146. mBorderSize = 1;
  147. mDetailSampleDist = 6.0f;
  148. mDetailSampleMaxError = 1.0f;
  149. mMaxEdgeLen = 12;
  150. mMaxSimplificationError = 1.3f;
  151. mMinRegionArea = 8;
  152. mMergeRegionArea = 20;
  153. mTileSize = 10.0f;
  154. mMaxPolysPerTile = 128;
  155. mSmallCharacters = false;
  156. mRegularCharacters = true;
  157. mLargeCharacters = false;
  158. mVehicles = false;
  159. mCoverSet = StringTable->insert("");
  160. mInnerCover = false;
  161. mCoverDist = 1.0f;
  162. mPeekDist = 0.7f;
  163. mAlwaysRender = false;
  164. mBuilding = false;
  165. }
  166. NavMesh::~NavMesh()
  167. {
  168. dtFreeNavMesh(nm);
  169. nm = NULL;
  170. delete ctx;
  171. ctx = NULL;
  172. }
  173. bool NavMesh::setProtectedDetailSampleDist(void *obj, const char *index, const char *data)
  174. {
  175. F32 dist = dAtof(data);
  176. if(dist == 0.0f || dist >= 0.9f)
  177. return true;
  178. Con::errorf("NavMesh::detailSampleDist must be 0 or greater than 0.9!");
  179. return false;
  180. }
  181. bool NavMesh::setProtectedAlwaysRender(void *obj, const char *index, const char *data)
  182. {
  183. NavMesh *mesh = static_cast<NavMesh*>(obj);
  184. bool always = dAtob(data);
  185. if(always)
  186. {
  187. if(!gEditingMission)
  188. mesh->mNetFlags.set(Ghostable);
  189. }
  190. else
  191. {
  192. if(!gEditingMission)
  193. mesh->mNetFlags.clear(Ghostable);
  194. }
  195. mesh->mAlwaysRender = always;
  196. mesh->setMaskBits(LoadFlag);
  197. return true;
  198. }
  199. FRangeValidator ValidCellSize(0.01f, 10.0f);
  200. FRangeValidator ValidSlopeAngle(0.0f, 89.9f);
  201. IRangeValidator PositiveInt(0, S32_MAX);
  202. IRangeValidator NaturalNumber(1, S32_MAX);
  203. FRangeValidator CornerAngle(0.0f, 90.0f);
  204. void NavMesh::initPersistFields()
  205. {
  206. addGroup("NavMesh Options");
  207. addField("fileName", TypeString, Offset(mFileName, NavMesh),
  208. "Name of the data file to store this navmesh in (relative to engine executable).");
  209. addField("waterMethod", TYPEID<NavMeshWaterMethod>(), Offset(mWaterMethod, NavMesh),
  210. "The method to use to handle water surfaces.");
  211. addFieldV("cellSize", TypeF32, Offset(mCellSize, NavMesh), &ValidCellSize,
  212. "Length/width of a voxel.");
  213. addFieldV("cellHeight", TypeF32, Offset(mCellHeight, NavMesh), &ValidCellSize,
  214. "Height of a voxel.");
  215. addFieldV("tileSize", TypeF32, Offset(mTileSize, NavMesh), &CommonValidators::PositiveNonZeroFloat,
  216. "The horizontal size of tiles.");
  217. addFieldV("actorHeight", TypeF32, Offset(mWalkableHeight, NavMesh), &CommonValidators::PositiveFloat,
  218. "Height of an actor.");
  219. addFieldV("actorClimb", TypeF32, Offset(mWalkableClimb, NavMesh), &CommonValidators::PositiveFloat,
  220. "Maximum climbing height of an actor.");
  221. addFieldV("actorRadius", TypeF32, Offset(mWalkableRadius, NavMesh), &CommonValidators::PositiveFloat,
  222. "Radius of an actor.");
  223. addFieldV("walkableSlope", TypeF32, Offset(mWalkableSlope, NavMesh), &ValidSlopeAngle,
  224. "Maximum walkable slope in degrees.");
  225. addField("smallCharacters", TypeBool, Offset(mSmallCharacters, NavMesh),
  226. "Is this NavMesh for smaller-than-usual characters?");
  227. addField("regularCharacters", TypeBool, Offset(mRegularCharacters, NavMesh),
  228. "Is this NavMesh for regular-sized characters?");
  229. addField("largeCharacters", TypeBool, Offset(mLargeCharacters, NavMesh),
  230. "Is this NavMesh for larger-than-usual characters?");
  231. addField("vehicles", TypeBool, Offset(mVehicles, NavMesh),
  232. "Is this NavMesh for characters driving vehicles?");
  233. endGroup("NavMesh Options");
  234. addGroup("NavMesh Annotations");
  235. addField("coverGroup", TypeString, Offset(mCoverSet, NavMesh),
  236. "Name of the SimGroup to store cover points in.");
  237. addField("innerCover", TypeBool, Offset(mInnerCover, NavMesh),
  238. "Add cover points everywhere, not just on corners?");
  239. addField("coverDist", TypeF32, Offset(mCoverDist, NavMesh),
  240. "Distance from the edge of the NavMesh to search for cover.");
  241. addField("peekDist", TypeF32, Offset(mPeekDist, NavMesh),
  242. "Distance to the side of each cover point that peeking happens.");
  243. endGroup("NavMesh Annotations");
  244. addGroup("NavMesh Rendering");
  245. addProtectedField("alwaysRender", TypeBool, Offset(mAlwaysRender, NavMesh),
  246. &setProtectedAlwaysRender, &defaultProtectedGetFn,
  247. "Display this NavMesh even outside the editor.");
  248. endGroup("NavMesh Rendering");
  249. addGroup("NavMesh Advanced Options");
  250. addFieldV("borderSize", TypeS32, Offset(mBorderSize, NavMesh), &PositiveInt,
  251. "Size of the non-walkable border around the navigation mesh (in voxels).");
  252. addProtectedField("detailSampleDist", TypeF32, Offset(mDetailSampleDist, NavMesh),
  253. &setProtectedDetailSampleDist, &defaultProtectedGetFn,
  254. "Sets the sampling distance to use when generating the detail mesh.");
  255. addFieldV("detailSampleError", TypeF32, Offset(mDetailSampleMaxError, NavMesh), &CommonValidators::PositiveFloat,
  256. "The maximum distance the detail mesh surface should deviate from heightfield data.");
  257. addFieldV("maxEdgeLen", TypeS32, Offset(mDetailSampleDist, NavMesh), &PositiveInt,
  258. "The maximum allowed length for contour edges along the border of the mesh.");
  259. addFieldV("simplificationError", TypeF32, Offset(mMaxSimplificationError, NavMesh), &CommonValidators::PositiveFloat,
  260. "The maximum distance a simplfied contour's border edges should deviate from the original raw contour.");
  261. addFieldV("minRegionArea", TypeS32, Offset(mMinRegionArea, NavMesh), &PositiveInt,
  262. "The minimum number of cells allowed to form isolated island areas.");
  263. addFieldV("mergeRegionArea", TypeS32, Offset(mMergeRegionArea, NavMesh), &PositiveInt,
  264. "Any regions with a span count smaller than this value will, if possible, be merged with larger regions.");
  265. addFieldV("maxPolysPerTile", TypeS32, Offset(mMaxPolysPerTile, NavMesh), &NaturalNumber,
  266. "The maximum number of polygons allowed in a tile.");
  267. endGroup("NavMesh Advanced Options");
  268. Parent::initPersistFields();
  269. }
  270. bool NavMesh::onAdd()
  271. {
  272. if(!Parent::onAdd())
  273. return false;
  274. mObjBox.set(Point3F(-0.5f, -0.5f, -0.5f),
  275. Point3F( 0.5f, 0.5f, 0.5f));
  276. resetWorldBox();
  277. addToScene();
  278. if(gEditingMission || mAlwaysRender)
  279. {
  280. mNetFlags.set(Ghostable);
  281. if(isClientObject())
  282. renderToDrawer();
  283. }
  284. if(isServerObject())
  285. {
  286. getServerSet()->addObject(this);
  287. ctx = new NavContext();
  288. setProcessTick(true);
  289. if(getEventManager())
  290. getEventManager()->postEvent("NavMeshCreated", getIdString());
  291. }
  292. load();
  293. return true;
  294. }
  295. void NavMesh::onRemove()
  296. {
  297. if(getEventManager())
  298. getEventManager()->postEvent("NavMeshRemoved", getIdString());
  299. removeFromScene();
  300. Parent::onRemove();
  301. }
  302. void NavMesh::setTransform(const MatrixF &mat)
  303. {
  304. Parent::setTransform(mat);
  305. }
  306. void NavMesh::setScale(const VectorF &scale)
  307. {
  308. Parent::setScale(scale);
  309. }
  310. S32 NavMesh::addLink(const Point3F &from, const Point3F &to, U32 flags)
  311. {
  312. Point3F rcFrom = DTStoRC(from), rcTo = DTStoRC(to);
  313. mLinkVerts.push_back(rcFrom.x);
  314. mLinkVerts.push_back(rcFrom.y);
  315. mLinkVerts.push_back(rcFrom.z);
  316. mLinkVerts.push_back(rcTo.x);
  317. mLinkVerts.push_back(rcTo.y);
  318. mLinkVerts.push_back(rcTo.z);
  319. mLinksUnsynced.push_back(true);
  320. mLinkRads.push_back(mWalkableRadius);
  321. mLinkDirs.push_back(0);
  322. mLinkAreas.push_back(OffMeshArea);
  323. if (flags == 0) {
  324. Point3F dir = to - from;
  325. F32 drop = -dir.z;
  326. dir.z = 0;
  327. // If we drop more than we travel horizontally, we're a drop link.
  328. if(drop > dir.len())
  329. mLinkFlags.push_back(DropFlag);
  330. else
  331. mLinkFlags.push_back(JumpFlag);
  332. }
  333. mLinkIDs.push_back(1000 + mCurLinkID);
  334. mLinkSelectStates.push_back(Unselected);
  335. mDeleteLinks.push_back(false);
  336. mCurLinkID++;
  337. return mLinkIDs.size() - 1;
  338. }
  339. DefineEngineMethod(NavMesh, addLink, S32, (Point3F from, Point3F to, U32 flags), (0),
  340. "Add a link to this NavMesh between two points.\n\n"
  341. "")
  342. {
  343. return object->addLink(from, to, flags);
  344. }
  345. S32 NavMesh::getLink(const Point3F &pos)
  346. {
  347. for(U32 i = 0; i < mLinkIDs.size(); i++)
  348. {
  349. if(mDeleteLinks[i])
  350. continue;
  351. SphereF start(getLinkStart(i), mLinkRads[i]);
  352. SphereF end(getLinkEnd(i), mLinkRads[i]);
  353. if(start.isContained(pos) || end.isContained(pos))
  354. return i;
  355. }
  356. return -1;
  357. }
  358. DefineEngineMethod(NavMesh, getLink, S32, (Point3F pos),,
  359. "Get the off-mesh link closest to a given world point.")
  360. {
  361. return object->getLink(pos);
  362. }
  363. S32 NavMesh::getLinkCount()
  364. {
  365. return mLinkIDs.size();
  366. }
  367. DefineEngineMethod(NavMesh, getLinkCount, S32, (),,
  368. "Return the number of links this mesh has.")
  369. {
  370. return object->getLinkCount();
  371. }
  372. LinkData NavMesh::getLinkFlags(U32 idx)
  373. {
  374. if(idx < mLinkIDs.size())
  375. {
  376. return LinkData(mLinkFlags[idx]);
  377. }
  378. return LinkData();
  379. }
  380. DefineEngineMethod(NavMesh, getLinkFlags, S32, (U32 id),,
  381. "Get the flags set for a particular off-mesh link.")
  382. {
  383. return object->getLinkFlags(id).getFlags();
  384. }
  385. void NavMesh::setLinkFlags(U32 idx, const LinkData &d)
  386. {
  387. if(idx < mLinkIDs.size())
  388. {
  389. mLinkFlags[idx] = d.getFlags();
  390. mLinksUnsynced[idx] = true;
  391. }
  392. }
  393. DefineEngineMethod(NavMesh, setLinkFlags, void, (U32 id, U32 flags),,
  394. "Set the flags of a particular off-mesh link.")
  395. {
  396. LinkData d(flags);
  397. object->setLinkFlags(id, d);
  398. }
  399. Point3F NavMesh::getLinkStart(U32 idx)
  400. {
  401. return RCtoDTS(Point3F(
  402. mLinkVerts[idx*6],
  403. mLinkVerts[idx*6 + 1],
  404. mLinkVerts[idx*6 + 2]));
  405. }
  406. DefineEngineMethod(NavMesh, getLinkStart, Point3F, (U32 id),,
  407. "Get the starting point of an off-mesh link.")
  408. {
  409. return object->getLinkStart(id);
  410. }
  411. Point3F NavMesh::getLinkEnd(U32 idx)
  412. {
  413. return RCtoDTS(Point3F(
  414. mLinkVerts[idx*6 + 3],
  415. mLinkVerts[idx*6 + 4],
  416. mLinkVerts[idx*6 + 5]));
  417. }
  418. DefineEngineMethod(NavMesh, getLinkEnd, Point3F, (U32 id),,
  419. "Get the ending point of an off-mesh link.")
  420. {
  421. return object->getLinkEnd(id);
  422. }
  423. void NavMesh::selectLink(U32 idx, bool select, bool hover)
  424. {
  425. if(idx < mLinkIDs.size())
  426. {
  427. if(!select)
  428. mLinkSelectStates[idx] = Unselected;
  429. else
  430. mLinkSelectStates[idx] = hover ? Hovered : Selected;
  431. }
  432. }
  433. void NavMesh::eraseLink(U32 i)
  434. {
  435. mLinkVerts.erase(i*6, 6);
  436. mLinksUnsynced.erase(i);
  437. mLinkRads.erase(i);
  438. mLinkDirs.erase(i);
  439. mLinkAreas.erase(i);
  440. mLinkFlags.erase(i);
  441. mLinkIDs.erase(i);
  442. mLinkSelectStates.erase(i);
  443. mDeleteLinks.erase(i);
  444. }
  445. void NavMesh::eraseLinks()
  446. {
  447. mLinkVerts.clear();
  448. mLinksUnsynced.clear();
  449. mLinkRads.clear();
  450. mLinkDirs.clear();
  451. mLinkAreas.clear();
  452. mLinkFlags.clear();
  453. mLinkIDs.clear();
  454. mLinkSelectStates.clear();
  455. mDeleteLinks.clear();
  456. }
  457. void NavMesh::setLinkCount(U32 c)
  458. {
  459. eraseLinks();
  460. mLinkVerts.setSize(c * 6);
  461. mLinksUnsynced.setSize(c);
  462. mLinkRads.setSize(c);
  463. mLinkDirs.setSize(c);
  464. mLinkAreas.setSize(c);
  465. mLinkFlags.setSize(c);
  466. mLinkIDs.setSize(c);
  467. mLinkSelectStates.setSize(c);
  468. mDeleteLinks.setSize(c);
  469. }
  470. void NavMesh::deleteLink(U32 idx)
  471. {
  472. if(idx < mLinkIDs.size())
  473. {
  474. mDeleteLinks[idx] = true;
  475. if(mLinksUnsynced[idx])
  476. eraseLink(idx);
  477. else
  478. mLinksUnsynced[idx] = true;
  479. }
  480. }
  481. DefineEngineMethod(NavMesh, deleteLink, void, (U32 id),,
  482. "Delete a given off-mesh link.")
  483. {
  484. object->deleteLink(id);
  485. }
  486. DefineEngineMethod(NavMesh, deleteLinks, void, (),,
  487. "Deletes all off-mesh links on this NavMesh.")
  488. {
  489. //object->eraseLinks();
  490. }
  491. bool NavMesh::build(bool background, bool saveIntermediates)
  492. {
  493. if(mBuilding)
  494. cancelBuild();
  495. else
  496. {
  497. if(getEventManager())
  498. getEventManager()->postEvent("NavMeshStartUpdate", getIdString());
  499. }
  500. mBuilding = true;
  501. ctx->startTimer(RC_TIMER_TOTAL);
  502. dtFreeNavMesh(nm);
  503. // Allocate a new navmesh.
  504. nm = dtAllocNavMesh();
  505. if(!nm)
  506. {
  507. Con::errorf("Could not allocate dtNavMesh for NavMesh %s", getIdString());
  508. return false;
  509. }
  510. updateConfig();
  511. // Build navmesh parameters from console members.
  512. dtNavMeshParams params;
  513. rcVcopy(params.orig, cfg.bmin);
  514. params.tileWidth = cfg.tileSize * mCellSize;
  515. params.tileHeight = cfg.tileSize * mCellSize;
  516. params.maxTiles = mCeil(getWorldBox().len_x() / params.tileWidth) * mCeil(getWorldBox().len_y() / params.tileHeight);
  517. params.maxPolys = mMaxPolysPerTile;
  518. // Initialise our navmesh.
  519. if(dtStatusFailed(nm->init(&params)))
  520. {
  521. Con::errorf("Could not init dtNavMesh for NavMesh %s", getIdString());
  522. return false;
  523. }
  524. // Update links to be deleted.
  525. for(U32 i = 0; i < mLinkIDs.size();)
  526. {
  527. if(mDeleteLinks[i])
  528. eraseLink(i);
  529. else
  530. i++;
  531. }
  532. mLinksUnsynced.fill(false);
  533. mCurLinkID = 0;
  534. mSaveIntermediates = saveIntermediates;
  535. updateTiles(true);
  536. if(!background)
  537. {
  538. while(!mDirtyTiles.empty())
  539. buildNextTile();
  540. }
  541. return true;
  542. }
  543. DefineEngineMethod(NavMesh, build, bool, (bool background, bool save), (true, false),
  544. "@brief Create a Recast nav mesh.")
  545. {
  546. return object->build(background, save);
  547. }
  548. void NavMesh::cancelBuild()
  549. {
  550. while(!mDirtyTiles.empty()) mDirtyTiles.pop();
  551. ctx->stopTimer(RC_TIMER_TOTAL);
  552. mBuilding = false;
  553. }
  554. DefineEngineMethod(NavMesh, cancelBuild, void, (),,
  555. "@brief Cancel the current NavMesh build.")
  556. {
  557. object->cancelBuild();
  558. }
  559. void NavMesh::inspectPostApply()
  560. {
  561. if(mBuilding)
  562. cancelBuild();
  563. }
  564. void NavMesh::updateConfig()
  565. {
  566. // Build rcConfig object from our console members.
  567. dMemset(&cfg, 0, sizeof(cfg));
  568. cfg.cs = mCellSize;
  569. cfg.ch = mCellHeight;
  570. Box3F box = DTStoRC(getWorldBox());
  571. rcVcopy(cfg.bmin, box.minExtents);
  572. rcVcopy(cfg.bmax, box.maxExtents);
  573. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  574. cfg.walkableHeight = mCeil(mWalkableHeight / mCellHeight);
  575. cfg.walkableClimb = mCeil(mWalkableClimb / mCellHeight);
  576. cfg.walkableRadius = mCeil(mWalkableRadius / mCellSize);
  577. cfg.walkableSlopeAngle = mWalkableSlope;
  578. cfg.borderSize = cfg.walkableRadius + 3;
  579. cfg.detailSampleDist = mDetailSampleDist;
  580. cfg.detailSampleMaxError = mDetailSampleMaxError;
  581. cfg.maxEdgeLen = mMaxEdgeLen;
  582. cfg.maxSimplificationError = mMaxSimplificationError;
  583. cfg.maxVertsPerPoly = mMaxVertsPerPoly;
  584. cfg.minRegionArea = mMinRegionArea;
  585. cfg.mergeRegionArea = mMergeRegionArea;
  586. cfg.tileSize = mTileSize / cfg.cs;
  587. }
  588. S32 NavMesh::getTile(const Point3F& pos)
  589. {
  590. if(mBuilding)
  591. return -1;
  592. for(U32 i = 0; i < mTiles.size(); i++)
  593. {
  594. if(mTiles[i].box.isContained(pos))
  595. return i;
  596. }
  597. return -1;
  598. }
  599. Box3F NavMesh::getTileBox(U32 id)
  600. {
  601. if(mBuilding || id >= mTiles.size())
  602. return Box3F::Invalid;
  603. return mTiles[id].box;
  604. }
  605. void NavMesh::updateTiles(bool dirty)
  606. {
  607. if(!isProperlyAdded())
  608. return;
  609. mTiles.clear();
  610. mTileData.clear();
  611. while(!mDirtyTiles.empty()) mDirtyTiles.pop();
  612. const Box3F &box = DTStoRC(getWorldBox());
  613. if(box.isEmpty())
  614. return;
  615. updateConfig();
  616. // Calculate tile dimensions.
  617. const U32 ts = cfg.tileSize;
  618. const U32 tw = (cfg.width + ts-1) / ts;
  619. const U32 th = (cfg.height + ts-1) / ts;
  620. const F32 tcs = cfg.tileSize * cfg.cs;
  621. // Iterate over tiles.
  622. F32 tileBmin[3], tileBmax[3];
  623. for(U32 y = 0; y < th; ++y)
  624. {
  625. for(U32 x = 0; x < tw; ++x)
  626. {
  627. tileBmin[0] = cfg.bmin[0] + x*tcs;
  628. tileBmin[1] = cfg.bmin[1];
  629. tileBmin[2] = cfg.bmin[2] + y*tcs;
  630. tileBmax[0] = cfg.bmin[0] + (x+1)*tcs;
  631. tileBmax[1] = cfg.bmax[1];
  632. tileBmax[2] = cfg.bmin[2] + (y+1)*tcs;
  633. mTiles.push_back(
  634. Tile(RCtoDTS(tileBmin, tileBmax),
  635. x, y,
  636. tileBmin, tileBmax));
  637. if(dirty)
  638. mDirtyTiles.push(mTiles.size() - 1);
  639. if(mSaveIntermediates)
  640. mTileData.increment();
  641. }
  642. }
  643. }
  644. void NavMesh::processTick(const Move *move)
  645. {
  646. buildNextTile();
  647. }
  648. void NavMesh::buildNextTile()
  649. {
  650. if(!mDirtyTiles.empty())
  651. {
  652. // Pop a single dirty tile and process it.
  653. U32 i = mDirtyTiles.front();
  654. mDirtyTiles.pop();
  655. const Tile &tile = mTiles[i];
  656. // Intermediate data for tile build.
  657. TileData tempdata;
  658. TileData &tdata = mSaveIntermediates ? mTileData[i] : tempdata;
  659. // Remove any previous data.
  660. nm->removeTile(nm->getTileRefAt(tile.x, tile.y, 0), 0, 0);
  661. // Generate navmesh for this tile.
  662. U32 dataSize = 0;
  663. unsigned char* data = buildTileData(tile, tdata, dataSize);
  664. if(data)
  665. {
  666. // Add new data (navmesh owns and deletes the data).
  667. dtStatus status = nm->addTile(data, dataSize, DT_TILE_FREE_DATA, 0, 0);
  668. int success = 1;
  669. if(dtStatusFailed(status))
  670. {
  671. success = 0;
  672. dtFree(data);
  673. }
  674. if(getEventManager())
  675. {
  676. String str = String::ToString("%d %d %d (%d, %d) %d %.3f %s",
  677. getId(),
  678. i, mTiles.size(),
  679. tile.x, tile.y,
  680. success,
  681. ctx->getAccumulatedTime(RC_TIMER_TOTAL) / 1000.0f,
  682. castConsoleTypeToString(tile.box));
  683. getEventManager()->postEvent("NavMeshTileUpdate", str.c_str());
  684. setMaskBits(LoadFlag);
  685. }
  686. }
  687. // Did we just build the last tile?
  688. if(mDirtyTiles.empty())
  689. {
  690. ctx->stopTimer(RC_TIMER_TOTAL);
  691. if(getEventManager())
  692. {
  693. String str = String::ToString("%d %.3f", getId(), ctx->getAccumulatedTime(RC_TIMER_TOTAL) / 1000.0f);
  694. getEventManager()->postEvent("NavMeshUpdate", str.c_str());
  695. setMaskBits(LoadFlag);
  696. }
  697. mBuilding = false;
  698. }
  699. }
  700. }
  701. static void buildCallback(SceneObject* object,void *key)
  702. {
  703. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  704. object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
  705. }
  706. unsigned char *NavMesh::buildTileData(const Tile &tile, TileData &data, U32 &dataSize)
  707. {
  708. // Push out tile boundaries a bit.
  709. F32 tileBmin[3], tileBmax[3];
  710. rcVcopy(tileBmin, tile.bmin);
  711. rcVcopy(tileBmax, tile.bmax);
  712. tileBmin[0] -= cfg.borderSize * cfg.cs;
  713. tileBmin[2] -= cfg.borderSize * cfg.cs;
  714. tileBmax[0] += cfg.borderSize * cfg.cs;
  715. tileBmax[2] += cfg.borderSize * cfg.cs;
  716. // Parse objects from level into RC-compatible format.
  717. Box3F box = RCtoDTS(tileBmin, tileBmax);
  718. SceneContainer::CallbackInfo info;
  719. info.context = PLC_Navigation;
  720. info.boundingBox = box;
  721. data.geom.clear();
  722. info.polyList = &data.geom;
  723. info.key = this;
  724. getContainer()->findObjects(box, StaticShapeObjectType | TerrainObjectType, buildCallback, &info);
  725. // Parse water objects into the same list, but remember how much geometry was /not/ water.
  726. U32 nonWaterVertCount = data.geom.getVertCount();
  727. U32 nonWaterTriCount = data.geom.getTriCount();
  728. if(mWaterMethod != Ignore)
  729. {
  730. getContainer()->findObjects(box, WaterObjectType, buildCallback, &info);
  731. }
  732. // Check for no geometry.
  733. if (!data.geom.getVertCount())
  734. {
  735. data.geom.clear();
  736. return NULL;
  737. }
  738. // Figure out voxel dimensions of this tile.
  739. U32 width = 0, height = 0;
  740. width = cfg.tileSize + cfg.borderSize * 2;
  741. height = cfg.tileSize + cfg.borderSize * 2;
  742. // Create a heightfield to voxelise our input geometry.
  743. data.hf = rcAllocHeightfield();
  744. if(!data.hf)
  745. {
  746. Con::errorf("Out of memory (rcHeightField) for NavMesh %s", getIdString());
  747. return NULL;
  748. }
  749. if(!rcCreateHeightfield(ctx, *data.hf, width, height, tileBmin, tileBmax, cfg.cs, cfg.ch))
  750. {
  751. Con::errorf("Could not generate rcHeightField for NavMesh %s", getIdString());
  752. return NULL;
  753. }
  754. unsigned char *areas = new unsigned char[data.geom.getTriCount()];
  755. dMemset(areas, 0, data.geom.getTriCount() * sizeof(unsigned char));
  756. // Mark walkable triangles with the appropriate area flags, and rasterize.
  757. if(mWaterMethod == Solid)
  758. {
  759. // Treat water as solid: i.e. mark areas as walkable based on angle.
  760. rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
  761. data.geom.getVerts(), data.geom.getVertCount(),
  762. data.geom.getTris(), data.geom.getTriCount(), areas);
  763. }
  764. else
  765. {
  766. // Treat water as impassable: leave all area flags 0.
  767. rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
  768. data.geom.getVerts(), nonWaterVertCount,
  769. data.geom.getTris(), nonWaterTriCount, areas);
  770. }
  771. rcRasterizeTriangles(ctx,
  772. data.geom.getVerts(), data.geom.getVertCount(),
  773. data.geom.getTris(), areas, data.geom.getTriCount(),
  774. *data.hf, cfg.walkableClimb);
  775. delete[] areas;
  776. // Filter out areas with low ceilings and other stuff.
  777. rcFilterLowHangingWalkableObstacles(ctx, cfg.walkableClimb, *data.hf);
  778. rcFilterLedgeSpans(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf);
  779. rcFilterWalkableLowHeightSpans(ctx, cfg.walkableHeight, *data.hf);
  780. data.chf = rcAllocCompactHeightfield();
  781. if(!data.chf)
  782. {
  783. Con::errorf("Out of memory (rcCompactHeightField) for NavMesh %s", getIdString());
  784. return NULL;
  785. }
  786. if(!rcBuildCompactHeightfield(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf, *data.chf))
  787. {
  788. Con::errorf("Could not generate rcCompactHeightField for NavMesh %s", getIdString());
  789. return NULL;
  790. }
  791. if(!rcErodeWalkableArea(ctx, cfg.walkableRadius, *data.chf))
  792. {
  793. Con::errorf("Could not erode walkable area for NavMesh %s", getIdString());
  794. return NULL;
  795. }
  796. //--------------------------
  797. // Todo: mark areas here.
  798. //const ConvexVolume* vols = m_geom->getConvexVolumes();
  799. //for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i)
  800. //rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf);
  801. //--------------------------
  802. if(false)
  803. {
  804. if(!rcBuildRegionsMonotone(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  805. {
  806. Con::errorf("Could not build regions for NavMesh %s", getIdString());
  807. return NULL;
  808. }
  809. }
  810. else
  811. {
  812. if(!rcBuildDistanceField(ctx, *data.chf))
  813. {
  814. Con::errorf("Could not build distance field for NavMesh %s", getIdString());
  815. return NULL;
  816. }
  817. if(!rcBuildRegions(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  818. {
  819. Con::errorf("Could not build regions for NavMesh %s", getIdString());
  820. return NULL;
  821. }
  822. }
  823. data.cs = rcAllocContourSet();
  824. if(!data.cs)
  825. {
  826. Con::errorf("Out of memory (rcContourSet) for NavMesh %s", getIdString());
  827. return NULL;
  828. }
  829. if(!rcBuildContours(ctx, *data.chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *data.cs))
  830. {
  831. Con::errorf("Could not construct rcContourSet for NavMesh %s", getIdString());
  832. return NULL;
  833. }
  834. if(data.cs->nconts <= 0)
  835. {
  836. Con::errorf("No contours in rcContourSet for NavMesh %s", getIdString());
  837. return NULL;
  838. }
  839. data.pm = rcAllocPolyMesh();
  840. if(!data.pm)
  841. {
  842. Con::errorf("Out of memory (rcPolyMesh) for NavMesh %s", getIdString());
  843. return NULL;
  844. }
  845. if(!rcBuildPolyMesh(ctx, *data.cs, cfg.maxVertsPerPoly, *data.pm))
  846. {
  847. Con::errorf("Could not construct rcPolyMesh for NavMesh %s", getIdString());
  848. return NULL;
  849. }
  850. data.pmd = rcAllocPolyMeshDetail();
  851. if(!data.pmd)
  852. {
  853. Con::errorf("Out of memory (rcPolyMeshDetail) for NavMesh %s", getIdString());
  854. return NULL;
  855. }
  856. if(!rcBuildPolyMeshDetail(ctx, *data.pm, *data.chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *data.pmd))
  857. {
  858. Con::errorf("Could not construct rcPolyMeshDetail for NavMesh %s", getIdString());
  859. return NULL;
  860. }
  861. if(data.pm->nverts >= 0xffff)
  862. {
  863. Con::errorf("Too many vertices in rcPolyMesh for NavMesh %s", getIdString());
  864. return NULL;
  865. }
  866. for(U32 i = 0; i < data.pm->npolys; i++)
  867. {
  868. if(data.pm->areas[i] == RC_WALKABLE_AREA)
  869. data.pm->areas[i] = GroundArea;
  870. if(data.pm->areas[i] == GroundArea)
  871. data.pm->flags[i] |= WalkFlag;
  872. if(data.pm->areas[i] == WaterArea)
  873. data.pm->flags[i] |= SwimFlag;
  874. }
  875. unsigned char* navData = 0;
  876. int navDataSize = 0;
  877. dtNavMeshCreateParams params;
  878. dMemset(&params, 0, sizeof(params));
  879. params.verts = data.pm->verts;
  880. params.vertCount = data.pm->nverts;
  881. params.polys = data.pm->polys;
  882. params.polyAreas = data.pm->areas;
  883. params.polyFlags = data.pm->flags;
  884. params.polyCount = data.pm->npolys;
  885. params.nvp = data.pm->nvp;
  886. params.detailMeshes = data.pmd->meshes;
  887. params.detailVerts = data.pmd->verts;
  888. params.detailVertsCount = data.pmd->nverts;
  889. params.detailTris = data.pmd->tris;
  890. params.detailTriCount = data.pmd->ntris;
  891. params.offMeshConVerts = mLinkVerts.address();
  892. params.offMeshConRad = mLinkRads.address();
  893. params.offMeshConDir = mLinkDirs.address();
  894. params.offMeshConAreas = mLinkAreas.address();
  895. params.offMeshConFlags = mLinkFlags.address();
  896. params.offMeshConUserID = mLinkIDs.address();
  897. params.offMeshConCount = mLinkIDs.size();
  898. params.walkableHeight = mWalkableHeight;
  899. params.walkableRadius = mWalkableRadius;
  900. params.walkableClimb = mWalkableClimb;
  901. params.tileX = tile.x;
  902. params.tileY = tile.y;
  903. params.tileLayer = 0;
  904. rcVcopy(params.bmin, data.pm->bmin);
  905. rcVcopy(params.bmax, data.pm->bmax);
  906. params.cs = cfg.cs;
  907. params.ch = cfg.ch;
  908. params.buildBvTree = true;
  909. if(!dtCreateNavMeshData(&params, &navData, &navDataSize))
  910. {
  911. Con::errorf("Could not create dtNavMeshData for tile (%d, %d) of NavMesh %s",
  912. tile.x, tile.y, getIdString());
  913. return NULL;
  914. }
  915. dataSize = navDataSize;
  916. return navData;
  917. }
  918. /// This method should never be called in a separate thread to the rendering
  919. /// or pathfinding logic. It directly replaces data in the dtNavMesh for
  920. /// this NavMesh object.
  921. void NavMesh::buildTiles(const Box3F &box)
  922. {
  923. // Make sure we've already built or loaded.
  924. if(!nm)
  925. return;
  926. // Iterate over tiles.
  927. for(U32 i = 0; i < mTiles.size(); i++)
  928. {
  929. const Tile &tile = mTiles[i];
  930. // Check tile box.
  931. if(!tile.box.isOverlapped(box))
  932. continue;
  933. // Mark as dirty.
  934. mDirtyTiles.push(i);
  935. }
  936. if(mDirtyTiles.size())
  937. ctx->startTimer(RC_TIMER_TOTAL);
  938. }
  939. DefineEngineMethod(NavMesh, buildTiles, void, (Box3F box),,
  940. "@brief Rebuild the tiles overlapped by the input box.")
  941. {
  942. return object->buildTiles(box);
  943. }
  944. void NavMesh::buildTile(const U32 &tile)
  945. {
  946. if(tile < mTiles.size())
  947. {
  948. mDirtyTiles.push(tile);
  949. ctx->startTimer(RC_TIMER_TOTAL);
  950. }
  951. }
  952. void NavMesh::buildLinks()
  953. {
  954. // Make sure we've already built or loaded.
  955. if(!nm)
  956. return;
  957. // Iterate over tiles.
  958. for(U32 i = 0; i < mTiles.size(); i++)
  959. {
  960. const Tile &tile = mTiles[i];
  961. // Iterate over links
  962. for(U32 j = 0; j < mLinkIDs.size(); j++)
  963. {
  964. if(tile.box.isContained(getLinkStart(j)) ||
  965. tile.box.isContained(getLinkEnd(j)) &&
  966. mLinksUnsynced[j])
  967. {
  968. // Mark tile for build.
  969. mDirtyTiles.push(i);
  970. // Delete link if necessary
  971. if(mDeleteLinks[j])
  972. {
  973. eraseLink(j);
  974. j--;
  975. }
  976. else
  977. mLinksUnsynced[j] = false;
  978. }
  979. }
  980. }
  981. if(mDirtyTiles.size())
  982. ctx->startTimer(RC_TIMER_TOTAL);
  983. }
  984. DefineEngineMethod(NavMesh, buildLinks, void, (),,
  985. "@brief Build tiles of this mesh where there are unsynchronised links.")
  986. {
  987. object->buildLinks();
  988. }
  989. void NavMesh::deleteCoverPoints()
  990. {
  991. SimSet *set = NULL;
  992. if(Sim::findObject(mCoverSet, set))
  993. set->deleteAllObjects();
  994. }
  995. DefineEngineMethod(NavMesh, deleteCoverPoints, void, (),,
  996. "@brief Remove all cover points for this NavMesh.")
  997. {
  998. object->deleteCoverPoints();
  999. }
  1000. bool NavMesh::createCoverPoints()
  1001. {
  1002. if(!nm || !isServerObject())
  1003. return false;
  1004. SimSet *set = NULL;
  1005. if(Sim::findObject(mCoverSet, set))
  1006. {
  1007. set->deleteAllObjects();
  1008. }
  1009. else
  1010. {
  1011. set = new SimGroup();
  1012. if(set->registerObject(mCoverSet))
  1013. {
  1014. getGroup()->addObject(set);
  1015. }
  1016. else
  1017. {
  1018. delete set;
  1019. set = getGroup();
  1020. }
  1021. }
  1022. dtNavMeshQuery *query = dtAllocNavMeshQuery();
  1023. if(!query || dtStatusFailed(query->init(nm, 1)))
  1024. return false;
  1025. dtQueryFilter f;
  1026. // Iterate over all polys in our navmesh.
  1027. const int MAX_SEGS = 6;
  1028. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1029. {
  1030. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1031. if(!tile->header) continue;
  1032. const dtPolyRef base = nm->getPolyRefBase(tile);
  1033. for(U32 j = 0; j < tile->header->polyCount; ++j)
  1034. {
  1035. const dtPolyRef ref = base | j;
  1036. float segs[MAX_SEGS*6];
  1037. int nsegs = 0;
  1038. query->getPolyWallSegments(ref, &f, segs, NULL, &nsegs, MAX_SEGS);
  1039. for(int j = 0; j < nsegs; ++j)
  1040. {
  1041. const float* sa = &segs[j*6];
  1042. const float* sb = &segs[j*6+3];
  1043. Point3F a = RCtoDTS(sa), b = RCtoDTS(sb);
  1044. F32 len = (b - a).len();
  1045. if(len < mWalkableRadius * 2)
  1046. continue;
  1047. Point3F edge = b - a;
  1048. edge.normalize();
  1049. // Number of points to try placing - for now, one at each end.
  1050. U32 pointCount = (len > mWalkableRadius * 4) ? 2 : 1;
  1051. for(U32 i = 0; i < pointCount; i++)
  1052. {
  1053. MatrixF mat;
  1054. Point3F pos;
  1055. // If we're only placing one point, put it in the middle.
  1056. if(pointCount == 1)
  1057. pos = a + edge * len / 2;
  1058. // Otherwise, stand off from edge ends.
  1059. else
  1060. {
  1061. if(i % 2)
  1062. pos = a + edge * (i/2+1) * mWalkableRadius;
  1063. else
  1064. pos = b - edge * (i/2+1) * mWalkableRadius;
  1065. }
  1066. CoverPointData data;
  1067. if(testEdgeCover(pos, edge, data))
  1068. {
  1069. CoverPoint *m = new CoverPoint();
  1070. if(!m->registerObject())
  1071. delete m;
  1072. else
  1073. {
  1074. m->setTransform(data.trans);
  1075. m->setSize(data.size);
  1076. m->setPeek(data.peek[0], data.peek[1], data.peek[2]);
  1077. if(set)
  1078. set->addObject(m);
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. }
  1085. return true;
  1086. }
  1087. DefineEngineMethod(NavMesh, createCoverPoints, bool, (),,
  1088. "@brief Create cover points for this NavMesh.")
  1089. {
  1090. return object->createCoverPoints();
  1091. }
  1092. bool NavMesh::testEdgeCover(const Point3F &pos, const VectorF &dir, CoverPointData &data)
  1093. {
  1094. data.peek[0] = data.peek[1] = data.peek[2] = false;
  1095. // Get the edge normal.
  1096. Point3F norm;
  1097. mCross(dir, Point3F(0, 0, 1), &norm);
  1098. RayInfo ray;
  1099. U32 hits = 0;
  1100. for(U32 j = 0; j < CoverPoint::NumSizes; j++)
  1101. {
  1102. Point3F test = pos + Point3F(0.0f, 0.0f, mWalkableHeight * j / CoverPoint::NumSizes);
  1103. if(getContainer()->castRay(test, test + norm * mCoverDist, StaticObjectType, &ray))
  1104. {
  1105. // Test peeking.
  1106. Point3F left = test + dir * mPeekDist;
  1107. data.peek[0] = !getContainer()->castRay(test, left, StaticObjectType, &ray)
  1108. && !getContainer()->castRay(left, left + norm * mCoverDist, StaticObjectType, &ray);
  1109. Point3F right = test - dir * mPeekDist;
  1110. data.peek[1] = !getContainer()->castRay(test, right, StaticObjectType, &ray)
  1111. && !getContainer()->castRay(right, right + norm * mCoverDist, StaticObjectType, &ray);
  1112. Point3F over = test + Point3F(0, 0, 1) * 0.2f;
  1113. data.peek[2] = !getContainer()->castRay(test, over, StaticObjectType, &ray)
  1114. && !getContainer()->castRay(over, over + norm * mCoverDist, StaticObjectType, &ray);
  1115. if(mInnerCover || data.peek[0] || data.peek[1] || data.peek[2])
  1116. hits++;
  1117. // If we couldn't peek here, we may be able to peek further up.
  1118. }
  1119. else
  1120. // No cover at this height - break off.
  1121. break;
  1122. }
  1123. if(hits > 0)
  1124. {
  1125. data.size = (CoverPoint::Size)(hits - 1);
  1126. data.trans = MathUtils::createOrientFromDir(norm);
  1127. data.trans.setPosition(pos);
  1128. }
  1129. return hits > 0;
  1130. }
  1131. void NavMesh::renderToDrawer()
  1132. {
  1133. dd.clear();
  1134. // Recast debug draw
  1135. NetObject *no = getServerObject();
  1136. if(no)
  1137. {
  1138. NavMesh *n = static_cast<NavMesh*>(no);
  1139. if(n->nm)
  1140. {
  1141. dd.beginGroup(0);
  1142. duDebugDrawNavMesh (&dd, *n->nm, 0);
  1143. dd.beginGroup(1);
  1144. duDebugDrawNavMeshPortals(&dd, *n->nm);
  1145. dd.beginGroup(2);
  1146. duDebugDrawNavMeshBVTree (&dd, *n->nm);
  1147. }
  1148. }
  1149. }
  1150. void NavMesh::prepRenderImage(SceneRenderState *state)
  1151. {
  1152. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1153. ri->renderDelegate.bind(this, &NavMesh::render);
  1154. ri->type = RenderPassManager::RIT_Object;
  1155. ri->translucentSort = true;
  1156. ri->defaultKey = 1;
  1157. state->getRenderPass()->addInst(ri);
  1158. }
  1159. void NavMesh::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat)
  1160. {
  1161. if(overrideMat)
  1162. return;
  1163. if(state->isReflectPass())
  1164. return;
  1165. PROFILE_SCOPE(NavMesh_Render);
  1166. // Recast debug draw
  1167. NetObject *no = getServerObject();
  1168. if(no)
  1169. {
  1170. NavMesh *n = static_cast<NavMesh*>(no);
  1171. if(n->isSelected())
  1172. {
  1173. GFXDrawUtil *drawer = GFX->getDrawUtil();
  1174. GFXStateBlockDesc desc;
  1175. desc.setZReadWrite(true, false);
  1176. desc.setBlend(true);
  1177. desc.setCullMode(GFXCullNone);
  1178. drawer->drawCube(desc, getWorldBox(), n->mBuilding
  1179. ? ColorI(255, 0, 0, 80)
  1180. : ColorI(136, 228, 255, 45));
  1181. desc.setFillModeWireframe();
  1182. drawer->drawCube(desc, getWorldBox(), ColorI::BLACK);
  1183. }
  1184. if(n->mBuilding)
  1185. {
  1186. int alpha = 80;
  1187. if(!n->isSelected() || !Con::getBoolVariable("$Nav::EditorOpen"))
  1188. alpha = 20;
  1189. dd.overrideColor(duRGBA(255, 0, 0, alpha));
  1190. }
  1191. else
  1192. {
  1193. dd.cancelOverride();
  1194. }
  1195. if((!gEditingMission && n->mAlwaysRender) || (gEditingMission && Con::getBoolVariable("$Nav::Editor::renderMesh", 1))) dd.renderGroup(0);
  1196. if(Con::getBoolVariable("$Nav::Editor::renderPortals")) dd.renderGroup(1);
  1197. if(Con::getBoolVariable("$Nav::Editor::renderBVTree")) dd.renderGroup(2);
  1198. }
  1199. }
  1200. void NavMesh::renderLinks(duDebugDraw &dd)
  1201. {
  1202. if(mBuilding)
  1203. return;
  1204. dd.depthMask(true);
  1205. dd.begin(DU_DRAW_LINES);
  1206. for(U32 i = 0; i < mLinkIDs.size(); i++)
  1207. {
  1208. U32 col = 0;
  1209. switch(mLinkSelectStates[i])
  1210. {
  1211. case Unselected: col = mLinksUnsynced[i] ? duRGBA(255, 0, 0, 200) : duRGBA(0, 0, 255, 255); break;
  1212. case Hovered: col = duRGBA(255, 255, 255, 255); break;
  1213. case Selected: col = duRGBA(0, 255, 0, 255); break;
  1214. }
  1215. F32 *s = &mLinkVerts[i*6];
  1216. F32 *e = &mLinkVerts[i*6 + 3];
  1217. if(!mDeleteLinks[i])
  1218. duAppendCircle(&dd, s[0], s[1], s[2], mLinkRads[i], col);
  1219. duAppendArc(&dd,
  1220. s[0], s[1], s[2],
  1221. e[0], e[1], e[2],
  1222. 0.3f,
  1223. 0.0f, mLinkFlags[i] == DropFlag ? 0.0f : 0.4f,
  1224. col);
  1225. if(!mDeleteLinks[i])
  1226. duAppendCircle(&dd, e[0], e[1], e[2], mLinkRads[i], col);
  1227. }
  1228. dd.end();
  1229. }
  1230. void NavMesh::renderTileData(duDebugDrawTorque &dd, U32 tile)
  1231. {
  1232. if(tile >= mTileData.size())
  1233. return;
  1234. if(nm)
  1235. {
  1236. dd.beginGroup(0);
  1237. if(mTileData[tile].chf) duDebugDrawCompactHeightfieldSolid(&dd, *mTileData[tile].chf);
  1238. dd.beginGroup(1);
  1239. int col = duRGBA(255, 0, 255, 255);
  1240. RecastPolyList &in = mTileData[tile].geom;
  1241. dd.begin(DU_DRAW_LINES);
  1242. const F32 *verts = in.getVerts();
  1243. const S32 *tris = in.getTris();
  1244. for(U32 t = 0; t < in.getTriCount(); t++)
  1245. {
  1246. dd.vertex(&verts[tris[t*3]*3], col);
  1247. dd.vertex(&verts[tris[t*3+1]*3], col);
  1248. dd.vertex(&verts[tris[t*3+1]*3], col);
  1249. dd.vertex(&verts[tris[t*3+2]*3], col);
  1250. dd.vertex(&verts[tris[t*3+2]*3], col);
  1251. dd.vertex(&verts[tris[t*3]*3], col);
  1252. }
  1253. dd.end();
  1254. }
  1255. }
  1256. void NavMesh::onEditorEnable()
  1257. {
  1258. mNetFlags.set(Ghostable);
  1259. if(isClientObject() && !mAlwaysRender)
  1260. addToScene();
  1261. }
  1262. void NavMesh::onEditorDisable()
  1263. {
  1264. if(!mAlwaysRender)
  1265. {
  1266. mNetFlags.clear(Ghostable);
  1267. if(isClientObject())
  1268. removeFromScene();
  1269. }
  1270. }
  1271. U32 NavMesh::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  1272. {
  1273. U32 retMask = Parent::packUpdate(conn, mask, stream);
  1274. mathWrite(*stream, getTransform());
  1275. mathWrite(*stream, getScale());
  1276. stream->writeFlag(mAlwaysRender);
  1277. return retMask;
  1278. }
  1279. void NavMesh::unpackUpdate(NetConnection *conn, BitStream *stream)
  1280. {
  1281. Parent::unpackUpdate(conn, stream);
  1282. mathRead(*stream, &mObjToWorld);
  1283. mathRead(*stream, &mObjScale);
  1284. mAlwaysRender = stream->readFlag();
  1285. setTransform(mObjToWorld);
  1286. renderToDrawer();
  1287. }
  1288. static const int NAVMESHSET_MAGIC = 'M'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'MSET';
  1289. static const int NAVMESHSET_VERSION = 1;
  1290. struct NavMeshSetHeader
  1291. {
  1292. int magic;
  1293. int version;
  1294. int numTiles;
  1295. dtNavMeshParams params;
  1296. };
  1297. struct NavMeshTileHeader
  1298. {
  1299. dtTileRef tileRef;
  1300. int dataSize;
  1301. };
  1302. bool NavMesh::load()
  1303. {
  1304. if(!dStrlen(mFileName))
  1305. return false;
  1306. File file;
  1307. if(file.open(mFileName, File::Read) != File::Ok)
  1308. {
  1309. file.close();
  1310. Con::errorf("Could not open file %s when loading navmesh %s.",
  1311. mFileName, getName() ? getName() : getIdString());
  1312. return false;
  1313. }
  1314. // Read header.
  1315. NavMeshSetHeader header;
  1316. file.read(sizeof(NavMeshSetHeader), (char*)&header);
  1317. if(header.magic != NAVMESHSET_MAGIC)
  1318. {
  1319. file.close();
  1320. Con::errorf("Navmesh magic incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1321. getName() ? getName() : getIdString(), mFileName);
  1322. return false;
  1323. }
  1324. if(header.version != NAVMESHSET_VERSION)
  1325. {
  1326. file.close();
  1327. Con::errorf("Navmesh version incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1328. getName() ? getName() : getIdString(), mFileName);
  1329. return false;
  1330. }
  1331. if(nm)
  1332. dtFreeNavMesh(nm);
  1333. nm = dtAllocNavMesh();
  1334. if(!nm)
  1335. {
  1336. file.close();
  1337. Con::errorf("Out of memory when loading navmesh %s.",
  1338. getName() ? getName() : getIdString());
  1339. return false;
  1340. }
  1341. dtStatus status = nm->init(&header.params);
  1342. if(dtStatusFailed(status))
  1343. {
  1344. file.close();
  1345. Con::errorf("Failed to initialise navmesh params when loading navmesh %s.",
  1346. getName() ? getName() : getIdString());
  1347. return false;
  1348. }
  1349. // Read tiles.
  1350. for(U32 i = 0; i < header.numTiles; ++i)
  1351. {
  1352. NavMeshTileHeader tileHeader;
  1353. file.read(sizeof(NavMeshTileHeader), (char*)&tileHeader);
  1354. if(!tileHeader.tileRef || !tileHeader.dataSize)
  1355. break;
  1356. unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
  1357. if(!data) break;
  1358. memset(data, 0, tileHeader.dataSize);
  1359. file.read(tileHeader.dataSize, (char*)data);
  1360. nm->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0);
  1361. }
  1362. S32 s;
  1363. file.read(sizeof(S32), (char*)&s);
  1364. setLinkCount(s);
  1365. file.read(sizeof(F32) * s * 6, (char*)const_cast<F32*>(mLinkVerts.address()));
  1366. file.read(sizeof(F32) * s, (char*)const_cast<F32*>(mLinkRads.address()));
  1367. file.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkDirs.address()));
  1368. file.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkAreas.address()));
  1369. file.read(sizeof(U16) * s, (char*)const_cast<U16*>(mLinkFlags.address()));
  1370. file.read(sizeof(F32) * s, (char*)const_cast<U32*>(mLinkIDs.address()));
  1371. mLinksUnsynced.fill(false);
  1372. mLinkSelectStates.fill(Unselected);
  1373. mDeleteLinks.fill(false);
  1374. file.close();
  1375. updateTiles();
  1376. if(isServerObject())
  1377. {
  1378. setMaskBits(LoadFlag);
  1379. if(getEventManager())
  1380. getEventManager()->postEvent("NavMeshUpdate", getIdString());
  1381. }
  1382. return true;
  1383. }
  1384. DefineEngineMethod(NavMesh, load, bool, (),,
  1385. "@brief Load this NavMesh from its file.")
  1386. {
  1387. return object->load();
  1388. }
  1389. bool NavMesh::save()
  1390. {
  1391. if(!dStrlen(mFileName) || !nm)
  1392. return false;
  1393. File file;
  1394. if(file.open(mFileName, File::Write) != File::Ok)
  1395. {
  1396. file.close();
  1397. Con::errorf("Could not open file %s when saving navmesh %s.",
  1398. mFileName, getName() ? getName() : getIdString());
  1399. return false;
  1400. }
  1401. // Store header.
  1402. NavMeshSetHeader header;
  1403. header.magic = NAVMESHSET_MAGIC;
  1404. header.version = NAVMESHSET_VERSION;
  1405. header.numTiles = 0;
  1406. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1407. {
  1408. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1409. if (!tile || !tile->header || !tile->dataSize) continue;
  1410. header.numTiles++;
  1411. }
  1412. memcpy(&header.params, nm->getParams(), sizeof(dtNavMeshParams));
  1413. file.write(sizeof(NavMeshSetHeader), (const char*)&header);
  1414. // Store tiles.
  1415. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1416. {
  1417. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1418. if(!tile || !tile->header || !tile->dataSize) continue;
  1419. NavMeshTileHeader tileHeader;
  1420. tileHeader.tileRef = nm->getTileRef(tile);
  1421. tileHeader.dataSize = tile->dataSize;
  1422. file.write(sizeof(tileHeader), (const char*)&tileHeader);
  1423. file.write(tile->dataSize, (const char*)tile->data);
  1424. }
  1425. S32 s = mLinkIDs.size();
  1426. file.write(sizeof(S32), (const char*)&s);
  1427. file.write(sizeof(F32) * s * 6, (const char*)mLinkVerts.address());
  1428. file.write(sizeof(F32) * s, (const char*)mLinkRads.address());
  1429. file.write(sizeof(U8) * s, (const char*)mLinkDirs.address());
  1430. file.write(sizeof(U8) * s, (const char*)mLinkAreas.address());
  1431. file.write(sizeof(U16) * s, (const char*)mLinkFlags.address());
  1432. file.write(sizeof(U32) * s, (const char*)mLinkIDs.address());
  1433. file.close();
  1434. return true;
  1435. }
  1436. DefineEngineMethod(NavMesh, save, void, (),,
  1437. "@brief Save this NavMesh to its file.")
  1438. {
  1439. object->save();
  1440. }
  1441. void NavMesh::write(Stream &stream, U32 tabStop, U32 flags)
  1442. {
  1443. save();
  1444. Parent::write(stream, tabStop, flags);
  1445. }