navMesh.cpp 48 KB

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