navMesh.cpp 48 KB

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