ODEScene.cs 90 KB

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