ODEScene.cs 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471
  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. // Revision 2011/12/13 by Ubit Umarov
  28. using System;
  29. using System.Collections.Concurrent;
  30. using System.Collections.Generic;
  31. using System.Linq;
  32. using System.Reflection;
  33. using System.Runtime.InteropServices;
  34. using System.Threading;
  35. using log4net;
  36. using Nini.Config;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Framework.Scenes;
  39. using OpenSim.Region.PhysicsModules.SharedBase;
  40. using OpenMetaverse;
  41. namespace OpenSim.Region.PhysicsModule.ubOde
  42. {
  43. // colision flags of things others can colide with
  44. // rays, sensors, probes removed since can't be colided with
  45. // The top space where things are placed provided further selection
  46. // ie physical are in active space nonphysical in static
  47. // this should be exclusive as possible
  48. [Flags]
  49. public enum CollisionCategories : uint
  50. {
  51. Disabled = 0,
  52. //by 'things' types
  53. Space = 0x01,
  54. Geom = 0x02, // aka prim/part
  55. Character = 0x04,
  56. Land = 0x08,
  57. Water = 0x010,
  58. // by state
  59. Phantom = 0x01000,
  60. VolumeDtc = 0x02000,
  61. Selected = 0x04000,
  62. NoShape = 0x08000,
  63. All = 0xffffffff
  64. }
  65. /// <summary>
  66. /// Material type for a primitive
  67. /// </summary>
  68. public enum Material : int
  69. {
  70. /// <summary></summary>
  71. Stone = 0,
  72. /// <summary></summary>
  73. Metal = 1,
  74. /// <summary></summary>
  75. Glass = 2,
  76. /// <summary></summary>
  77. Wood = 3,
  78. /// <summary></summary>
  79. Flesh = 4,
  80. /// <summary></summary>
  81. Plastic = 5,
  82. /// <summary></summary>
  83. Rubber = 6,
  84. light = 7 // compatibility with old viewers
  85. }
  86. public enum changes : int
  87. {
  88. Add = 0, // arg null. finishs the prim creation. should be used internally only ( to remove later ?)
  89. Remove,
  90. Link, // arg AuroraODEPrim new parent prim or null to delink. Makes the prim part of a object with prim parent as root
  91. // or removes from a object if arg is null
  92. DeLink,
  93. Position, // arg Vector3 new position in world coords. Changes prim position. Prim must know if it is root or child
  94. Orientation, // arg Quaternion new orientation in world coords. Changes prim position. Prim must know it it is root or child
  95. PosOffset, // not in use
  96. // arg Vector3 new position in local coords. Changes prim position in object
  97. OriOffset, // not in use
  98. // arg Vector3 new position in local coords. Changes prim position in object
  99. Velocity,
  100. TargetVelocity,
  101. AngVelocity,
  102. Acceleration,
  103. Force,
  104. Torque,
  105. Momentum,
  106. AddForce,
  107. AddAngForce,
  108. AngLock,
  109. Buoyancy,
  110. PIDTarget,
  111. PIDTau,
  112. PIDActive,
  113. PIDHoverHeight,
  114. PIDHoverType,
  115. PIDHoverTau,
  116. PIDHoverActive,
  117. Size,
  118. AvatarSize,
  119. Shape,
  120. PhysRepData,
  121. AddPhysRep,
  122. CollidesWater,
  123. VolumeDtc,
  124. Physical,
  125. Phantom,
  126. Selected,
  127. disabled,
  128. building,
  129. VehicleType,
  130. VehicleFloatParam,
  131. VehicleVectorParam,
  132. VehicleRotationParam,
  133. VehicleFlags,
  134. SetVehicle,
  135. SetInertia,
  136. Null //keep this last used do dim the methods array. does nothing but pulsing the prim
  137. }
  138. public struct ODEchangeitem
  139. {
  140. public PhysicsActor actor;
  141. public changes what;
  142. public Object arg;
  143. }
  144. public class ODEScene : PhysicsScene
  145. {
  146. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  147. public bool m_OSOdeLib = false;
  148. public Scene m_frameWorkScene = null;
  149. // private int threadid = 0;
  150. // const d.ContactFlags comumContactFlags = d.ContactFlags.SoftERP | d.ContactFlags.SoftCFM |d.ContactFlags.Approx1 | d.ContactFlags.Bounce;
  151. // const d.ContactFlags comumContactFlags = d.ContactFlags.Bounce | d.ContactFlags.Approx1 | d.ContactFlags.Slip1 | d.ContactFlags.Slip2;
  152. const SafeNativeMethods.ContactFlags comumContactFlags = SafeNativeMethods.ContactFlags.Bounce | SafeNativeMethods.ContactFlags.Approx1;
  153. const float comumContactERP = 0.75f;
  154. const float comumContactCFM = 0.0001f;
  155. const float comumContactSLIP = 0f;
  156. // float frictionMovementMult = 0.2f;
  157. float TerrainBounce = 0.001f;
  158. float TerrainFriction = 0.3f;
  159. public float AvatarFriction = 0;// 0.9f * 0.5f;
  160. // this netx dimensions are only relevant for terrain partition (mega regions)
  161. // WorldExtents below has the simulation dimensions
  162. // they should be identical except on mega regions
  163. private int m_regionWidth = (int)Constants.RegionSize;
  164. private int m_regionHeight = (int)Constants.RegionSize;
  165. public float ODE_STEPSIZE = 0.020f;
  166. public float HalfOdeStep = 0.01f;
  167. public int odetimestepMS = 20; // rounded
  168. private float m_timeDilation = 1.0f;
  169. private double m_lastframe;
  170. private double m_lastMeshExpire;
  171. public float gravityx = 0f;
  172. public float gravityy = 0f;
  173. public float gravityz = -9.8f;
  174. private float waterlevel = 0f;
  175. private int framecount = 0;
  176. private float avDensity = 80f;
  177. private float avMovementDivisorWalk = 1.3f;
  178. private float avMovementDivisorRun = 0.8f;
  179. private float minimumGroundFlightOffset = 3f;
  180. public float maximumMassObject = 10000.01f;
  181. public float geomDefaultDensity = 10.0f;
  182. public float maximumAngularVelocity = 12.0f; // default 12rad/s
  183. public float maxAngVelocitySQ = 144f; // squared value
  184. public float bodyPIDD = 35f;
  185. public float bodyPIDG = 25;
  186. public int bodyFramesAutoDisable = 10;
  187. private SafeNativeMethods.NearCallback nearCallback;
  188. private Dictionary<uint,OdePrim> _prims = new Dictionary<uint,OdePrim>();
  189. private HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
  190. private HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
  191. private HashSet<OdePrim> _activegroups = new HashSet<OdePrim>();
  192. public ConcurrentQueue<ODEchangeitem> ChangesQueue = new ConcurrentQueue<ODEchangeitem>();
  193. /// <summary>
  194. /// A list of actors that should receive collision events.
  195. /// </summary>
  196. private List<PhysicsActor> _collisionEventPrim = new List<PhysicsActor>();
  197. private List<PhysicsActor> _collisionEventPrimRemove = new List<PhysicsActor>();
  198. private HashSet<OdeCharacter> _badCharacter = new HashSet<OdeCharacter>();
  199. public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
  200. private float contactsurfacelayer = 0.002f;
  201. private int contactsPerCollision = 80;
  202. internal IntPtr ContactgeomsArray = IntPtr.Zero;
  203. private IntPtr GlobalContactsArray = IntPtr.Zero;
  204. private SafeNativeMethods.Contact SharedTmpcontact = new SafeNativeMethods.Contact();
  205. const int maxContactsbeforedeath = 6000;
  206. private volatile int m_global_contactcount = 0;
  207. private IntPtr contactgroup;
  208. public ContactData[] m_materialContactsData = new ContactData[8];
  209. private IntPtr m_terrainGeom;
  210. private float[] m_terrainHeights;
  211. private GCHandle m_terrainHeightsHandler = new GCHandle();
  212. private IntPtr HeightmapData;
  213. private int m_lastRegionWidth;
  214. private int m_lastRegionHeight;
  215. private int m_physicsiterations = 15;
  216. private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
  217. // private PhysicsActor PANull = new NullPhysicsActor();
  218. private float step_time = 0.0f;
  219. public IntPtr world;
  220. // split the spaces acording to contents type
  221. // ActiveSpace contains characters and active prims
  222. // StaticSpace contains land and other that is mostly static in enviroment
  223. // this can contain subspaces, like the grid in staticspace
  224. // as now space only contains this 2 top spaces
  225. public IntPtr TopSpace; // the global space
  226. public IntPtr ActiveSpace; // space for active prims
  227. public IntPtr CharsSpace; // space for active prims
  228. public IntPtr StaticSpace; // space for the static things around
  229. public IntPtr GroundSpace; // space for ground
  230. public object OdeLock = new object();
  231. public static object SimulationLock = new object();
  232. public IMesher mesher;
  233. public IConfigSource m_config;
  234. public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  235. private ODERayCastRequestManager m_rayCastManager;
  236. public ODEMeshWorker m_meshWorker;
  237. /* maybe needed if ode uses tls
  238. private void checkThread()
  239. {
  240. int th = Thread.CurrentThread.ManagedThreadId;
  241. if(th != threadid)
  242. {
  243. threadid = th;
  244. d.AllocateODEDataForThread(~0U);
  245. }
  246. }
  247. */
  248. IConfig physicsconfig = null;
  249. public ODEScene(Scene pscene, IConfigSource psourceconfig, string pname, string pversion, bool pOSOdeLib)
  250. {
  251. EngineType = pname;
  252. PhysicsSceneName = EngineType + "/" + pscene.RegionInfo.RegionName;
  253. EngineName = pname + " " + pversion;
  254. m_config = psourceconfig;
  255. m_OSOdeLib = pOSOdeLib;
  256. // m_OSOdeLib = false; //debug
  257. m_frameWorkScene = pscene;
  258. m_frameWorkScene.RegisterModuleInterface<PhysicsScene>(this);
  259. Initialization();
  260. }
  261. public void RegionLoaded()
  262. {
  263. mesher = m_frameWorkScene.RequestModuleInterface<IMesher>();
  264. if (mesher == null)
  265. {
  266. m_log.ErrorFormat("[ubOde] No mesher. module disabled");
  267. return;
  268. }
  269. m_meshWorker = new ODEMeshWorker(this, m_log, mesher, physicsconfig);
  270. m_frameWorkScene.PhysicsEnabled = true;
  271. }
  272. /// <summary>
  273. /// Initiailizes the scene
  274. /// Sets many properties that ODE requires to be stable
  275. /// These settings need to be tweaked 'exactly' right or weird stuff happens.
  276. /// </summary>
  277. private void Initialization()
  278. {
  279. SafeNativeMethods.AllocateODEDataForThread(~0U);
  280. nearCallback = near;
  281. m_rayCastManager = new ODERayCastRequestManager(this);
  282. WorldExtents.X = m_frameWorkScene.RegionInfo.RegionSizeX;
  283. m_regionWidth = (int)WorldExtents.X;
  284. WorldExtents.Y = m_frameWorkScene.RegionInfo.RegionSizeY;
  285. m_regionHeight = (int)WorldExtents.Y;
  286. lock (OdeLock)
  287. {
  288. // Create the world and the first space
  289. try
  290. {
  291. world = SafeNativeMethods.WorldCreate();
  292. TopSpace = SafeNativeMethods.SimpleSpaceCreate(IntPtr.Zero);
  293. ActiveSpace = SafeNativeMethods.SimpleSpaceCreate(TopSpace);
  294. CharsSpace = SafeNativeMethods.SimpleSpaceCreate(TopSpace);
  295. GroundSpace = SafeNativeMethods.SimpleSpaceCreate(TopSpace);
  296. float sx = WorldExtents.X + 16;
  297. float sy = WorldExtents.Y + 16;
  298. SafeNativeMethods.Vector3 ex =new SafeNativeMethods.Vector3(sx, sy, 0);
  299. SafeNativeMethods.Vector3 px =new SafeNativeMethods.Vector3(sx * 0.5f, sx * 0.5f, 0);
  300. if(sx < sy)
  301. sx = sy;
  302. sx = (float)Math.Log(sx) * 1.442695f + 0.5f;
  303. int dp = (int)sx - 2;
  304. if(dp > 8)
  305. dp = 8;
  306. else if(dp < 4)
  307. dp = 4;
  308. StaticSpace = SafeNativeMethods.QuadTreeSpaceCreate(TopSpace, ref px, ref ex, dp);
  309. }
  310. catch
  311. {
  312. // i must RtC#FM
  313. // i did!
  314. }
  315. // demote to second level
  316. SafeNativeMethods.SpaceSetSublevel(ActiveSpace, 1);
  317. SafeNativeMethods.SpaceSetSublevel(CharsSpace, 1);
  318. SafeNativeMethods.SpaceSetSublevel(StaticSpace, 1);
  319. SafeNativeMethods.SpaceSetSublevel(GroundSpace, 1);
  320. SafeNativeMethods.GeomSetCategoryBits(ActiveSpace, (uint)(CollisionCategories.Space |
  321. CollisionCategories.Geom |
  322. CollisionCategories.Character |
  323. CollisionCategories.Phantom |
  324. CollisionCategories.VolumeDtc
  325. ));
  326. SafeNativeMethods.GeomSetCollideBits(ActiveSpace, (uint)(CollisionCategories.Space |
  327. CollisionCategories.Geom |
  328. CollisionCategories.Character |
  329. CollisionCategories.Phantom |
  330. CollisionCategories.VolumeDtc
  331. ));
  332. SafeNativeMethods.GeomSetCategoryBits(CharsSpace, (uint)(CollisionCategories.Space |
  333. CollisionCategories.Geom |
  334. CollisionCategories.Character |
  335. CollisionCategories.Phantom |
  336. CollisionCategories.VolumeDtc
  337. ));
  338. SafeNativeMethods.GeomSetCollideBits(CharsSpace, 0);
  339. SafeNativeMethods.GeomSetCategoryBits(StaticSpace, (uint)(CollisionCategories.Space |
  340. CollisionCategories.Geom |
  341. // CollisionCategories.Land |
  342. // CollisionCategories.Water |
  343. CollisionCategories.Phantom |
  344. CollisionCategories.VolumeDtc
  345. ));
  346. SafeNativeMethods.GeomSetCollideBits(StaticSpace, 0);
  347. SafeNativeMethods.GeomSetCategoryBits(GroundSpace, (uint)(CollisionCategories.Land));
  348. SafeNativeMethods.GeomSetCollideBits(GroundSpace, 0);
  349. contactgroup = SafeNativeMethods.JointGroupCreate(maxContactsbeforedeath + 1);
  350. //contactgroup
  351. SafeNativeMethods.WorldSetAutoDisableFlag(world, false);
  352. }
  353. // checkThread();
  354. // Defaults
  355. int contactsPerCollision = 80;
  356. physicsconfig = null;
  357. if (m_config != null)
  358. {
  359. physicsconfig = m_config.Configs["ODEPhysicsSettings"];
  360. if (physicsconfig != null)
  361. {
  362. gravityx = physicsconfig.GetFloat("world_gravityx", gravityx);
  363. gravityy = physicsconfig.GetFloat("world_gravityy", gravityy);
  364. gravityz = physicsconfig.GetFloat("world_gravityz", gravityz);
  365. // contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", contactsurfacelayer);
  366. ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", ODE_STEPSIZE);
  367. avDensity = physicsconfig.GetFloat("av_density", avDensity);
  368. avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", avMovementDivisorWalk);
  369. avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", avMovementDivisorRun);
  370. contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", contactsPerCollision);
  371. geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", geomDefaultDensity);
  372. // bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", bodyFramesAutoDisable);
  373. minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", minimumGroundFlightOffset);
  374. maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", maximumMassObject);
  375. avDensity *= 3f / 80f; // scale other engines density option to this
  376. }
  377. }
  378. float heartbeat = 1/m_frameWorkScene.FrameTime;
  379. maximumAngularVelocity = 0.49f * heartbeat *(float)Math.PI;
  380. maxAngVelocitySQ = maximumAngularVelocity * maximumAngularVelocity;
  381. SafeNativeMethods.WorldSetCFM(world, comumContactCFM);
  382. SafeNativeMethods.WorldSetERP(world, comumContactERP);
  383. SafeNativeMethods.WorldSetGravity(world, gravityx, gravityy, gravityz);
  384. SafeNativeMethods.WorldSetLinearDamping(world, 0.001f);
  385. SafeNativeMethods.WorldSetAngularDamping(world, 0.002f);
  386. SafeNativeMethods.WorldSetAngularDampingThreshold(world, 0f);
  387. SafeNativeMethods.WorldSetLinearDampingThreshold(world, 0f);
  388. SafeNativeMethods.WorldSetMaxAngularSpeed(world, maximumAngularVelocity);
  389. SafeNativeMethods.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  390. SafeNativeMethods.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
  391. SafeNativeMethods.WorldSetContactMaxCorrectingVel(world, 60.0f);
  392. HalfOdeStep = ODE_STEPSIZE * 0.5f;
  393. odetimestepMS = (int)(1000.0f * ODE_STEPSIZE + 0.5f);
  394. ContactgeomsArray = Marshal.AllocHGlobal(contactsPerCollision * SafeNativeMethods.ContactGeom.unmanagedSizeOf);
  395. GlobalContactsArray = Marshal.AllocHGlobal((maxContactsbeforedeath + 100) * SafeNativeMethods.Contact.unmanagedSizeOf);
  396. SharedTmpcontact.geom.g1 = IntPtr.Zero;
  397. SharedTmpcontact.geom.g2 = IntPtr.Zero;
  398. SharedTmpcontact.geom.side1 = -1;
  399. SharedTmpcontact.geom.side2 = -1;
  400. SharedTmpcontact.surface.mode = comumContactFlags;
  401. SharedTmpcontact.surface.mu = 0;
  402. SharedTmpcontact.surface.bounce = 0;
  403. SharedTmpcontact.surface.bounce_vel = 1.5f;
  404. SharedTmpcontact.surface.soft_cfm = comumContactCFM;
  405. SharedTmpcontact.surface.soft_erp = comumContactERP;
  406. SharedTmpcontact.surface.slip1 = comumContactSLIP;
  407. SharedTmpcontact.surface.slip2 = comumContactSLIP;
  408. m_materialContactsData[(int)Material.Stone].mu = 0.8f;
  409. m_materialContactsData[(int)Material.Stone].bounce = 0.4f;
  410. m_materialContactsData[(int)Material.Metal].mu = 0.3f;
  411. m_materialContactsData[(int)Material.Metal].bounce = 0.4f;
  412. m_materialContactsData[(int)Material.Glass].mu = 0.2f;
  413. m_materialContactsData[(int)Material.Glass].bounce = 0.7f;
  414. m_materialContactsData[(int)Material.Wood].mu = 0.6f;
  415. m_materialContactsData[(int)Material.Wood].bounce = 0.5f;
  416. m_materialContactsData[(int)Material.Flesh].mu = 0.9f;
  417. m_materialContactsData[(int)Material.Flesh].bounce = 0.3f;
  418. m_materialContactsData[(int)Material.Plastic].mu = 0.4f;
  419. m_materialContactsData[(int)Material.Plastic].bounce = 0.7f;
  420. m_materialContactsData[(int)Material.Rubber].mu = 0.9f;
  421. m_materialContactsData[(int)Material.Rubber].bounce = 0.95f;
  422. m_materialContactsData[(int)Material.light].mu = 0.0f;
  423. m_materialContactsData[(int)Material.light].bounce = 0.0f;
  424. m_lastframe = Util.GetTimeStamp();
  425. m_lastMeshExpire = m_lastframe;
  426. step_time = -1;
  427. base.Initialise(m_frameWorkScene.PhysicsRequestAsset,
  428. (m_frameWorkScene.Heightmap != null ? m_frameWorkScene.Heightmap.GetFloatsSerialised() : new float[m_frameWorkScene.RegionInfo.RegionSizeX * m_frameWorkScene.RegionInfo.RegionSizeY]),
  429. (float)m_frameWorkScene.RegionInfo.RegionSettings.WaterHeight);
  430. }
  431. internal void waitForSpaceUnlock(IntPtr space)
  432. {
  433. //if (space != IntPtr.Zero)
  434. //while (d.SpaceLockQuery(space)) { } // Wait and do nothing
  435. }
  436. #region Collision Detection
  437. // sets a global contact for a joint for contactgeom , and base contact description)
  438. private IntPtr CreateContacJoint(ref SafeNativeMethods.ContactGeom contactGeom,bool smooth)
  439. {
  440. if (m_global_contactcount >= maxContactsbeforedeath)
  441. return IntPtr.Zero;
  442. m_global_contactcount++;
  443. if(smooth)
  444. SharedTmpcontact.geom.depth = contactGeom.depth * 0.05f;
  445. else
  446. SharedTmpcontact.geom.depth = contactGeom.depth;
  447. SharedTmpcontact.geom.pos = contactGeom.pos;
  448. SharedTmpcontact.geom.normal = contactGeom.normal;
  449. IntPtr contact = new IntPtr(GlobalContactsArray.ToInt64() + (Int64)(m_global_contactcount * SafeNativeMethods.Contact.unmanagedSizeOf));
  450. Marshal.StructureToPtr(SharedTmpcontact, contact, true);
  451. return SafeNativeMethods.JointCreateContactPtr(world, contactgroup, contact);
  452. }
  453. private bool GetCurContactGeom(int index, ref SafeNativeMethods.ContactGeom newcontactgeom)
  454. {
  455. if (ContactgeomsArray == IntPtr.Zero || index >= contactsPerCollision)
  456. return false;
  457. IntPtr contactptr = new IntPtr(ContactgeomsArray.ToInt64() + (Int64)(index * SafeNativeMethods.ContactGeom.unmanagedSizeOf));
  458. newcontactgeom = (SafeNativeMethods.ContactGeom)Marshal.PtrToStructure(contactptr, typeof(SafeNativeMethods.ContactGeom));
  459. return true;
  460. }
  461. /// <summary>
  462. /// This is our near callback. A geometry is near a body
  463. /// </summary>
  464. /// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
  465. /// <param name="g1">a geometry or space</param>
  466. /// <param name="g2">another geometry or space</param>
  467. ///
  468. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  469. {
  470. // no lock here! It's invoked from within Simulate(), which is thread-locked
  471. if (m_global_contactcount >= maxContactsbeforedeath)
  472. return;
  473. // Test if we're colliding a geom with a space.
  474. // If so we have to drill down into the space recursively
  475. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  476. return;
  477. if (SafeNativeMethods.GeomIsSpace(g1) || SafeNativeMethods.GeomIsSpace(g2))
  478. {
  479. // We'll be calling near recursivly if one
  480. // of them is a space to find all of the
  481. // contact points in the space
  482. try
  483. {
  484. SafeNativeMethods.SpaceCollide2(g1, g2, IntPtr.Zero, nearCallback);
  485. }
  486. catch (AccessViolationException)
  487. {
  488. m_log.Warn("[PHYSICS]: Unable to collide test a space");
  489. return;
  490. }
  491. //here one should check collisions of geoms inside a space
  492. // but on each space we only should have geoms that not colide amoung each other
  493. // so we don't dig inside spaces
  494. return;
  495. }
  496. // Figure out how many contact points we have
  497. int count = 0;
  498. try
  499. {
  500. if (g1 == g2)
  501. return; // Can't collide with yourself
  502. if (SafeNativeMethods.GeomGetCategoryBits(g1) == (uint)CollisionCategories.VolumeDtc ||
  503. SafeNativeMethods.GeomGetCategoryBits(g2) == (uint)CollisionCategories.VolumeDtc)
  504. {
  505. int cflags;
  506. unchecked
  507. {
  508. cflags = (int)(1 | SafeNativeMethods.CONTACTS_UNIMPORTANT);
  509. }
  510. count = SafeNativeMethods.CollidePtr(g1, g2, cflags, ContactgeomsArray, SafeNativeMethods.ContactGeom.unmanagedSizeOf);
  511. }
  512. else
  513. count = SafeNativeMethods.CollidePtr(g1, g2, (contactsPerCollision & 0xffff), ContactgeomsArray, SafeNativeMethods.ContactGeom.unmanagedSizeOf);
  514. }
  515. catch (SEHException)
  516. {
  517. m_log.Error("[PHYSICS]: 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.");
  518. // ode.drelease(world);
  519. base.TriggerPhysicsBasedRestart();
  520. }
  521. catch (Exception e)
  522. {
  523. m_log.WarnFormat("[PHYSICS]: Unable to collide test an object: {0}", e.Message);
  524. return;
  525. }
  526. // contacts done
  527. if (count == 0)
  528. return;
  529. // get first contact
  530. SafeNativeMethods.ContactGeom curContact = new SafeNativeMethods.ContactGeom();
  531. if (!GetCurContactGeom(0, ref curContact))
  532. return;
  533. // try get physical actors
  534. PhysicsActor p1;
  535. if (!actor_name_map.TryGetValue(g1, out p1))
  536. {
  537. m_log.WarnFormat("[PHYSICS]: failed actor mapping for geom 1");
  538. return;
  539. }
  540. PhysicsActor p2;
  541. if (!actor_name_map.TryGetValue(g2, out p2))
  542. {
  543. m_log.WarnFormat("[PHYSICS]: failed actor mapping for geom 2");
  544. return;
  545. }
  546. ContactPoint maxDepthContact = new ContactPoint();
  547. // do volume detection case
  548. if ((p1.IsVolumeDtc || p2.IsVolumeDtc))
  549. {
  550. maxDepthContact = new ContactPoint(
  551. new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
  552. new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
  553. curContact.depth, false
  554. );
  555. collision_accounting_events(p1, p2, maxDepthContact);
  556. return;
  557. }
  558. // big messy collision analises
  559. float mu = 0;
  560. float bounce = 0;
  561. // bool IgnoreNegSides = false;
  562. ContactData contactdata1 = new ContactData(0, 0, false);
  563. ContactData contactdata2 = new ContactData(0, 0, false);
  564. bool dop1ava = false;
  565. bool dop2ava = false;
  566. bool ignore = false;
  567. bool smoothMesh = false;
  568. switch (p1.PhysicsActorType)
  569. {
  570. case (int)ActorTypes.Agent:
  571. {
  572. dop1ava = true;
  573. switch (p2.PhysicsActorType)
  574. {
  575. case (int)ActorTypes.Agent:
  576. case (int)ActorTypes.Prim:
  577. break;
  578. default:
  579. ignore = true; // avatar to terrain and water ignored
  580. break;
  581. }
  582. break;
  583. }
  584. case (int)ActorTypes.Prim:
  585. {
  586. switch (p2.PhysicsActorType)
  587. {
  588. case (int)ActorTypes.Agent:
  589. dop2ava = true;
  590. break;
  591. case (int)ActorTypes.Prim:
  592. // Vector3 relV = p1.rootVelocity - p2.rootVelocity;
  593. // float relVlenSQ = relV.LengthSquared();
  594. // if (relVlenSQ > 0.0001f)
  595. {
  596. p1.CollidingObj = true;
  597. p2.CollidingObj = true;
  598. }
  599. p1.getContactData(ref contactdata1);
  600. p2.getContactData(ref contactdata2);
  601. bounce = contactdata1.bounce * contactdata2.bounce;
  602. mu = (float)Math.Sqrt(contactdata1.mu * contactdata2.mu);
  603. // if (relVlenSQ > 0.01f)
  604. // mu *= frictionMovementMult;
  605. if(SafeNativeMethods.GeomGetClass(g2) == SafeNativeMethods.GeomClassID.TriMeshClass &&
  606. SafeNativeMethods.GeomGetClass(g1) == SafeNativeMethods.GeomClassID.TriMeshClass)
  607. smoothMesh = true;
  608. break;
  609. case (int)ActorTypes.Ground:
  610. p1.getContactData(ref contactdata1);
  611. bounce = contactdata1.bounce * TerrainBounce;
  612. mu = (float)Math.Sqrt(contactdata1.mu * TerrainFriction);
  613. // Vector3 v1 = p1.rootVelocity;
  614. // if (Math.Abs(v1.X) > 0.1f || Math.Abs(v1.Y) > 0.1f)
  615. // mu *= frictionMovementMult;
  616. p1.CollidingGround = true;
  617. if(SafeNativeMethods.GeomGetClass(g1) == SafeNativeMethods.GeomClassID.TriMeshClass)
  618. smoothMesh = true;
  619. break;
  620. case (int)ActorTypes.Water:
  621. default:
  622. ignore = true;
  623. break;
  624. }
  625. }
  626. break;
  627. case (int)ActorTypes.Ground:
  628. if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  629. {
  630. p2.CollidingGround = true;
  631. p2.getContactData(ref contactdata2);
  632. bounce = contactdata2.bounce * TerrainBounce;
  633. mu = (float)Math.Sqrt(contactdata2.mu * TerrainFriction);
  634. // if (curContact.side1 > 0) // should be 2 ?
  635. // IgnoreNegSides = true;
  636. // Vector3 v2 = p2.rootVelocity;
  637. // if (Math.Abs(v2.X) > 0.1f || Math.Abs(v2.Y) > 0.1f)
  638. // mu *= frictionMovementMult;
  639. if(SafeNativeMethods.GeomGetClass(g2) == SafeNativeMethods.GeomClassID.TriMeshClass)
  640. smoothMesh = true;
  641. }
  642. else
  643. ignore = true;
  644. break;
  645. case (int)ActorTypes.Water:
  646. default:
  647. break;
  648. }
  649. if (ignore)
  650. return;
  651. IntPtr Joint;
  652. bool FeetCollision = false;
  653. int ncontacts = 0;
  654. int i = 0;
  655. maxDepthContact = new ContactPoint();
  656. maxDepthContact.PenetrationDepth = float.MinValue;
  657. ContactPoint minDepthContact = new ContactPoint();
  658. minDepthContact.PenetrationDepth = float.MaxValue;
  659. SharedTmpcontact.geom.depth = 0;
  660. SharedTmpcontact.surface.mu = mu;
  661. SharedTmpcontact.surface.bounce = bounce;
  662. SafeNativeMethods.ContactGeom altContact = new SafeNativeMethods.ContactGeom();
  663. bool useAltcontact;
  664. bool noskip;
  665. if(dop1ava || dop2ava)
  666. smoothMesh = false;
  667. IntPtr b1 = SafeNativeMethods.GeomGetBody(g1);
  668. IntPtr b2 = SafeNativeMethods.GeomGetBody(g2);
  669. while (true)
  670. {
  671. noskip = true;
  672. useAltcontact = false;
  673. if (dop1ava)
  674. {
  675. if ((((OdeCharacter)p1).Collide(g1, g2, false, ref curContact, ref altContact , ref useAltcontact, ref FeetCollision)))
  676. {
  677. if (p2.PhysicsActorType == (int)ActorTypes.Agent)
  678. {
  679. p1.CollidingObj = true;
  680. p2.CollidingObj = true;
  681. }
  682. else if (p2.rootVelocity.LengthSquared() > 0.0f)
  683. p2.CollidingObj = true;
  684. }
  685. else
  686. noskip = false;
  687. }
  688. else if (dop2ava)
  689. {
  690. if ((((OdeCharacter)p2).Collide(g2, g1, true, ref curContact, ref altContact , ref useAltcontact, ref FeetCollision)))
  691. {
  692. if (p1.PhysicsActorType == (int)ActorTypes.Agent)
  693. {
  694. p1.CollidingObj = true;
  695. p2.CollidingObj = true;
  696. }
  697. else if (p1.rootVelocity.LengthSquared() > 0.0f)
  698. p1.CollidingObj = true;
  699. }
  700. else
  701. noskip = false;
  702. }
  703. if (noskip)
  704. {
  705. if(useAltcontact)
  706. Joint = CreateContacJoint(ref altContact,smoothMesh);
  707. else
  708. Joint = CreateContacJoint(ref curContact,smoothMesh);
  709. if (Joint == IntPtr.Zero)
  710. break;
  711. SafeNativeMethods.JointAttach(Joint, b1, b2);
  712. ncontacts++;
  713. if (curContact.depth > maxDepthContact.PenetrationDepth)
  714. {
  715. maxDepthContact.Position.X = curContact.pos.X;
  716. maxDepthContact.Position.Y = curContact.pos.Y;
  717. maxDepthContact.Position.Z = curContact.pos.Z;
  718. maxDepthContact.PenetrationDepth = curContact.depth;
  719. maxDepthContact.CharacterFeet = FeetCollision;
  720. }
  721. if (curContact.depth < minDepthContact.PenetrationDepth)
  722. {
  723. minDepthContact.PenetrationDepth = curContact.depth;
  724. minDepthContact.SurfaceNormal.X = curContact.normal.X;
  725. minDepthContact.SurfaceNormal.Y = curContact.normal.Y;
  726. minDepthContact.SurfaceNormal.Z = curContact.normal.Z;
  727. }
  728. }
  729. if (++i >= count)
  730. break;
  731. if (!GetCurContactGeom(i, ref curContact))
  732. break;
  733. }
  734. if (ncontacts > 0)
  735. {
  736. maxDepthContact.SurfaceNormal.X = minDepthContact.SurfaceNormal.X;
  737. maxDepthContact.SurfaceNormal.Y = minDepthContact.SurfaceNormal.Y;
  738. maxDepthContact.SurfaceNormal.Z = minDepthContact.SurfaceNormal.Z;
  739. collision_accounting_events(p1, p2, maxDepthContact);
  740. }
  741. }
  742. private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
  743. {
  744. uint obj2LocalID = 0;
  745. // update actors collision score
  746. if (p1.CollisionScore < float.MaxValue)
  747. p1.CollisionScore += 1.0f;
  748. if (p2.CollisionScore < float.MaxValue)
  749. p2.CollisionScore += 1.0f;
  750. bool p1events = p1.SubscribedEvents();
  751. bool p2events = p2.SubscribedEvents();
  752. if (p1.IsVolumeDtc)
  753. p2events = false;
  754. if (p2.IsVolumeDtc)
  755. p1events = false;
  756. if (!p2events && !p1events)
  757. return;
  758. Vector3 vel = Vector3.Zero;
  759. if (p2 != null && p2.IsPhysical)
  760. vel = p2.rootVelocity;
  761. if (p1 != null && p1.IsPhysical)
  762. vel -= p1.rootVelocity;
  763. contact.RelativeSpeed = Vector3.Dot(vel, contact.SurfaceNormal);
  764. switch ((ActorTypes)p1.PhysicsActorType)
  765. {
  766. case ActorTypes.Agent:
  767. case ActorTypes.Prim:
  768. {
  769. switch ((ActorTypes)p2.PhysicsActorType)
  770. {
  771. case ActorTypes.Agent:
  772. case ActorTypes.Prim:
  773. if (p2events)
  774. {
  775. //AddCollisionEventReporting(p2);
  776. p2.AddCollisionEvent(p1.ParentActor.LocalID, contact);
  777. }
  778. else if(p1.IsVolumeDtc)
  779. p2.AddVDTCCollisionEvent(p1.ParentActor.LocalID, contact);
  780. obj2LocalID = p2.ParentActor.LocalID;
  781. break;
  782. case ActorTypes.Ground:
  783. case ActorTypes.Unknown:
  784. default:
  785. obj2LocalID = 0;
  786. break;
  787. }
  788. if (p1events)
  789. {
  790. contact.SurfaceNormal = -contact.SurfaceNormal;
  791. contact.RelativeSpeed = -contact.RelativeSpeed;
  792. //AddCollisionEventReporting(p1);
  793. p1.AddCollisionEvent(obj2LocalID, contact);
  794. }
  795. else if(p2.IsVolumeDtc)
  796. {
  797. contact.SurfaceNormal = -contact.SurfaceNormal;
  798. contact.RelativeSpeed = -contact.RelativeSpeed;
  799. //AddCollisionEventReporting(p1);
  800. p1.AddVDTCCollisionEvent(obj2LocalID, contact);
  801. }
  802. break;
  803. }
  804. case ActorTypes.Ground:
  805. case ActorTypes.Unknown:
  806. default:
  807. {
  808. if (p2events && !p2.IsVolumeDtc)
  809. {
  810. //AddCollisionEventReporting(p2);
  811. p2.AddCollisionEvent(0, contact);
  812. }
  813. break;
  814. }
  815. }
  816. }
  817. /// <summary>
  818. /// This is our collision testing routine in ODE
  819. /// </summary>
  820. /// <param name="timeStep"></param>
  821. private void collision_optimized()
  822. {
  823. lock (_characters)
  824. {
  825. try
  826. {
  827. foreach (OdeCharacter chr in _characters)
  828. {
  829. if (chr == null)
  830. continue;
  831. chr.IsColliding = false;
  832. // chr.CollidingGround = false; not done here
  833. chr.CollidingObj = false;
  834. if(chr.Body == IntPtr.Zero || chr.collider == IntPtr.Zero )
  835. continue;
  836. // do colisions with static space
  837. SafeNativeMethods.SpaceCollide2(chr.collider, StaticSpace, IntPtr.Zero, nearCallback);
  838. // no coll with gnd
  839. }
  840. // chars with chars
  841. SafeNativeMethods.SpaceCollide(CharsSpace, IntPtr.Zero, nearCallback);
  842. }
  843. catch (AccessViolationException)
  844. {
  845. m_log.Warn("[PHYSICS]: Unable to collide Character to static space");
  846. }
  847. }
  848. lock (_activeprims)
  849. {
  850. foreach (OdePrim aprim in _activeprims)
  851. {
  852. aprim.CollisionScore = 0;
  853. aprim.IsColliding = false;
  854. if(!aprim.m_outbounds && SafeNativeMethods.BodyIsEnabled(aprim.Body))
  855. aprim.clearSleeperCollisions();
  856. }
  857. }
  858. lock (_activegroups)
  859. {
  860. try
  861. {
  862. foreach (OdePrim aprim in _activegroups)
  863. {
  864. if(!aprim.m_outbounds && SafeNativeMethods.BodyIsEnabled(aprim.Body) &&
  865. aprim.collide_geom != IntPtr.Zero)
  866. {
  867. SafeNativeMethods.SpaceCollide2(StaticSpace, aprim.collide_geom, IntPtr.Zero, nearCallback);
  868. SafeNativeMethods.SpaceCollide2(GroundSpace, aprim.collide_geom, IntPtr.Zero, nearCallback);
  869. }
  870. }
  871. }
  872. catch (Exception e)
  873. {
  874. m_log.Warn("[PHYSICS]: Unable to collide Active to Static: " + e.Message);
  875. }
  876. }
  877. // colide active amoung them
  878. try
  879. {
  880. SafeNativeMethods.SpaceCollide(ActiveSpace, IntPtr.Zero, nearCallback);
  881. }
  882. catch (Exception e)
  883. {
  884. m_log.Warn("[PHYSICS]: Unable to collide in Active: " + e.Message);
  885. }
  886. // and with chars
  887. try
  888. {
  889. SafeNativeMethods.SpaceCollide2(CharsSpace,ActiveSpace, IntPtr.Zero, nearCallback);
  890. }
  891. catch (Exception e)
  892. {
  893. m_log.Warn("[PHYSICS]: Unable to collide Active to Character: " + e.Message);
  894. }
  895. }
  896. #endregion
  897. /// <summary>
  898. /// Add actor to the list that should receive collision events in the simulate loop.
  899. /// </summary>
  900. /// <param name="obj"></param>
  901. public void AddCollisionEventReporting(PhysicsActor obj)
  902. {
  903. if (!_collisionEventPrim.Contains(obj))
  904. _collisionEventPrim.Add(obj);
  905. }
  906. /// <summary>
  907. /// Remove actor from the list that should receive collision events in the simulate loop.
  908. /// </summary>
  909. /// <param name="obj"></param>
  910. public void RemoveCollisionEventReporting(PhysicsActor obj)
  911. {
  912. lock(_collisionEventPrimRemove)
  913. {
  914. if (_collisionEventPrim.Contains(obj) && !_collisionEventPrimRemove.Contains(obj))
  915. _collisionEventPrimRemove.Add(obj);
  916. }
  917. }
  918. public override float TimeDilation
  919. {
  920. get { return m_timeDilation; }
  921. }
  922. public override bool SupportsNINJAJoints
  923. {
  924. get { return false; }
  925. }
  926. #region Add/Remove Entities
  927. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
  928. {
  929. return null;
  930. }
  931. public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, float feetOffset, bool isFlying)
  932. {
  933. OdeCharacter newAv = new OdeCharacter(localID, avName, this, position,
  934. size, feetOffset, avDensity, avMovementDivisorWalk, avMovementDivisorRun);
  935. newAv.Flying = isFlying;
  936. newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
  937. return newAv;
  938. }
  939. public void AddCharacter(OdeCharacter chr)
  940. {
  941. lock (_characters)
  942. {
  943. if (!_characters.Contains(chr))
  944. {
  945. _characters.Add(chr);
  946. if (chr.bad)
  947. m_log.DebugFormat("[PHYSICS] Added BAD actor {0} to characters list", chr.m_uuid);
  948. }
  949. }
  950. }
  951. public void RemoveCharacter(OdeCharacter chr)
  952. {
  953. lock (_characters)
  954. {
  955. if (_characters.Contains(chr))
  956. {
  957. _characters.Remove(chr);
  958. }
  959. }
  960. }
  961. public void BadCharacter(OdeCharacter chr)
  962. {
  963. lock (_badCharacter)
  964. {
  965. if (!_badCharacter.Contains(chr))
  966. _badCharacter.Add(chr);
  967. }
  968. }
  969. public override void RemoveAvatar(PhysicsActor actor)
  970. {
  971. //m_log.Debug("[PHYSICS]:ODELOCK");
  972. if (world == IntPtr.Zero)
  973. return;
  974. ((OdeCharacter) actor).Destroy();
  975. }
  976. public void addActivePrim(OdePrim activatePrim)
  977. {
  978. // adds active prim..
  979. lock (_activeprims)
  980. {
  981. if (!_activeprims.Contains(activatePrim))
  982. _activeprims.Add(activatePrim);
  983. }
  984. }
  985. public void addActiveGroups(OdePrim activatePrim)
  986. {
  987. lock (_activegroups)
  988. {
  989. if (!_activegroups.Contains(activatePrim))
  990. _activegroups.Add(activatePrim);
  991. }
  992. }
  993. private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
  994. PrimitiveBaseShape pbs, bool isphysical, bool isPhantom, byte shapeType, uint localID)
  995. {
  996. OdePrim newPrim;
  997. lock (OdeLock)
  998. {
  999. newPrim = new OdePrim(name, this, position, size, rotation, pbs, isphysical, isPhantom, shapeType, localID);
  1000. }
  1001. return newPrim;
  1002. }
  1003. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1004. Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, uint localid)
  1005. {
  1006. return AddPrim(primName, position, size, rotation, pbs, isPhysical, isPhantom, 0 , localid);
  1007. }
  1008. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1009. Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
  1010. {
  1011. return AddPrim(primName, position, size, rotation, pbs, isPhysical,false, 0, localid);
  1012. }
  1013. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1014. Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, byte shapeType, uint localid)
  1015. {
  1016. return AddPrim(primName, position, size, rotation, pbs, isPhysical,isPhantom, shapeType, localid);
  1017. }
  1018. public void remActivePrim(OdePrim deactivatePrim)
  1019. {
  1020. lock (_activeprims)
  1021. {
  1022. _activeprims.Remove(deactivatePrim);
  1023. }
  1024. }
  1025. public void remActiveGroup(OdePrim deactivatePrim)
  1026. {
  1027. lock (_activegroups)
  1028. {
  1029. _activegroups.Remove(deactivatePrim);
  1030. }
  1031. }
  1032. public override void RemovePrim(PhysicsActor prim)
  1033. {
  1034. // As with all ODE physics operations, we don't remove the prim immediately but signal that it should be
  1035. // removed in the next physics simulate pass.
  1036. if (prim is OdePrim)
  1037. {
  1038. OdePrim p = (OdePrim)prim;
  1039. p.setPrimForRemoval();
  1040. }
  1041. }
  1042. public void RemovePrimThreadLocked(OdePrim prim)
  1043. {
  1044. //Console.WriteLine("RemovePrimThreadLocked " + prim.m_primName);
  1045. lock (_prims)
  1046. _prims.Remove(prim.LocalID);
  1047. }
  1048. public void addToPrims(OdePrim prim)
  1049. {
  1050. lock (_prims)
  1051. _prims[prim.LocalID] = prim;
  1052. }
  1053. public OdePrim getPrim(uint id)
  1054. {
  1055. lock (_prims)
  1056. {
  1057. if(_prims.ContainsKey(id))
  1058. return _prims[id];
  1059. else
  1060. return null;
  1061. }
  1062. }
  1063. public bool havePrim(OdePrim prm)
  1064. {
  1065. lock (_prims)
  1066. return _prims.ContainsKey(prm.LocalID);
  1067. }
  1068. public void changePrimID(OdePrim prim,uint oldID)
  1069. {
  1070. lock (_prims)
  1071. {
  1072. if(_prims.ContainsKey(oldID))
  1073. _prims.Remove(oldID);
  1074. _prims[prim.LocalID] = prim;
  1075. }
  1076. }
  1077. public bool haveActor(PhysicsActor actor)
  1078. {
  1079. if (actor is OdePrim)
  1080. {
  1081. lock (_prims)
  1082. return _prims.ContainsKey(((OdePrim)actor).LocalID);
  1083. }
  1084. else if (actor is OdeCharacter)
  1085. {
  1086. lock (_characters)
  1087. return _characters.Contains((OdeCharacter)actor);
  1088. }
  1089. return false;
  1090. }
  1091. #endregion
  1092. #region Space Separation Calculation
  1093. /// <summary>
  1094. /// Called when a static prim moves or becomes static
  1095. /// Places the prim in a space one the static space
  1096. /// </summary>
  1097. /// <param name="geom">the pointer to the geom that moved</param>
  1098. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  1099. /// <returns>a pointer to the new space it's in</returns>
  1100. public IntPtr MoveGeomToStaticSpace(IntPtr geom, IntPtr currentspace)
  1101. {
  1102. // moves a prim into static sub-space
  1103. // Called ODEPrim so
  1104. // it's already in locked space.
  1105. if (geom == IntPtr.Zero) // shouldn't happen
  1106. return IntPtr.Zero;
  1107. if (StaticSpace == currentspace) // if we are there all done
  1108. return StaticSpace;
  1109. // else remove it from its current space
  1110. if (currentspace != IntPtr.Zero && SafeNativeMethods.SpaceQuery(currentspace, geom))
  1111. {
  1112. if (SafeNativeMethods.GeomIsSpace(currentspace))
  1113. {
  1114. waitForSpaceUnlock(currentspace);
  1115. SafeNativeMethods.SpaceRemove(currentspace, geom);
  1116. if (SafeNativeMethods.SpaceGetSublevel(currentspace) > 2 && SafeNativeMethods.SpaceGetNumGeoms(currentspace) == 0)
  1117. {
  1118. SafeNativeMethods.SpaceDestroy(currentspace);
  1119. }
  1120. }
  1121. else
  1122. {
  1123. m_log.Info("[Physics]: Invalid or empty Space passed to 'MoveGeomToStaticSpace':" + currentspace +
  1124. " Geom:" + geom);
  1125. }
  1126. }
  1127. else
  1128. {
  1129. currentspace = SafeNativeMethods.GeomGetSpace(geom);
  1130. if (currentspace != IntPtr.Zero)
  1131. {
  1132. if (SafeNativeMethods.GeomIsSpace(currentspace))
  1133. {
  1134. waitForSpaceUnlock(currentspace);
  1135. SafeNativeMethods.SpaceRemove(currentspace, geom);
  1136. if (SafeNativeMethods.SpaceGetSublevel(currentspace) > 2 && SafeNativeMethods.SpaceGetNumGeoms(currentspace) == 0)
  1137. {
  1138. SafeNativeMethods.SpaceDestroy(currentspace);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. // put the geom in the newspace
  1144. waitForSpaceUnlock(StaticSpace);
  1145. if(SafeNativeMethods.SpaceQuery(StaticSpace, geom))
  1146. m_log.Info("[Physics]: 'MoveGeomToStaticSpace' geom already in static space:" + geom);
  1147. else
  1148. SafeNativeMethods.SpaceAdd(StaticSpace, geom);
  1149. return StaticSpace;
  1150. }
  1151. #endregion
  1152. /// <summary>
  1153. /// Called to queue a change to a actor
  1154. /// to use in place of old taint mechanism so changes do have a time sequence
  1155. /// </summary>
  1156. public void AddChange(PhysicsActor _actor, changes _what, Object _arg)
  1157. {
  1158. if (world == IntPtr.Zero)
  1159. return;
  1160. ODEchangeitem item = new ODEchangeitem
  1161. {
  1162. actor = _actor,
  1163. what = _what,
  1164. arg = _arg
  1165. };
  1166. ChangesQueue.Enqueue(item);
  1167. }
  1168. /// <summary>
  1169. /// Called after our prim properties are set Scale, position etc.
  1170. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  1171. /// This assures us that we have no race conditions
  1172. /// </summary>
  1173. /// <param name="prim"></param>
  1174. public override void AddPhysicsActorTaint(PhysicsActor prim)
  1175. {
  1176. }
  1177. // does all pending changes generated during region load process
  1178. public override void ProcessPreSimulation()
  1179. {
  1180. lock (OdeLock)
  1181. {
  1182. if (world == IntPtr.Zero)
  1183. return;
  1184. ODEchangeitem item;
  1185. int donechanges = 0;
  1186. if (!ChangesQueue.IsEmpty)
  1187. {
  1188. m_log.InfoFormat("[ubOde] start processing pending actor operations");
  1189. int tstart = Util.EnvironmentTickCount();
  1190. SafeNativeMethods.AllocateODEDataForThread(~0U);
  1191. while (ChangesQueue.TryDequeue(out item))
  1192. {
  1193. if (item.actor != null)
  1194. {
  1195. try
  1196. {
  1197. lock (SimulationLock)
  1198. {
  1199. if (item.actor is OdeCharacter)
  1200. ((OdeCharacter)item.actor).DoAChange(item.what, item.arg);
  1201. else if (((OdePrim)item.actor).DoAChange(item.what, item.arg))
  1202. RemovePrimThreadLocked((OdePrim)item.actor);
  1203. }
  1204. }
  1205. catch
  1206. {
  1207. m_log.WarnFormat("[PHYSICS]: Operation failed for a actor {0} {1}",
  1208. item.actor.Name, item.what.ToString());
  1209. }
  1210. }
  1211. donechanges++;
  1212. }
  1213. int time = Util.EnvironmentTickCountSubtract(tstart);
  1214. m_log.InfoFormat("[ubOde] finished {0} operations in {1}ms", donechanges, time);
  1215. }
  1216. m_log.InfoFormat("[ubOde] {0} prim actors loaded",_prims.Count);
  1217. }
  1218. m_lastframe = Util.GetTimeStamp() + 0.5;
  1219. step_time = -0.5f;
  1220. }
  1221. /// <summary>
  1222. /// This is our main simulate loop
  1223. /// It's thread locked by a Mutex in the scene.
  1224. /// It holds Collisions, it instructs ODE to step through the physical reactions
  1225. /// It moves the objects around in memory
  1226. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  1227. /// </summary>
  1228. /// <param name="timeStep"></param>
  1229. /// <returns></returns>
  1230. public override float Simulate(float reqTimeStep)
  1231. {
  1232. if (world == IntPtr.Zero)
  1233. return 0;
  1234. double now = Util.GetTimeStamp();
  1235. double timeStep = now - m_lastframe;
  1236. m_lastframe = now;
  1237. // acumulate time so we can reduce error
  1238. step_time += (float)timeStep;
  1239. if (step_time < HalfOdeStep)
  1240. return 0;
  1241. if (framecount < 0)
  1242. framecount = 0;
  1243. framecount++;
  1244. // checkThread();
  1245. int nodeframes = 0;
  1246. float fps = 0;
  1247. lock (OdeLock)
  1248. {
  1249. // d.WorldSetQuickStepNumIterations(world, curphysiteractions);
  1250. double loopstartMS = Util.GetTimeStampMS();
  1251. double looptimeMS = 0;
  1252. double changestimeMS = 0;
  1253. double maxChangestime = (int)(reqTimeStep * 500f); // half the time
  1254. double maxLoopTime = (int)(reqTimeStep * 1200f); // 1.2 the time
  1255. /*
  1256. double collisionTime = 0;
  1257. double qstepTIme = 0;
  1258. double tmpTime = 0;
  1259. double changestot = 0;
  1260. double collisonRepo = 0;
  1261. double updatesTime = 0;
  1262. double moveTime = 0;
  1263. double rayTime = 0;
  1264. */
  1265. SafeNativeMethods.AllocateODEDataForThread(~0U);
  1266. if (!ChangesQueue.IsEmpty)
  1267. {
  1268. ODEchangeitem item;
  1269. while (ChangesQueue.TryDequeue(out item))
  1270. {
  1271. if (item.actor != null)
  1272. {
  1273. try
  1274. {
  1275. lock (SimulationLock)
  1276. {
  1277. if (item.actor is OdeCharacter)
  1278. ((OdeCharacter)item.actor).DoAChange(item.what, item.arg);
  1279. else if (((OdePrim)item.actor).DoAChange(item.what, item.arg))
  1280. RemovePrimThreadLocked((OdePrim)item.actor);
  1281. }
  1282. }
  1283. catch
  1284. {
  1285. m_log.WarnFormat("[PHYSICS]: doChange failed for a actor {0} {1}",
  1286. item.actor.Name, item.what.ToString());
  1287. }
  1288. }
  1289. changestimeMS = Util.GetTimeStampMS() - loopstartMS;
  1290. if (changestimeMS > maxChangestime)
  1291. break;
  1292. }
  1293. }
  1294. // do simulation taking at most 150ms total time including changes
  1295. while (step_time > HalfOdeStep)
  1296. {
  1297. try
  1298. {
  1299. // clear pointer/counter to contacts to pass into joints
  1300. m_global_contactcount = 0;
  1301. // tmpTime = Util.GetTimeStampMS();
  1302. // Move characters
  1303. lock (_characters)
  1304. {
  1305. foreach (OdeCharacter actor in _characters)
  1306. {
  1307. lock (SimulationLock)
  1308. actor.Move();
  1309. }
  1310. }
  1311. // Move other active objects
  1312. lock (_activegroups)
  1313. {
  1314. foreach (OdePrim aprim in _activegroups)
  1315. {
  1316. lock (SimulationLock)
  1317. aprim.Move();
  1318. }
  1319. }
  1320. // moveTime += Util.GetTimeStampMS() - tmpTime;
  1321. // tmpTime = Util.GetTimeStampMS();
  1322. lock (SimulationLock)
  1323. {
  1324. m_rayCastManager.ProcessQueuedRequests();
  1325. // rayTime += Util.GetTimeStampMS() - tmpTime;
  1326. // tmpTime = Util.GetTimeStampMS();
  1327. collision_optimized();
  1328. }
  1329. // collisionTime += Util.GetTimeStampMS() - tmpTime;
  1330. // tmpTime = Util.GetTimeStampMS();
  1331. lock(_collisionEventPrimRemove)
  1332. {
  1333. foreach (PhysicsActor obj in _collisionEventPrimRemove)
  1334. _collisionEventPrim.Remove(obj);
  1335. _collisionEventPrimRemove.Clear();
  1336. }
  1337. List<OdePrim> sleepers = new List<OdePrim>();
  1338. foreach (PhysicsActor obj in _collisionEventPrim)
  1339. {
  1340. switch ((ActorTypes)obj.PhysicsActorType)
  1341. {
  1342. case ActorTypes.Agent:
  1343. OdeCharacter cobj = (OdeCharacter)obj;
  1344. cobj.SendCollisions((int)(odetimestepMS));
  1345. break;
  1346. case ActorTypes.Prim:
  1347. OdePrim pobj = (OdePrim)obj;
  1348. if (!pobj.m_outbounds)
  1349. {
  1350. pobj.SendCollisions((int)(odetimestepMS));
  1351. lock(SimulationLock)
  1352. {
  1353. if(pobj.Body != IntPtr.Zero && !pobj.m_isSelected &&
  1354. !pobj.m_disabled && !pobj.m_building &&
  1355. !SafeNativeMethods.BodyIsEnabled(pobj.Body))
  1356. sleepers.Add(pobj);
  1357. }
  1358. }
  1359. break;
  1360. }
  1361. }
  1362. foreach(OdePrim prm in sleepers)
  1363. prm.SleeperAddCollisionEvents();
  1364. sleepers.Clear();
  1365. // collisonRepo += Util.GetTimeStampMS() - tmpTime;
  1366. // do a ode simulation step
  1367. // tmpTime = Util.GetTimeStampMS();
  1368. lock (SimulationLock)
  1369. {
  1370. SafeNativeMethods.WorldQuickStep(world, ODE_STEPSIZE);
  1371. SafeNativeMethods.JointGroupEmpty(contactgroup);
  1372. }
  1373. // qstepTIme += Util.GetTimeStampMS() - tmpTime;
  1374. // update managed ideia of physical data and do updates to core
  1375. /*
  1376. lock (_characters)
  1377. {
  1378. foreach (OdeCharacter actor in _characters)
  1379. {
  1380. if (actor != null)
  1381. {
  1382. if (actor.bad)
  1383. m_log.WarnFormat("[PHYSICS]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  1384. actor.UpdatePositionAndVelocity();
  1385. }
  1386. }
  1387. }
  1388. */
  1389. // tmpTime = Util.GetTimeStampMS();
  1390. //lock (SimulationLock)
  1391. {
  1392. lock (_activegroups)
  1393. {
  1394. {
  1395. foreach (OdePrim actor in _activegroups)
  1396. {
  1397. if (actor.IsPhysical)
  1398. {
  1399. lock (SimulationLock)
  1400. actor.UpdatePositionAndVelocity(framecount);
  1401. }
  1402. }
  1403. }
  1404. }
  1405. }
  1406. // updatesTime += Util.GetTimeStampMS() - tmpTime;
  1407. }
  1408. catch (Exception e)
  1409. {
  1410. m_log.ErrorFormat("[PHYSICS]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  1411. // ode.dunlock(world);
  1412. }
  1413. step_time -= ODE_STEPSIZE;
  1414. nodeframes++;
  1415. looptimeMS = Util.GetTimeStampMS() - loopstartMS;
  1416. if (looptimeMS > maxLoopTime)
  1417. break;
  1418. }
  1419. lock (_badCharacter)
  1420. {
  1421. if (_badCharacter.Count > 0)
  1422. {
  1423. foreach (OdeCharacter chr in _badCharacter)
  1424. {
  1425. RemoveCharacter(chr);
  1426. }
  1427. _badCharacter.Clear();
  1428. }
  1429. }
  1430. /*
  1431. // information block for in debug breakpoint only
  1432. int ntopactivegeoms = d.SpaceGetNumGeoms(ActiveSpace);
  1433. int ntopstaticgeoms = d.SpaceGetNumGeoms(StaticSpace);
  1434. int ngroundgeoms = d.SpaceGetNumGeoms(GroundSpace);
  1435. int nactivegeoms = 0;
  1436. int nactivespaces = 0;
  1437. int nstaticgeoms = 0;
  1438. int nstaticspaces = 0;
  1439. IntPtr sp;
  1440. for (int i = 0; i < ntopactivegeoms; i++)
  1441. {
  1442. sp = d.SpaceGetGeom(ActiveSpace, i);
  1443. if (d.GeomIsSpace(sp))
  1444. {
  1445. nactivespaces++;
  1446. nactivegeoms += d.SpaceGetNumGeoms(sp);
  1447. }
  1448. else
  1449. nactivegeoms++;
  1450. }
  1451. for (int i = 0; i < ntopstaticgeoms; i++)
  1452. {
  1453. sp = d.SpaceGetGeom(StaticSpace, i);
  1454. if (d.GeomIsSpace(sp))
  1455. {
  1456. nstaticspaces++;
  1457. nstaticgeoms += d.SpaceGetNumGeoms(sp);
  1458. }
  1459. else
  1460. nstaticgeoms++;
  1461. }
  1462. int ntopgeoms = d.SpaceGetNumGeoms(TopSpace);
  1463. int totgeoms = nstaticgeoms + nactivegeoms + ngroundgeoms + 1; // one ray
  1464. int nbodies = d.NTotalBodies;
  1465. int ngeoms = d.NTotalGeoms;
  1466. */
  1467. /*
  1468. looptimeMS /= nodeframes;
  1469. collisionTime /= nodeframes;
  1470. qstepTIme /= nodeframes;
  1471. changestot /= nodeframes;
  1472. collisonRepo /= nodeframes;
  1473. updatesTime /= nodeframes;
  1474. moveTime /= nodeframes;
  1475. rayTime /= nodeframes;
  1476. if(looptimeMS > .05)
  1477. {
  1478. }
  1479. */
  1480. fps = (float)nodeframes * ODE_STEPSIZE / reqTimeStep;
  1481. if(step_time < HalfOdeStep)
  1482. m_timeDilation = 1.0f;
  1483. else if (step_time > m_SkipFramesAtms)
  1484. {
  1485. // if we lag too much skip frames
  1486. m_timeDilation = 0.0f;
  1487. step_time = 0;
  1488. m_lastframe = Util.GetTimeStamp(); // skip also the time lost
  1489. }
  1490. else
  1491. {
  1492. m_timeDilation = ODE_STEPSIZE / step_time;
  1493. if (m_timeDilation > 1)
  1494. m_timeDilation = 1;
  1495. }
  1496. if (m_timeDilation == 1 && now - m_lastMeshExpire > 30)
  1497. {
  1498. mesher.ExpireReleaseMeshs();
  1499. m_lastMeshExpire = now;
  1500. }
  1501. }
  1502. return fps;
  1503. }
  1504. public float GetTerrainHeightAtXY(float x, float y)
  1505. {
  1506. if (m_terrainGeom == IntPtr.Zero)
  1507. return 0f;
  1508. if (m_terrainHeights == null || m_terrainHeights.Length == 0)
  1509. return 0f;
  1510. // TerrainHeightField for ODE as offset 1m
  1511. x += 1f;
  1512. y += 1f;
  1513. // make position fit into array
  1514. if (x < 0)
  1515. x = 0;
  1516. if (y < 0)
  1517. y = 0;
  1518. // integer indexs
  1519. int ix;
  1520. int iy;
  1521. // interpolators offset
  1522. float dx;
  1523. float dy;
  1524. int regsizeX = (int)m_regionWidth + 3; // map size see setterrain number of samples
  1525. int regsizeY = (int)m_regionHeight + 3; // map size see setterrain number of samples
  1526. int regsize = regsizeX;
  1527. if (x < regsizeX - 1)
  1528. {
  1529. ix = (int)x;
  1530. dx = x - (float)ix;
  1531. }
  1532. else // out world use external height
  1533. {
  1534. ix = regsizeX - 2;
  1535. dx = 0;
  1536. }
  1537. if (y < regsizeY - 1)
  1538. {
  1539. iy = (int)y;
  1540. dy = y - (float)iy;
  1541. }
  1542. else
  1543. {
  1544. iy = regsizeY - 2;
  1545. dy = 0;
  1546. }
  1547. float h0;
  1548. float h1;
  1549. float h2;
  1550. iy *= regsize;
  1551. iy += ix; // all indexes have iy + ix
  1552. float[] heights = m_terrainHeights;
  1553. /*
  1554. if ((dx + dy) <= 1.0f)
  1555. {
  1556. h0 = ((float)heights[iy]); // 0,0 vertice
  1557. h1 = (((float)heights[iy + 1]) - h0) * dx; // 1,0 vertice minus 0,0
  1558. h2 = (((float)heights[iy + regsize]) - h0) * dy; // 0,1 vertice minus 0,0
  1559. }
  1560. else
  1561. {
  1562. h0 = ((float)heights[iy + regsize + 1]); // 1,1 vertice
  1563. h1 = (((float)heights[iy + 1]) - h0) * (1 - dy); // 1,1 vertice minus 1,0
  1564. h2 = (((float)heights[iy + regsize]) - h0) * (1 - dx); // 1,1 vertice minus 0,1
  1565. }
  1566. */
  1567. h0 = ((float)heights[iy]); // 0,0 vertice
  1568. if (dy>dx)
  1569. {
  1570. iy += regsize;
  1571. h2 = (float)heights[iy]; // 0,1 vertice
  1572. h1 = (h2 - h0) * dy; // 0,1 vertice minus 0,0
  1573. h2 = ((float)heights[iy + 1] - h2) * dx; // 1,1 vertice minus 0,1
  1574. }
  1575. else
  1576. {
  1577. iy++;
  1578. h2 = (float)heights[iy]; // vertice 1,0
  1579. h1 = (h2 - h0) * dx; // 1,0 vertice minus 0,0
  1580. h2 = (((float)heights[iy + regsize]) - h2) * dy; // 1,1 vertice minus 1,0
  1581. }
  1582. return h0 + h1 + h2;
  1583. }
  1584. public Vector3 GetTerrainNormalAtXY(float x, float y)
  1585. {
  1586. Vector3 norm = new Vector3(0, 0, 1);
  1587. if (m_terrainGeom == IntPtr.Zero)
  1588. return norm;
  1589. if (m_terrainHeights == null || m_terrainHeights.Length == 0)
  1590. return norm;
  1591. // TerrainHeightField for ODE as offset 1m
  1592. x += 1f;
  1593. y += 1f;
  1594. // make position fit into array
  1595. if (x < 0)
  1596. x = 0;
  1597. if (y < 0)
  1598. y = 0;
  1599. // integer indexs
  1600. int ix;
  1601. int iy;
  1602. // interpolators offset
  1603. float dx;
  1604. float dy;
  1605. int regsizeX = (int)m_regionWidth + 3; // map size see setterrain number of samples
  1606. int regsizeY = (int)m_regionHeight + 3; // map size see setterrain number of samples
  1607. int regsize = regsizeX;
  1608. int xstep = 1;
  1609. int ystep = regsizeX;
  1610. bool firstTri = false;
  1611. if (x < regsizeX - 1)
  1612. {
  1613. ix = (int)x;
  1614. dx = x - (float)ix;
  1615. }
  1616. else // out world use external height
  1617. {
  1618. ix = regsizeX - 2;
  1619. dx = 0;
  1620. }
  1621. if (y < regsizeY - 1)
  1622. {
  1623. iy = (int)y;
  1624. dy = y - (float)iy;
  1625. }
  1626. else
  1627. {
  1628. iy = regsizeY - 2;
  1629. dy = 0;
  1630. }
  1631. firstTri = dy > dx;
  1632. float h0;
  1633. float h1;
  1634. float h2;
  1635. iy *= regsize;
  1636. iy += ix; // all indexes have iy + ix
  1637. float[] heights = m_terrainHeights;
  1638. if (firstTri)
  1639. {
  1640. h1 = ((float)heights[iy]); // 0,0 vertice
  1641. iy += ystep;
  1642. h0 = (float)heights[iy]; // 0,1
  1643. h2 = (float)heights[iy+xstep]; // 1,1 vertice
  1644. norm.X = h0 - h2;
  1645. norm.Y = h1 - h0;
  1646. }
  1647. else
  1648. {
  1649. h2 = ((float)heights[iy]); // 0,0 vertice
  1650. iy += xstep;
  1651. h0 = ((float)heights[iy]); // 1,0 vertice
  1652. h1 = (float)heights[iy+ystep]; // vertice 1,1
  1653. norm.X = h2 - h0;
  1654. norm.Y = h0 - h1;
  1655. }
  1656. norm.Z = 1;
  1657. norm.Normalize();
  1658. return norm;
  1659. }
  1660. private void InitTerrain()
  1661. {
  1662. lock(SimulationLock)
  1663. lock (OdeLock)
  1664. {
  1665. SafeNativeMethods.AllocateODEDataForThread(~0U);
  1666. if (m_terrainGeom != IntPtr.Zero)
  1667. {
  1668. actor_name_map.Remove(m_terrainGeom);
  1669. SafeNativeMethods.GeomDestroy(m_terrainGeom);
  1670. }
  1671. if (m_terrainHeightsHandler.IsAllocated)
  1672. m_terrainHeightsHandler.Free();
  1673. m_terrainHeights = null;
  1674. int heightmapWidthSamples = m_regionWidth + 3;
  1675. int heightmapHeightSamples = m_regionHeight + 3;
  1676. m_terrainHeights = new float[heightmapWidthSamples * heightmapHeightSamples];
  1677. m_terrainHeightsHandler = GCHandle.Alloc(m_terrainHeights, GCHandleType.Pinned);
  1678. m_lastRegionWidth = m_regionWidth;
  1679. HeightmapData = SafeNativeMethods.GeomOSTerrainDataCreate();
  1680. SafeNativeMethods.GeomOSTerrainDataBuild(HeightmapData, m_terrainHeightsHandler.AddrOfPinnedObject(), 0, 1.0f,
  1681. heightmapWidthSamples, heightmapHeightSamples,
  1682. 1, 0);
  1683. m_terrainGeom = SafeNativeMethods.CreateOSTerrain(GroundSpace, HeightmapData, 1);
  1684. if (m_terrainGeom != IntPtr.Zero)
  1685. {
  1686. SafeNativeMethods.GeomSetCategoryBits(m_terrainGeom, (uint)(CollisionCategories.Land));
  1687. SafeNativeMethods.GeomSetCollideBits(m_terrainGeom, 0);
  1688. PhysicsActor pa = new NullPhysicsActor();
  1689. pa.Name = "Terrain";
  1690. pa.PhysicsActorType = (int)ActorTypes.Ground;
  1691. actor_name_map[m_terrainGeom] = pa;
  1692. //geom_name_map[GroundGeom] = "Terrain";
  1693. SafeNativeMethods.GeomSetPosition(m_terrainGeom, m_regionWidth * 0.5f, m_regionHeight * 0.5f, 0.0f);
  1694. }
  1695. else
  1696. m_terrainHeightsHandler.Free();
  1697. }
  1698. }
  1699. public override void SetTerrain(float[] heightMap)
  1700. {
  1701. // assumes 1m size grid and constante size square regions
  1702. // needs to know about sims around in future
  1703. if(m_regionWidth != m_lastRegionWidth ||
  1704. m_regionHeight != m_lastRegionHeight ||
  1705. !m_terrainHeightsHandler.IsAllocated ||
  1706. m_terrainGeom == IntPtr.Zero)
  1707. InitTerrain();
  1708. int regionsizeX = m_regionWidth;
  1709. int regionsizeY = m_regionHeight;
  1710. int heightmapWidth = regionsizeX + 2;
  1711. int heightmapHeight = regionsizeY + 2;
  1712. int heightmapWidthSamples = heightmapWidth + 1;
  1713. int heightmapHeightSamples = heightmapHeight + 1;
  1714. float val;
  1715. int maxXX = regionsizeX + 1;
  1716. int maxYY = regionsizeY + 1;
  1717. // adding one margin all around so things don't fall in edges
  1718. int xx;
  1719. int yy = 0;
  1720. int yt = 0;
  1721. float minH = float.MaxValue;
  1722. float maxH = float.MinValue;
  1723. for (int y = 0; y < heightmapHeightSamples; y++)
  1724. {
  1725. if (y > 1 && y < maxYY)
  1726. yy += regionsizeX;
  1727. xx = 0;
  1728. lock(OdeLock)
  1729. {
  1730. for (int x = 0; x < heightmapWidthSamples; x++)
  1731. {
  1732. if (x > 1 && x < maxXX)
  1733. xx++;
  1734. val = heightMap[yy + xx];
  1735. if (val < -100.0f)
  1736. val = -100.0f;
  1737. if(val > maxH)
  1738. maxH = val;
  1739. if(val < minH)
  1740. minH = val;
  1741. m_terrainHeights[yt + x] = val;
  1742. }
  1743. }
  1744. yt += heightmapWidthSamples;
  1745. }
  1746. lock(SimulationLock)
  1747. lock (OdeLock)
  1748. {
  1749. SafeNativeMethods.GeomOSTerrainDataSetBounds(HeightmapData, minH, maxH);
  1750. SafeNativeMethods.GeomSetPosition(m_terrainGeom, m_regionWidth * 0.5f, m_regionHeight * 0.5f, 0.0f);
  1751. }
  1752. }
  1753. public override void DeleteTerrain()
  1754. {
  1755. }
  1756. public float GetWaterLevel()
  1757. {
  1758. return waterlevel;
  1759. }
  1760. public override void SetWaterLevel(float baseheight)
  1761. {
  1762. waterlevel = baseheight;
  1763. }
  1764. public override void Dispose()
  1765. {
  1766. lock(SimulationLock)
  1767. lock (OdeLock)
  1768. {
  1769. if (world == IntPtr.Zero)
  1770. return;
  1771. SafeNativeMethods.AllocateODEDataForThread(~0U);
  1772. if (m_meshWorker != null)
  1773. m_meshWorker.Stop();
  1774. if (m_rayCastManager != null)
  1775. {
  1776. m_rayCastManager.Dispose();
  1777. m_rayCastManager = null;
  1778. }
  1779. lock (_prims)
  1780. {
  1781. foreach (OdePrim prm in _prims.Values)
  1782. {
  1783. prm.DoAChange(changes.Remove, null);
  1784. _collisionEventPrim.Remove(prm);
  1785. }
  1786. _prims.Clear();
  1787. }
  1788. OdeCharacter[] chtorem;
  1789. lock (_characters)
  1790. {
  1791. chtorem = new OdeCharacter[_characters.Count];
  1792. _characters.CopyTo(chtorem);
  1793. }
  1794. foreach (OdeCharacter ch in chtorem)
  1795. ch.DoAChange(changes.Remove, null);
  1796. if (m_terrainGeom != IntPtr.Zero)
  1797. SafeNativeMethods.GeomDestroy(m_terrainGeom);
  1798. m_terrainGeom = IntPtr.Zero;
  1799. if (m_terrainHeightsHandler.IsAllocated)
  1800. m_terrainHeightsHandler.Free();
  1801. m_terrainHeights = null;
  1802. m_lastRegionWidth = 0;
  1803. m_lastRegionHeight = 0;
  1804. if (ContactgeomsArray != IntPtr.Zero)
  1805. {
  1806. Marshal.FreeHGlobal(ContactgeomsArray);
  1807. ContactgeomsArray = IntPtr.Zero;
  1808. }
  1809. if (GlobalContactsArray != IntPtr.Zero)
  1810. {
  1811. Marshal.FreeHGlobal(GlobalContactsArray);
  1812. GlobalContactsArray = IntPtr.Zero;
  1813. }
  1814. SafeNativeMethods.WorldDestroy(world);
  1815. world = IntPtr.Zero;
  1816. //d.CloseODE();
  1817. }
  1818. }
  1819. private int compareByCollisionsDesc(OdePrim A, OdePrim B)
  1820. {
  1821. return -A.CollisionScore.CompareTo(B.CollisionScore);
  1822. }
  1823. public override Dictionary<uint, float> GetTopColliders()
  1824. {
  1825. Dictionary<uint, float> topColliders;
  1826. List<OdePrim> orderedPrims;
  1827. lock (_activeprims)
  1828. orderedPrims = new List<OdePrim>(_activeprims);
  1829. orderedPrims.Sort(compareByCollisionsDesc);
  1830. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  1831. return topColliders;
  1832. }
  1833. public override bool SupportsRayCast()
  1834. {
  1835. return true;
  1836. }
  1837. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  1838. {
  1839. if (retMethod != null)
  1840. {
  1841. ODERayRequest req = new ODERayRequest();
  1842. req.actor = null;
  1843. req.callbackMethod = retMethod;
  1844. req.length = length;
  1845. req.Normal = direction;
  1846. req.Origin = position;
  1847. req.Count = 0;
  1848. req.filter = RayFilterFlags.AllPrims;
  1849. m_rayCastManager.QueueRequest(req);
  1850. }
  1851. }
  1852. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
  1853. {
  1854. if (retMethod != null)
  1855. {
  1856. ODERayRequest req = new ODERayRequest();
  1857. req.actor = null;
  1858. req.callbackMethod = retMethod;
  1859. req.length = length;
  1860. req.Normal = direction;
  1861. req.Origin = position;
  1862. req.Count = Count;
  1863. req.filter = RayFilterFlags.AllPrims;
  1864. m_rayCastManager.QueueRequest(req);
  1865. }
  1866. }
  1867. public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
  1868. {
  1869. List<ContactResult> ourresults = new List<ContactResult>();
  1870. object SyncObject = new object();
  1871. RayCallback retMethod = delegate(List<ContactResult> results)
  1872. {
  1873. lock (SyncObject)
  1874. {
  1875. ourresults = results;
  1876. Monitor.PulseAll(SyncObject);
  1877. }
  1878. };
  1879. ODERayRequest req = new ODERayRequest();
  1880. req.actor = null;
  1881. req.callbackMethod = retMethod;
  1882. req.length = length;
  1883. req.Normal = direction;
  1884. req.Origin = position;
  1885. req.Count = Count;
  1886. req.filter = RayFilterFlags.AllPrims;
  1887. lock (SyncObject)
  1888. {
  1889. m_rayCastManager.QueueRequest(req);
  1890. if (!Monitor.Wait(SyncObject, 500))
  1891. return null;
  1892. else
  1893. return ourresults;
  1894. }
  1895. }
  1896. public override bool SupportsRaycastWorldFiltered()
  1897. {
  1898. return true;
  1899. }
  1900. public override object RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
  1901. {
  1902. object SyncObject = new object();
  1903. List<ContactResult> ourresults = new List<ContactResult>();
  1904. RayCallback retMethod = delegate(List<ContactResult> results)
  1905. {
  1906. lock (SyncObject)
  1907. {
  1908. ourresults = results;
  1909. Monitor.PulseAll(SyncObject);
  1910. }
  1911. };
  1912. ODERayRequest req = new ODERayRequest();
  1913. req.actor = null;
  1914. req.callbackMethod = retMethod;
  1915. req.length = length;
  1916. req.Normal = direction;
  1917. req.Origin = position;
  1918. req.Count = Count;
  1919. req.filter = filter;
  1920. lock (SyncObject)
  1921. {
  1922. m_rayCastManager.QueueRequest(req);
  1923. if (!Monitor.Wait(SyncObject, 500))
  1924. return null;
  1925. else
  1926. return ourresults;
  1927. }
  1928. }
  1929. public override List<ContactResult> RaycastActor(PhysicsActor actor, Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags flags)
  1930. {
  1931. if (actor == null)
  1932. return new List<ContactResult>();
  1933. IntPtr geom;
  1934. if (actor is OdePrim)
  1935. geom = ((OdePrim)actor).prim_geom;
  1936. else if (actor is OdeCharacter)
  1937. geom = ((OdePrim)actor).prim_geom;
  1938. else
  1939. return new List<ContactResult>();
  1940. if (geom == IntPtr.Zero)
  1941. return new List<ContactResult>();
  1942. List<ContactResult> ourResults = null;
  1943. object SyncObject = new object();
  1944. RayCallback retMethod = delegate(List<ContactResult> results)
  1945. {
  1946. lock (SyncObject)
  1947. {
  1948. ourResults = results;
  1949. Monitor.PulseAll(SyncObject);
  1950. }
  1951. };
  1952. ODERayRequest req = new ODERayRequest();
  1953. req.actor = actor;
  1954. req.callbackMethod = retMethod;
  1955. req.length = length;
  1956. req.Normal = direction;
  1957. req.Origin = position;
  1958. req.Count = Count;
  1959. req.filter = flags;
  1960. lock (SyncObject)
  1961. {
  1962. m_rayCastManager.QueueRequest(req);
  1963. if (!Monitor.Wait(SyncObject, 500))
  1964. return new List<ContactResult>();
  1965. }
  1966. if (ourResults == null)
  1967. return new List<ContactResult>();
  1968. return ourResults;
  1969. }
  1970. public override List<ContactResult> BoxProbe(Vector3 position, Vector3 size, Quaternion orientation, int Count, RayFilterFlags flags)
  1971. {
  1972. List<ContactResult> ourResults = null;
  1973. object SyncObject = new object();
  1974. ProbeBoxCallback retMethod = delegate(List<ContactResult> results)
  1975. {
  1976. lock (SyncObject)
  1977. {
  1978. ourResults = results;
  1979. Monitor.PulseAll(SyncObject);
  1980. }
  1981. };
  1982. ODERayRequest req = new ODERayRequest();
  1983. req.actor = null;
  1984. req.callbackMethod = retMethod;
  1985. req.Normal = size;
  1986. req.Origin = position;
  1987. req.orientation = orientation;
  1988. req.Count = Count;
  1989. req.filter = flags;
  1990. lock (SyncObject)
  1991. {
  1992. m_rayCastManager.QueueRequest(req);
  1993. if (!Monitor.Wait(SyncObject, 500))
  1994. return new List<ContactResult>();
  1995. }
  1996. if (ourResults == null)
  1997. return new List<ContactResult>();
  1998. return ourResults;
  1999. }
  2000. public override List<ContactResult> SphereProbe(Vector3 position, float radius, int Count, RayFilterFlags flags)
  2001. {
  2002. List<ContactResult> ourResults = null;
  2003. object SyncObject = new object();
  2004. ProbeSphereCallback retMethod = delegate(List<ContactResult> results)
  2005. {
  2006. ourResults = results;
  2007. Monitor.PulseAll(SyncObject);
  2008. };
  2009. ODERayRequest req = new ODERayRequest();
  2010. req.actor = null;
  2011. req.callbackMethod = retMethod;
  2012. req.length = radius;
  2013. req.Origin = position;
  2014. req.Count = Count;
  2015. req.filter = flags;
  2016. lock (SyncObject)
  2017. {
  2018. m_rayCastManager.QueueRequest(req);
  2019. if (!Monitor.Wait(SyncObject, 500))
  2020. return new List<ContactResult>();
  2021. }
  2022. if (ourResults == null)
  2023. return new List<ContactResult>();
  2024. return ourResults;
  2025. }
  2026. public override List<ContactResult> PlaneProbe(PhysicsActor actor, Vector4 plane, int Count, RayFilterFlags flags)
  2027. {
  2028. IntPtr geom = IntPtr.Zero;;
  2029. if (actor != null)
  2030. {
  2031. if (actor is OdePrim)
  2032. geom = ((OdePrim)actor).prim_geom;
  2033. else if (actor is OdeCharacter)
  2034. geom = ((OdePrim)actor).prim_geom;
  2035. }
  2036. List<ContactResult> ourResults = null;
  2037. object SyncObject = new object();
  2038. ProbePlaneCallback retMethod = delegate(List<ContactResult> results)
  2039. {
  2040. ourResults = results;
  2041. Monitor.PulseAll(SyncObject);
  2042. };
  2043. ODERayRequest req = new ODERayRequest();
  2044. req.actor = null;
  2045. req.callbackMethod = retMethod;
  2046. req.length = plane.W;
  2047. req.Normal.X = plane.X;
  2048. req.Normal.Y = plane.Y;
  2049. req.Normal.Z = plane.Z;
  2050. req.Count = Count;
  2051. req.filter = flags;
  2052. lock (SyncObject)
  2053. {
  2054. m_rayCastManager.QueueRequest(req);
  2055. if (!Monitor.Wait(SyncObject, 500))
  2056. return new List<ContactResult>();
  2057. }
  2058. if (ourResults == null)
  2059. return new List<ContactResult>();
  2060. return ourResults;
  2061. }
  2062. public override int SitAvatar(PhysicsActor actor, Vector3 AbsolutePosition, Vector3 CameraPosition, Vector3 offset, Vector3 AvatarSize, SitAvatarCallback PhysicsSitResponse)
  2063. {
  2064. Util.FireAndForget( delegate
  2065. {
  2066. ODESitAvatar sitAvatar = new ODESitAvatar(this, m_rayCastManager);
  2067. if(sitAvatar != null)
  2068. sitAvatar.Sit(actor, AbsolutePosition, CameraPosition, offset, AvatarSize, PhysicsSitResponse);
  2069. });
  2070. return 1;
  2071. }
  2072. }
  2073. }