1
0

OdeScene.cs 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. // changes for varsize regions
  28. // note that raycasts need to have limited range
  29. // (even in normal regions)
  30. // or application thread stack may just blowup
  31. // see RayCast(ODERayCastRequest req)
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Diagnostics;
  35. using System.IO;
  36. using System.Linq;
  37. using System.Reflection;
  38. using System.Runtime.ExceptionServices;
  39. using System.Runtime.InteropServices;
  40. using System.Threading;
  41. using log4net;
  42. using Nini.Config;
  43. using Mono.Addins;
  44. using OpenMetaverse;
  45. using OpenSim.Framework;
  46. using OpenSim.Region.PhysicsModules.SharedBase;
  47. using OpenSim.Region.Framework.Scenes;
  48. using OpenSim.Region.Framework.Interfaces;
  49. namespace OpenSim.Region.PhysicsModule.ODE
  50. {
  51. public enum StatusIndicators : int
  52. {
  53. Generic = 0,
  54. Start = 1,
  55. End = 2
  56. }
  57. [Flags]
  58. public enum CollisionCategories : int
  59. {
  60. Disabled = 0,
  61. Geom = 0x00000001,
  62. Body = 0x00000002,
  63. Space = 0x00000004,
  64. Character = 0x00000008,
  65. Land = 0x00000010,
  66. Water = 0x00000020,
  67. Wind = 0x00000040,
  68. Sensor = 0x00000080,
  69. Selected = 0x00000100
  70. }
  71. /// <summary>
  72. /// Material type for a primitive
  73. /// </summary>
  74. public enum Material : int
  75. {
  76. /// <summary></summary>
  77. Stone = 0,
  78. /// <summary></summary>
  79. Metal = 1,
  80. /// <summary></summary>
  81. Glass = 2,
  82. /// <summary></summary>
  83. Wood = 3,
  84. /// <summary></summary>
  85. Flesh = 4,
  86. /// <summary></summary>
  87. Plastic = 5,
  88. /// <summary></summary>
  89. Rubber = 6
  90. }
  91. public class OdeScene : PhysicsScene
  92. {
  93. private readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.ToString());
  94. // private Dictionary<string, sCollisionData> m_storedCollisions = new Dictionary<string, sCollisionData>();
  95. /// <summary>
  96. /// Provide a sync object so that only one thread calls d.Collide() at a time across all OdeScene instances.
  97. /// </summary>
  98. /// <remarks>
  99. /// With ODE as of r1755 (though also tested on r1860), only one thread can call d.Collide() at a
  100. /// time, even where physics objects are in entirely different ODE worlds. This is because generating contacts
  101. /// uses a static cache at the ODE level.
  102. ///
  103. /// Without locking, simulators running multiple regions will eventually crash with a native stack trace similar
  104. /// to
  105. ///
  106. /// mono() [0x489171]
  107. /// mono() [0x4d154f]
  108. /// /lib/x86_64-linux-gnu/libpthread.so.0(+0xfc60) [0x7f6ded592c60]
  109. /// .../opensim/bin/libode-x86_64.so(_ZN6Opcode11OBBCollider8_CollideEPKNS_14AABBNoLeafNodeE+0xd7a) [0x7f6dd822628a]
  110. ///
  111. /// ODE provides an experimental option to cache in thread local storage but compiling ODE with this option
  112. /// causes OpenSimulator to immediately crash with a native stack trace similar to
  113. ///
  114. /// mono() [0x489171]
  115. /// mono() [0x4d154f]
  116. /// /lib/x86_64-linux-gnu/libpthread.so.0(+0xfc60) [0x7f03c9849c60]
  117. /// .../opensim/bin/libode-x86_64.so(_Z12dCollideCCTLP6dxGeomS0_iP12dContactGeomi+0x92) [0x7f03b44bcf82]
  118. /// </remarks>
  119. internal static object UniversalColliderSyncObject = new object();
  120. internal static object SimulationLock = new object();
  121. /// <summary>
  122. /// Is stats collecting enabled for this ODE scene?
  123. /// </summary>
  124. public bool CollectStats { get; set; }
  125. /// <summary>
  126. /// Statistics for this scene.
  127. /// </summary>
  128. private Dictionary<string, float> m_stats = new Dictionary<string, float>();
  129. /// <summary>
  130. /// Stat name for total number of avatars in this ODE scene.
  131. /// </summary>
  132. public const string ODETotalAvatarsStatName = "ODETotalAvatars";
  133. /// <summary>
  134. /// Stat name for total number of prims in this ODE scene.
  135. /// </summary>
  136. public const string ODETotalPrimsStatName = "ODETotalPrims";
  137. /// <summary>
  138. /// Stat name for total number of prims with active physics in this ODE scene.
  139. /// </summary>
  140. public const string ODEActivePrimsStatName = "ODEActivePrims";
  141. /// <summary>
  142. /// Stat name for the total time spent in ODE frame processing.
  143. /// </summary>
  144. /// <remarks>
  145. /// A sanity check for the main scene loop physics time.
  146. /// </remarks>
  147. public const string ODETotalFrameMsStatName = "ODETotalFrameMS";
  148. /// <summary>
  149. /// Stat name for time spent processing avatar taints per frame
  150. /// </summary>
  151. public const string ODEAvatarTaintMsStatName = "ODEAvatarTaintFrameMS";
  152. /// <summary>
  153. /// Stat name for time spent processing prim taints per frame
  154. /// </summary>
  155. public const string ODEPrimTaintMsStatName = "ODEPrimTaintFrameMS";
  156. /// <summary>
  157. /// Stat name for time spent calculating avatar forces per frame.
  158. /// </summary>
  159. public const string ODEAvatarForcesFrameMsStatName = "ODEAvatarForcesFrameMS";
  160. /// <summary>
  161. /// Stat name for time spent calculating prim forces per frame
  162. /// </summary>
  163. public const string ODEPrimForcesFrameMsStatName = "ODEPrimForcesFrameMS";
  164. /// <summary>
  165. /// Stat name for time spent fulfilling raycasting requests per frame
  166. /// </summary>
  167. public const string ODERaycastingFrameMsStatName = "ODERaycastingFrameMS";
  168. /// <summary>
  169. /// Stat name for time spent in native code that actually steps through the simulation.
  170. /// </summary>
  171. public const string ODENativeStepFrameMsStatName = "ODENativeStepFrameMS";
  172. /// <summary>
  173. /// Stat name for the number of milliseconds that ODE spends in native space collision code.
  174. /// </summary>
  175. public const string ODENativeSpaceCollisionFrameMsStatName = "ODENativeSpaceCollisionFrameMS";
  176. /// <summary>
  177. /// Stat name for milliseconds that ODE spends in native geom collision code.
  178. /// </summary>
  179. public const string ODENativeGeomCollisionFrameMsStatName = "ODENativeGeomCollisionFrameMS";
  180. /// <summary>
  181. /// Time spent in collision processing that is not spent in native space or geom collision code.
  182. /// </summary>
  183. public const string ODEOtherCollisionFrameMsStatName = "ODEOtherCollisionFrameMS";
  184. /// <summary>
  185. /// Stat name for time spent notifying listeners of collisions
  186. /// </summary>
  187. public const string ODECollisionNotificationFrameMsStatName = "ODECollisionNotificationFrameMS";
  188. /// <summary>
  189. /// Stat name for milliseconds spent updating avatar position and velocity
  190. /// </summary>
  191. public const string ODEAvatarUpdateFrameMsStatName = "ODEAvatarUpdateFrameMS";
  192. /// <summary>
  193. /// Stat name for the milliseconds spent updating prim position and velocity
  194. /// </summary>
  195. public const string ODEPrimUpdateFrameMsStatName = "ODEPrimUpdateFrameMS";
  196. /// <summary>
  197. /// Stat name for avatar collisions with another entity.
  198. /// </summary>
  199. public const string ODEAvatarContactsStatsName = "ODEAvatarContacts";
  200. /// <summary>
  201. /// Stat name for prim collisions with another entity.
  202. /// </summary>
  203. public const string ODEPrimContactsStatName = "ODEPrimContacts";
  204. /// <summary>
  205. /// Used to hold tick numbers for stat collection purposes.
  206. /// </summary>
  207. private int m_nativeCollisionStartTick;
  208. /// <summary>
  209. /// A messy way to tell if we need to avoid adding a collision time because this was already done in the callback.
  210. /// </summary>
  211. private bool m_inCollisionTiming;
  212. /// <summary>
  213. /// A temporary holder for the number of avatar collisions in a frame, so we can work out how many object
  214. /// collisions occured using the _perloopcontact if stats collection is enabled.
  215. /// </summary>
  216. private int m_tempAvatarCollisionsThisFrame;
  217. /// <summary>
  218. /// Used in calculating physics frame time dilation
  219. /// </summary>
  220. private int tickCountFrameRun;
  221. /// <summary>
  222. /// Used in calculating physics frame time dilation
  223. /// </summary>
  224. private int latertickcount;
  225. private Random fluidRandomizer = new Random(Environment.TickCount);
  226. private uint m_regionWidth = Constants.RegionSize;
  227. private uint m_regionHeight = Constants.RegionSize;
  228. public float ODE_STEPSIZE = 0.0178f;
  229. private float metersInSpace = 29.9f;
  230. private float m_timeDilation = 1.0f;
  231. public float gravityx = 0f;
  232. public float gravityy = 0f;
  233. public float gravityz = -9.8f;
  234. public float AvatarTerminalVelocity { get; set; }
  235. private float contactsurfacelayer = 0.001f;
  236. private int HashspaceLow = -5;
  237. private int HashspaceHigh = 12;
  238. private float waterlevel = 0f;
  239. private int framecount = 0;
  240. //private int m_returncollisions = 10;
  241. private IntPtr contactgroup;
  242. // internal IntPtr WaterGeom;
  243. private float nmTerrainContactFriction = 255.0f;
  244. private float nmTerrainContactBounce = 0.1f;
  245. private float nmTerrainContactERP = 0.1025f;
  246. private float mTerrainContactFriction = 75f;
  247. private float mTerrainContactBounce = 0.1f;
  248. private float mTerrainContactERP = 0.05025f;
  249. private float nmAvatarObjectContactFriction = 250f;
  250. private float nmAvatarObjectContactBounce = 0.1f;
  251. private float mAvatarObjectContactFriction = 75f;
  252. private float mAvatarObjectContactBounce = 0.1f;
  253. private float avPIDD = 3200f;
  254. private float avPIDP = 1400f;
  255. private float avCapRadius = 0.37f;
  256. private float avStandupTensor = 2000000f;
  257. /// <summary>
  258. /// true = old compatibility mode with leaning capsule; false = new corrected mode
  259. /// </summary>
  260. /// <remarks>
  261. /// Even when set to false, the capsule still tilts but this is done in a different way.
  262. /// </remarks>
  263. public bool IsAvCapsuleTilted { get; private set; }
  264. private float avDensity = 80f;
  265. private float avMovementDivisorWalk = 1.3f;
  266. private float avMovementDivisorRun = 0.8f;
  267. private float minimumGroundFlightOffset = 3f;
  268. public float maximumMassObject = 10000.01f;
  269. public bool meshSculptedPrim = true;
  270. public bool forceSimplePrimMeshing = false;
  271. public float meshSculptLOD = 32;
  272. public float MeshSculptphysicalLOD = 16;
  273. public float geomDefaultDensity = 10.000006836f;
  274. public int geomContactPointsStartthrottle = 3;
  275. public int geomUpdatesPerThrottledUpdate = 15;
  276. private const int avatarExpectedContacts = 3;
  277. public float bodyPIDD = 35f;
  278. public float bodyPIDG = 25;
  279. public int bodyFramesAutoDisable = 20;
  280. private bool m_filterCollisions = true;
  281. private OdeNative.NearCallback nearCallback;
  282. /// <summary>
  283. /// Avatars in the physics scene.
  284. /// </summary>
  285. private readonly HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
  286. /// <summary>
  287. /// Prims in the physics scene.
  288. /// </summary>
  289. private readonly HashSet<OdePrim> _prims = new HashSet<OdePrim>();
  290. /// <summary>
  291. /// Prims in the physics scene that are subject to physics, not just collisions.
  292. /// </summary>
  293. private readonly HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
  294. /// <summary>
  295. /// Prims that the simulator has created/deleted/updated and so need updating in ODE.
  296. /// </summary>
  297. private readonly HashSet<OdePrim> _taintedPrims = new HashSet<OdePrim>();
  298. /// <summary>
  299. /// Record a character that has taints to be processed.
  300. /// </summary>
  301. private readonly HashSet<OdeCharacter> _taintedActors = new HashSet<OdeCharacter>();
  302. /// <summary>
  303. /// Keep record of contacts in the physics loop so that we can remove duplicates.
  304. /// </summary>
  305. private readonly List<OdeNative.ContactGeom> _perloopContact = new List<OdeNative.ContactGeom>();
  306. /// <summary>
  307. /// A dictionary of actors that should receive collision events.
  308. /// </summary>
  309. private readonly Dictionary<uint, PhysicsActor> m_collisionEventActors = new Dictionary<uint, PhysicsActor>();
  310. /// <summary>
  311. /// A dictionary of collision event changes that are waiting to be processed.
  312. /// </summary>
  313. private readonly Dictionary<uint, PhysicsActor> m_collisionEventActorsChanges = new Dictionary<uint, PhysicsActor>();
  314. /// <summary>
  315. /// Maps a unique geometry id (a memory location) to a physics actor name.
  316. /// </summary>
  317. /// <remarks>
  318. /// Only actors participating in collisions have geometries. This has to be maintained separately from
  319. /// actor_name_map because terrain and water currently don't conceptually have a physics actor of their own
  320. /// apart from the singleton PANull
  321. /// </remarks>
  322. public Dictionary<IntPtr, String> geom_name_map = new Dictionary<IntPtr, String>();
  323. /// <summary>
  324. /// Maps a unique geometry id (a memory location) to a physics actor.
  325. /// </summary>
  326. /// <remarks>
  327. /// Only actors participating in collisions have geometries.
  328. /// </remarks>
  329. public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
  330. /// <summary>
  331. /// Defects list to remove characters that no longer have finite positions due to some other bug.
  332. /// </summary>
  333. /// <remarks>
  334. /// Used repeatedly in Simulate() but initialized once here.
  335. /// </remarks>
  336. private readonly List<OdeCharacter> defects = new List<OdeCharacter>();
  337. private OdeNative.ContactGeom[] contacts;
  338. private readonly DoubleDictionary<Vector3, IntPtr, IntPtr> RegionTerrain = new DoubleDictionary<Vector3, IntPtr, IntPtr>();
  339. private readonly Dictionary<IntPtr,float[]> TerrainHeightFieldHeights = new Dictionary<IntPtr, float[]>();
  340. private OdeNative.Contact contact;
  341. private OdeNative.Contact TerrainContact;
  342. private OdeNative.Contact AvatarMovementprimContact;
  343. private OdeNative.Contact AvatarMovementTerrainContact;
  344. private OdeNative.Contact WaterContact;
  345. private OdeNative.Contact[,] m_materialContacts;
  346. private int m_physicsiterations = 10;
  347. private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
  348. private readonly PhysicsActor PANull = new NullPhysicsActor();
  349. private float step_time = 0.0f;
  350. public IntPtr world;
  351. private uint obj2LocalID = 0;
  352. private OdeCharacter cc1;
  353. private OdePrim cp1;
  354. private OdeCharacter cc2;
  355. private OdePrim cp2;
  356. private int p1ExpectedPoints = 0;
  357. private int p2ExpectedPoints = 0;
  358. public IntPtr space;
  359. // split static geometry collision handling into spaces of 30 meters
  360. public IntPtr[,] staticPrimspace;
  361. /// <summary>
  362. /// Used to lock the entire physics scene. Locked during the main part of Simulate()
  363. /// </summary>
  364. internal Object OdeLock = new Object();
  365. private bool _worldInitialized = false;
  366. public IMesher mesher;
  367. private IConfigSource m_config;
  368. public bool physics_logging = false;
  369. public int physics_logging_interval = 0;
  370. public bool physics_logging_append_existing_logfile = false;
  371. private bool avplanted = false;
  372. private bool av_av_collisions_off = false;
  373. internal OdeNative.Vector3 xyz = new OdeNative.Vector3(128.1640f, 128.3079f, 25.7600f);
  374. internal OdeNative.Vector3 hpr = new OdeNative.Vector3(125.5000f, -17.0000f, 0.0000f);
  375. private volatile int m_global_contactcount = 0;
  376. private Vector3 m_worldOffset = Vector3.Zero;
  377. public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  378. private PhysicsScene m_parentScene = null;
  379. float spacesPerMeterX;
  380. float spacesPerMeterY;
  381. int spaceGridMaxX;
  382. int spaceGridMaxY;
  383. private ODERayCastRequestManager m_rayCastManager;
  384. public Scene m_frameWorkScene = null;
  385. public OdeScene(Scene pscene, IConfigSource psourceconfig, string pname, string pversion)
  386. {
  387. OdeNative.AllocateODEDataForThread(~0U);
  388. m_config = psourceconfig;
  389. m_frameWorkScene = pscene;
  390. EngineType = pname;
  391. PhysicsSceneName = EngineType + "/" + pscene.RegionInfo.RegionName;
  392. EngineName = pname + " " + pversion;
  393. pscene.RegisterModuleInterface<PhysicsScene>(this);
  394. Vector3 extent = new Vector3(pscene.RegionInfo.RegionSizeX, pscene.RegionInfo.RegionSizeY, pscene.RegionInfo.RegionSizeZ);
  395. Initialise(extent);
  396. InitialiseFromConfig(m_config);
  397. // This may not be that good since terrain may not be avaiable at this point
  398. base.Initialise(pscene.PhysicsRequestAsset,
  399. (pscene.Heightmap != null ? pscene.Heightmap.GetFloatsSerialised() : new float[(int)(extent.X * extent.Y)]),
  400. (float)pscene.RegionInfo.RegionSettings.WaterHeight);
  401. }
  402. public void RegionLoaded()
  403. {
  404. mesher = m_frameWorkScene.RequestModuleInterface<IMesher>();
  405. if (mesher == null)
  406. m_log.WarnFormat("[ODE SCENE]: No mesher in {0}. Things will not work well.", PhysicsSceneName);
  407. m_frameWorkScene.PhysicsEnabled = true;
  408. }
  409. /// <summary>
  410. /// Initiailizes the scene
  411. /// Sets many properties that ODE requires to be stable
  412. /// These settings need to be tweaked 'exactly' right or weird stuff happens.
  413. /// </summary>
  414. private void Initialise(Vector3 regionExtent)
  415. {
  416. WorldExtents.X = regionExtent.X;
  417. m_regionWidth = (uint)regionExtent.X;
  418. WorldExtents.Y = regionExtent.Y;
  419. m_regionHeight = (uint)regionExtent.Y;
  420. nearCallback = near;
  421. m_rayCastManager = new ODERayCastRequestManager(this);
  422. // Create the world and the first space
  423. world = OdeNative.WorldCreate();
  424. space = OdeNative.HashSpaceCreate(IntPtr.Zero);
  425. contactgroup = OdeNative.JointGroupCreate(0);
  426. OdeNative.WorldSetAutoDisableFlag(world, false);
  427. }
  428. // Initialize from configs
  429. private void InitialiseFromConfig(IConfigSource config)
  430. {
  431. InitializeExtraStats();
  432. m_config = config;
  433. // Defaults
  434. avPIDD = 2200.0f;
  435. avPIDP = 900.0f;
  436. avStandupTensor = 550000f;
  437. int contactsPerCollision = 80;
  438. if (m_config != null)
  439. {
  440. IConfig physicsconfig = m_config.Configs["ODEPhysicsSettings"];
  441. if (physicsconfig != null)
  442. {
  443. CollectStats = physicsconfig.GetBoolean("collect_stats", false);
  444. gravityx = physicsconfig.GetFloat("world_gravityx", 0f);
  445. gravityy = physicsconfig.GetFloat("world_gravityy", 0f);
  446. gravityz = physicsconfig.GetFloat("world_gravityz", -9.8f);
  447. float avatarTerminalVelocity = physicsconfig.GetFloat("avatar_terminal_velocity", 54f);
  448. AvatarTerminalVelocity = Util.Clamp<float>(avatarTerminalVelocity, 0, 255f);
  449. if (AvatarTerminalVelocity != avatarTerminalVelocity)
  450. {
  451. m_log.WarnFormat(
  452. "[ODE SCENE]: avatar_terminal_velocity of {0} is invalid. Clamping to {1}",
  453. avatarTerminalVelocity, AvatarTerminalVelocity);
  454. }
  455. HashspaceLow = physicsconfig.GetInt("world_hashspace_level_low", -5);
  456. HashspaceHigh = physicsconfig.GetInt("world_hashspace_level_high", 12);
  457. metersInSpace = physicsconfig.GetFloat("meters_in_small_space", 29.9f);
  458. contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", 0.001f);
  459. nmTerrainContactFriction = physicsconfig.GetFloat("nm_terraincontact_friction", 255.0f);
  460. nmTerrainContactBounce = physicsconfig.GetFloat("nm_terraincontact_bounce", 0.1f);
  461. nmTerrainContactERP = physicsconfig.GetFloat("nm_terraincontact_erp", 0.1025f);
  462. mTerrainContactFriction = physicsconfig.GetFloat("m_terraincontact_friction", 75f);
  463. mTerrainContactBounce = physicsconfig.GetFloat("m_terraincontact_bounce", 0.05f);
  464. mTerrainContactERP = physicsconfig.GetFloat("m_terraincontact_erp", 0.05025f);
  465. nmAvatarObjectContactFriction = physicsconfig.GetFloat("objectcontact_friction", 250f);
  466. nmAvatarObjectContactBounce = physicsconfig.GetFloat("objectcontact_bounce", 0.2f);
  467. mAvatarObjectContactFriction = physicsconfig.GetFloat("m_avatarobjectcontact_friction", 75f);
  468. mAvatarObjectContactBounce = physicsconfig.GetFloat("m_avatarobjectcontact_bounce", 0.1f);
  469. ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", ODE_STEPSIZE);
  470. m_physicsiterations = physicsconfig.GetInt("world_solver_iterations", 10);
  471. avDensity = physicsconfig.GetFloat("av_density", 80f);
  472. // avHeightFudgeFactor = physicsconfig.GetFloat("av_height_fudge_factor", 0.52f);
  473. avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", 1.3f);
  474. avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", 0.8f);
  475. avCapRadius = physicsconfig.GetFloat("av_capsule_radius", 0.37f);
  476. avplanted = physicsconfig.GetBoolean("av_planted", false);
  477. av_av_collisions_off = physicsconfig.GetBoolean("av_av_collisions_off", false);
  478. IsAvCapsuleTilted = physicsconfig.GetBoolean("av_capsule_tilted", false);
  479. contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80);
  480. geomContactPointsStartthrottle = physicsconfig.GetInt("geom_contactpoints_start_throttling", 5);
  481. geomUpdatesPerThrottledUpdate = physicsconfig.GetInt("geom_updates_before_throttled_update", 15);
  482. geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", 10.000006836f);
  483. bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", 20);
  484. bodyPIDD = physicsconfig.GetFloat("body_pid_derivative", 35f);
  485. bodyPIDG = physicsconfig.GetFloat("body_pid_gain", 25f);
  486. forceSimplePrimMeshing = physicsconfig.GetBoolean("force_simple_prim_meshing", forceSimplePrimMeshing);
  487. meshSculptedPrim = physicsconfig.GetBoolean("mesh_sculpted_prim", true);
  488. meshSculptLOD = physicsconfig.GetFloat("mesh_lod", 32f);
  489. MeshSculptphysicalLOD = physicsconfig.GetFloat("mesh_physical_lod", 16f);
  490. m_filterCollisions = physicsconfig.GetBoolean("filter_collisions", false);
  491. avPIDD = physicsconfig.GetFloat("av_pid_derivative", 2200.0f);
  492. avPIDP = physicsconfig.GetFloat("av_pid_proportional", 900.0f);
  493. avStandupTensor = physicsconfig.GetFloat("av_capsule_standup_tensor", 550000f);
  494. physics_logging = physicsconfig.GetBoolean("physics_logging", false);
  495. physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
  496. physics_logging_append_existing_logfile = physicsconfig.GetBoolean("physics_logging_append_existing_logfile", false);
  497. minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", 3f);
  498. maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", 10000.01f);
  499. }
  500. }
  501. contacts = new OdeNative.ContactGeom[contactsPerCollision];
  502. spacesPerMeterX = 1.0f / metersInSpace;
  503. spacesPerMeterY = 1.0f / metersInSpace;
  504. spaceGridMaxX = (int)(WorldExtents.X * spacesPerMeterX);
  505. spaceGridMaxY = (int)(WorldExtents.Y * spacesPerMeterY);
  506. // note: limit number of spaces
  507. if (spaceGridMaxX > 24)
  508. {
  509. spaceGridMaxX = 24;
  510. spacesPerMeterX = spaceGridMaxX / WorldExtents.X;
  511. }
  512. if (spaceGridMaxY > 24)
  513. {
  514. spaceGridMaxY = 24;
  515. spacesPerMeterY = spaceGridMaxY / WorldExtents.Y;
  516. }
  517. staticPrimspace = new IntPtr[spaceGridMaxX, spaceGridMaxY];
  518. // make this index limits
  519. spaceGridMaxX--;
  520. spaceGridMaxY--;
  521. // Centeral contact friction and bounce
  522. // ckrinke 11/10/08 Enabling soft_erp but not soft_cfm until I figure out why
  523. // an avatar falls through in Z but not in X or Y when walking on a prim.
  524. contact.surface.mode |= OdeNative.ContactFlags.SoftERP;
  525. contact.surface.mu = nmAvatarObjectContactFriction;
  526. contact.surface.bounce = nmAvatarObjectContactBounce;
  527. contact.surface.soft_cfm = 0.010f;
  528. contact.surface.soft_erp = 0.010f;
  529. // Terrain contact friction and Bounce
  530. // This is the *non* moving version. Use this when an avatar
  531. // isn't moving to keep it in place better
  532. TerrainContact.surface.mode |= OdeNative.ContactFlags.SoftERP;
  533. TerrainContact.surface.mu = nmTerrainContactFriction;
  534. TerrainContact.surface.bounce = nmTerrainContactBounce;
  535. TerrainContact.surface.soft_erp = nmTerrainContactERP;
  536. WaterContact.surface.mode |= (OdeNative.ContactFlags.SoftERP | OdeNative.ContactFlags.SoftCFM);
  537. WaterContact.surface.mu = 0f; // No friction
  538. WaterContact.surface.bounce = 0.0f; // No bounce
  539. WaterContact.surface.soft_cfm = 0.010f;
  540. WaterContact.surface.soft_erp = 0.010f;
  541. // Prim contact friction and bounce
  542. // THis is the *non* moving version of friction and bounce
  543. // Use this when an avatar comes in contact with a prim
  544. // and is moving
  545. AvatarMovementprimContact.surface.mu = mAvatarObjectContactFriction;
  546. AvatarMovementprimContact.surface.bounce = mAvatarObjectContactBounce;
  547. // Terrain contact friction bounce and various error correcting calculations
  548. // Use this when an avatar is in contact with the terrain and moving.
  549. AvatarMovementTerrainContact.surface.mode |= OdeNative.ContactFlags.SoftERP;
  550. AvatarMovementTerrainContact.surface.mu = mTerrainContactFriction;
  551. AvatarMovementTerrainContact.surface.bounce = mTerrainContactBounce;
  552. AvatarMovementTerrainContact.surface.soft_erp = mTerrainContactERP;
  553. /*
  554. <summary></summary>
  555. Stone = 0,
  556. /// <summary></summary>
  557. Metal = 1,
  558. /// <summary></summary>
  559. Glass = 2,
  560. /// <summary></summary>
  561. Wood = 3,
  562. /// <summary></summary>
  563. Flesh = 4,
  564. /// <summary></summary>
  565. Plastic = 5,
  566. /// <summary></summary>
  567. Rubber = 6
  568. */
  569. m_materialContacts = new OdeNative.Contact[7,2];
  570. m_materialContacts[(int)Material.Stone, 0] = new OdeNative.Contact();
  571. m_materialContacts[(int)Material.Stone, 0].surface.mode |= OdeNative.ContactFlags.SoftERP;
  572. m_materialContacts[(int)Material.Stone, 0].surface.mu = nmAvatarObjectContactFriction;
  573. m_materialContacts[(int)Material.Stone, 0].surface.bounce = nmAvatarObjectContactBounce;
  574. m_materialContacts[(int)Material.Stone, 0].surface.soft_cfm = 0.010f;
  575. m_materialContacts[(int)Material.Stone, 0].surface.soft_erp = 0.010f;
  576. m_materialContacts[(int)Material.Stone, 1] = new OdeNative.Contact();
  577. m_materialContacts[(int)Material.Stone, 1].surface.mode |= OdeNative.ContactFlags.SoftERP;
  578. m_materialContacts[(int)Material.Stone, 1].surface.mu = mAvatarObjectContactFriction;
  579. m_materialContacts[(int)Material.Stone, 1].surface.bounce = mAvatarObjectContactBounce;
  580. m_materialContacts[(int)Material.Stone, 1].surface.soft_cfm = 0.010f;
  581. m_materialContacts[(int)Material.Stone, 1].surface.soft_erp = 0.010f;
  582. m_materialContacts[(int)Material.Metal, 0] = new OdeNative.Contact();
  583. m_materialContacts[(int)Material.Metal, 0].surface.mode |= OdeNative.ContactFlags.SoftERP;
  584. m_materialContacts[(int)Material.Metal, 0].surface.mu = nmAvatarObjectContactFriction;
  585. m_materialContacts[(int)Material.Metal, 0].surface.bounce = nmAvatarObjectContactBounce;
  586. m_materialContacts[(int)Material.Metal, 0].surface.soft_cfm = 0.010f;
  587. m_materialContacts[(int)Material.Metal, 0].surface.soft_erp = 0.010f;
  588. m_materialContacts[(int)Material.Metal, 1] = new OdeNative.Contact();
  589. m_materialContacts[(int)Material.Metal, 1].surface.mode |= OdeNative.ContactFlags.SoftERP;
  590. m_materialContacts[(int)Material.Metal, 1].surface.mu = mAvatarObjectContactFriction;
  591. m_materialContacts[(int)Material.Metal, 1].surface.bounce = mAvatarObjectContactBounce;
  592. m_materialContacts[(int)Material.Metal, 1].surface.soft_cfm = 0.010f;
  593. m_materialContacts[(int)Material.Metal, 1].surface.soft_erp = 0.010f;
  594. m_materialContacts[(int)Material.Glass, 0] = new OdeNative.Contact();
  595. m_materialContacts[(int)Material.Glass, 0].surface.mode |= OdeNative.ContactFlags.SoftERP;
  596. m_materialContacts[(int)Material.Glass, 0].surface.mu = 1f;
  597. m_materialContacts[(int)Material.Glass, 0].surface.bounce = 0.5f;
  598. m_materialContacts[(int)Material.Glass, 0].surface.soft_cfm = 0.010f;
  599. m_materialContacts[(int)Material.Glass, 0].surface.soft_erp = 0.010f;
  600. /*
  601. private float nmAvatarObjectContactFriction = 250f;
  602. private float nmAvatarObjectContactBounce = 0.1f;
  603. private float mAvatarObjectContactFriction = 75f;
  604. private float mAvatarObjectContactBounce = 0.1f;
  605. */
  606. m_materialContacts[(int)Material.Glass, 1] = new OdeNative.Contact();
  607. m_materialContacts[(int)Material.Glass, 1].surface.mode |= OdeNative.ContactFlags.SoftERP;
  608. m_materialContacts[(int)Material.Glass, 1].surface.mu = 1f;
  609. m_materialContacts[(int)Material.Glass, 1].surface.bounce = 0.5f;
  610. m_materialContacts[(int)Material.Glass, 1].surface.soft_cfm = 0.010f;
  611. m_materialContacts[(int)Material.Glass, 1].surface.soft_erp = 0.010f;
  612. m_materialContacts[(int)Material.Wood, 0] = new OdeNative.Contact();
  613. m_materialContacts[(int)Material.Wood, 0].surface.mode |= OdeNative.ContactFlags.SoftERP;
  614. m_materialContacts[(int)Material.Wood, 0].surface.mu = nmAvatarObjectContactFriction;
  615. m_materialContacts[(int)Material.Wood, 0].surface.bounce = nmAvatarObjectContactBounce;
  616. m_materialContacts[(int)Material.Wood, 0].surface.soft_cfm = 0.010f;
  617. m_materialContacts[(int)Material.Wood, 0].surface.soft_erp = 0.010f;
  618. m_materialContacts[(int)Material.Wood, 1] = new OdeNative.Contact();
  619. m_materialContacts[(int)Material.Wood, 1].surface.mode |= OdeNative.ContactFlags.SoftERP;
  620. m_materialContacts[(int)Material.Wood, 1].surface.mu = mAvatarObjectContactFriction;
  621. m_materialContacts[(int)Material.Wood, 1].surface.bounce = mAvatarObjectContactBounce;
  622. m_materialContacts[(int)Material.Wood, 1].surface.soft_cfm = 0.010f;
  623. m_materialContacts[(int)Material.Wood, 1].surface.soft_erp = 0.010f;
  624. m_materialContacts[(int)Material.Flesh, 0] = new OdeNative.Contact();
  625. m_materialContacts[(int)Material.Flesh, 0].surface.mode |= OdeNative.ContactFlags.SoftERP;
  626. m_materialContacts[(int)Material.Flesh, 0].surface.mu = nmAvatarObjectContactFriction;
  627. m_materialContacts[(int)Material.Flesh, 0].surface.bounce = nmAvatarObjectContactBounce;
  628. m_materialContacts[(int)Material.Flesh, 0].surface.soft_cfm = 0.010f;
  629. m_materialContacts[(int)Material.Flesh, 0].surface.soft_erp = 0.010f;
  630. m_materialContacts[(int)Material.Flesh, 1] = new OdeNative.Contact();
  631. m_materialContacts[(int)Material.Flesh, 1].surface.mode |= OdeNative.ContactFlags.SoftERP;
  632. m_materialContacts[(int)Material.Flesh, 1].surface.mu = mAvatarObjectContactFriction;
  633. m_materialContacts[(int)Material.Flesh, 1].surface.bounce = mAvatarObjectContactBounce;
  634. m_materialContacts[(int)Material.Flesh, 1].surface.soft_cfm = 0.010f;
  635. m_materialContacts[(int)Material.Flesh, 1].surface.soft_erp = 0.010f;
  636. m_materialContacts[(int)Material.Plastic, 0] = new OdeNative.Contact();
  637. m_materialContacts[(int)Material.Plastic, 0].surface.mode |= OdeNative.ContactFlags.SoftERP;
  638. m_materialContacts[(int)Material.Plastic, 0].surface.mu = nmAvatarObjectContactFriction;
  639. m_materialContacts[(int)Material.Plastic, 0].surface.bounce = nmAvatarObjectContactBounce;
  640. m_materialContacts[(int)Material.Plastic, 0].surface.soft_cfm = 0.010f;
  641. m_materialContacts[(int)Material.Plastic, 0].surface.soft_erp = 0.010f;
  642. m_materialContacts[(int)Material.Plastic, 1] = new OdeNative.Contact();
  643. m_materialContacts[(int)Material.Plastic, 1].surface.mode |= OdeNative.ContactFlags.SoftERP;
  644. m_materialContacts[(int)Material.Plastic, 1].surface.mu = mAvatarObjectContactFriction;
  645. m_materialContacts[(int)Material.Plastic, 1].surface.bounce = mAvatarObjectContactBounce;
  646. m_materialContacts[(int)Material.Plastic, 1].surface.soft_cfm = 0.010f;
  647. m_materialContacts[(int)Material.Plastic, 1].surface.soft_erp = 0.010f;
  648. m_materialContacts[(int)Material.Rubber, 0] = new OdeNative.Contact();
  649. m_materialContacts[(int)Material.Rubber, 0].surface.mode |= OdeNative.ContactFlags.SoftERP;
  650. m_materialContacts[(int)Material.Rubber, 0].surface.mu = nmAvatarObjectContactFriction;
  651. m_materialContacts[(int)Material.Rubber, 0].surface.bounce = nmAvatarObjectContactBounce;
  652. m_materialContacts[(int)Material.Rubber, 0].surface.soft_cfm = 0.010f;
  653. m_materialContacts[(int)Material.Rubber, 0].surface.soft_erp = 0.010f;
  654. m_materialContacts[(int)Material.Rubber, 1] = new OdeNative.Contact();
  655. m_materialContacts[(int)Material.Rubber, 1].surface.mode |= OdeNative.ContactFlags.SoftERP;
  656. m_materialContacts[(int)Material.Rubber, 1].surface.mu = mAvatarObjectContactFriction;
  657. m_materialContacts[(int)Material.Rubber, 1].surface.bounce = mAvatarObjectContactBounce;
  658. m_materialContacts[(int)Material.Rubber, 1].surface.soft_cfm = 0.010f;
  659. m_materialContacts[(int)Material.Rubber, 1].surface.soft_erp = 0.010f;
  660. OdeNative.HashSpaceSetLevels(space, HashspaceLow, HashspaceHigh);
  661. // Set the gravity,, don't disable things automatically (we set it explicitly on some things)
  662. OdeNative.WorldSetGravity(world, gravityx, gravityy, gravityz);
  663. OdeNative.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
  664. OdeNative.WorldSetLinearDamping(world, 256f);
  665. OdeNative.WorldSetAngularDamping(world, 256f);
  666. OdeNative.WorldSetAngularDampingThreshold(world, 256f);
  667. OdeNative.WorldSetLinearDampingThreshold(world, 256f);
  668. OdeNative.WorldSetMaxAngularSpeed(world, 256f);
  669. OdeNative.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  670. //d.WorldSetContactMaxCorrectingVel(world, 1000.0f);
  671. for (int i = 0; i < staticPrimspace.GetLength(0); i++)
  672. {
  673. for (int j = 0; j < staticPrimspace.GetLength(1); j++)
  674. {
  675. staticPrimspace[i, j] = IntPtr.Zero;
  676. }
  677. }
  678. _worldInitialized = true;
  679. }
  680. #region Collision Detection
  681. /// <summary>
  682. /// Collides two geometries.
  683. /// </summary>
  684. /// <returns></returns>
  685. /// <param name='geom1'></param>
  686. /// <param name='geom2'>/param>
  687. /// <param name='maxContacts'></param>
  688. /// <param name='contactsArray'></param>
  689. /// <param name='contactGeomSize'></param>
  690. private int CollideGeoms(
  691. IntPtr geom1, IntPtr geom2, int maxContacts, OdeNative.ContactGeom[] contactsArray, int contactGeomSize)
  692. {
  693. int count;
  694. lock (OdeScene.UniversalColliderSyncObject)
  695. {
  696. // We do this inside the lock so that we don't count any delay in acquiring it
  697. if (CollectStats)
  698. m_nativeCollisionStartTick = Util.EnvironmentTickCount();
  699. count = OdeNative.Collide(geom1, geom2, maxContacts, contactsArray, contactGeomSize);
  700. }
  701. // We do this outside the lock so that any waiting threads aren't held up, though the effect is probably
  702. // negligable
  703. if (CollectStats)
  704. m_stats[ODENativeGeomCollisionFrameMsStatName]
  705. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  706. return count;
  707. }
  708. /// <summary>
  709. /// Collide two spaces or a space and a geometry.
  710. /// </summary>
  711. /// <param name='space1'></param>
  712. /// <param name='space2'>/param>
  713. /// <param name='data'></param>
  714. private void CollideSpaces(IntPtr space1, IntPtr space2, IntPtr data)
  715. {
  716. if (CollectStats)
  717. {
  718. m_inCollisionTiming = true;
  719. m_nativeCollisionStartTick = Util.EnvironmentTickCount();
  720. }
  721. OdeNative.SpaceCollide2(space1, space2, data, nearCallback);
  722. if (CollectStats && m_inCollisionTiming)
  723. {
  724. m_stats[ODENativeSpaceCollisionFrameMsStatName]
  725. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  726. m_inCollisionTiming = false;
  727. }
  728. }
  729. /// <summary>
  730. /// This is our near callback. A geometry is near a body
  731. /// </summary>
  732. /// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
  733. /// <param name="g1">a geometry or space</param>
  734. /// <param name="g2">another geometry or space</param>
  735. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  736. {
  737. if (CollectStats && m_inCollisionTiming)
  738. {
  739. m_stats[ODENativeSpaceCollisionFrameMsStatName]
  740. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  741. m_inCollisionTiming = false;
  742. }
  743. // m_log.DebugFormat("[PHYSICS]: Colliding {0} and {1} in {2}", g1, g2, space);
  744. // no lock here! It's invoked from within Simulate(), which is thread-locked
  745. // Test if we're colliding a geom with a space.
  746. // If so we have to drill down into the space recursively
  747. if (OdeNative.GeomIsSpace(g1) || OdeNative.GeomIsSpace(g2))
  748. {
  749. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  750. return;
  751. // Separating static prim geometry spaces.
  752. // We'll be calling near recursivly if one
  753. // of them is a space to find all of the
  754. // contact points in the space
  755. try
  756. {
  757. CollideSpaces(g1, g2, IntPtr.Zero);
  758. }
  759. catch (AccessViolationException)
  760. {
  761. m_log.Error("[ODE SCENE]: Unable to collide test a space");
  762. return;
  763. }
  764. //Colliding a space or a geom with a space or a geom. so drill down
  765. //Collide all geoms in each space..
  766. //if (d.GeomIsSpace(g1)) d.SpaceCollide(g1, IntPtr.Zero, nearCallback);
  767. //if (d.GeomIsSpace(g2)) d.SpaceCollide(g2, IntPtr.Zero, nearCallback);
  768. return;
  769. }
  770. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  771. return;
  772. IntPtr b1 = OdeNative.GeomGetBody(g1);
  773. IntPtr b2 = OdeNative.GeomGetBody(g2);
  774. // d.GeomClassID id = d.GeomGetClass(g1);
  775. String name1 = null;
  776. String name2 = null;
  777. if (!geom_name_map.TryGetValue(g1, out name1))
  778. {
  779. name1 = "null";
  780. }
  781. if (!geom_name_map.TryGetValue(g2, out name2))
  782. {
  783. name2 = "null";
  784. }
  785. // Figure out how many contact points we have
  786. int count = 0;
  787. try
  788. {
  789. // Colliding Geom To Geom
  790. // This portion of the function 'was' blatantly ripped off from BoxStack.cs
  791. if (g1 == g2)
  792. return; // Can't collide with yourself
  793. if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && OdeNative.AreConnectedExcluding(b1, b2, OdeNative.JointType.Contact))
  794. return;
  795. count = CollideGeoms(g1, g2, contacts.Length, contacts, OdeNative.ContactGeom.unmanagedSizeOf);
  796. // All code after this is only relevant if we have any collisions
  797. if (count <= 0)
  798. return;
  799. if (count > contacts.Length)
  800. m_log.Error("[ODE SCENE]: Got " + count + " contacts when we asked for a maximum of " + contacts.Length);
  801. }
  802. catch (SEHException)
  803. {
  804. m_log.Error(
  805. "[ODE SCENE]: The Operating system shut down ODE because of corrupt memory. This could be a result of really irregular terrain. If this repeats continuously, restart using Basic Physics and terrain fill your terrain. Restarting the sim.");
  806. base.TriggerPhysicsBasedRestart();
  807. }
  808. catch (Exception e)
  809. {
  810. m_log.ErrorFormat("[ODE SCENE]: Unable to collide test an object: {0}", e.Message);
  811. return;
  812. }
  813. PhysicsActor p1;
  814. PhysicsActor p2;
  815. p1ExpectedPoints = 0;
  816. p2ExpectedPoints = 0;
  817. if (!actor_name_map.TryGetValue(g1, out p1))
  818. {
  819. p1 = PANull;
  820. }
  821. if (!actor_name_map.TryGetValue(g2, out p2))
  822. {
  823. p2 = PANull;
  824. }
  825. ContactPoint maxDepthContact = new ContactPoint();
  826. if (p1.CollisionScore + count >= float.MaxValue)
  827. p1.CollisionScore = 0;
  828. p1.CollisionScore += count;
  829. if (p2.CollisionScore + count >= float.MaxValue)
  830. p2.CollisionScore = 0;
  831. p2.CollisionScore += count;
  832. for (int i = 0; i < count; i++)
  833. {
  834. OdeNative.ContactGeom curContact = contacts[i];
  835. if (curContact.depth > maxDepthContact.PenetrationDepth)
  836. {
  837. maxDepthContact = new ContactPoint(
  838. new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
  839. new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
  840. curContact.depth
  841. );
  842. }
  843. //m_log.Warn("[CCOUNT]: " + count);
  844. IntPtr joint;
  845. // If we're colliding with terrain, use 'TerrainContact' instead of contact.
  846. // allows us to have different settings
  847. // We only need to test p2 for 'jump crouch purposes'
  848. if (p2 is OdeCharacter && p1.PhysicsActorType == (int)ActorTypes.Prim)
  849. {
  850. // Testing if the collision is at the feet of the avatar
  851. //m_log.DebugFormat("[PHYSICS]: {0} - {1} - {2} - {3}", curContact.pos.Z, p2.Position.Z, (p2.Position.Z - curContact.pos.Z), (p2.Size.Z * 0.6f));
  852. if ((p2.Position.Z - curContact.pos.Z) > (p2.Size.Z * 0.6f))
  853. p2.IsColliding = true;
  854. }
  855. else
  856. {
  857. p2.IsColliding = true;
  858. }
  859. //if ((framecount % m_returncollisions) == 0)
  860. switch (p1.PhysicsActorType)
  861. {
  862. case (int)ActorTypes.Agent:
  863. p1ExpectedPoints = avatarExpectedContacts;
  864. p2.CollidingObj = true;
  865. break;
  866. case (int)ActorTypes.Prim:
  867. if (p1 != null && p1 is OdePrim)
  868. p1ExpectedPoints = ((OdePrim) p1).ExpectedCollisionContacts;
  869. if (p2.Velocity.LengthSquared() > 0.0f)
  870. p2.CollidingObj = true;
  871. break;
  872. case (int)ActorTypes.Unknown:
  873. p2.CollidingGround = true;
  874. break;
  875. default:
  876. p2.CollidingGround = true;
  877. break;
  878. }
  879. // we don't want prim or avatar to explode
  880. #region InterPenetration Handling - Unintended physics explosions
  881. if (curContact.depth >= 0.08f)
  882. {
  883. if (curContact.depth >= 1.00f)
  884. {
  885. //m_log.Info("[P]: " + contact.depth.ToString());
  886. if ((p2.PhysicsActorType == (int) ActorTypes.Agent &&
  887. p1.PhysicsActorType == (int) ActorTypes.Unknown) ||
  888. (p1.PhysicsActorType == (int) ActorTypes.Agent &&
  889. p2.PhysicsActorType == (int) ActorTypes.Unknown))
  890. {
  891. if (p2.PhysicsActorType == (int) ActorTypes.Agent)
  892. {
  893. if (p2 is OdeCharacter)
  894. {
  895. OdeCharacter character = (OdeCharacter) p2;
  896. //p2.CollidingObj = true;
  897. curContact.depth = 0.00000003f;
  898. p2.Velocity = p2.Velocity + new Vector3(0f, 0f, 0.5f);
  899. curContact.pos =
  900. new OdeNative.Vector3(curContact.pos.X + (p1.Size.X/2),
  901. curContact.pos.Y + (p1.Size.Y/2),
  902. curContact.pos.Z + (p1.Size.Z/2));
  903. character.SetPidStatus(true);
  904. }
  905. }
  906. if (p1.PhysicsActorType == (int) ActorTypes.Agent)
  907. {
  908. if (p1 is OdeCharacter)
  909. {
  910. OdeCharacter character = (OdeCharacter) p1;
  911. //p2.CollidingObj = true;
  912. curContact.depth = 0.00000003f;
  913. p1.Velocity = p1.Velocity + new Vector3(0f, 0f, 0.5f);
  914. curContact.pos =
  915. new OdeNative.Vector3(curContact.pos.X + (p1.Size.X/2),
  916. curContact.pos.Y + (p1.Size.Y/2),
  917. curContact.pos.Z + (p1.Size.Z/2));
  918. character.SetPidStatus(true);
  919. }
  920. }
  921. }
  922. }
  923. }
  924. #endregion
  925. // Logic for collision handling
  926. // Note, that if *all* contacts are skipped (VolumeDetect)
  927. // The prim still detects (and forwards) collision events but
  928. // appears to be phantom for the world
  929. Boolean skipThisContact = false;
  930. if ((p1 is OdePrim) && (((OdePrim)p1).m_isVolumeDetect))
  931. skipThisContact = true; // No collision on volume detect prims
  932. if (av_av_collisions_off)
  933. if ((p1 is OdeCharacter) && (p2 is OdeCharacter))
  934. skipThisContact = true;
  935. if (!skipThisContact && (p2 is OdePrim) && (((OdePrim)p2).m_isVolumeDetect))
  936. skipThisContact = true; // No collision on volume detect prims
  937. if (!skipThisContact && curContact.depth < 0f)
  938. skipThisContact = true;
  939. if (!skipThisContact && checkDupe(curContact, p2.PhysicsActorType))
  940. skipThisContact = true;
  941. const int maxContactsbeforedeath = 4000;
  942. joint = IntPtr.Zero;
  943. if (!skipThisContact)
  944. {
  945. _perloopContact.Add(curContact);
  946. if (name1 == "Terrain" || name2 == "Terrain")
  947. {
  948. if ((p2.PhysicsActorType == (int) ActorTypes.Agent) &&
  949. (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  950. {
  951. p2ExpectedPoints = avatarExpectedContacts;
  952. // Avatar is moving on terrain, use the movement terrain contact
  953. AvatarMovementTerrainContact.geom = curContact;
  954. if (m_global_contactcount < maxContactsbeforedeath)
  955. {
  956. joint = OdeNative.JointCreateContact(world, contactgroup, ref AvatarMovementTerrainContact);
  957. m_global_contactcount++;
  958. }
  959. }
  960. else
  961. {
  962. if (p2.PhysicsActorType == (int)ActorTypes.Agent)
  963. {
  964. p2ExpectedPoints = avatarExpectedContacts;
  965. // Avatar is standing on terrain, use the non moving terrain contact
  966. TerrainContact.geom = curContact;
  967. if (m_global_contactcount < maxContactsbeforedeath)
  968. {
  969. joint = OdeNative.JointCreateContact(world, contactgroup, ref TerrainContact);
  970. m_global_contactcount++;
  971. }
  972. }
  973. else
  974. {
  975. if (p2.PhysicsActorType == (int)ActorTypes.Prim && p1.PhysicsActorType == (int)ActorTypes.Prim)
  976. {
  977. // prim prim contact
  978. // int pj294950 = 0;
  979. int movintYN = 0;
  980. int material = (int) Material.Wood;
  981. // prim terrain contact
  982. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  983. {
  984. movintYN = 1;
  985. }
  986. if (p2 is OdePrim)
  987. {
  988. material = ((OdePrim) p2).m_material;
  989. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  990. }
  991. // Unnessesary because p1 is defined above
  992. //if (p1 is OdePrim)
  993. // {
  994. // p1ExpectedPoints = ((OdePrim)p1).ExpectedCollisionContacts;
  995. // }
  996. //m_log.DebugFormat("Material: {0}", material);
  997. m_materialContacts[material, movintYN].geom = curContact;
  998. if (m_global_contactcount < maxContactsbeforedeath)
  999. {
  1000. joint = OdeNative.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  1001. m_global_contactcount++;
  1002. }
  1003. }
  1004. else
  1005. {
  1006. int movintYN = 0;
  1007. // prim terrain contact
  1008. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  1009. {
  1010. movintYN = 1;
  1011. }
  1012. int material = (int)Material.Wood;
  1013. if (p2 is OdePrim)
  1014. {
  1015. material = ((OdePrim)p2).m_material;
  1016. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1017. }
  1018. //m_log.DebugFormat("Material: {0}", material);
  1019. m_materialContacts[material, movintYN].geom = curContact;
  1020. if (m_global_contactcount < maxContactsbeforedeath)
  1021. {
  1022. joint = OdeNative.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  1023. m_global_contactcount++;
  1024. }
  1025. }
  1026. }
  1027. }
  1028. //if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1029. //{
  1030. //m_log.Debug("[PHYSICS]: prim contacting with ground");
  1031. //}
  1032. }
  1033. else if (name1 == "Water" || name2 == "Water")
  1034. {
  1035. /*
  1036. if ((p2.PhysicsActorType == (int) ActorTypes.Prim))
  1037. {
  1038. }
  1039. else
  1040. {
  1041. }
  1042. */
  1043. //WaterContact.surface.soft_cfm = 0.0000f;
  1044. //WaterContact.surface.soft_erp = 0.00000f;
  1045. if (curContact.depth > 0.1f)
  1046. {
  1047. curContact.depth *= 52;
  1048. //contact.normal = new d.Vector3(0, 0, 1);
  1049. //contact.pos = new d.Vector3(0, 0, contact.pos.Z - 5f);
  1050. }
  1051. WaterContact.geom = curContact;
  1052. if (m_global_contactcount < maxContactsbeforedeath)
  1053. {
  1054. joint = OdeNative.JointCreateContact(world, contactgroup, ref WaterContact);
  1055. m_global_contactcount++;
  1056. }
  1057. //m_log.Info("[PHYSICS]: Prim Water Contact" + contact.depth);
  1058. }
  1059. else
  1060. {
  1061. if ((p2.PhysicsActorType == (int)ActorTypes.Agent))
  1062. {
  1063. p2ExpectedPoints = avatarExpectedContacts;
  1064. if ((Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  1065. {
  1066. // Avatar is moving on a prim, use the Movement prim contact
  1067. AvatarMovementprimContact.geom = curContact;
  1068. if (m_global_contactcount < maxContactsbeforedeath)
  1069. {
  1070. joint = OdeNative.JointCreateContact(world, contactgroup, ref AvatarMovementprimContact);
  1071. m_global_contactcount++;
  1072. }
  1073. }
  1074. else
  1075. {
  1076. // Avatar is standing still on a prim, use the non movement contact
  1077. contact.geom = curContact;
  1078. if (m_global_contactcount < maxContactsbeforedeath)
  1079. {
  1080. joint = OdeNative.JointCreateContact(world, contactgroup, ref contact);
  1081. m_global_contactcount++;
  1082. }
  1083. }
  1084. }
  1085. else if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1086. {
  1087. //p1.PhysicsActorType
  1088. int material = (int)Material.Wood;
  1089. if (p2 is OdePrim)
  1090. {
  1091. material = ((OdePrim)p2).m_material;
  1092. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1093. }
  1094. //m_log.DebugFormat("Material: {0}", material);
  1095. m_materialContacts[material, 0].geom = curContact;
  1096. if (m_global_contactcount < maxContactsbeforedeath)
  1097. {
  1098. joint = OdeNative.JointCreateContact(world, contactgroup, ref m_materialContacts[material, 0]);
  1099. m_global_contactcount++;
  1100. }
  1101. }
  1102. }
  1103. if (m_global_contactcount < maxContactsbeforedeath && joint != IntPtr.Zero) // stack collide!
  1104. {
  1105. OdeNative.JointAttach(joint, b1, b2);
  1106. m_global_contactcount++;
  1107. }
  1108. }
  1109. collision_accounting_events(p1, p2, maxDepthContact);
  1110. if (count > ((p1ExpectedPoints + p2ExpectedPoints) * 0.25) + (geomContactPointsStartthrottle))
  1111. {
  1112. // If there are more then 3 contact points, it's likely
  1113. // that we've got a pile of objects, so ...
  1114. // We don't want to send out hundreds of terse updates over and over again
  1115. // so lets throttle them and send them again after it's somewhat sorted out.
  1116. p2.ThrottleUpdates = true;
  1117. }
  1118. //m_log.Debug(count.ToString());
  1119. //m_log.Debug("near: A collision was detected between {1} and {2}", 0, name1, name2);
  1120. }
  1121. }
  1122. private bool checkDupe(OdeNative.ContactGeom contactGeom, int atype)
  1123. {
  1124. if (!m_filterCollisions)
  1125. return false;
  1126. bool result = false;
  1127. ActorTypes at = (ActorTypes)atype;
  1128. foreach (OdeNative.ContactGeom contact in _perloopContact)
  1129. {
  1130. //if ((contact.g1 == contactGeom.g1 && contact.g2 == contactGeom.g2))
  1131. //{
  1132. // || (contact.g2 == contactGeom.g1 && contact.g1 == contactGeom.g2)
  1133. if (at == ActorTypes.Agent)
  1134. {
  1135. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f)
  1136. && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f)
  1137. && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)))
  1138. {
  1139. if (Math.Abs(contact.depth - contactGeom.depth) < 0.052f)
  1140. {
  1141. result = true;
  1142. break;
  1143. }
  1144. }
  1145. }
  1146. else if (at == ActorTypes.Prim)
  1147. {
  1148. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f) && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f) && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)))
  1149. {
  1150. if (contactGeom.normal.X == contact.normal.X && contactGeom.normal.Y == contact.normal.Y && contactGeom.normal.Z == contact.normal.Z)
  1151. {
  1152. if (Math.Abs(contact.depth - contactGeom.depth) < 0.272f)
  1153. {
  1154. result = true;
  1155. break;
  1156. }
  1157. }
  1158. //m_log.DebugFormat("[Collision]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1159. //m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1160. }
  1161. }
  1162. }
  1163. return result;
  1164. }
  1165. private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
  1166. {
  1167. // obj1LocalID = 0;
  1168. //returncollisions = false;
  1169. obj2LocalID = 0;
  1170. //ctype = 0;
  1171. //cStartStop = 0;
  1172. // if (!p2.SubscribedEvents() && !p1.SubscribedEvents())
  1173. // return;
  1174. bool p1events = p1.SubscribedEvents();
  1175. bool p2events = p2.SubscribedEvents();
  1176. if (p1.IsVolumeDtc)
  1177. p2events = false;
  1178. if (p2.IsVolumeDtc)
  1179. p1events = false;
  1180. if (!p2events && !p1events)
  1181. return;
  1182. Vector3 vel = Vector3.Zero;
  1183. if (p2 != null && p2.IsPhysical)
  1184. vel = p2.Velocity;
  1185. if (p1 != null && p1.IsPhysical)
  1186. vel -= p1.Velocity;
  1187. contact.RelativeSpeed = Vector3.Dot(vel, contact.SurfaceNormal);
  1188. switch ((ActorTypes)p2.PhysicsActorType)
  1189. {
  1190. case ActorTypes.Agent:
  1191. cc2 = (OdeCharacter)p2;
  1192. // obj1LocalID = cc2.m_localID;
  1193. switch ((ActorTypes)p1.PhysicsActorType)
  1194. {
  1195. case ActorTypes.Agent:
  1196. cc1 = (OdeCharacter)p1;
  1197. obj2LocalID = cc1.LocalID;
  1198. cc1.AddCollisionEvent(cc2.LocalID, contact);
  1199. break;
  1200. case ActorTypes.Prim:
  1201. if (p1 is OdePrim)
  1202. {
  1203. cp1 = (OdePrim) p1;
  1204. obj2LocalID = cp1.LocalID;
  1205. cp1.AddCollisionEvent(cc2.LocalID, contact);
  1206. }
  1207. break;
  1208. case ActorTypes.Ground:
  1209. case ActorTypes.Unknown:
  1210. obj2LocalID = 0;
  1211. break;
  1212. }
  1213. cc2.AddCollisionEvent(obj2LocalID, contact);
  1214. break;
  1215. case ActorTypes.Prim:
  1216. if (p2 is OdePrim)
  1217. {
  1218. cp2 = (OdePrim) p2;
  1219. // obj1LocalID = cp2.m_localID;
  1220. switch ((ActorTypes) p1.PhysicsActorType)
  1221. {
  1222. case ActorTypes.Agent:
  1223. if (p1 is OdeCharacter)
  1224. {
  1225. cc1 = (OdeCharacter) p1;
  1226. obj2LocalID = cc1.LocalID;
  1227. cc1.AddCollisionEvent(cp2.LocalID, contact);
  1228. }
  1229. break;
  1230. case ActorTypes.Prim:
  1231. if (p1 is OdePrim)
  1232. {
  1233. cp1 = (OdePrim) p1;
  1234. obj2LocalID = cp1.LocalID;
  1235. cp1.AddCollisionEvent(cp2.LocalID, contact);
  1236. }
  1237. break;
  1238. case ActorTypes.Ground:
  1239. case ActorTypes.Unknown:
  1240. obj2LocalID = 0;
  1241. break;
  1242. }
  1243. cp2.AddCollisionEvent(obj2LocalID, contact);
  1244. }
  1245. break;
  1246. }
  1247. }
  1248. /// <summary>
  1249. /// This is our collision testing routine in ODE
  1250. /// </summary>
  1251. private void collision_optimized()
  1252. {
  1253. _perloopContact.Clear();
  1254. foreach (OdeCharacter chr in _characters)
  1255. {
  1256. // Reset the collision values to false
  1257. // since we don't know if we're colliding yet
  1258. if (chr.Shell == IntPtr.Zero || chr.Body == IntPtr.Zero)
  1259. continue;
  1260. chr.IsColliding = false;
  1261. chr.CollidingGround = false;
  1262. chr.CollidingObj = false;
  1263. // Test the avatar's geometry for collision with the space
  1264. // This will return near and the space that they are the closest to
  1265. // And we'll run this again against the avatar and the space segment
  1266. // This will return with a bunch of possible objects in the space segment
  1267. // and we'll run it again on all of them.
  1268. try
  1269. {
  1270. CollideSpaces(space, chr.Shell, IntPtr.Zero);
  1271. }
  1272. catch (AccessViolationException)
  1273. {
  1274. m_log.ErrorFormat("[ODE SCENE]: Unable to space collide {0}", PhysicsSceneName);
  1275. }
  1276. //float terrainheight = GetTerrainHeightAtXY(chr.Position.X, chr.Position.Y);
  1277. //if (chr.Position.Z + (chr.Velocity.Z * timeStep) < terrainheight + 10)
  1278. //{
  1279. //chr.Position.Z = terrainheight + 10.0f;
  1280. //forcedZ = true;
  1281. //}
  1282. }
  1283. if (CollectStats)
  1284. {
  1285. m_tempAvatarCollisionsThisFrame = _perloopContact.Count;
  1286. m_stats[ODEAvatarContactsStatsName] += m_tempAvatarCollisionsThisFrame;
  1287. }
  1288. List<OdePrim> removeprims = null;
  1289. foreach (OdePrim chr in _activeprims)
  1290. {
  1291. if (chr.Body != IntPtr.Zero && OdeNative.BodyIsEnabled(chr.Body) && (!chr.m_disabled))
  1292. {
  1293. try
  1294. {
  1295. lock (chr)
  1296. {
  1297. if (space != IntPtr.Zero && chr.prim_geom != IntPtr.Zero && chr.m_taintremove == false)
  1298. {
  1299. CollideSpaces(space, chr.prim_geom, IntPtr.Zero);
  1300. }
  1301. else
  1302. {
  1303. if (removeprims == null)
  1304. {
  1305. removeprims = new List<OdePrim>();
  1306. }
  1307. removeprims.Add(chr);
  1308. m_log.Error(
  1309. "[ODE SCENE]: unable to collide test active prim against space. The space was zero, the geom was zero or it was in the process of being removed. Removed it from the active prim list. This needs to be fixed!");
  1310. }
  1311. }
  1312. }
  1313. catch (AccessViolationException)
  1314. {
  1315. m_log.Error("[ODE SCENE]: Unable to space collide");
  1316. }
  1317. }
  1318. }
  1319. if (CollectStats)
  1320. m_stats[ODEPrimContactsStatName] += _perloopContact.Count - m_tempAvatarCollisionsThisFrame;
  1321. if (removeprims != null)
  1322. {
  1323. foreach (OdePrim chr in removeprims)
  1324. {
  1325. _activeprims.Remove(chr);
  1326. }
  1327. }
  1328. }
  1329. #endregion
  1330. // Recovered for use by fly height. Kitto Flora
  1331. internal float GetTerrainHeightAtXY(float x, float y)
  1332. {
  1333. IntPtr heightFieldGeom = IntPtr.Zero;
  1334. int offsetX = 0;
  1335. int offsetY = 0;
  1336. if(RegionTerrain.TryGetValue(new Vector3(offsetX,offsetY,0), out heightFieldGeom))
  1337. {
  1338. if (heightFieldGeom != IntPtr.Zero)
  1339. {
  1340. if (TerrainHeightFieldHeights.ContainsKey(heightFieldGeom))
  1341. {
  1342. int index;
  1343. if ((int)x > WorldExtents.X || (int)y > WorldExtents.Y ||
  1344. (int)x < 0.001f || (int)y < 0.001f)
  1345. return 0;
  1346. x = x - offsetX + 1f;
  1347. y = y - offsetY + 1f;
  1348. // map is rotated
  1349. index = (int)x * ((int)m_regionHeight + 3) + (int)y;
  1350. if (index < TerrainHeightFieldHeights[heightFieldGeom].Length)
  1351. {
  1352. //m_log.DebugFormat("x{0} y{1} = {2}", x, y, (float)TerrainHeightFieldHeights[heightFieldGeom][index]);
  1353. return (float)TerrainHeightFieldHeights[heightFieldGeom][index];
  1354. }
  1355. else
  1356. return 0f;
  1357. }
  1358. else
  1359. {
  1360. return 0f;
  1361. }
  1362. }
  1363. else
  1364. {
  1365. return 0f;
  1366. }
  1367. }
  1368. else
  1369. {
  1370. return 0f;
  1371. }
  1372. }
  1373. // End recovered. Kitto Flora
  1374. /// <summary>
  1375. /// Add actor to the list that should receive collision events in the simulate loop.
  1376. /// </summary>
  1377. /// <param name="obj"></param>
  1378. internal void AddCollisionEventReporting(PhysicsActor obj)
  1379. {
  1380. // m_log.DebugFormat("[PHYSICS]: Adding {0} {1} to collision event reporting", obj.SOPName, obj.LocalID);
  1381. lock (m_collisionEventActorsChanges)
  1382. m_collisionEventActorsChanges[obj.LocalID] = obj;
  1383. }
  1384. /// <summary>
  1385. /// Remove actor from the list that should receive collision events in the simulate loop.
  1386. /// </summary>
  1387. /// <param name="obj"></param>
  1388. internal void RemoveCollisionEventReporting(PhysicsActor obj)
  1389. {
  1390. // m_log.DebugFormat("[PHYSICS]: Removing {0} {1} from collision event reporting", obj.SOPName, obj.LocalID);
  1391. lock (m_collisionEventActorsChanges)
  1392. m_collisionEventActorsChanges[obj.LocalID] = null;
  1393. }
  1394. #region Add/Remove Entities
  1395. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
  1396. {
  1397. OdeNative.AllocateODEDataForThread(0);
  1398. OdeCharacter newAv
  1399. = new OdeCharacter(
  1400. avName, this, position, velocity, size, avPIDD, avPIDP,
  1401. avCapRadius, avStandupTensor, avDensity,
  1402. avMovementDivisorWalk, avMovementDivisorRun);
  1403. newAv.Flying = isFlying;
  1404. newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
  1405. newAv.m_avatarplanted = avplanted;
  1406. return newAv;
  1407. }
  1408. public override void RemoveAvatar(PhysicsActor actor)
  1409. {
  1410. // m_log.DebugFormat(
  1411. // "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2}",
  1412. // actor.Name, actor.LocalID, Name);
  1413. lock (OdeLock)
  1414. {
  1415. OdeNative.AllocateODEDataForThread(0);
  1416. ((OdeCharacter) actor).Destroy();
  1417. }
  1418. }
  1419. internal void AddCharacter(OdeCharacter chr)
  1420. {
  1421. chr.m_avatarplanted = avplanted;
  1422. if (!_characters.Contains(chr))
  1423. {
  1424. _characters.Add(chr);
  1425. // m_log.DebugFormat(
  1426. // "[ODE SCENE]: Adding physics character {0} {1} to physics scene {2}. Count now {3}",
  1427. // chr.Name, chr.LocalID, Name, _characters.Count);
  1428. if (chr.bad)
  1429. m_log.ErrorFormat("[ODE SCENE]: Added BAD actor {0} to characters list", chr.m_uuid);
  1430. }
  1431. else
  1432. {
  1433. m_log.ErrorFormat(
  1434. "[ODE SCENE]: Tried to add character {0} {1} but they are already in the set!",
  1435. chr.Name, chr.LocalID);
  1436. }
  1437. }
  1438. internal void RemoveCharacter(OdeCharacter chr)
  1439. {
  1440. if (_characters.Contains(chr))
  1441. {
  1442. _characters.Remove(chr);
  1443. // m_log.DebugFormat(
  1444. // "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2}. Count now {3}",
  1445. // chr.Name, chr.LocalID, Name, _characters.Count);
  1446. }
  1447. else
  1448. {
  1449. m_log.ErrorFormat(
  1450. "[ODE SCENE]: Tried to remove character {0} {1} but they are not in the list!",
  1451. chr.Name, chr.LocalID);
  1452. }
  1453. }
  1454. private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
  1455. PrimitiveBaseShape pbs, bool isphysical, uint localID)
  1456. {
  1457. Vector3 pos = position;
  1458. Vector3 siz = size;
  1459. Quaternion rot = rotation;
  1460. OdePrim newPrim;
  1461. lock (OdeLock)
  1462. {
  1463. OdeNative.AllocateODEDataForThread(0);
  1464. newPrim = new OdePrim(name, this, pos, siz, rot, pbs, isphysical);
  1465. lock (_prims)
  1466. _prims.Add(newPrim);
  1467. }
  1468. newPrim.LocalID = localID;
  1469. return newPrim;
  1470. }
  1471. /// <summary>
  1472. /// Make this prim subject to physics.
  1473. /// </summary>
  1474. /// <param name="prim"></param>
  1475. internal void ActivatePrim(OdePrim prim)
  1476. {
  1477. // adds active prim.. (ones that should be iterated over in collisions_optimized
  1478. if (!_activeprims.Contains(prim))
  1479. _activeprims.Add(prim);
  1480. //else
  1481. // m_log.Warn("[PHYSICS]: Double Entry in _activeprims detected, potential crash immenent");
  1482. }
  1483. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1484. Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
  1485. {
  1486. // m_log.DebugFormat("[ODE SCENE]: Adding physics prim {0} {1} to physics scene {2}", primName, localid, Name);
  1487. return AddPrim(primName, position, size, rotation, pbs, isPhysical, localid);
  1488. }
  1489. public override float TimeDilation
  1490. {
  1491. get { return m_timeDilation; }
  1492. }
  1493. /// <summary>
  1494. /// Stop this prim being subject to physics
  1495. /// </summary>
  1496. /// <param name="prim"></param>
  1497. internal void DeactivatePrim(OdePrim prim)
  1498. {
  1499. _activeprims.Remove(prim);
  1500. }
  1501. public override void RemovePrim(PhysicsActor prim)
  1502. {
  1503. // As with all ODE physics operations, we don't remove the prim immediately but signal that it should be
  1504. // removed in the next physics simulate pass.
  1505. if (prim is OdePrim)
  1506. {
  1507. lock (OdeLock)
  1508. {
  1509. OdePrim p = (OdePrim) prim;
  1510. p.setPrimForRemoval();
  1511. AddPhysicsActorTaint(prim);
  1512. }
  1513. }
  1514. }
  1515. /// <summary>
  1516. /// This is called from within simulate but outside the locked portion
  1517. /// We need to do our own locking here
  1518. /// (Note: As of 20110801 this no longer appears to be true - this is being called within lock (odeLock) in
  1519. /// Simulate() -- justincc).
  1520. ///
  1521. /// Essentially, we need to remove the prim from our space segment, whatever segment it's in.
  1522. ///
  1523. /// If there are no more prim in the segment, we need to empty (spacedestroy)the segment and reclaim memory
  1524. /// that the space was using.
  1525. /// </summary>
  1526. /// <param name="prim"></param>
  1527. internal void RemovePrimThreadLocked(OdePrim prim)
  1528. {
  1529. // m_log.DebugFormat("[ODE SCENE]: Removing physical prim {0} {1}", prim.Name, prim.LocalID);
  1530. lock (prim)
  1531. {
  1532. RemoveCollisionEventReporting(prim);
  1533. if (prim.prim_geom != IntPtr.Zero)
  1534. {
  1535. prim.ResetTaints();
  1536. if (prim.IsPhysical)
  1537. {
  1538. prim.disableBody();
  1539. if (prim.childPrim)
  1540. {
  1541. prim.childPrim = false;
  1542. prim.Body = IntPtr.Zero;
  1543. prim.m_disabled = true;
  1544. prim.IsPhysical = false;
  1545. }
  1546. }
  1547. prim.m_targetSpace = IntPtr.Zero;
  1548. if (!prim.RemoveGeom())
  1549. m_log.Warn("[ODE SCENE]: Unable to remove prim from physics scene");
  1550. lock (_prims)
  1551. _prims.Remove(prim);
  1552. }
  1553. }
  1554. }
  1555. #endregion
  1556. #region Space Separation Calculation
  1557. /// <summary>
  1558. /// Takes a space pointer and zeros out the array we're using to hold the spaces
  1559. /// </summary>
  1560. /// <param name="pSpace"></param>
  1561. private void resetSpaceArrayItemToZero(IntPtr pSpace)
  1562. {
  1563. for (int x = 0; x < staticPrimspace.GetLength(0); x++)
  1564. {
  1565. for (int y = 0; y < staticPrimspace.GetLength(1); y++)
  1566. {
  1567. if (staticPrimspace[x, y] == pSpace)
  1568. staticPrimspace[x, y] = IntPtr.Zero;
  1569. }
  1570. }
  1571. }
  1572. // private void resetSpaceArrayItemToZero(int arrayitemX, int arrayitemY)
  1573. // {
  1574. // staticPrimspace[arrayitemX, arrayitemY] = IntPtr.Zero;
  1575. // }
  1576. /// <summary>
  1577. /// Called when a static prim moves. Allocates a space for the prim based on its position
  1578. /// </summary>
  1579. /// <param name="geom">the pointer to the geom that moved</param>
  1580. /// <param name="pos">the position that the geom moved to</param>
  1581. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  1582. /// <returns>a pointer to the new space it's in</returns>
  1583. internal IntPtr recalculateSpaceForGeom(IntPtr geom, Vector3 pos, IntPtr currentspace)
  1584. {
  1585. // Called from setting the Position and Size of an ODEPrim so
  1586. // it's already in locked space.
  1587. // we don't want to remove the main space
  1588. // we don't need to test physical here because this function should
  1589. // never be called if the prim is physical(active)
  1590. // All physical prim end up in the root space
  1591. //Thread.Sleep(20);
  1592. if (currentspace != space)
  1593. {
  1594. //m_log.Info("[SPACE]: C:" + currentspace.ToString() + " g:" + geom.ToString());
  1595. //if (currentspace == IntPtr.Zero)
  1596. //{
  1597. //int adfadf = 0;
  1598. //}
  1599. if (OdeNative.SpaceQuery(currentspace, geom) && currentspace != IntPtr.Zero)
  1600. {
  1601. if (OdeNative.GeomIsSpace(currentspace))
  1602. {
  1603. // waitForSpaceUnlock(currentspace);
  1604. OdeNative.SpaceRemove(currentspace, geom);
  1605. }
  1606. else
  1607. {
  1608. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" + currentspace +
  1609. " Geom:" + geom);
  1610. }
  1611. }
  1612. else
  1613. {
  1614. IntPtr sGeomIsIn = OdeNative.GeomGetSpace(geom);
  1615. if (sGeomIsIn != IntPtr.Zero)
  1616. {
  1617. if (OdeNative.GeomIsSpace(currentspace))
  1618. {
  1619. // waitForSpaceUnlock(sGeomIsIn);
  1620. OdeNative.SpaceRemove(sGeomIsIn, geom);
  1621. }
  1622. else
  1623. {
  1624. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  1625. sGeomIsIn + " Geom:" + geom);
  1626. }
  1627. }
  1628. }
  1629. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  1630. if (OdeNative.SpaceGetNumGeoms(currentspace) == 0)
  1631. {
  1632. if (currentspace != IntPtr.Zero)
  1633. {
  1634. if (OdeNative.GeomIsSpace(currentspace))
  1635. {
  1636. OdeNative.SpaceRemove(space, currentspace);
  1637. // free up memory used by the space.
  1638. resetSpaceArrayItemToZero(currentspace);
  1639. }
  1640. else
  1641. {
  1642. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  1643. currentspace + " Geom:" + geom);
  1644. }
  1645. }
  1646. }
  1647. }
  1648. else
  1649. {
  1650. // this is a physical object that got disabled. ;.;
  1651. if (currentspace != IntPtr.Zero && geom != IntPtr.Zero)
  1652. {
  1653. if (OdeNative.SpaceQuery(currentspace, geom))
  1654. {
  1655. if (OdeNative.GeomIsSpace(currentspace))
  1656. {
  1657. // waitForSpaceUnlock(currentspace);
  1658. OdeNative.SpaceRemove(currentspace, geom);
  1659. }
  1660. else
  1661. {
  1662. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  1663. currentspace + " Geom:" + geom);
  1664. }
  1665. }
  1666. else
  1667. {
  1668. IntPtr sGeomIsIn = OdeNative.GeomGetSpace(geom);
  1669. if (sGeomIsIn != IntPtr.Zero)
  1670. {
  1671. if (OdeNative.GeomIsSpace(sGeomIsIn))
  1672. {
  1673. // waitForSpaceUnlock(sGeomIsIn);
  1674. OdeNative.SpaceRemove(sGeomIsIn, geom);
  1675. }
  1676. else
  1677. {
  1678. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  1679. sGeomIsIn + " Geom:" + geom);
  1680. }
  1681. }
  1682. }
  1683. }
  1684. }
  1685. // The routines in the Position and Size sections do the 'inserting' into the space,
  1686. // so all we have to do is make sure that the space that we're putting the prim into
  1687. // is in the 'main' space.
  1688. int[] iprimspaceArrItem = calculateSpaceArrayItemFromPos(pos);
  1689. IntPtr newspace = calculateSpaceForGeom(pos);
  1690. if (newspace == IntPtr.Zero)
  1691. {
  1692. newspace = createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  1693. OdeNative.HashSpaceSetLevels(newspace, HashspaceLow, HashspaceHigh);
  1694. }
  1695. return newspace;
  1696. }
  1697. /// <summary>
  1698. /// Creates a new space at X Y
  1699. /// </summary>
  1700. /// <param name="iprimspaceArrItemX"></param>
  1701. /// <param name="iprimspaceArrItemY"></param>
  1702. /// <returns>A pointer to the created space</returns>
  1703. internal IntPtr createprimspace(int iprimspaceArrItemX, int iprimspaceArrItemY)
  1704. {
  1705. // creating a new space for prim and inserting it into main space.
  1706. staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY] = OdeNative.HashSpaceCreate(IntPtr.Zero);
  1707. OdeNative.GeomSetCategoryBits(staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY], (int)CollisionCategories.Space);
  1708. // waitForSpaceUnlock(space);
  1709. OdeNative.SpaceSetSublevel(space, 1);
  1710. OdeNative.SpaceAdd(space, staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY]);
  1711. return staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY];
  1712. }
  1713. /// <summary>
  1714. /// Calculates the space the prim should be in by its position
  1715. /// </summary>
  1716. /// <param name="pos"></param>
  1717. /// <returns>a pointer to the space. This could be a new space or reused space.</returns>
  1718. internal IntPtr calculateSpaceForGeom(Vector3 pos)
  1719. {
  1720. int[] xyspace = calculateSpaceArrayItemFromPos(pos);
  1721. //m_log.Info("[Physics]: Attempting to use arrayItem: " + xyspace[0].ToString() + "," + xyspace[1].ToString());
  1722. return staticPrimspace[xyspace[0], xyspace[1]];
  1723. }
  1724. /// <summary>
  1725. /// Holds the space allocation logic
  1726. /// </summary>
  1727. /// <param name="pos"></param>
  1728. /// <returns>an array item based on the position</returns>
  1729. internal int[] calculateSpaceArrayItemFromPos(Vector3 pos)
  1730. {
  1731. int[] returnint = new int[2];
  1732. returnint[0] = (int) (pos.X * spacesPerMeterX);
  1733. if (returnint[0] > spaceGridMaxX)
  1734. returnint[0] = spaceGridMaxX;
  1735. if (returnint[0] < 0)
  1736. returnint[0] = 0;
  1737. returnint[1] = (int)(pos.Y * spacesPerMeterY);
  1738. if (returnint[1] > spaceGridMaxY)
  1739. returnint[1] = spaceGridMaxY;
  1740. if (returnint[1] < 0)
  1741. returnint[1] = 0;
  1742. return returnint;
  1743. }
  1744. #endregion
  1745. /// <summary>
  1746. /// Routine to figure out if we need to mesh this prim with our mesher
  1747. /// </summary>
  1748. /// <param name="pbs"></param>
  1749. /// <returns></returns>
  1750. internal bool needsMeshing(PrimitiveBaseShape pbs)
  1751. {
  1752. // most of this is redundant now as the mesher will return null if it cant mesh a prim
  1753. // but we still need to check for sculptie meshing being enabled so this is the most
  1754. // convenient place to do it for now...
  1755. // //if (pbs.PathCurve == (byte)Primitive.PathCurve.Circle && pbs.ProfileCurve == (byte)Primitive.ProfileCurve.Circle && pbs.PathScaleY <= 0.75f)
  1756. // //m_log.Debug("needsMeshing: " + " pathCurve: " + pbs.PathCurve.ToString() + " profileCurve: " + pbs.ProfileCurve.ToString() + " pathScaleY: " + Primitive.UnpackPathScale(pbs.PathScaleY).ToString());
  1757. int iPropertiesNotSupportedDefault = 0;
  1758. if (pbs.SculptEntry && !meshSculptedPrim)
  1759. {
  1760. #if SPAM
  1761. m_log.Warn("NonMesh");
  1762. #endif
  1763. return false;
  1764. }
  1765. // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since ODE can use an internal representation for the prim
  1766. if (!forceSimplePrimMeshing && !pbs.SculptEntry)
  1767. {
  1768. if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  1769. || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
  1770. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
  1771. {
  1772. if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  1773. && pbs.ProfileHollow == 0
  1774. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  1775. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  1776. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  1777. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  1778. && pbs.PathShearX == 0 && pbs.PathShearY == 0)
  1779. {
  1780. #if SPAM
  1781. m_log.Warn("NonMesh");
  1782. #endif
  1783. return false;
  1784. }
  1785. }
  1786. }
  1787. if (pbs.ProfileHollow != 0)
  1788. iPropertiesNotSupportedDefault++;
  1789. if ((pbs.PathBegin != 0) || pbs.PathEnd != 0)
  1790. iPropertiesNotSupportedDefault++;
  1791. if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
  1792. iPropertiesNotSupportedDefault++;
  1793. if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
  1794. iPropertiesNotSupportedDefault++;
  1795. if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
  1796. iPropertiesNotSupportedDefault++;
  1797. if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
  1798. iPropertiesNotSupportedDefault++;
  1799. if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
  1800. iPropertiesNotSupportedDefault++;
  1801. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X))
  1802. iPropertiesNotSupportedDefault++;
  1803. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
  1804. iPropertiesNotSupportedDefault++;
  1805. // test for torus
  1806. if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
  1807. {
  1808. if (pbs.PathCurve == (byte)Extrusion.Curve1)
  1809. {
  1810. iPropertiesNotSupportedDefault++;
  1811. }
  1812. }
  1813. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  1814. {
  1815. if (pbs.PathCurve == (byte)Extrusion.Straight)
  1816. {
  1817. iPropertiesNotSupportedDefault++;
  1818. }
  1819. // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
  1820. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  1821. {
  1822. iPropertiesNotSupportedDefault++;
  1823. }
  1824. }
  1825. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  1826. {
  1827. if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
  1828. {
  1829. iPropertiesNotSupportedDefault++;
  1830. }
  1831. }
  1832. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  1833. {
  1834. if (pbs.PathCurve == (byte)Extrusion.Straight)
  1835. {
  1836. iPropertiesNotSupportedDefault++;
  1837. }
  1838. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  1839. {
  1840. iPropertiesNotSupportedDefault++;
  1841. }
  1842. }
  1843. if (pbs.SculptEntry && meshSculptedPrim)
  1844. iPropertiesNotSupportedDefault++;
  1845. if (iPropertiesNotSupportedDefault == 0)
  1846. {
  1847. #if SPAM
  1848. m_log.Warn("NonMesh");
  1849. #endif
  1850. return false;
  1851. }
  1852. #if SPAM
  1853. m_log.Debug("Mesh");
  1854. #endif
  1855. return true;
  1856. }
  1857. /// <summary>
  1858. /// Called after our prim properties are set Scale, position etc.
  1859. /// </summary>
  1860. /// <remarks>
  1861. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  1862. /// This assures us that we have no race conditions
  1863. /// </remarks>
  1864. /// <param name="actor"></param>
  1865. public override void AddPhysicsActorTaint(PhysicsActor actor)
  1866. {
  1867. if (actor is OdePrim)
  1868. {
  1869. OdePrim taintedprim = ((OdePrim)actor);
  1870. lock (_taintedPrims)
  1871. _taintedPrims.Add(taintedprim);
  1872. }
  1873. else if (actor is OdeCharacter)
  1874. {
  1875. OdeCharacter taintedchar = ((OdeCharacter)actor);
  1876. lock (_taintedActors)
  1877. {
  1878. _taintedActors.Add(taintedchar);
  1879. if (taintedchar.bad)
  1880. m_log.ErrorFormat("[ODE SCENE]: Added BAD actor {0} to tainted actors", taintedchar.m_uuid);
  1881. }
  1882. }
  1883. }
  1884. // does all pending changes generated during region load process
  1885. public override void ProcessPreSimulation()
  1886. {
  1887. lock (OdeLock)
  1888. {
  1889. if (world == IntPtr.Zero)
  1890. {
  1891. _taintedPrims.Clear();;
  1892. return;
  1893. }
  1894. int donechanges = 0;
  1895. if (_taintedPrims.Count > 0)
  1896. {
  1897. m_log.InfoFormat("[Ode] start processing pending actor operations");
  1898. int tstart = Util.EnvironmentTickCount();
  1899. OdeNative.AllocateODEDataForThread(0);
  1900. lock (_taintedPrims)
  1901. {
  1902. foreach (OdePrim prim in _taintedPrims)
  1903. {
  1904. if (prim.m_taintremove)
  1905. RemovePrimThreadLocked(prim);
  1906. else
  1907. prim.ProcessTaints();
  1908. prim.m_collisionscore = 0;
  1909. donechanges++;
  1910. }
  1911. _taintedPrims.Clear();
  1912. }
  1913. int time = Util.EnvironmentTickCountSubtract(tstart);
  1914. m_log.InfoFormat("[Ode] finished {0} operations in {1}ms", donechanges, time);
  1915. }
  1916. m_log.InfoFormat("[Ode] {0} prim actors loaded",_prims.Count);
  1917. }
  1918. }
  1919. /// <summary>
  1920. /// This is our main simulate loop
  1921. /// </summary>
  1922. /// <remarks>
  1923. /// It's thread locked by a Mutex in the scene.
  1924. /// It holds Collisions, it instructs ODE to step through the physical reactions
  1925. /// It moves the objects around in memory
  1926. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  1927. /// </remarks>
  1928. /// <param name="timeStep"></param>
  1929. /// <returns>The number of frames simulated over that period.</returns>
  1930. public override float Simulate(float timeStep)
  1931. {
  1932. if (!_worldInitialized)
  1933. return 1.0f;
  1934. int startFrameTick = CollectStats ? Util.EnvironmentTickCount() : 0;
  1935. int tempTick = 0, tempTick2 = 0;
  1936. if (framecount >= int.MaxValue)
  1937. framecount = 0;
  1938. framecount++;
  1939. float fps = 0;
  1940. step_time += timeStep;
  1941. float HalfOdeStep = ODE_STEPSIZE * 0.5f;
  1942. if (step_time < HalfOdeStep)
  1943. return 0;
  1944. // We change _collisionEventPrimChanges to avoid locking _collisionEventPrim itself and causing potential
  1945. // deadlock if the collision event tries to lock something else later on which is already locked by a
  1946. // caller that is adding or removing the collision event.
  1947. lock (m_collisionEventActorsChanges)
  1948. {
  1949. foreach (KeyValuePair<uint, PhysicsActor> kvp in m_collisionEventActorsChanges)
  1950. {
  1951. if (kvp.Value == null)
  1952. m_collisionEventActors.Remove(kvp.Key);
  1953. else
  1954. m_collisionEventActors[kvp.Key] = kvp.Value;
  1955. }
  1956. m_collisionEventActorsChanges.Clear();
  1957. }
  1958. lock (OdeLock)
  1959. {
  1960. OdeNative.AllocateODEDataForThread(~0U);
  1961. while (step_time > HalfOdeStep)
  1962. {
  1963. try
  1964. {
  1965. if (CollectStats)
  1966. tempTick = Util.EnvironmentTickCount();
  1967. lock (_taintedActors)
  1968. {
  1969. foreach (OdeCharacter character in _taintedActors)
  1970. character.ProcessTaints();
  1971. _taintedActors.Clear();
  1972. }
  1973. if (CollectStats)
  1974. {
  1975. tempTick2 = Util.EnvironmentTickCount();
  1976. m_stats[ODEAvatarTaintMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  1977. tempTick = tempTick2;
  1978. }
  1979. lock (_taintedPrims)
  1980. {
  1981. foreach (OdePrim prim in _taintedPrims)
  1982. {
  1983. if (prim.m_taintremove)
  1984. {
  1985. // Console.WriteLine("Simulate calls RemovePrimThreadLocked for {0}", prim.Name);
  1986. RemovePrimThreadLocked(prim);
  1987. }
  1988. else
  1989. {
  1990. // Console.WriteLine("Simulate calls ProcessTaints for {0}", prim.Name);
  1991. prim.ProcessTaints();
  1992. }
  1993. prim.m_collisionscore = 0;
  1994. // This loop can block up the Heartbeat for a very long time on large regions.
  1995. // We need to let the Watchdog know that the Heartbeat is not dead
  1996. // NOTE: This is currently commented out, but if things like OAR loading are
  1997. // timing the heartbeat out we will need to uncomment it
  1998. //Watchdog.UpdateThread();
  1999. }
  2000. _taintedPrims.Clear();
  2001. }
  2002. if (CollectStats)
  2003. {
  2004. tempTick2 = Util.EnvironmentTickCount();
  2005. m_stats[ODEPrimTaintMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2006. tempTick = tempTick2;
  2007. }
  2008. // Move characters
  2009. foreach (OdeCharacter actor in _characters)
  2010. actor.Move(defects);
  2011. if (defects.Count != 0)
  2012. {
  2013. foreach (OdeCharacter actor in defects)
  2014. {
  2015. m_log.ErrorFormat(
  2016. "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2} due to defect found when moving",
  2017. actor.Name, actor.LocalID, PhysicsSceneName);
  2018. RemoveCharacter(actor);
  2019. actor.DestroyOdeStructures();
  2020. }
  2021. defects.Clear();
  2022. }
  2023. if (CollectStats)
  2024. {
  2025. tempTick2 = Util.EnvironmentTickCount();
  2026. m_stats[ODEAvatarForcesFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2027. tempTick = tempTick2;
  2028. }
  2029. // Move other active objects
  2030. foreach (OdePrim prim in _activeprims)
  2031. {
  2032. prim.m_collisionscore = 0;
  2033. prim.Move(timeStep);
  2034. }
  2035. if (CollectStats)
  2036. {
  2037. tempTick2 = Util.EnvironmentTickCount();
  2038. m_stats[ODEPrimForcesFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2039. tempTick = tempTick2;
  2040. }
  2041. m_rayCastManager.ProcessQueuedRequests();
  2042. if (CollectStats)
  2043. {
  2044. tempTick2 = Util.EnvironmentTickCount();
  2045. m_stats[ODERaycastingFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2046. tempTick = tempTick2;
  2047. }
  2048. collision_optimized();
  2049. if (CollectStats)
  2050. {
  2051. tempTick2 = Util.EnvironmentTickCount();
  2052. m_stats[ODEOtherCollisionFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2053. tempTick = tempTick2;
  2054. }
  2055. foreach (PhysicsActor obj in m_collisionEventActors.Values)
  2056. {
  2057. // m_log.DebugFormat("[PHYSICS]: Assessing {0} {1} for collision events", obj.SOPName, obj.LocalID);
  2058. switch ((ActorTypes)obj.PhysicsActorType)
  2059. {
  2060. case ActorTypes.Agent:
  2061. OdeCharacter cobj = (OdeCharacter)obj;
  2062. cobj.AddCollisionFrameTime(100);
  2063. cobj.SendCollisions();
  2064. break;
  2065. case ActorTypes.Prim:
  2066. OdePrim pobj = (OdePrim)obj;
  2067. pobj.SendCollisions();
  2068. break;
  2069. }
  2070. }
  2071. // if (m_global_contactcount > 0)
  2072. // m_log.DebugFormat(
  2073. // "[PHYSICS]: Collision contacts to process this frame = {0}", m_global_contactcount);
  2074. m_global_contactcount = 0;
  2075. if (CollectStats)
  2076. {
  2077. tempTick2 = Util.EnvironmentTickCount();
  2078. m_stats[ODECollisionNotificationFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2079. tempTick = tempTick2;
  2080. }
  2081. lock(SimulationLock)
  2082. OdeNative.WorldQuickStep(world, ODE_STEPSIZE);
  2083. if (CollectStats)
  2084. m_stats[ODENativeStepFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick);
  2085. OdeNative.JointGroupEmpty(contactgroup);
  2086. }
  2087. catch (Exception e)
  2088. {
  2089. m_log.ErrorFormat("[ODE SCENE]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  2090. }
  2091. step_time -= ODE_STEPSIZE;
  2092. fps += ODE_STEPSIZE;
  2093. }
  2094. if (CollectStats)
  2095. tempTick = Util.EnvironmentTickCount();
  2096. foreach (OdeCharacter actor in _characters)
  2097. {
  2098. if (actor.bad)
  2099. m_log.ErrorFormat("[ODE SCENE]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  2100. actor.UpdatePositionAndVelocity(defects);
  2101. }
  2102. if (defects.Count != 0)
  2103. {
  2104. foreach (OdeCharacter actor in defects)
  2105. {
  2106. m_log.ErrorFormat(
  2107. "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2} due to defect found when updating position and velocity",
  2108. actor.Name, actor.LocalID, PhysicsSceneName);
  2109. RemoveCharacter(actor);
  2110. actor.DestroyOdeStructures();
  2111. }
  2112. defects.Clear();
  2113. }
  2114. if (CollectStats)
  2115. {
  2116. tempTick2 = Util.EnvironmentTickCount();
  2117. m_stats[ODEAvatarUpdateFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2118. tempTick = tempTick2;
  2119. }
  2120. //if (timeStep < 0.2f)
  2121. foreach (OdePrim prim in _activeprims)
  2122. {
  2123. if (prim.IsPhysical && (OdeNative.BodyIsEnabled(prim.Body) || !prim._zeroFlag))
  2124. {
  2125. prim.UpdatePositionAndVelocity();
  2126. }
  2127. }
  2128. if (CollectStats)
  2129. m_stats[ODEPrimUpdateFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick);
  2130. //DumpJointInfo();
  2131. // Finished with all sim stepping. If requested, dump world state to file for debugging.
  2132. // TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
  2133. // TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
  2134. if (physics_logging && (physics_logging_interval > 0) && (framecount % physics_logging_interval == 0))
  2135. {
  2136. string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
  2137. string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
  2138. if (physics_logging_append_existing_logfile)
  2139. {
  2140. string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
  2141. TextWriter fwriter = File.AppendText(fname);
  2142. fwriter.WriteLine(header);
  2143. fwriter.Close();
  2144. }
  2145. OdeNative.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
  2146. }
  2147. latertickcount = Util.EnvironmentTickCountSubtract(tickCountFrameRun);
  2148. // OpenSimulator above does 10 fps. 10 fps = means that the main thread loop and physics
  2149. // has a max of 100 ms to run theoretically.
  2150. // If the main loop stalls, it calls Simulate later which makes the tick count ms larger.
  2151. // If Physics stalls, it takes longer which makes the tick count ms larger.
  2152. if (latertickcount < 100)
  2153. {
  2154. m_timeDilation = 1.0f;
  2155. }
  2156. else
  2157. {
  2158. m_timeDilation = 100f / latertickcount;
  2159. //m_timeDilation = Math.Min((Math.Max(100 - (Util.EnvironmentTickCount() - tickCountFrameRun), 1) / 100f), 1.0f);
  2160. }
  2161. tickCountFrameRun = Util.EnvironmentTickCount();
  2162. if (CollectStats)
  2163. m_stats[ODETotalFrameMsStatName] += Util.EnvironmentTickCountSubtract(startFrameTick);
  2164. }
  2165. fps *= 1.0f/timeStep;
  2166. return fps;
  2167. }
  2168. public override void SetTerrain(float[] heightMap)
  2169. {
  2170. if (m_worldOffset != Vector3.Zero && m_parentScene != null)
  2171. {
  2172. if (m_parentScene is OdeScene)
  2173. {
  2174. ((OdeScene)m_parentScene).SetTerrain(heightMap, m_worldOffset);
  2175. }
  2176. }
  2177. else
  2178. {
  2179. SetTerrain(heightMap, m_worldOffset);
  2180. }
  2181. }
  2182. private void SetTerrain(float[] heightMap, Vector3 pOffset)
  2183. {
  2184. int startTime = Util.EnvironmentTickCount();
  2185. m_log.DebugFormat("[ODE SCENE]: Setting terrain for {0} with offset {1}", PhysicsSceneName, pOffset);
  2186. float[] _heightmap;
  2187. // ok im lasy this are just a aliases
  2188. uint regionsizeX = m_regionWidth;
  2189. uint regionsizeY = m_regionHeight;
  2190. // map is rotated
  2191. uint heightmapWidth = regionsizeY + 2;
  2192. uint heightmapHeight = regionsizeX + 2;
  2193. uint heightmapWidthSamples = heightmapWidth + 1;
  2194. uint heightmapHeightSamples = heightmapHeight + 1;
  2195. _heightmap = new float[heightmapWidthSamples * heightmapHeightSamples];
  2196. const float scale = 1.0f;
  2197. const float offset = 0.0f;
  2198. const float thickness = 10f;
  2199. const int wrap = 0;
  2200. float hfmin = float.MaxValue;
  2201. float hfmax = float.MinValue;
  2202. float val;
  2203. uint xx;
  2204. uint yy;
  2205. uint maxXX = regionsizeX - 1;
  2206. uint maxYY = regionsizeY - 1;
  2207. // flipping map adding one margin all around so things don't fall in edges
  2208. uint xt = 0;
  2209. xx = 0;
  2210. for (uint x = 0; x < heightmapWidthSamples; x++)
  2211. {
  2212. if (x > 1 && xx < maxXX)
  2213. xx++;
  2214. yy = 0;
  2215. for (uint y = 0; y < heightmapHeightSamples; y++)
  2216. {
  2217. if (y > 1 && y < maxYY)
  2218. yy += regionsizeX;
  2219. val = heightMap[yy + xx];
  2220. if (val < 0.0f)
  2221. val = 0.0f;
  2222. _heightmap[xt + y] = val;
  2223. if (hfmin > val)
  2224. hfmin = val;
  2225. if (hfmax < val)
  2226. hfmax = val;
  2227. }
  2228. xt += heightmapHeightSamples;
  2229. }
  2230. lock (OdeLock)
  2231. {
  2232. OdeNative.AllocateODEDataForThread(~0U);
  2233. IntPtr GroundGeom = IntPtr.Zero;
  2234. if (RegionTerrain.TryGetValue(pOffset, out GroundGeom))
  2235. {
  2236. RegionTerrain.Remove(pOffset);
  2237. if (GroundGeom != IntPtr.Zero)
  2238. {
  2239. if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
  2240. {
  2241. TerrainHeightFieldHeights.Remove(GroundGeom);
  2242. }
  2243. OdeNative.SpaceRemove(space, GroundGeom);
  2244. OdeNative.GeomDestroy(GroundGeom);
  2245. }
  2246. }
  2247. IntPtr HeightmapData = OdeNative.GeomHeightfieldDataCreate();
  2248. OdeNative.GeomHeightfieldDataBuildSingle(HeightmapData, _heightmap, 0,
  2249. heightmapWidth, heightmapHeight,
  2250. (int)heightmapWidthSamples,
  2251. (int)heightmapHeightSamples,
  2252. scale, offset, thickness, wrap);
  2253. OdeNative.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  2254. GroundGeom = OdeNative.CreateHeightfield(space, HeightmapData, 1);
  2255. if (GroundGeom != IntPtr.Zero)
  2256. {
  2257. OdeNative.GeomSetCategoryBits(GroundGeom, (int)(CollisionCategories.Land));
  2258. OdeNative.GeomSetCollideBits(GroundGeom, (int)(CollisionCategories.Space));
  2259. }
  2260. geom_name_map[GroundGeom] = "Terrain";
  2261. OdeNative.Matrix3 R = new OdeNative.Matrix3();
  2262. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  2263. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  2264. q1 = q1 * q2;
  2265. Vector3 v3;
  2266. float angle;
  2267. q1.GetAxisAngle(out v3, out angle);
  2268. OdeNative.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  2269. OdeNative.GeomSetRotation(GroundGeom, ref R);
  2270. OdeNative.GeomSetPosition(GroundGeom, pOffset.X + regionsizeX * 0.5f, pOffset.Y + regionsizeY * 0.5f, 0.0f);
  2271. IntPtr testGround = IntPtr.Zero;
  2272. if (RegionTerrain.TryGetValue(pOffset, out testGround))
  2273. {
  2274. RegionTerrain.Remove(pOffset);
  2275. }
  2276. RegionTerrain.Add(pOffset, GroundGeom, GroundGeom);
  2277. TerrainHeightFieldHeights.Add(GroundGeom,_heightmap);
  2278. }
  2279. m_log.DebugFormat(
  2280. "[ODE SCENE]: Setting terrain for {0} took {1}ms", PhysicsSceneName, Util.EnvironmentTickCountSubtract(startTime));
  2281. }
  2282. public override void DeleteTerrain()
  2283. {
  2284. }
  2285. internal float GetWaterLevel()
  2286. {
  2287. return waterlevel;
  2288. }
  2289. public override void SetWaterLevel(float baseheight)
  2290. {
  2291. waterlevel = baseheight;
  2292. }
  2293. [HandleProcessCorruptedStateExceptions]
  2294. public override void Dispose()
  2295. {
  2296. lock(SimulationLock)
  2297. lock(OdeLock)
  2298. {
  2299. if(world == IntPtr.Zero)
  2300. return;
  2301. _worldInitialized = false;
  2302. OdeNative.AllocateODEDataForThread(~0U);
  2303. if (m_rayCastManager != null)
  2304. {
  2305. m_rayCastManager.Dispose();
  2306. m_rayCastManager = null;
  2307. }
  2308. lock (_prims)
  2309. {
  2310. foreach (OdePrim prm in _prims)
  2311. {
  2312. RemovePrim(prm);
  2313. }
  2314. }
  2315. //foreach (OdeCharacter act in _characters)
  2316. //{
  2317. //RemoveAvatar(act);
  2318. //}
  2319. IntPtr GroundGeom = IntPtr.Zero;
  2320. if (RegionTerrain.TryGetValue(m_worldOffset, out GroundGeom))
  2321. {
  2322. RegionTerrain.Remove(m_worldOffset);
  2323. if (GroundGeom != IntPtr.Zero)
  2324. {
  2325. if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
  2326. TerrainHeightFieldHeights.Remove(GroundGeom);
  2327. OdeNative.GeomDestroy(GroundGeom);
  2328. }
  2329. }
  2330. try
  2331. {
  2332. OdeNative.WorldDestroy(world);
  2333. world = IntPtr.Zero;
  2334. }
  2335. catch (AccessViolationException e)
  2336. {
  2337. m_log.ErrorFormat("[ODE SCENE]: exception {0}", e.Message);
  2338. }
  2339. }
  2340. }
  2341. private int compareByCollisionsDesc(OdePrim A, OdePrim B)
  2342. {
  2343. return -A.CollisionScore.CompareTo(B.CollisionScore);
  2344. }
  2345. public override Dictionary<uint, float> GetTopColliders()
  2346. {
  2347. Dictionary<uint, float> topColliders;
  2348. lock (_prims)
  2349. {
  2350. List<OdePrim> orderedPrims = new List<OdePrim>(_prims);
  2351. orderedPrims.Sort(compareByCollisionsDesc);
  2352. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  2353. foreach (OdePrim p in _prims)
  2354. p.CollisionScore = 0;
  2355. }
  2356. return topColliders;
  2357. }
  2358. public override bool SupportsRayCast()
  2359. {
  2360. return true;
  2361. }
  2362. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  2363. {
  2364. if (retMethod != null)
  2365. {
  2366. m_rayCastManager.QueueRequest(position, direction, length, retMethod);
  2367. }
  2368. }
  2369. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
  2370. {
  2371. if (retMethod != null)
  2372. {
  2373. m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
  2374. }
  2375. }
  2376. public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
  2377. {
  2378. ContactResult[] ourResults = null;
  2379. RayCallback retMethod = delegate(List<ContactResult> results)
  2380. {
  2381. ourResults = new ContactResult[results.Count];
  2382. results.CopyTo(ourResults, 0);
  2383. };
  2384. int waitTime = 0;
  2385. m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
  2386. while (ourResults == null && waitTime < 1000)
  2387. {
  2388. Thread.Sleep(1);
  2389. waitTime++;
  2390. }
  2391. if (ourResults == null)
  2392. return new List<ContactResult> ();
  2393. return new List<ContactResult>(ourResults);
  2394. }
  2395. public override Dictionary<string, float> GetStats()
  2396. {
  2397. if (!CollectStats)
  2398. return null;
  2399. Dictionary<string, float> returnStats;
  2400. lock (OdeLock)
  2401. {
  2402. returnStats = new Dictionary<string, float>(m_stats);
  2403. // FIXME: This is a SUPER DUMB HACK until we can establish stats that aren't subject to a division by
  2404. // 3 from the SimStatsReporter.
  2405. returnStats[ODETotalAvatarsStatName] = _characters.Count * 3;
  2406. returnStats[ODETotalPrimsStatName] = _prims.Count * 3;
  2407. returnStats[ODEActivePrimsStatName] = _activeprims.Count * 3;
  2408. InitializeExtraStats();
  2409. }
  2410. returnStats[ODEOtherCollisionFrameMsStatName]
  2411. = returnStats[ODEOtherCollisionFrameMsStatName]
  2412. - returnStats[ODENativeSpaceCollisionFrameMsStatName]
  2413. - returnStats[ODENativeGeomCollisionFrameMsStatName];
  2414. return returnStats;
  2415. }
  2416. private void InitializeExtraStats()
  2417. {
  2418. m_stats[ODETotalFrameMsStatName] = 0;
  2419. m_stats[ODEAvatarTaintMsStatName] = 0;
  2420. m_stats[ODEPrimTaintMsStatName] = 0;
  2421. m_stats[ODEAvatarForcesFrameMsStatName] = 0;
  2422. m_stats[ODEPrimForcesFrameMsStatName] = 0;
  2423. m_stats[ODERaycastingFrameMsStatName] = 0;
  2424. m_stats[ODENativeStepFrameMsStatName] = 0;
  2425. m_stats[ODENativeSpaceCollisionFrameMsStatName] = 0;
  2426. m_stats[ODENativeGeomCollisionFrameMsStatName] = 0;
  2427. m_stats[ODEOtherCollisionFrameMsStatName] = 0;
  2428. m_stats[ODECollisionNotificationFrameMsStatName] = 0;
  2429. m_stats[ODEAvatarContactsStatsName] = 0;
  2430. m_stats[ODEPrimContactsStatName] = 0;
  2431. m_stats[ODEAvatarUpdateFrameMsStatName] = 0;
  2432. m_stats[ODEPrimUpdateFrameMsStatName] = 0;
  2433. }
  2434. }
  2435. }