ODEPrim.cs 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382
  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. /*
  28. * Revised August 26 2009 by Kitto Flora. ODEDynamics.cs replaces
  29. * ODEVehicleSettings.cs. It and ODEPrim.cs are re-organised:
  30. * ODEPrim.cs contains methods dealing with Prim editing, Prim
  31. * characteristics and Kinetic motion.
  32. * ODEDynamics.cs contains methods dealing with Prim Physical motion
  33. * (dynamics) and the associated settings. Old Linear and angular
  34. * motors for dynamic motion have been replace with MoveLinear()
  35. * and MoveAngular(); 'Physical' is used only to switch ODE dynamic
  36. * simualtion on/off; VEHICAL_TYPE_NONE/VEHICAL_TYPE_<other> is to
  37. * switch between 'VEHICLE' parameter use and general dynamics
  38. * settings use.
  39. */
  40. //#define SPAM
  41. using System;
  42. using System.Collections.Generic;
  43. using System.Reflection;
  44. using System.Runtime.InteropServices;
  45. using System.Threading;
  46. using log4net;
  47. using OpenMetaverse;
  48. using Ode.NET;
  49. using OpenSim.Framework;
  50. using OpenSim.Region.PhysicsModules.SharedBase;
  51. namespace OpenSim.Region.PhysicsModule.ODE
  52. {
  53. /// <summary>
  54. /// Various properties that ODE uses for AMotors but isn't exposed in ODE.NET so we must define them ourselves.
  55. /// </summary>
  56. public class OdePrim : PhysicsActor
  57. {
  58. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. private bool m_isphysical;
  60. public int ExpectedCollisionContacts { get { return m_expectedCollisionContacts; } }
  61. private int m_expectedCollisionContacts = 0;
  62. /// <summary>
  63. /// Gets collide bits so that we can still perform land collisions if a mesh fails to load.
  64. /// </summary>
  65. private int BadMeshAssetCollideBits
  66. {
  67. get { return m_isphysical ? (int)CollisionCategories.Land : 0; }
  68. }
  69. /// <summary>
  70. /// Is this prim subject to physics? Even if not, it's still solid for collision purposes.
  71. /// </summary>
  72. public override bool IsPhysical
  73. {
  74. get { return m_isphysical; }
  75. set
  76. {
  77. m_isphysical = value;
  78. if (!m_isphysical) // Zero the remembered last velocity
  79. m_lastVelocity = Vector3.Zero;
  80. }
  81. }
  82. private Vector3 _position;
  83. private Vector3 _velocity;
  84. private Vector3 _torque;
  85. private Vector3 m_lastVelocity;
  86. private Vector3 m_lastposition;
  87. private Quaternion m_lastorientation = new Quaternion();
  88. private Vector3 m_rotationalVelocity;
  89. private Vector3 _size;
  90. private Vector3 _acceleration;
  91. // private d.Vector3 _zeroPosition = new d.Vector3(0.0f, 0.0f, 0.0f);
  92. private Quaternion _orientation;
  93. private Vector3 m_taintposition;
  94. private Vector3 m_taintsize;
  95. private Vector3 m_taintVelocity;
  96. private Vector3 m_taintTorque;
  97. private Quaternion m_taintrot;
  98. private Vector3 m_angularlock = Vector3.One;
  99. private Vector3 m_taintAngularLock = Vector3.One;
  100. private IntPtr Amotor = IntPtr.Zero;
  101. private bool m_assetFailed = false;
  102. private Vector3 m_PIDTarget;
  103. private float m_PIDTau;
  104. private float PID_D = 35f;
  105. private float PID_G = 25f;
  106. // KF: These next 7 params apply to llSetHoverHeight(float height, integer water, float tau),
  107. // and are for non-VEHICLES only.
  108. private float m_PIDHoverHeight;
  109. private float m_PIDHoverTau;
  110. private bool m_useHoverPID;
  111. private PIDHoverType m_PIDHoverType = PIDHoverType.Ground;
  112. private float m_targetHoverHeight;
  113. private float m_groundHeight;
  114. private float m_waterHeight;
  115. private float m_buoyancy; //KF: m_buoyancy should be set by llSetBuoyancy() for non-vehicle.
  116. // private float m_tensor = 5f;
  117. private int body_autodisable_frames = 20;
  118. private const CollisionCategories m_default_collisionFlags = (CollisionCategories.Geom
  119. | CollisionCategories.Space
  120. | CollisionCategories.Body
  121. | CollisionCategories.Character
  122. );
  123. private bool m_taintshape;
  124. private bool m_taintPhysics;
  125. private bool m_collidesLand = true;
  126. private bool m_collidesWater;
  127. // Default we're a Geometry
  128. private CollisionCategories m_collisionCategories = (CollisionCategories.Geom);
  129. // Default, Collide with Other Geometries, spaces and Bodies
  130. private CollisionCategories m_collisionFlags = m_default_collisionFlags;
  131. public bool m_taintremove { get; private set; }
  132. public bool m_taintdisable { get; private set; }
  133. internal bool m_disabled;
  134. public bool m_taintadd { get; private set; }
  135. public bool m_taintselected { get; private set; }
  136. public bool m_taintCollidesWater { get; private set; }
  137. private bool m_taintforce = false;
  138. private bool m_taintaddangularforce = false;
  139. private Vector3 m_force;
  140. private List<Vector3> m_forcelist = new List<Vector3>();
  141. private List<Vector3> m_angularforcelist = new List<Vector3>();
  142. private PrimitiveBaseShape _pbs;
  143. private OdeScene _parent_scene;
  144. /// <summary>
  145. /// The physics space which contains prim geometries
  146. /// </summary>
  147. public IntPtr m_targetSpace = IntPtr.Zero;
  148. /// <summary>
  149. /// The prim geometry, used for collision detection.
  150. /// </summary>
  151. /// <remarks>
  152. /// This is never null except for a brief period when the geometry needs to be replaced (due to resizing or
  153. /// mesh change) or when the physical prim is being removed from the scene.
  154. /// </remarks>
  155. public IntPtr prim_geom { get; private set; }
  156. public IntPtr _triMeshData { get; private set; }
  157. private IntPtr _linkJointGroup = IntPtr.Zero;
  158. private PhysicsActor _parent;
  159. private PhysicsActor m_taintparent;
  160. private List<OdePrim> childrenPrim = new List<OdePrim>();
  161. private bool iscolliding;
  162. private bool m_isSelected;
  163. internal bool m_isVolumeDetect; // If true, this prim only detects collisions but doesn't collide actively
  164. private bool m_throttleUpdates;
  165. private int throttleCounter;
  166. public int m_interpenetrationcount { get; private set; }
  167. internal float m_collisionscore;
  168. public int m_roundsUnderMotionThreshold { get; private set; }
  169. private int m_crossingfailures;
  170. public bool outofBounds { get; private set; }
  171. private float m_density = 10.000006836f; // Aluminum g/cm3;
  172. public bool _zeroFlag { get; private set; }
  173. private bool m_lastUpdateSent;
  174. public IntPtr Body = IntPtr.Zero;
  175. private Vector3 _target_velocity;
  176. private d.Mass pMass;
  177. private int m_eventsubscription;
  178. private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate();
  179. /// <summary>
  180. /// Signal whether there were collisions on the previous frame, so we know if we need to send the
  181. /// empty CollisionEventsThisFrame to the prim so that it can detect the end of a collision.
  182. /// </summary>
  183. /// <remarks>
  184. /// This is probably a temporary measure, pending storing this information consistently in CollisionEventUpdate itself.
  185. /// </remarks>
  186. private bool m_collisionsOnPreviousFrame;
  187. private IntPtr m_linkJoint = IntPtr.Zero;
  188. internal volatile bool childPrim;
  189. private ODEDynamics m_vehicle;
  190. internal int m_material = (int)Material.Wood;
  191. public OdePrim(
  192. String primName, OdeScene parent_scene, Vector3 pos, Vector3 size,
  193. Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical)
  194. {
  195. Name = primName;
  196. m_vehicle = new ODEDynamics();
  197. //gc = GCHandle.Alloc(prim_geom, GCHandleType.Pinned);
  198. if (!pos.IsFinite())
  199. {
  200. pos = new Vector3(((float)Constants.RegionSize * 0.5f), ((float)Constants.RegionSize * 0.5f),
  201. parent_scene.GetTerrainHeightAtXY(((float)Constants.RegionSize * 0.5f), ((float)Constants.RegionSize * 0.5f)) + 0.5f);
  202. m_log.WarnFormat("[PHYSICS]: Got nonFinite Object create Position for {0}", Name);
  203. }
  204. _position = pos;
  205. m_taintposition = pos;
  206. PID_D = parent_scene.bodyPIDD;
  207. PID_G = parent_scene.bodyPIDG;
  208. m_density = parent_scene.geomDefaultDensity;
  209. // m_tensor = parent_scene.bodyMotorJointMaxforceTensor;
  210. body_autodisable_frames = parent_scene.bodyFramesAutoDisable;
  211. prim_geom = IntPtr.Zero;
  212. if (!pos.IsFinite())
  213. {
  214. size = new Vector3(0.5f, 0.5f, 0.5f);
  215. m_log.WarnFormat("[PHYSICS]: Got nonFinite Object create Size for {0}", Name);
  216. }
  217. if (size.X <= 0) size.X = 0.01f;
  218. if (size.Y <= 0) size.Y = 0.01f;
  219. if (size.Z <= 0) size.Z = 0.01f;
  220. _size = size;
  221. m_taintsize = _size;
  222. if (!QuaternionIsFinite(rotation))
  223. {
  224. rotation = Quaternion.Identity;
  225. m_log.WarnFormat("[PHYSICS]: Got nonFinite Object create Rotation for {0}", Name);
  226. }
  227. _orientation = rotation;
  228. m_taintrot = _orientation;
  229. _pbs = pbs;
  230. _parent_scene = parent_scene;
  231. m_targetSpace = (IntPtr)0;
  232. if (pos.Z < 0)
  233. {
  234. IsPhysical = false;
  235. }
  236. else
  237. {
  238. IsPhysical = pisPhysical;
  239. // If we're physical, we need to be in the master space for now.
  240. // linksets *should* be in a space together.. but are not currently
  241. if (IsPhysical)
  242. m_targetSpace = _parent_scene.space;
  243. }
  244. m_taintadd = true;
  245. m_assetFailed = false;
  246. _parent_scene.AddPhysicsActorTaint(this);
  247. }
  248. public override int PhysicsActorType
  249. {
  250. get { return (int) ActorTypes.Prim; }
  251. set { return; }
  252. }
  253. public override bool SetAlwaysRun
  254. {
  255. get { return false; }
  256. set { return; }
  257. }
  258. public override bool Grabbed
  259. {
  260. set { return; }
  261. }
  262. public override bool Selected
  263. {
  264. set
  265. {
  266. // This only makes the object not collidable if the object
  267. // is physical or the object is modified somehow *IN THE FUTURE*
  268. // without this, if an avatar selects prim, they can walk right
  269. // through it while it's selected
  270. m_collisionscore = 0;
  271. if ((IsPhysical && !_zeroFlag) || !value)
  272. {
  273. m_taintselected = value;
  274. _parent_scene.AddPhysicsActorTaint(this);
  275. }
  276. else
  277. {
  278. m_taintselected = value;
  279. m_isSelected = value;
  280. }
  281. if (m_isSelected)
  282. disableBodySoft();
  283. }
  284. }
  285. /// <summary>
  286. /// Set a new geometry for this prim.
  287. /// </summary>
  288. /// <param name="geom"></param>
  289. private void SetGeom(IntPtr geom)
  290. {
  291. prim_geom = geom;
  292. //Console.WriteLine("SetGeom to " + prim_geom + " for " + Name);
  293. if (m_assetFailed)
  294. {
  295. d.GeomSetCategoryBits(prim_geom, 0);
  296. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  297. }
  298. else
  299. {
  300. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  301. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  302. }
  303. _parent_scene.geom_name_map[prim_geom] = Name;
  304. _parent_scene.actor_name_map[prim_geom] = this;
  305. if (childPrim)
  306. {
  307. if (_parent != null && _parent is OdePrim)
  308. {
  309. OdePrim parent = (OdePrim)_parent;
  310. //Console.WriteLine("SetGeom calls ChildSetGeom");
  311. parent.ChildSetGeom(this);
  312. }
  313. }
  314. //m_log.Warn("Setting Geom to: " + prim_geom);
  315. }
  316. private void enableBodySoft()
  317. {
  318. if (!childPrim)
  319. {
  320. if (IsPhysical && Body != IntPtr.Zero)
  321. {
  322. d.BodyEnable(Body);
  323. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  324. m_vehicle.Enable(Body, _parent_scene);
  325. }
  326. m_disabled = false;
  327. }
  328. }
  329. private void disableBodySoft()
  330. {
  331. m_disabled = true;
  332. if (IsPhysical && Body != IntPtr.Zero)
  333. {
  334. d.BodyDisable(Body);
  335. }
  336. }
  337. /// <summary>
  338. /// Make a prim subject to physics.
  339. /// </summary>
  340. private void enableBody()
  341. {
  342. // Don't enable this body if we're a child prim
  343. // this should be taken care of in the parent function not here
  344. if (!childPrim)
  345. {
  346. // Sets the geom to a body
  347. Body = d.BodyCreate(_parent_scene.world);
  348. setMass();
  349. d.BodySetPosition(Body, _position.X, _position.Y, _position.Z);
  350. d.Quaternion myrot = new d.Quaternion();
  351. myrot.X = _orientation.X;
  352. myrot.Y = _orientation.Y;
  353. myrot.Z = _orientation.Z;
  354. myrot.W = _orientation.W;
  355. d.BodySetQuaternion(Body, ref myrot);
  356. d.GeomSetBody(prim_geom, Body);
  357. if (m_assetFailed)
  358. {
  359. d.GeomSetCategoryBits(prim_geom, 0);
  360. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  361. }
  362. else
  363. {
  364. m_collisionCategories |= CollisionCategories.Body;
  365. m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind);
  366. }
  367. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  368. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  369. d.BodySetAutoDisableFlag(Body, true);
  370. d.BodySetAutoDisableSteps(Body, body_autodisable_frames);
  371. // disconnect from world gravity so we can apply buoyancy
  372. d.BodySetGravityMode (Body, false);
  373. m_interpenetrationcount = 0;
  374. m_collisionscore = 0;
  375. m_disabled = false;
  376. // The body doesn't already have a finite rotation mode set here
  377. if ((!m_angularlock.ApproxEquals(Vector3.One, 0.0f)) && _parent == null)
  378. {
  379. createAMotor(m_angularlock);
  380. }
  381. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  382. {
  383. m_vehicle.Enable(Body, _parent_scene);
  384. }
  385. _parent_scene.ActivatePrim(this);
  386. }
  387. }
  388. #region Mass Calculation
  389. private float CalculateMass()
  390. {
  391. float volume = _size.X * _size.Y * _size.Z; // default
  392. float tmp;
  393. float returnMass = 0;
  394. float hollowAmount = (float)_pbs.ProfileHollow * 2.0e-5f;
  395. float hollowVolume = hollowAmount * hollowAmount;
  396. switch (_pbs.ProfileShape)
  397. {
  398. case ProfileShape.Square:
  399. // default box
  400. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  401. {
  402. if (hollowAmount > 0.0)
  403. {
  404. switch (_pbs.HollowShape)
  405. {
  406. case HollowShape.Square:
  407. case HollowShape.Same:
  408. break;
  409. case HollowShape.Circle:
  410. hollowVolume *= 0.78539816339f;
  411. break;
  412. case HollowShape.Triangle:
  413. hollowVolume *= (0.5f * .5f);
  414. break;
  415. default:
  416. hollowVolume = 0;
  417. break;
  418. }
  419. volume *= (1.0f - hollowVolume);
  420. }
  421. }
  422. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  423. {
  424. //a tube
  425. volume *= 0.78539816339e-2f * (float)(200 - _pbs.PathScaleX);
  426. tmp= 1.0f -2.0e-2f * (float)(200 - _pbs.PathScaleY);
  427. volume -= volume*tmp*tmp;
  428. if (hollowAmount > 0.0)
  429. {
  430. hollowVolume *= hollowAmount;
  431. switch (_pbs.HollowShape)
  432. {
  433. case HollowShape.Square:
  434. case HollowShape.Same:
  435. break;
  436. case HollowShape.Circle:
  437. hollowVolume *= 0.78539816339f;;
  438. break;
  439. case HollowShape.Triangle:
  440. hollowVolume *= 0.5f * 0.5f;
  441. break;
  442. default:
  443. hollowVolume = 0;
  444. break;
  445. }
  446. volume *= (1.0f - hollowVolume);
  447. }
  448. }
  449. break;
  450. case ProfileShape.Circle:
  451. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  452. {
  453. volume *= 0.78539816339f; // elipse base
  454. if (hollowAmount > 0.0)
  455. {
  456. switch (_pbs.HollowShape)
  457. {
  458. case HollowShape.Same:
  459. case HollowShape.Circle:
  460. break;
  461. case HollowShape.Square:
  462. hollowVolume *= 0.5f * 2.5984480504799f;
  463. break;
  464. case HollowShape.Triangle:
  465. hollowVolume *= .5f * 1.27323954473516f;
  466. break;
  467. default:
  468. hollowVolume = 0;
  469. break;
  470. }
  471. volume *= (1.0f - hollowVolume);
  472. }
  473. }
  474. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  475. {
  476. volume *= 0.61685027506808491367715568749226e-2f * (float)(200 - _pbs.PathScaleX);
  477. tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY);
  478. volume *= (1.0f - tmp * tmp);
  479. if (hollowAmount > 0.0)
  480. {
  481. // calculate the hollow volume by it's shape compared to the prim shape
  482. hollowVolume *= hollowAmount;
  483. switch (_pbs.HollowShape)
  484. {
  485. case HollowShape.Same:
  486. case HollowShape.Circle:
  487. break;
  488. case HollowShape.Square:
  489. hollowVolume *= 0.5f * 2.5984480504799f;
  490. break;
  491. case HollowShape.Triangle:
  492. hollowVolume *= .5f * 1.27323954473516f;
  493. break;
  494. default:
  495. hollowVolume = 0;
  496. break;
  497. }
  498. volume *= (1.0f - hollowVolume);
  499. }
  500. }
  501. break;
  502. case ProfileShape.HalfCircle:
  503. if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  504. {
  505. volume *= 0.52359877559829887307710723054658f;
  506. }
  507. break;
  508. case ProfileShape.EquilateralTriangle:
  509. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  510. {
  511. volume *= 0.32475953f;
  512. if (hollowAmount > 0.0)
  513. {
  514. // calculate the hollow volume by it's shape compared to the prim shape
  515. switch (_pbs.HollowShape)
  516. {
  517. case HollowShape.Same:
  518. case HollowShape.Triangle:
  519. hollowVolume *= .25f;
  520. break;
  521. case HollowShape.Square:
  522. hollowVolume *= 0.499849f * 3.07920140172638f;
  523. break;
  524. case HollowShape.Circle:
  525. // Hollow shape is a perfect cyllinder in respect to the cube's scale
  526. // Cyllinder hollow volume calculation
  527. hollowVolume *= 0.1963495f * 3.07920140172638f;
  528. break;
  529. default:
  530. hollowVolume = 0;
  531. break;
  532. }
  533. volume *= (1.0f - hollowVolume);
  534. }
  535. }
  536. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  537. {
  538. volume *= 0.32475953f;
  539. volume *= 0.01f * (float)(200 - _pbs.PathScaleX);
  540. tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY);
  541. volume *= (1.0f - tmp * tmp);
  542. if (hollowAmount > 0.0)
  543. {
  544. hollowVolume *= hollowAmount;
  545. switch (_pbs.HollowShape)
  546. {
  547. case HollowShape.Same:
  548. case HollowShape.Triangle:
  549. hollowVolume *= .25f;
  550. break;
  551. case HollowShape.Square:
  552. hollowVolume *= 0.499849f * 3.07920140172638f;
  553. break;
  554. case HollowShape.Circle:
  555. hollowVolume *= 0.1963495f * 3.07920140172638f;
  556. break;
  557. default:
  558. hollowVolume = 0;
  559. break;
  560. }
  561. volume *= (1.0f - hollowVolume);
  562. }
  563. }
  564. break;
  565. default:
  566. break;
  567. }
  568. float taperX1;
  569. float taperY1;
  570. float taperX;
  571. float taperY;
  572. float pathBegin;
  573. float pathEnd;
  574. float profileBegin;
  575. float profileEnd;
  576. if (_pbs.PathCurve == (byte)Extrusion.Straight || _pbs.PathCurve == (byte)Extrusion.Flexible)
  577. {
  578. taperX1 = _pbs.PathScaleX * 0.01f;
  579. if (taperX1 > 1.0f)
  580. taperX1 = 2.0f - taperX1;
  581. taperX = 1.0f - taperX1;
  582. taperY1 = _pbs.PathScaleY * 0.01f;
  583. if (taperY1 > 1.0f)
  584. taperY1 = 2.0f - taperY1;
  585. taperY = 1.0f - taperY1;
  586. }
  587. else
  588. {
  589. taperX = _pbs.PathTaperX * 0.01f;
  590. if (taperX < 0.0f)
  591. taperX = -taperX;
  592. taperX1 = 1.0f - taperX;
  593. taperY = _pbs.PathTaperY * 0.01f;
  594. if (taperY < 0.0f)
  595. taperY = -taperY;
  596. taperY1 = 1.0f - taperY;
  597. }
  598. volume *= (taperX1 * taperY1 + 0.5f * (taperX1 * taperY + taperX * taperY1) + 0.3333333333f * taperX * taperY);
  599. pathBegin = (float)_pbs.PathBegin * 2.0e-5f;
  600. pathEnd = 1.0f - (float)_pbs.PathEnd * 2.0e-5f;
  601. volume *= (pathEnd - pathBegin);
  602. // this is crude aproximation
  603. profileBegin = (float)_pbs.ProfileBegin * 2.0e-5f;
  604. profileEnd = 1.0f - (float)_pbs.ProfileEnd * 2.0e-5f;
  605. volume *= (profileEnd - profileBegin);
  606. returnMass = m_density * volume;
  607. if (returnMass <= 0)
  608. returnMass = 0.0001f;//ckrinke: Mass must be greater then zero.
  609. // else if (returnMass > _parent_scene.maximumMassObject)
  610. // returnMass = _parent_scene.maximumMassObject;
  611. // Recursively calculate mass
  612. bool HasChildPrim = false;
  613. lock (childrenPrim)
  614. {
  615. if (childrenPrim.Count > 0)
  616. {
  617. HasChildPrim = true;
  618. }
  619. }
  620. if (HasChildPrim)
  621. {
  622. OdePrim[] childPrimArr = new OdePrim[0];
  623. lock (childrenPrim)
  624. childPrimArr = childrenPrim.ToArray();
  625. for (int i = 0; i < childPrimArr.Length; i++)
  626. {
  627. if (childPrimArr[i] != null && !childPrimArr[i].m_taintremove)
  628. returnMass += childPrimArr[i].CalculateMass();
  629. // failsafe, this shouldn't happen but with OpenSim, you never know :)
  630. if (i > 256)
  631. break;
  632. }
  633. }
  634. if (returnMass > _parent_scene.maximumMassObject)
  635. returnMass = _parent_scene.maximumMassObject;
  636. return returnMass;
  637. }
  638. #endregion
  639. private void setMass()
  640. {
  641. if (Body != (IntPtr) 0)
  642. {
  643. float newmass = CalculateMass();
  644. //m_log.Info("[PHYSICS]: New Mass: " + newmass.ToString());
  645. d.MassSetBoxTotal(out pMass, newmass, _size.X, _size.Y, _size.Z);
  646. d.BodySetMass(Body, ref pMass);
  647. }
  648. }
  649. private void setAngularVelocity(float x, float y, float z)
  650. {
  651. if (Body != (IntPtr)0)
  652. {
  653. d.BodySetAngularVel(Body, x, y, z);
  654. }
  655. }
  656. /// <summary>
  657. /// Stop a prim from being subject to physics.
  658. /// </summary>
  659. internal void disableBody()
  660. {
  661. //this kills the body so things like 'mesh' can re-create it.
  662. lock (this)
  663. {
  664. if (!childPrim)
  665. {
  666. if (Body != IntPtr.Zero)
  667. {
  668. _parent_scene.DeactivatePrim(this);
  669. m_collisionCategories &= ~CollisionCategories.Body;
  670. m_collisionFlags &= ~(CollisionCategories.Wind | CollisionCategories.Land);
  671. if (m_assetFailed)
  672. {
  673. d.GeomSetCategoryBits(prim_geom, 0);
  674. d.GeomSetCollideBits(prim_geom, 0);
  675. }
  676. else
  677. {
  678. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  679. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  680. }
  681. d.BodyDestroy(Body);
  682. lock (childrenPrim)
  683. {
  684. if (childrenPrim.Count > 0)
  685. {
  686. foreach (OdePrim prm in childrenPrim)
  687. {
  688. _parent_scene.DeactivatePrim(prm);
  689. prm.Body = IntPtr.Zero;
  690. }
  691. }
  692. }
  693. Body = IntPtr.Zero;
  694. }
  695. }
  696. else
  697. {
  698. _parent_scene.DeactivatePrim(this);
  699. m_collisionCategories &= ~CollisionCategories.Body;
  700. m_collisionFlags &= ~(CollisionCategories.Wind | CollisionCategories.Land);
  701. if (m_assetFailed)
  702. {
  703. d.GeomSetCategoryBits(prim_geom, 0);
  704. d.GeomSetCollideBits(prim_geom, 0);
  705. }
  706. else
  707. {
  708. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  709. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  710. }
  711. Body = IntPtr.Zero;
  712. }
  713. }
  714. m_disabled = true;
  715. m_collisionscore = 0;
  716. }
  717. private static Dictionary<IMesh, IntPtr> m_MeshToTriMeshMap = new Dictionary<IMesh, IntPtr>();
  718. private void setMesh(OdeScene parent_scene, IMesh mesh)
  719. {
  720. // m_log.DebugFormat("[ODE PRIM]: Setting mesh on {0} to {1}", Name, mesh);
  721. // This sleeper is there to moderate how long it takes between
  722. // setting up the mesh and pre-processing it when we get rapid fire mesh requests on a single object
  723. //Thread.Sleep(10);
  724. //Kill Body so that mesh can re-make the geom
  725. if (IsPhysical && Body != IntPtr.Zero)
  726. {
  727. if (childPrim)
  728. {
  729. if (_parent != null)
  730. {
  731. OdePrim parent = (OdePrim)_parent;
  732. parent.ChildDelink(this);
  733. }
  734. }
  735. else
  736. {
  737. disableBody();
  738. }
  739. }
  740. IntPtr vertices, indices;
  741. int vertexCount, indexCount;
  742. int vertexStride, triStride;
  743. mesh.getVertexListAsPtrToFloatArray(out vertices, out vertexStride, out vertexCount); // Note, that vertices are fixed in unmanaged heap
  744. mesh.getIndexListAsPtrToIntArray(out indices, out triStride, out indexCount); // Also fixed, needs release after usage
  745. m_expectedCollisionContacts = indexCount;
  746. mesh.releaseSourceMeshData(); // free up the original mesh data to save memory
  747. // We must lock here since m_MeshToTriMeshMap is static and multiple scene threads may call this method at
  748. // the same time.
  749. lock (m_MeshToTriMeshMap)
  750. {
  751. if (m_MeshToTriMeshMap.ContainsKey(mesh))
  752. {
  753. _triMeshData = m_MeshToTriMeshMap[mesh];
  754. }
  755. else
  756. {
  757. _triMeshData = d.GeomTriMeshDataCreate();
  758. d.GeomTriMeshDataBuildSimple(_triMeshData, vertices, vertexStride, vertexCount, indices, indexCount, triStride);
  759. d.GeomTriMeshDataPreprocess(_triMeshData);
  760. m_MeshToTriMeshMap[mesh] = _triMeshData;
  761. }
  762. }
  763. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  764. try
  765. {
  766. SetGeom(d.CreateTriMesh(m_targetSpace, _triMeshData, parent_scene.triCallback, null, null));
  767. }
  768. catch (AccessViolationException)
  769. {
  770. m_log.ErrorFormat("[PHYSICS]: MESH LOCKED FOR {0}", Name);
  771. return;
  772. }
  773. // if (IsPhysical && Body == (IntPtr) 0)
  774. // {
  775. // Recreate the body
  776. // m_interpenetrationcount = 0;
  777. // m_collisionscore = 0;
  778. // enableBody();
  779. // }
  780. }
  781. internal void ProcessTaints()
  782. {
  783. #if SPAM
  784. Console.WriteLine("ZProcessTaints for " + Name);
  785. #endif
  786. // This must be processed as the very first taint so that later operations have a prim_geom to work with
  787. // if this is a new prim.
  788. if (m_taintadd)
  789. changeadd();
  790. if (!_position.ApproxEquals(m_taintposition, 0f))
  791. changemove();
  792. if (m_taintrot != _orientation)
  793. {
  794. if (childPrim && IsPhysical) // For physical child prim...
  795. {
  796. rotate();
  797. // KF: ODE will also rotate the parent prim!
  798. // so rotate the root back to where it was
  799. OdePrim parent = (OdePrim)_parent;
  800. parent.rotate();
  801. }
  802. else
  803. {
  804. //Just rotate the prim
  805. rotate();
  806. }
  807. }
  808. if (m_taintPhysics != IsPhysical && !(m_taintparent != _parent))
  809. changePhysicsStatus();
  810. if (!_size.ApproxEquals(m_taintsize, 0f))
  811. changesize();
  812. if (m_taintshape)
  813. changeshape();
  814. if (m_taintforce)
  815. changeAddForce();
  816. if (m_taintaddangularforce)
  817. changeAddAngularForce();
  818. if (!m_taintTorque.ApproxEquals(Vector3.Zero, 0.001f))
  819. changeSetTorque();
  820. if (m_taintdisable)
  821. changedisable();
  822. if (m_taintselected != m_isSelected)
  823. changeSelectedStatus();
  824. if (!m_taintVelocity.ApproxEquals(Vector3.Zero, 0.001f))
  825. changevelocity();
  826. if (m_taintparent != _parent)
  827. changelink();
  828. if (m_taintCollidesWater != m_collidesWater)
  829. changefloatonwater();
  830. if (!m_angularlock.ApproxEquals(m_taintAngularLock,0f))
  831. changeAngularLock();
  832. }
  833. /// <summary>
  834. /// Change prim in response to an angular lock taint.
  835. /// </summary>
  836. private void changeAngularLock()
  837. {
  838. // do we have a Physical object?
  839. if (Body != IntPtr.Zero)
  840. {
  841. //Check that we have a Parent
  842. //If we have a parent then we're not authorative here
  843. if (_parent == null)
  844. {
  845. if (!m_taintAngularLock.ApproxEquals(Vector3.One, 0f))
  846. {
  847. //d.BodySetFiniteRotationMode(Body, 0);
  848. //d.BodySetFiniteRotationAxis(Body,m_taintAngularLock.X,m_taintAngularLock.Y,m_taintAngularLock.Z);
  849. createAMotor(m_taintAngularLock);
  850. }
  851. else
  852. {
  853. if (Amotor != IntPtr.Zero)
  854. {
  855. d.JointDestroy(Amotor);
  856. Amotor = IntPtr.Zero;
  857. }
  858. }
  859. }
  860. }
  861. // Store this for later in case we get turned into a separate body
  862. m_angularlock = m_taintAngularLock;
  863. }
  864. /// <summary>
  865. /// Change prim in response to a link taint.
  866. /// </summary>
  867. private void changelink()
  868. {
  869. // If the newly set parent is not null
  870. // create link
  871. if (_parent == null && m_taintparent != null)
  872. {
  873. if (m_taintparent.PhysicsActorType == (int)ActorTypes.Prim)
  874. {
  875. OdePrim obj = (OdePrim)m_taintparent;
  876. //obj.disableBody();
  877. //Console.WriteLine("changelink calls ParentPrim");
  878. obj.AddChildPrim(this);
  879. /*
  880. if (obj.Body != (IntPtr)0 && Body != (IntPtr)0 && obj.Body != Body)
  881. {
  882. _linkJointGroup = d.JointGroupCreate(0);
  883. m_linkJoint = d.JointCreateFixed(_parent_scene.world, _linkJointGroup);
  884. d.JointAttach(m_linkJoint, obj.Body, Body);
  885. d.JointSetFixed(m_linkJoint);
  886. }
  887. */
  888. }
  889. }
  890. // If the newly set parent is null
  891. // destroy link
  892. else if (_parent != null && m_taintparent == null)
  893. {
  894. //Console.WriteLine(" changelink B");
  895. if (_parent is OdePrim)
  896. {
  897. OdePrim obj = (OdePrim)_parent;
  898. obj.ChildDelink(this);
  899. childPrim = false;
  900. //_parent = null;
  901. }
  902. /*
  903. if (Body != (IntPtr)0 && _linkJointGroup != (IntPtr)0)
  904. d.JointGroupDestroy(_linkJointGroup);
  905. _linkJointGroup = (IntPtr)0;
  906. m_linkJoint = (IntPtr)0;
  907. */
  908. }
  909. _parent = m_taintparent;
  910. m_taintPhysics = IsPhysical;
  911. }
  912. /// <summary>
  913. /// Add a child prim to this parent prim.
  914. /// </summary>
  915. /// <param name="prim">Child prim</param>
  916. private void AddChildPrim(OdePrim prim)
  917. {
  918. if (LocalID == prim.LocalID)
  919. return;
  920. if (Body == IntPtr.Zero)
  921. {
  922. Body = d.BodyCreate(_parent_scene.world);
  923. setMass();
  924. }
  925. lock (childrenPrim)
  926. {
  927. if (childrenPrim.Contains(prim))
  928. return;
  929. // m_log.DebugFormat(
  930. // "[ODE PRIM]: Linking prim {0} {1} to {2} {3}", prim.Name, prim.LocalID, Name, LocalID);
  931. childrenPrim.Add(prim);
  932. foreach (OdePrim prm in childrenPrim)
  933. {
  934. d.Mass m2;
  935. d.MassSetZero(out m2);
  936. d.MassSetBoxTotal(out m2, prm.CalculateMass(), prm._size.X, prm._size.Y, prm._size.Z);
  937. d.Quaternion quat = new d.Quaternion();
  938. quat.W = prm._orientation.W;
  939. quat.X = prm._orientation.X;
  940. quat.Y = prm._orientation.Y;
  941. quat.Z = prm._orientation.Z;
  942. d.Matrix3 mat = new d.Matrix3();
  943. d.RfromQ(out mat, ref quat);
  944. d.MassRotate(ref m2, ref mat);
  945. d.MassTranslate(ref m2, Position.X - prm.Position.X, Position.Y - prm.Position.Y, Position.Z - prm.Position.Z);
  946. d.MassAdd(ref pMass, ref m2);
  947. }
  948. foreach (OdePrim prm in childrenPrim)
  949. {
  950. prm.m_collisionCategories |= CollisionCategories.Body;
  951. prm.m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind);
  952. //Console.WriteLine(" GeomSetCategoryBits 1: " + prm.prim_geom + " - " + (int)prm.m_collisionCategories + " for " + Name);
  953. if (prm.m_assetFailed)
  954. {
  955. d.GeomSetCategoryBits(prm.prim_geom, 0);
  956. d.GeomSetCollideBits(prm.prim_geom, prm.BadMeshAssetCollideBits);
  957. }
  958. else
  959. {
  960. d.GeomSetCategoryBits(prm.prim_geom, (int)prm.m_collisionCategories);
  961. d.GeomSetCollideBits(prm.prim_geom, (int)prm.m_collisionFlags);
  962. }
  963. d.Quaternion quat = new d.Quaternion();
  964. quat.W = prm._orientation.W;
  965. quat.X = prm._orientation.X;
  966. quat.Y = prm._orientation.Y;
  967. quat.Z = prm._orientation.Z;
  968. d.Matrix3 mat = new d.Matrix3();
  969. d.RfromQ(out mat, ref quat);
  970. if (Body != IntPtr.Zero)
  971. {
  972. d.GeomSetBody(prm.prim_geom, Body);
  973. prm.childPrim = true;
  974. d.GeomSetOffsetWorldPosition(prm.prim_geom, prm.Position.X , prm.Position.Y, prm.Position.Z);
  975. //d.GeomSetOffsetPosition(prim.prim_geom,
  976. // (Position.X - prm.Position.X) - pMass.c.X,
  977. // (Position.Y - prm.Position.Y) - pMass.c.Y,
  978. // (Position.Z - prm.Position.Z) - pMass.c.Z);
  979. d.GeomSetOffsetWorldRotation(prm.prim_geom, ref mat);
  980. //d.GeomSetOffsetRotation(prm.prim_geom, ref mat);
  981. d.MassTranslate(ref pMass, -pMass.c.X, -pMass.c.Y, -pMass.c.Z);
  982. d.BodySetMass(Body, ref pMass);
  983. }
  984. else
  985. {
  986. m_log.DebugFormat("[PHYSICS]: {0} ain't got no boooooooooddy, no body", Name);
  987. }
  988. prm.m_interpenetrationcount = 0;
  989. prm.m_collisionscore = 0;
  990. prm.m_disabled = false;
  991. prm.Body = Body;
  992. _parent_scene.ActivatePrim(prm);
  993. }
  994. m_collisionCategories |= CollisionCategories.Body;
  995. m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind);
  996. if (m_assetFailed)
  997. {
  998. d.GeomSetCategoryBits(prim_geom, 0);
  999. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1000. }
  1001. else
  1002. {
  1003. //Console.WriteLine("GeomSetCategoryBits 2: " + prim_geom + " - " + (int)m_collisionCategories + " for " + Name);
  1004. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1005. //Console.WriteLine(" Post GeomSetCategoryBits 2");
  1006. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1007. }
  1008. d.Quaternion quat2 = new d.Quaternion();
  1009. quat2.W = _orientation.W;
  1010. quat2.X = _orientation.X;
  1011. quat2.Y = _orientation.Y;
  1012. quat2.Z = _orientation.Z;
  1013. d.Matrix3 mat2 = new d.Matrix3();
  1014. d.RfromQ(out mat2, ref quat2);
  1015. d.GeomSetBody(prim_geom, Body);
  1016. d.GeomSetOffsetWorldPosition(prim_geom, Position.X - pMass.c.X, Position.Y - pMass.c.Y, Position.Z - pMass.c.Z);
  1017. //d.GeomSetOffsetPosition(prim.prim_geom,
  1018. // (Position.X - prm.Position.X) - pMass.c.X,
  1019. // (Position.Y - prm.Position.Y) - pMass.c.Y,
  1020. // (Position.Z - prm.Position.Z) - pMass.c.Z);
  1021. //d.GeomSetOffsetRotation(prim_geom, ref mat2);
  1022. d.MassTranslate(ref pMass, -pMass.c.X, -pMass.c.Y, -pMass.c.Z);
  1023. d.BodySetMass(Body, ref pMass);
  1024. d.BodySetAutoDisableFlag(Body, true);
  1025. d.BodySetAutoDisableSteps(Body, body_autodisable_frames);
  1026. m_interpenetrationcount = 0;
  1027. m_collisionscore = 0;
  1028. m_disabled = false;
  1029. // The body doesn't already have a finite rotation mode set here
  1030. if ((!m_angularlock.ApproxEquals(Vector3.One, 0f)) && _parent == null)
  1031. {
  1032. createAMotor(m_angularlock);
  1033. }
  1034. d.BodySetPosition(Body, Position.X, Position.Y, Position.Z);
  1035. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1036. m_vehicle.Enable(Body, _parent_scene);
  1037. _parent_scene.ActivatePrim(this);
  1038. }
  1039. }
  1040. private void ChildSetGeom(OdePrim odePrim)
  1041. {
  1042. // m_log.DebugFormat(
  1043. // "[ODE PRIM]: ChildSetGeom {0} {1} for {2} {3}", odePrim.Name, odePrim.LocalID, Name, LocalID);
  1044. //if (IsPhysical && Body != IntPtr.Zero)
  1045. lock (childrenPrim)
  1046. {
  1047. foreach (OdePrim prm in childrenPrim)
  1048. {
  1049. //prm.childPrim = true;
  1050. prm.disableBody();
  1051. //prm.m_taintparent = null;
  1052. //prm._parent = null;
  1053. //prm.m_taintPhysics = false;
  1054. //prm.m_disabled = true;
  1055. //prm.childPrim = false;
  1056. }
  1057. }
  1058. disableBody();
  1059. // Spurious - Body == IntPtr.Zero after disableBody()
  1060. // if (Body != IntPtr.Zero)
  1061. // {
  1062. // _parent_scene.DeactivatePrim(this);
  1063. // }
  1064. lock (childrenPrim)
  1065. {
  1066. foreach (OdePrim prm in childrenPrim)
  1067. {
  1068. //Console.WriteLine("ChildSetGeom calls ParentPrim");
  1069. AddChildPrim(prm);
  1070. }
  1071. }
  1072. }
  1073. private void ChildDelink(OdePrim odePrim)
  1074. {
  1075. // m_log.DebugFormat(
  1076. // "[ODE PRIM]: Delinking prim {0} {1} from {2} {3}", odePrim.Name, odePrim.LocalID, Name, LocalID);
  1077. // Okay, we have a delinked child.. need to rebuild the body.
  1078. lock (childrenPrim)
  1079. {
  1080. foreach (OdePrim prm in childrenPrim)
  1081. {
  1082. prm.childPrim = true;
  1083. prm.disableBody();
  1084. //prm.m_taintparent = null;
  1085. //prm._parent = null;
  1086. //prm.m_taintPhysics = false;
  1087. //prm.m_disabled = true;
  1088. //prm.childPrim = false;
  1089. }
  1090. }
  1091. disableBody();
  1092. lock (childrenPrim)
  1093. {
  1094. //Console.WriteLine("childrenPrim.Remove " + odePrim);
  1095. childrenPrim.Remove(odePrim);
  1096. }
  1097. // Spurious - Body == IntPtr.Zero after disableBody()
  1098. // if (Body != IntPtr.Zero)
  1099. // {
  1100. // _parent_scene.DeactivatePrim(this);
  1101. // }
  1102. lock (childrenPrim)
  1103. {
  1104. foreach (OdePrim prm in childrenPrim)
  1105. {
  1106. //Console.WriteLine("ChildDelink calls ParentPrim");
  1107. AddChildPrim(prm);
  1108. }
  1109. }
  1110. }
  1111. /// <summary>
  1112. /// Change prim in response to a selection taint.
  1113. /// </summary>
  1114. private void changeSelectedStatus()
  1115. {
  1116. if (m_taintselected)
  1117. {
  1118. m_collisionCategories = CollisionCategories.Selected;
  1119. m_collisionFlags = (CollisionCategories.Sensor | CollisionCategories.Space);
  1120. // We do the body disable soft twice because 'in theory' a collision could have happened
  1121. // in between the disabling and the collision properties setting
  1122. // which would wake the physical body up from a soft disabling and potentially cause it to fall
  1123. // through the ground.
  1124. // NOTE FOR JOINTS: this doesn't always work for jointed assemblies because if you select
  1125. // just one part of the assembly, the rest of the assembly is non-selected and still simulating,
  1126. // so that causes the selected part to wake up and continue moving.
  1127. // even if you select all parts of a jointed assembly, it is not guaranteed that the entire
  1128. // assembly will stop simulating during the selection, because of the lack of atomicity
  1129. // of select operations (their processing could be interrupted by a thread switch, causing
  1130. // simulation to continue before all of the selected object notifications trickle down to
  1131. // the physics engine).
  1132. // e.g. we select 100 prims that are connected by joints. non-atomically, the first 50 are
  1133. // selected and disabled. then, due to a thread switch, the selection processing is
  1134. // interrupted and the physics engine continues to simulate, so the last 50 items, whose
  1135. // selection was not yet processed, continues to simulate. this wakes up ALL of the
  1136. // first 50 again. then the last 50 are disabled. then the first 50, which were just woken
  1137. // up, start simulating again, which in turn wakes up the last 50.
  1138. if (IsPhysical)
  1139. {
  1140. disableBodySoft();
  1141. }
  1142. if (m_assetFailed)
  1143. {
  1144. d.GeomSetCategoryBits(prim_geom, 0);
  1145. d.GeomSetCollideBits(prim_geom, 0);
  1146. }
  1147. else
  1148. {
  1149. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1150. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1151. }
  1152. if (IsPhysical)
  1153. {
  1154. disableBodySoft();
  1155. }
  1156. }
  1157. else
  1158. {
  1159. m_collisionCategories = CollisionCategories.Geom;
  1160. if (IsPhysical)
  1161. m_collisionCategories |= CollisionCategories.Body;
  1162. m_collisionFlags = m_default_collisionFlags;
  1163. if (m_collidesLand)
  1164. m_collisionFlags |= CollisionCategories.Land;
  1165. if (m_collidesWater)
  1166. m_collisionFlags |= CollisionCategories.Water;
  1167. if (m_assetFailed)
  1168. {
  1169. d.GeomSetCategoryBits(prim_geom, 0);
  1170. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1171. }
  1172. else
  1173. {
  1174. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1175. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1176. }
  1177. if (IsPhysical)
  1178. {
  1179. if (Body != IntPtr.Zero)
  1180. {
  1181. d.BodySetLinearVel(Body, 0f, 0f, 0f);
  1182. d.BodySetForce(Body, 0, 0, 0);
  1183. enableBodySoft();
  1184. }
  1185. }
  1186. }
  1187. resetCollisionAccounting();
  1188. m_isSelected = m_taintselected;
  1189. }//end changeSelectedStatus
  1190. internal void ResetTaints()
  1191. {
  1192. m_taintposition = _position;
  1193. m_taintrot = _orientation;
  1194. m_taintPhysics = IsPhysical;
  1195. m_taintselected = m_isSelected;
  1196. m_taintsize = _size;
  1197. m_taintshape = false;
  1198. m_taintforce = false;
  1199. m_taintdisable = false;
  1200. m_taintVelocity = Vector3.Zero;
  1201. }
  1202. /// <summary>
  1203. /// Create a geometry for the given mesh in the given target space.
  1204. /// </summary>
  1205. /// <param name="m_targetSpace"></param>
  1206. /// <param name="mesh">If null, then a mesh is used that is based on the profile shape data.</param>
  1207. private void CreateGeom(IntPtr m_targetSpace, IMesh mesh)
  1208. {
  1209. #if SPAM
  1210. Console.WriteLine("CreateGeom:");
  1211. #endif
  1212. if (mesh != null)
  1213. {
  1214. setMesh(_parent_scene, mesh);
  1215. }
  1216. else
  1217. {
  1218. if (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1)
  1219. {
  1220. if (_size.X == _size.Y && _size.Y == _size.Z && _size.X == _size.Z)
  1221. {
  1222. if (((_size.X / 2f) > 0f))
  1223. {
  1224. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1225. try
  1226. {
  1227. //Console.WriteLine(" CreateGeom 1");
  1228. SetGeom(d.CreateSphere(m_targetSpace, _size.X / 2));
  1229. m_expectedCollisionContacts = 3;
  1230. }
  1231. catch (AccessViolationException)
  1232. {
  1233. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1234. return;
  1235. }
  1236. }
  1237. else
  1238. {
  1239. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1240. try
  1241. {
  1242. //Console.WriteLine(" CreateGeom 2");
  1243. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1244. m_expectedCollisionContacts = 4;
  1245. }
  1246. catch (AccessViolationException)
  1247. {
  1248. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1249. return;
  1250. }
  1251. }
  1252. }
  1253. else
  1254. {
  1255. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1256. try
  1257. {
  1258. //Console.WriteLine(" CreateGeom 3");
  1259. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1260. m_expectedCollisionContacts = 4;
  1261. }
  1262. catch (AccessViolationException)
  1263. {
  1264. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1265. return;
  1266. }
  1267. }
  1268. }
  1269. else
  1270. {
  1271. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1272. try
  1273. {
  1274. //Console.WriteLine(" CreateGeom 4");
  1275. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1276. m_expectedCollisionContacts = 4;
  1277. }
  1278. catch (AccessViolationException)
  1279. {
  1280. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1281. return;
  1282. }
  1283. }
  1284. }
  1285. }
  1286. /// <summary>
  1287. /// Remove the existing geom from this prim.
  1288. /// </summary>
  1289. /// <param name="m_targetSpace"></param>
  1290. /// <param name="mesh">If null, then a mesh is used that is based on the profile shape data.</param>
  1291. /// <returns>true if the geom was successfully removed, false if it was already gone or the remove failed.</returns>
  1292. internal bool RemoveGeom()
  1293. {
  1294. if (prim_geom != IntPtr.Zero)
  1295. {
  1296. try
  1297. {
  1298. _parent_scene.geom_name_map.Remove(prim_geom);
  1299. _parent_scene.actor_name_map.Remove(prim_geom);
  1300. d.GeomDestroy(prim_geom);
  1301. m_expectedCollisionContacts = 0;
  1302. prim_geom = IntPtr.Zero;
  1303. }
  1304. catch (System.AccessViolationException)
  1305. {
  1306. prim_geom = IntPtr.Zero;
  1307. m_expectedCollisionContacts = 0;
  1308. m_log.ErrorFormat("[PHYSICS]: PrimGeom dead for {0}", Name);
  1309. return false;
  1310. }
  1311. return true;
  1312. }
  1313. else
  1314. {
  1315. m_log.WarnFormat(
  1316. "[ODE PRIM]: Called RemoveGeom() on {0} {1} where geometry was already null.", Name, LocalID);
  1317. return false;
  1318. }
  1319. }
  1320. /// <summary>
  1321. /// Add prim in response to an add taint.
  1322. /// </summary>
  1323. private void changeadd()
  1324. {
  1325. // m_log.DebugFormat("[ODE PRIM]: Adding prim {0}", Name);
  1326. int[] iprimspaceArrItem = _parent_scene.calculateSpaceArrayItemFromPos(_position);
  1327. IntPtr targetspace = _parent_scene.calculateSpaceForGeom(_position);
  1328. if (targetspace == IntPtr.Zero)
  1329. targetspace = _parent_scene.createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  1330. m_targetSpace = targetspace;
  1331. IMesh mesh = null;
  1332. if (_parent_scene.needsMeshing(_pbs))
  1333. {
  1334. // Don't need to re-enable body.. it's done in SetMesh
  1335. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, _parent_scene.meshSculptLOD, IsPhysical);
  1336. // createmesh returns null when it's a shape that isn't a cube.
  1337. // m_log.Debug(m_localID);
  1338. if (mesh == null)
  1339. CheckMeshAsset();
  1340. else
  1341. m_assetFailed = false;
  1342. }
  1343. #if SPAM
  1344. Console.WriteLine("changeadd 1");
  1345. #endif
  1346. CreateGeom(m_targetSpace, mesh);
  1347. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1348. d.Quaternion myrot = new d.Quaternion();
  1349. myrot.X = _orientation.X;
  1350. myrot.Y = _orientation.Y;
  1351. myrot.Z = _orientation.Z;
  1352. myrot.W = _orientation.W;
  1353. d.GeomSetQuaternion(prim_geom, ref myrot);
  1354. if (IsPhysical && Body == IntPtr.Zero)
  1355. enableBody();
  1356. changeSelectedStatus();
  1357. m_taintadd = false;
  1358. }
  1359. /// <summary>
  1360. /// Move prim in response to a move taint.
  1361. /// </summary>
  1362. private void changemove()
  1363. {
  1364. if (IsPhysical)
  1365. {
  1366. if (!m_disabled && !m_taintremove && !childPrim)
  1367. {
  1368. if (Body == IntPtr.Zero)
  1369. enableBody();
  1370. //Prim auto disable after 20 frames,
  1371. //if you move it, re-enable the prim manually.
  1372. if (_parent != null)
  1373. {
  1374. if (m_linkJoint != IntPtr.Zero)
  1375. {
  1376. d.JointDestroy(m_linkJoint);
  1377. m_linkJoint = IntPtr.Zero;
  1378. }
  1379. }
  1380. if (Body != IntPtr.Zero)
  1381. {
  1382. d.BodySetPosition(Body, _position.X, _position.Y, _position.Z);
  1383. if (_parent != null)
  1384. {
  1385. OdePrim odParent = (OdePrim)_parent;
  1386. if (Body != (IntPtr)0 && odParent.Body != (IntPtr)0 && Body != odParent.Body)
  1387. {
  1388. // KF: Fixed Joints were removed? Anyway - this Console.WriteLine does not show up, so routine is not used??
  1389. Console.WriteLine(" JointCreateFixed");
  1390. m_linkJoint = d.JointCreateFixed(_parent_scene.world, _linkJointGroup);
  1391. d.JointAttach(m_linkJoint, Body, odParent.Body);
  1392. d.JointSetFixed(m_linkJoint);
  1393. }
  1394. }
  1395. d.BodyEnable(Body);
  1396. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1397. {
  1398. m_vehicle.Enable(Body, _parent_scene);
  1399. }
  1400. }
  1401. else
  1402. {
  1403. m_log.WarnFormat("[PHYSICS]: Body for {0} still null after enableBody(). This is a crash scenario.", Name);
  1404. }
  1405. }
  1406. //else
  1407. // {
  1408. //m_log.Debug("[BUG]: race!");
  1409. //}
  1410. }
  1411. // string primScenAvatarIn = _parent_scene.whichspaceamIin(_position);
  1412. // int[] arrayitem = _parent_scene.calculateSpaceArrayItemFromPos(_position);
  1413. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1414. IntPtr tempspace = _parent_scene.recalculateSpaceForGeom(prim_geom, _position, m_targetSpace);
  1415. m_targetSpace = tempspace;
  1416. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1417. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1418. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1419. d.SpaceAdd(m_targetSpace, prim_geom);
  1420. changeSelectedStatus();
  1421. resetCollisionAccounting();
  1422. m_taintposition = _position;
  1423. }
  1424. internal void Move(float timestep)
  1425. {
  1426. float fx = 0;
  1427. float fy = 0;
  1428. float fz = 0;
  1429. if (IsPhysical && (Body != IntPtr.Zero) && !m_isSelected && !childPrim) // KF: Only move root prims.
  1430. {
  1431. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1432. {
  1433. // 'VEHICLES' are dealt with in ODEDynamics.cs
  1434. m_vehicle.Step(timestep, _parent_scene);
  1435. }
  1436. else
  1437. {
  1438. //Console.WriteLine("Move " + Name);
  1439. if (!d.BodyIsEnabled (Body)) d.BodyEnable (Body); // KF add 161009
  1440. // NON-'VEHICLES' are dealt with here
  1441. // if (d.BodyIsEnabled(Body) && !m_angularlock.ApproxEquals(Vector3.Zero, 0.003f))
  1442. // {
  1443. // d.Vector3 avel2 = d.BodyGetAngularVel(Body);
  1444. // /*
  1445. // if (m_angularlock.X == 1)
  1446. // avel2.X = 0;
  1447. // if (m_angularlock.Y == 1)
  1448. // avel2.Y = 0;
  1449. // if (m_angularlock.Z == 1)
  1450. // avel2.Z = 0;
  1451. // d.BodySetAngularVel(Body, avel2.X, avel2.Y, avel2.Z);
  1452. // */
  1453. // }
  1454. //float PID_P = 900.0f;
  1455. float m_mass = CalculateMass();
  1456. // fz = 0f;
  1457. //m_log.Info(m_collisionFlags.ToString());
  1458. //KF: m_buoyancy should be set by llSetBuoyancy() for non-vehicle.
  1459. // would come from SceneObjectPart.cs, public void SetBuoyancy(float fvalue) , PhysActor.Buoyancy = fvalue; ??
  1460. // m_buoyancy: (unlimited value) <0=Falls fast; 0=1g; 1=0g; >1 = floats up
  1461. // gravityz multiplier = 1 - m_buoyancy
  1462. fz = _parent_scene.gravityz * (1.0f - m_buoyancy) * m_mass;
  1463. if (PIDActive)
  1464. {
  1465. //Console.WriteLine("PID " + Name);
  1466. // KF - this is for object move? eg. llSetPos() ?
  1467. //if (!d.BodyIsEnabled(Body))
  1468. //d.BodySetForce(Body, 0f, 0f, 0f);
  1469. // If we're using the PID controller, then we have no gravity
  1470. //fz = (-1 * _parent_scene.gravityz) * m_mass; //KF: ?? Prims have no global gravity,so simply...
  1471. fz = 0f;
  1472. // no lock; for now it's only called from within Simulate()
  1473. // If the PID Controller isn't active then we set our force
  1474. // calculating base velocity to the current position
  1475. if ((m_PIDTau < 1) && (m_PIDTau != 0))
  1476. {
  1477. //PID_G = PID_G / m_PIDTau;
  1478. m_PIDTau = 1;
  1479. }
  1480. if ((PID_G - m_PIDTau) <= 0)
  1481. {
  1482. PID_G = m_PIDTau + 1;
  1483. }
  1484. //PidStatus = true;
  1485. // PhysicsVector vec = new PhysicsVector();
  1486. d.Vector3 vel = d.BodyGetLinearVel(Body);
  1487. d.Vector3 pos = d.BodyGetPosition(Body);
  1488. _target_velocity =
  1489. new Vector3(
  1490. (m_PIDTarget.X - pos.X) * ((PID_G - m_PIDTau) * timestep),
  1491. (m_PIDTarget.Y - pos.Y) * ((PID_G - m_PIDTau) * timestep),
  1492. (m_PIDTarget.Z - pos.Z) * ((PID_G - m_PIDTau) * timestep)
  1493. );
  1494. // if velocity is zero, use position control; otherwise, velocity control
  1495. if (_target_velocity.ApproxEquals(Vector3.Zero,0.1f))
  1496. {
  1497. // keep track of where we stopped. No more slippin' & slidin'
  1498. // We only want to deactivate the PID Controller if we think we want to have our surrogate
  1499. // react to the physics scene by moving it's position.
  1500. // Avatar to Avatar collisions
  1501. // Prim to avatar collisions
  1502. //fx = (_target_velocity.X - vel.X) * (PID_D) + (_zeroPosition.X - pos.X) * (PID_P * 2);
  1503. //fy = (_target_velocity.Y - vel.Y) * (PID_D) + (_zeroPosition.Y - pos.Y) * (PID_P * 2);
  1504. //fz = fz + (_target_velocity.Z - vel.Z) * (PID_D) + (_zeroPosition.Z - pos.Z) * PID_P;
  1505. d.BodySetPosition(Body, m_PIDTarget.X, m_PIDTarget.Y, m_PIDTarget.Z);
  1506. d.BodySetLinearVel(Body, 0, 0, 0);
  1507. d.BodyAddForce(Body, 0, 0, fz);
  1508. return;
  1509. }
  1510. else
  1511. {
  1512. _zeroFlag = false;
  1513. // We're flying and colliding with something
  1514. fx = ((_target_velocity.X) - vel.X) * (PID_D);
  1515. fy = ((_target_velocity.Y) - vel.Y) * (PID_D);
  1516. // vec.Z = (_target_velocity.Z - vel.Z) * PID_D + (_zeroPosition.Z - pos.Z) * PID_P;
  1517. fz = fz + ((_target_velocity.Z - vel.Z) * (PID_D) * m_mass);
  1518. }
  1519. } // end if (PIDActive)
  1520. // Hover PID Controller needs to be mutually exlusive to MoveTo PID controller
  1521. if (m_useHoverPID && !PIDActive)
  1522. {
  1523. //Console.WriteLine("Hover " + Name);
  1524. // If we're using the PID controller, then we have no gravity
  1525. fz = (-1 * _parent_scene.gravityz) * m_mass;
  1526. // no lock; for now it's only called from within Simulate()
  1527. // If the PID Controller isn't active then we set our force
  1528. // calculating base velocity to the current position
  1529. if ((m_PIDTau < 1))
  1530. {
  1531. PID_G = PID_G / m_PIDTau;
  1532. }
  1533. if ((PID_G - m_PIDTau) <= 0)
  1534. {
  1535. PID_G = m_PIDTau + 1;
  1536. }
  1537. // Where are we, and where are we headed?
  1538. d.Vector3 pos = d.BodyGetPosition(Body);
  1539. d.Vector3 vel = d.BodyGetLinearVel(Body);
  1540. // Non-Vehicles have a limited set of Hover options.
  1541. // determine what our target height really is based on HoverType
  1542. switch (m_PIDHoverType)
  1543. {
  1544. case PIDHoverType.Ground:
  1545. m_groundHeight = _parent_scene.GetTerrainHeightAtXY(pos.X, pos.Y);
  1546. m_targetHoverHeight = m_groundHeight + m_PIDHoverHeight;
  1547. break;
  1548. case PIDHoverType.GroundAndWater:
  1549. m_groundHeight = _parent_scene.GetTerrainHeightAtXY(pos.X, pos.Y);
  1550. m_waterHeight = _parent_scene.GetWaterLevel();
  1551. if (m_groundHeight > m_waterHeight)
  1552. {
  1553. m_targetHoverHeight = m_groundHeight + m_PIDHoverHeight;
  1554. }
  1555. else
  1556. {
  1557. m_targetHoverHeight = m_waterHeight + m_PIDHoverHeight;
  1558. }
  1559. break;
  1560. } // end switch (m_PIDHoverType)
  1561. _target_velocity =
  1562. new Vector3(0.0f, 0.0f,
  1563. (m_targetHoverHeight - pos.Z) * ((PID_G - m_PIDHoverTau) * timestep)
  1564. );
  1565. // if velocity is zero, use position control; otherwise, velocity control
  1566. if (_target_velocity.ApproxEquals(Vector3.Zero, 0.1f))
  1567. {
  1568. // keep track of where we stopped. No more slippin' & slidin'
  1569. // We only want to deactivate the PID Controller if we think we want to have our surrogate
  1570. // react to the physics scene by moving it's position.
  1571. // Avatar to Avatar collisions
  1572. // Prim to avatar collisions
  1573. d.BodySetPosition(Body, pos.X, pos.Y, m_targetHoverHeight);
  1574. d.BodySetLinearVel(Body, vel.X, vel.Y, 0);
  1575. d.BodyAddForce(Body, 0, 0, fz);
  1576. return;
  1577. }
  1578. else
  1579. {
  1580. _zeroFlag = false;
  1581. // We're flying and colliding with something
  1582. fz = fz + ((_target_velocity.Z - vel.Z) * (PID_D) * m_mass);
  1583. }
  1584. }
  1585. fx *= m_mass;
  1586. fy *= m_mass;
  1587. //fz *= m_mass;
  1588. fx += m_force.X;
  1589. fy += m_force.Y;
  1590. fz += m_force.Z;
  1591. //m_log.Info("[OBJPID]: X:" + fx.ToString() + " Y:" + fy.ToString() + " Z:" + fz.ToString());
  1592. if (fx != 0 || fy != 0 || fz != 0)
  1593. {
  1594. //m_taintdisable = true;
  1595. //base.RaiseOutOfBounds(Position);
  1596. //d.BodySetLinearVel(Body, fx, fy, 0f);
  1597. if (!d.BodyIsEnabled(Body))
  1598. {
  1599. // A physical body at rest on a surface will auto-disable after a while,
  1600. // this appears to re-enable it incase the surface it is upon vanishes,
  1601. // and the body should fall again.
  1602. d.BodySetLinearVel(Body, 0f, 0f, 0f);
  1603. d.BodySetForce(Body, 0, 0, 0);
  1604. enableBodySoft();
  1605. }
  1606. // 35x10 = 350n times the mass per second applied maximum.
  1607. float nmax = 35f * m_mass;
  1608. float nmin = -35f * m_mass;
  1609. if (fx > nmax)
  1610. fx = nmax;
  1611. if (fx < nmin)
  1612. fx = nmin;
  1613. if (fy > nmax)
  1614. fy = nmax;
  1615. if (fy < nmin)
  1616. fy = nmin;
  1617. d.BodyAddForce(Body, fx, fy, fz);
  1618. //Console.WriteLine("AddForce " + fx + "," + fy + "," + fz);
  1619. }
  1620. }
  1621. }
  1622. else
  1623. { // is not physical, or is not a body or is selected
  1624. // _zeroPosition = d.BodyGetPosition(Body);
  1625. return;
  1626. //Console.WriteLine("Nothing " + Name);
  1627. }
  1628. }
  1629. private void rotate()
  1630. {
  1631. d.Quaternion myrot = new d.Quaternion();
  1632. myrot.X = _orientation.X;
  1633. myrot.Y = _orientation.Y;
  1634. myrot.Z = _orientation.Z;
  1635. myrot.W = _orientation.W;
  1636. if (Body != IntPtr.Zero)
  1637. {
  1638. // KF: If this is a root prim do BodySet
  1639. d.BodySetQuaternion(Body, ref myrot);
  1640. if (IsPhysical)
  1641. {
  1642. if (!m_angularlock.ApproxEquals(Vector3.One, 0f))
  1643. createAMotor(m_angularlock);
  1644. }
  1645. }
  1646. else
  1647. {
  1648. // daughter prim, do Geom set
  1649. d.GeomSetQuaternion(prim_geom, ref myrot);
  1650. }
  1651. resetCollisionAccounting();
  1652. m_taintrot = _orientation;
  1653. }
  1654. private void resetCollisionAccounting()
  1655. {
  1656. m_collisionscore = 0;
  1657. m_interpenetrationcount = 0;
  1658. m_disabled = false;
  1659. }
  1660. /// <summary>
  1661. /// Change prim in response to a disable taint.
  1662. /// </summary>
  1663. private void changedisable()
  1664. {
  1665. m_disabled = true;
  1666. if (Body != IntPtr.Zero)
  1667. {
  1668. d.BodyDisable(Body);
  1669. Body = IntPtr.Zero;
  1670. }
  1671. m_taintdisable = false;
  1672. }
  1673. /// <summary>
  1674. /// Change prim in response to a physics status taint
  1675. /// </summary>
  1676. private void changePhysicsStatus()
  1677. {
  1678. if (IsPhysical)
  1679. {
  1680. if (Body == IntPtr.Zero)
  1681. {
  1682. if (_pbs.SculptEntry && _parent_scene.meshSculptedPrim)
  1683. {
  1684. changeshape();
  1685. }
  1686. else
  1687. {
  1688. enableBody();
  1689. }
  1690. }
  1691. }
  1692. else
  1693. {
  1694. if (Body != IntPtr.Zero)
  1695. {
  1696. if (_pbs.SculptEntry && _parent_scene.meshSculptedPrim)
  1697. {
  1698. RemoveGeom();
  1699. //Console.WriteLine("changePhysicsStatus for " + Name);
  1700. changeadd();
  1701. }
  1702. if (childPrim)
  1703. {
  1704. if (_parent != null)
  1705. {
  1706. OdePrim parent = (OdePrim)_parent;
  1707. parent.ChildDelink(this);
  1708. }
  1709. }
  1710. else
  1711. {
  1712. disableBody();
  1713. }
  1714. }
  1715. }
  1716. changeSelectedStatus();
  1717. resetCollisionAccounting();
  1718. m_taintPhysics = IsPhysical;
  1719. }
  1720. /// <summary>
  1721. /// Change prim in response to a size taint.
  1722. /// </summary>
  1723. private void changesize()
  1724. {
  1725. #if SPAM
  1726. m_log.DebugFormat("[ODE PRIM]: Called changesize");
  1727. #endif
  1728. if (_size.X <= 0) _size.X = 0.01f;
  1729. if (_size.Y <= 0) _size.Y = 0.01f;
  1730. if (_size.Z <= 0) _size.Z = 0.01f;
  1731. //kill body to rebuild
  1732. if (IsPhysical && Body != IntPtr.Zero)
  1733. {
  1734. if (childPrim)
  1735. {
  1736. if (_parent != null)
  1737. {
  1738. OdePrim parent = (OdePrim)_parent;
  1739. parent.ChildDelink(this);
  1740. }
  1741. }
  1742. else
  1743. {
  1744. disableBody();
  1745. }
  1746. }
  1747. if (d.SpaceQuery(m_targetSpace, prim_geom))
  1748. {
  1749. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1750. d.SpaceRemove(m_targetSpace, prim_geom);
  1751. }
  1752. RemoveGeom();
  1753. // we don't need to do space calculation because the client sends a position update also.
  1754. IMesh mesh = null;
  1755. // Construction of new prim
  1756. if (_parent_scene.needsMeshing(_pbs))
  1757. {
  1758. float meshlod = _parent_scene.meshSculptLOD;
  1759. if (IsPhysical)
  1760. meshlod = _parent_scene.MeshSculptphysicalLOD;
  1761. // Don't need to re-enable body.. it's done in SetMesh
  1762. if (_parent_scene.needsMeshing(_pbs))
  1763. {
  1764. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical);
  1765. if (mesh == null)
  1766. CheckMeshAsset();
  1767. else
  1768. m_assetFailed = false;
  1769. }
  1770. }
  1771. CreateGeom(m_targetSpace, mesh);
  1772. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1773. d.Quaternion myrot = new d.Quaternion();
  1774. myrot.X = _orientation.X;
  1775. myrot.Y = _orientation.Y;
  1776. myrot.Z = _orientation.Z;
  1777. myrot.W = _orientation.W;
  1778. d.GeomSetQuaternion(prim_geom, ref myrot);
  1779. //d.GeomBoxSetLengths(prim_geom, _size.X, _size.Y, _size.Z);
  1780. if (IsPhysical && Body == IntPtr.Zero && !childPrim)
  1781. {
  1782. // Re creates body on size.
  1783. // EnableBody also does setMass()
  1784. enableBody();
  1785. d.BodyEnable(Body);
  1786. }
  1787. changeSelectedStatus();
  1788. if (childPrim)
  1789. {
  1790. if (_parent is OdePrim)
  1791. {
  1792. OdePrim parent = (OdePrim)_parent;
  1793. parent.ChildSetGeom(this);
  1794. }
  1795. }
  1796. resetCollisionAccounting();
  1797. m_taintsize = _size;
  1798. }
  1799. /// <summary>
  1800. /// Change prim in response to a float on water taint.
  1801. /// </summary>
  1802. /// <param name="timestep"></param>
  1803. private void changefloatonwater()
  1804. {
  1805. m_collidesWater = m_taintCollidesWater;
  1806. if (m_collidesWater)
  1807. {
  1808. m_collisionFlags |= CollisionCategories.Water;
  1809. }
  1810. else
  1811. {
  1812. m_collisionFlags &= ~CollisionCategories.Water;
  1813. }
  1814. if (m_assetFailed)
  1815. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1816. else
  1817. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1818. }
  1819. /// <summary>
  1820. /// Change prim in response to a shape taint.
  1821. /// </summary>
  1822. private void changeshape()
  1823. {
  1824. m_taintshape = false;
  1825. // Cleanup of old prim geometry and Bodies
  1826. if (IsPhysical && Body != IntPtr.Zero)
  1827. {
  1828. if (childPrim)
  1829. {
  1830. if (_parent != null)
  1831. {
  1832. OdePrim parent = (OdePrim)_parent;
  1833. parent.ChildDelink(this);
  1834. }
  1835. }
  1836. else
  1837. {
  1838. disableBody();
  1839. }
  1840. }
  1841. RemoveGeom();
  1842. // we don't need to do space calculation because the client sends a position update also.
  1843. if (_size.X <= 0) _size.X = 0.01f;
  1844. if (_size.Y <= 0) _size.Y = 0.01f;
  1845. if (_size.Z <= 0) _size.Z = 0.01f;
  1846. // Construction of new prim
  1847. IMesh mesh = null;
  1848. if (_parent_scene.needsMeshing(_pbs))
  1849. {
  1850. // Don't need to re-enable body.. it's done in CreateMesh
  1851. float meshlod = _parent_scene.meshSculptLOD;
  1852. if (IsPhysical)
  1853. meshlod = _parent_scene.MeshSculptphysicalLOD;
  1854. // createmesh returns null when it doesn't mesh.
  1855. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical);
  1856. if (mesh == null)
  1857. CheckMeshAsset();
  1858. else
  1859. m_assetFailed = false;
  1860. }
  1861. CreateGeom(m_targetSpace, mesh);
  1862. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1863. d.Quaternion myrot = new d.Quaternion();
  1864. //myrot.W = _orientation.w;
  1865. myrot.W = _orientation.W;
  1866. myrot.X = _orientation.X;
  1867. myrot.Y = _orientation.Y;
  1868. myrot.Z = _orientation.Z;
  1869. d.GeomSetQuaternion(prim_geom, ref myrot);
  1870. //d.GeomBoxSetLengths(prim_geom, _size.X, _size.Y, _size.Z);
  1871. if (IsPhysical && Body == IntPtr.Zero)
  1872. {
  1873. // Re creates body on size.
  1874. // EnableBody also does setMass()
  1875. enableBody();
  1876. if (Body != IntPtr.Zero)
  1877. {
  1878. d.BodyEnable(Body);
  1879. }
  1880. }
  1881. changeSelectedStatus();
  1882. if (childPrim)
  1883. {
  1884. if (_parent is OdePrim)
  1885. {
  1886. OdePrim parent = (OdePrim)_parent;
  1887. parent.ChildSetGeom(this);
  1888. }
  1889. }
  1890. resetCollisionAccounting();
  1891. // m_taintshape = false;
  1892. }
  1893. /// <summary>
  1894. /// Change prim in response to an add force taint.
  1895. /// </summary>
  1896. private void changeAddForce()
  1897. {
  1898. if (!m_isSelected)
  1899. {
  1900. lock (m_forcelist)
  1901. {
  1902. //m_log.Info("[PHYSICS]: dequeing forcelist");
  1903. if (IsPhysical)
  1904. {
  1905. Vector3 iforce = Vector3.Zero;
  1906. int i = 0;
  1907. try
  1908. {
  1909. for (i = 0; i < m_forcelist.Count; i++)
  1910. {
  1911. iforce = iforce + (m_forcelist[i] * 100);
  1912. }
  1913. }
  1914. catch (IndexOutOfRangeException)
  1915. {
  1916. m_forcelist = new List<Vector3>();
  1917. m_collisionscore = 0;
  1918. m_interpenetrationcount = 0;
  1919. m_taintforce = false;
  1920. return;
  1921. }
  1922. catch (ArgumentOutOfRangeException)
  1923. {
  1924. m_forcelist = new List<Vector3>();
  1925. m_collisionscore = 0;
  1926. m_interpenetrationcount = 0;
  1927. m_taintforce = false;
  1928. return;
  1929. }
  1930. d.BodyEnable(Body);
  1931. d.BodyAddForce(Body, iforce.X, iforce.Y, iforce.Z);
  1932. }
  1933. m_forcelist.Clear();
  1934. }
  1935. m_collisionscore = 0;
  1936. m_interpenetrationcount = 0;
  1937. }
  1938. m_taintforce = false;
  1939. }
  1940. /// <summary>
  1941. /// Change prim in response to a torque taint.
  1942. /// </summary>
  1943. private void changeSetTorque()
  1944. {
  1945. if (!m_isSelected)
  1946. {
  1947. if (IsPhysical && Body != IntPtr.Zero)
  1948. {
  1949. d.BodySetTorque(Body, m_taintTorque.X, m_taintTorque.Y, m_taintTorque.Z);
  1950. }
  1951. }
  1952. m_taintTorque = Vector3.Zero;
  1953. }
  1954. /// <summary>
  1955. /// Change prim in response to an angular force taint.
  1956. /// </summary>
  1957. private void changeAddAngularForce()
  1958. {
  1959. if (!m_isSelected)
  1960. {
  1961. lock (m_angularforcelist)
  1962. {
  1963. //m_log.Info("[PHYSICS]: dequeing forcelist");
  1964. if (IsPhysical)
  1965. {
  1966. Vector3 iforce = Vector3.Zero;
  1967. for (int i = 0; i < m_angularforcelist.Count; i++)
  1968. {
  1969. iforce = iforce + (m_angularforcelist[i] * 100);
  1970. }
  1971. d.BodyEnable(Body);
  1972. d.BodyAddTorque(Body, iforce.X, iforce.Y, iforce.Z);
  1973. }
  1974. m_angularforcelist.Clear();
  1975. }
  1976. m_collisionscore = 0;
  1977. m_interpenetrationcount = 0;
  1978. }
  1979. m_taintaddangularforce = false;
  1980. }
  1981. /// <summary>
  1982. /// Change prim in response to a velocity taint.
  1983. /// </summary>
  1984. private void changevelocity()
  1985. {
  1986. if (!m_isSelected)
  1987. {
  1988. // Not sure exactly why this sleep is here, but from experimentation it appears to stop an avatar
  1989. // walking through a default rez size prim if it keeps kicking it around - justincc.
  1990. Thread.Sleep(20);
  1991. if (IsPhysical)
  1992. {
  1993. if (Body != IntPtr.Zero)
  1994. {
  1995. d.BodySetLinearVel(Body, m_taintVelocity.X, m_taintVelocity.Y, m_taintVelocity.Z);
  1996. }
  1997. }
  1998. //resetCollisionAccounting();
  1999. }
  2000. m_taintVelocity = Vector3.Zero;
  2001. }
  2002. internal void setPrimForRemoval()
  2003. {
  2004. m_taintremove = true;
  2005. }
  2006. public override bool Flying
  2007. {
  2008. // no flying prims for you
  2009. get { return false; }
  2010. set { }
  2011. }
  2012. public override bool IsColliding
  2013. {
  2014. get { return iscolliding; }
  2015. set { iscolliding = value; }
  2016. }
  2017. public override bool CollidingGround
  2018. {
  2019. get { return false; }
  2020. set { return; }
  2021. }
  2022. public override bool CollidingObj
  2023. {
  2024. get { return false; }
  2025. set { return; }
  2026. }
  2027. public override bool ThrottleUpdates
  2028. {
  2029. get { return m_throttleUpdates; }
  2030. set { m_throttleUpdates = value; }
  2031. }
  2032. public override bool Stopped
  2033. {
  2034. get { return _zeroFlag; }
  2035. }
  2036. public override Vector3 Position
  2037. {
  2038. get { return _position; }
  2039. set { _position = value;
  2040. //m_log.Info("[PHYSICS]: " + _position.ToString());
  2041. }
  2042. }
  2043. public override Vector3 Size
  2044. {
  2045. get { return _size; }
  2046. set
  2047. {
  2048. if (value.IsFinite())
  2049. {
  2050. _size = value;
  2051. // m_log.DebugFormat("[PHYSICS]: Set size on {0} to {1}", Name, value);
  2052. }
  2053. else
  2054. {
  2055. m_log.WarnFormat("[PHYSICS]: Got NaN Size on object {0}", Name);
  2056. }
  2057. }
  2058. }
  2059. public override float Mass
  2060. {
  2061. get { return CalculateMass(); }
  2062. }
  2063. public override Vector3 Force
  2064. {
  2065. //get { return Vector3.Zero; }
  2066. get { return m_force; }
  2067. set
  2068. {
  2069. if (value.IsFinite())
  2070. {
  2071. m_force = value;
  2072. }
  2073. else
  2074. {
  2075. m_log.WarnFormat("[PHYSICS]: NaN in Force Applied to an Object {0}", Name);
  2076. }
  2077. }
  2078. }
  2079. public override int VehicleType
  2080. {
  2081. get { return (int)m_vehicle.Type; }
  2082. set { m_vehicle.ProcessTypeChange((Vehicle)value); }
  2083. }
  2084. public override void VehicleFloatParam(int param, float value)
  2085. {
  2086. m_vehicle.ProcessFloatVehicleParam((Vehicle) param, value);
  2087. }
  2088. public override void VehicleVectorParam(int param, Vector3 value)
  2089. {
  2090. m_vehicle.ProcessVectorVehicleParam((Vehicle) param, value);
  2091. }
  2092. public override void VehicleRotationParam(int param, Quaternion rotation)
  2093. {
  2094. m_vehicle.ProcessRotationVehicleParam((Vehicle) param, rotation);
  2095. }
  2096. public override void VehicleFlags(int param, bool remove)
  2097. {
  2098. m_vehicle.ProcessVehicleFlags(param, remove);
  2099. }
  2100. public override void SetVolumeDetect(int param)
  2101. {
  2102. // We have to lock the scene here so that an entire simulate loop either uses volume detect for all
  2103. // possible collisions with this prim or for none of them.
  2104. lock (_parent_scene.OdeLock)
  2105. {
  2106. m_isVolumeDetect = (param != 0);
  2107. }
  2108. }
  2109. public override Vector3 CenterOfMass
  2110. {
  2111. get { return Vector3.Zero; }
  2112. }
  2113. public override Vector3 GeometricCenter
  2114. {
  2115. get { return Vector3.Zero; }
  2116. }
  2117. public override PrimitiveBaseShape Shape
  2118. {
  2119. set
  2120. {
  2121. _pbs = value;
  2122. m_assetFailed = false;
  2123. m_taintshape = true;
  2124. }
  2125. }
  2126. public override Vector3 Velocity
  2127. {
  2128. get
  2129. {
  2130. // Average previous velocity with the new one so
  2131. // client object interpolation works a 'little' better
  2132. if (_zeroFlag)
  2133. return Vector3.Zero;
  2134. Vector3 returnVelocity = Vector3.Zero;
  2135. returnVelocity.X = (m_lastVelocity.X + _velocity.X) * 0.5f; // 0.5f is mathematically equiv to '/ 2'
  2136. returnVelocity.Y = (m_lastVelocity.Y + _velocity.Y) * 0.5f;
  2137. returnVelocity.Z = (m_lastVelocity.Z + _velocity.Z) * 0.5f;
  2138. return returnVelocity;
  2139. }
  2140. set
  2141. {
  2142. if (value.IsFinite())
  2143. {
  2144. _velocity = value;
  2145. m_taintVelocity = value;
  2146. _parent_scene.AddPhysicsActorTaint(this);
  2147. }
  2148. else
  2149. {
  2150. m_log.WarnFormat("[PHYSICS]: Got NaN Velocity in Object {0}", Name);
  2151. }
  2152. }
  2153. }
  2154. public override Vector3 Torque
  2155. {
  2156. get
  2157. {
  2158. if (!IsPhysical || Body == IntPtr.Zero)
  2159. return Vector3.Zero;
  2160. return _torque;
  2161. }
  2162. set
  2163. {
  2164. if (value.IsFinite())
  2165. {
  2166. m_taintTorque = value;
  2167. _parent_scene.AddPhysicsActorTaint(this);
  2168. }
  2169. else
  2170. {
  2171. m_log.WarnFormat("[PHYSICS]: Got NaN Torque in Object {0}", Name);
  2172. }
  2173. }
  2174. }
  2175. public override float CollisionScore
  2176. {
  2177. get { return m_collisionscore; }
  2178. set { m_collisionscore = value; }
  2179. }
  2180. public override bool Kinematic
  2181. {
  2182. get { return false; }
  2183. set { }
  2184. }
  2185. public override Quaternion Orientation
  2186. {
  2187. get { return _orientation; }
  2188. set
  2189. {
  2190. if (QuaternionIsFinite(value))
  2191. _orientation = value;
  2192. else
  2193. m_log.WarnFormat("[PHYSICS]: Got NaN quaternion Orientation from Scene in Object {0}", Name);
  2194. }
  2195. }
  2196. private static bool QuaternionIsFinite(Quaternion q)
  2197. {
  2198. if (Single.IsNaN(q.X) || Single.IsInfinity(q.X))
  2199. return false;
  2200. if (Single.IsNaN(q.Y) || Single.IsInfinity(q.Y))
  2201. return false;
  2202. if (Single.IsNaN(q.Z) || Single.IsInfinity(q.Z))
  2203. return false;
  2204. if (Single.IsNaN(q.W) || Single.IsInfinity(q.W))
  2205. return false;
  2206. return true;
  2207. }
  2208. public override Vector3 Acceleration
  2209. {
  2210. get { return _acceleration; }
  2211. set { _acceleration = value; }
  2212. }
  2213. public override void AddForce(Vector3 force, bool pushforce)
  2214. {
  2215. if (force.IsFinite())
  2216. {
  2217. lock (m_forcelist)
  2218. m_forcelist.Add(force);
  2219. m_taintforce = true;
  2220. }
  2221. else
  2222. {
  2223. m_log.WarnFormat("[PHYSICS]: Got Invalid linear force vector from Scene in Object {0}", Name);
  2224. }
  2225. //m_log.Info("[PHYSICS]: Added Force:" + force.ToString() + " to prim at " + Position.ToString());
  2226. }
  2227. public override void AddAngularForce(Vector3 force, bool pushforce)
  2228. {
  2229. if (force.IsFinite())
  2230. {
  2231. m_angularforcelist.Add(force);
  2232. m_taintaddangularforce = true;
  2233. }
  2234. else
  2235. {
  2236. m_log.WarnFormat("[PHYSICS]: Got Invalid Angular force vector from Scene in Object {0}", Name);
  2237. }
  2238. }
  2239. public override Vector3 RotationalVelocity
  2240. {
  2241. get
  2242. {
  2243. Vector3 pv = Vector3.Zero;
  2244. if (_zeroFlag)
  2245. return pv;
  2246. m_lastUpdateSent = false;
  2247. if (m_rotationalVelocity.ApproxEquals(pv, 0.2f))
  2248. return pv;
  2249. return m_rotationalVelocity;
  2250. }
  2251. set
  2252. {
  2253. if (value.IsFinite())
  2254. {
  2255. m_rotationalVelocity = value;
  2256. setAngularVelocity(value.X, value.Y, value.Z);
  2257. }
  2258. else
  2259. {
  2260. m_log.WarnFormat("[PHYSICS]: Got NaN RotationalVelocity in Object {0}", Name);
  2261. }
  2262. }
  2263. }
  2264. public override void CrossingFailure()
  2265. {
  2266. m_crossingfailures++;
  2267. if (m_crossingfailures > _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2268. {
  2269. base.RaiseOutOfBounds(_position);
  2270. return;
  2271. }
  2272. else if (m_crossingfailures == _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2273. {
  2274. m_log.Warn("[PHYSICS]: Too many crossing failures for: " + Name);
  2275. }
  2276. }
  2277. public override float Buoyancy
  2278. {
  2279. get { return m_buoyancy; }
  2280. set { m_buoyancy = value; }
  2281. }
  2282. public override void link(PhysicsActor obj)
  2283. {
  2284. m_taintparent = obj;
  2285. }
  2286. public override void delink()
  2287. {
  2288. m_taintparent = null;
  2289. }
  2290. public override void LockAngularMotion(Vector3 axis)
  2291. {
  2292. // reverse the zero/non zero values for ODE.
  2293. if (axis.IsFinite())
  2294. {
  2295. axis.X = (axis.X > 0) ? 1f : 0f;
  2296. axis.Y = (axis.Y > 0) ? 1f : 0f;
  2297. axis.Z = (axis.Z > 0) ? 1f : 0f;
  2298. m_log.DebugFormat("[axislock]: <{0},{1},{2}>", axis.X, axis.Y, axis.Z);
  2299. m_taintAngularLock = axis;
  2300. }
  2301. else
  2302. {
  2303. m_log.WarnFormat("[PHYSICS]: Got NaN locking axis from Scene on Object {0}", Name);
  2304. }
  2305. }
  2306. internal void UpdatePositionAndVelocity()
  2307. {
  2308. // no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
  2309. if (_parent == null)
  2310. {
  2311. Vector3 pv = Vector3.Zero;
  2312. bool lastZeroFlag = _zeroFlag;
  2313. float m_minvelocity = 0;
  2314. if (Body != (IntPtr)0) // FIXME -> or if it is a joint
  2315. {
  2316. d.Vector3 vec = d.BodyGetPosition(Body);
  2317. d.Quaternion ori = d.BodyGetQuaternion(Body);
  2318. d.Vector3 vel = d.BodyGetLinearVel(Body);
  2319. d.Vector3 rotvel = d.BodyGetAngularVel(Body);
  2320. d.Vector3 torque = d.BodyGetTorque(Body);
  2321. _torque = new Vector3(torque.X, torque.Y, torque.Z);
  2322. Vector3 l_position = Vector3.Zero;
  2323. Quaternion l_orientation = Quaternion.Identity;
  2324. // kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
  2325. //if (vec.X < 0.0f) { vec.X = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2326. //if (vec.Y < 0.0f) { vec.Y = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2327. //if (vec.X > 255.95f) { vec.X = 255.95f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2328. //if (vec.Y > 255.95f) { vec.Y = 255.95f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2329. m_lastposition = _position;
  2330. m_lastorientation = _orientation;
  2331. l_position.X = vec.X;
  2332. l_position.Y = vec.Y;
  2333. l_position.Z = vec.Z;
  2334. l_orientation.X = ori.X;
  2335. l_orientation.Y = ori.Y;
  2336. l_orientation.Z = ori.Z;
  2337. l_orientation.W = ori.W;
  2338. if (l_position.X > ((int)_parent_scene.WorldExtents.X - 0.05f) || l_position.X < 0f || l_position.Y > ((int)_parent_scene.WorldExtents.Y - 0.05f) || l_position.Y < 0f)
  2339. {
  2340. //base.RaiseOutOfBounds(l_position);
  2341. if (m_crossingfailures < _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2342. {
  2343. _position = l_position;
  2344. //_parent_scene.remActivePrim(this);
  2345. if (_parent == null)
  2346. base.RequestPhysicsterseUpdate();
  2347. return;
  2348. }
  2349. else
  2350. {
  2351. if (_parent == null)
  2352. base.RaiseOutOfBounds(l_position);
  2353. return;
  2354. }
  2355. }
  2356. if (l_position.Z < 0)
  2357. {
  2358. // This is so prim that get lost underground don't fall forever and suck up
  2359. //
  2360. // Sim resources and memory.
  2361. // Disables the prim's movement physics....
  2362. // It's a hack and will generate a console message if it fails.
  2363. //IsPhysical = false;
  2364. if (_parent == null)
  2365. base.RaiseOutOfBounds(_position);
  2366. _acceleration.X = 0;
  2367. _acceleration.Y = 0;
  2368. _acceleration.Z = 0;
  2369. _velocity.X = 0;
  2370. _velocity.Y = 0;
  2371. _velocity.Z = 0;
  2372. m_rotationalVelocity.X = 0;
  2373. m_rotationalVelocity.Y = 0;
  2374. m_rotationalVelocity.Z = 0;
  2375. if (_parent == null)
  2376. base.RequestPhysicsterseUpdate();
  2377. m_throttleUpdates = false;
  2378. throttleCounter = 0;
  2379. _zeroFlag = true;
  2380. //outofBounds = true;
  2381. }
  2382. //float Adiff = 1.0f - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation));
  2383. //Console.WriteLine("Adiff " + Name + " = " + Adiff);
  2384. if ((Math.Abs(m_lastposition.X - l_position.X) < 0.02)
  2385. && (Math.Abs(m_lastposition.Y - l_position.Y) < 0.02)
  2386. && (Math.Abs(m_lastposition.Z - l_position.Z) < 0.02)
  2387. // && (1.0 - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation)) < 0.01))
  2388. && (1.0 - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation)) < 0.0001)) // KF 0.01 is far to large
  2389. {
  2390. _zeroFlag = true;
  2391. //Console.WriteLine("ZFT 2");
  2392. m_throttleUpdates = false;
  2393. }
  2394. else
  2395. {
  2396. //m_log.Debug(Math.Abs(m_lastposition.X - l_position.X).ToString());
  2397. _zeroFlag = false;
  2398. m_lastUpdateSent = false;
  2399. //m_throttleUpdates = false;
  2400. }
  2401. if (_zeroFlag)
  2402. {
  2403. _velocity.X = 0.0f;
  2404. _velocity.Y = 0.0f;
  2405. _velocity.Z = 0.0f;
  2406. _acceleration.X = 0;
  2407. _acceleration.Y = 0;
  2408. _acceleration.Z = 0;
  2409. //_orientation.w = 0f;
  2410. //_orientation.X = 0f;
  2411. //_orientation.Y = 0f;
  2412. //_orientation.Z = 0f;
  2413. m_rotationalVelocity.X = 0;
  2414. m_rotationalVelocity.Y = 0;
  2415. m_rotationalVelocity.Z = 0;
  2416. if (!m_lastUpdateSent)
  2417. {
  2418. m_throttleUpdates = false;
  2419. throttleCounter = 0;
  2420. m_rotationalVelocity = pv;
  2421. if (_parent == null)
  2422. {
  2423. base.RequestPhysicsterseUpdate();
  2424. }
  2425. m_lastUpdateSent = true;
  2426. }
  2427. }
  2428. else
  2429. {
  2430. if (lastZeroFlag != _zeroFlag)
  2431. {
  2432. if (_parent == null)
  2433. {
  2434. base.RequestPhysicsterseUpdate();
  2435. }
  2436. }
  2437. m_lastVelocity = _velocity;
  2438. _position = l_position;
  2439. _velocity.X = vel.X;
  2440. _velocity.Y = vel.Y;
  2441. _velocity.Z = vel.Z;
  2442. _acceleration = ((_velocity - m_lastVelocity) / 0.1f);
  2443. _acceleration = new Vector3(_velocity.X - m_lastVelocity.X / 0.1f, _velocity.Y - m_lastVelocity.Y / 0.1f, _velocity.Z - m_lastVelocity.Z / 0.1f);
  2444. //m_log.Info("[PHYSICS]: V1: " + _velocity + " V2: " + m_lastVelocity + " Acceleration: " + _acceleration.ToString());
  2445. // Note here that linearvelocity is affecting angular velocity... so I'm guessing this is a vehicle specific thing...
  2446. // it does make sense to do this for tiny little instabilities with physical prim, however 0.5m/frame is fairly large.
  2447. // reducing this to 0.02m/frame seems to help the angular rubberbanding quite a bit, however, to make sure it doesn't affect elevators and vehicles
  2448. // adding these logical exclusion situations to maintain this where I think it was intended to be.
  2449. if (m_throttleUpdates || PIDActive || (m_vehicle != null && m_vehicle.Type != Vehicle.TYPE_NONE) || (Amotor != IntPtr.Zero))
  2450. {
  2451. m_minvelocity = 0.5f;
  2452. }
  2453. else
  2454. {
  2455. m_minvelocity = 0.02f;
  2456. }
  2457. if (_velocity.ApproxEquals(pv, m_minvelocity))
  2458. {
  2459. m_rotationalVelocity = pv;
  2460. }
  2461. else
  2462. {
  2463. m_rotationalVelocity = new Vector3(rotvel.X, rotvel.Y, rotvel.Z);
  2464. }
  2465. //m_log.Debug("ODE: " + m_rotationalVelocity.ToString());
  2466. _orientation.X = ori.X;
  2467. _orientation.Y = ori.Y;
  2468. _orientation.Z = ori.Z;
  2469. _orientation.W = ori.W;
  2470. m_lastUpdateSent = false;
  2471. if (!m_throttleUpdates || throttleCounter > _parent_scene.geomUpdatesPerThrottledUpdate)
  2472. {
  2473. if (_parent == null)
  2474. {
  2475. base.RequestPhysicsterseUpdate();
  2476. }
  2477. }
  2478. else
  2479. {
  2480. throttleCounter++;
  2481. }
  2482. }
  2483. m_lastposition = l_position;
  2484. }
  2485. else
  2486. {
  2487. // Not a body.. so Make sure the client isn't interpolating
  2488. _velocity.X = 0;
  2489. _velocity.Y = 0;
  2490. _velocity.Z = 0;
  2491. _acceleration.X = 0;
  2492. _acceleration.Y = 0;
  2493. _acceleration.Z = 0;
  2494. m_rotationalVelocity.X = 0;
  2495. m_rotationalVelocity.Y = 0;
  2496. m_rotationalVelocity.Z = 0;
  2497. _zeroFlag = true;
  2498. }
  2499. }
  2500. }
  2501. public override bool FloatOnWater
  2502. {
  2503. set {
  2504. m_taintCollidesWater = value;
  2505. _parent_scene.AddPhysicsActorTaint(this);
  2506. }
  2507. }
  2508. public override void SetMomentum(Vector3 momentum)
  2509. {
  2510. }
  2511. public override Vector3 PIDTarget
  2512. {
  2513. set
  2514. {
  2515. if (value.IsFinite())
  2516. {
  2517. m_PIDTarget = value;
  2518. }
  2519. else
  2520. m_log.WarnFormat("[PHYSICS]: Got NaN PIDTarget from Scene on Object {0}", Name);
  2521. }
  2522. }
  2523. public override bool PIDActive { get; set; }
  2524. public override float PIDTau { set { m_PIDTau = value; } }
  2525. public override float PIDHoverHeight { set { m_PIDHoverHeight = value; ; } }
  2526. public override bool PIDHoverActive { set { m_useHoverPID = value; } }
  2527. public override PIDHoverType PIDHoverType { set { m_PIDHoverType = value; } }
  2528. public override float PIDHoverTau { set { m_PIDHoverTau = value; } }
  2529. public override Quaternion APIDTarget{ set { return; } }
  2530. public override bool APIDActive{ set { return; } }
  2531. public override float APIDStrength{ set { return; } }
  2532. public override float APIDDamping{ set { return; } }
  2533. private void createAMotor(Vector3 axis)
  2534. {
  2535. if (Body == IntPtr.Zero)
  2536. return;
  2537. if (Amotor != IntPtr.Zero)
  2538. {
  2539. d.JointDestroy(Amotor);
  2540. Amotor = IntPtr.Zero;
  2541. }
  2542. float axisnum = 3;
  2543. axisnum = (axisnum - (axis.X + axis.Y + axis.Z));
  2544. // PhysicsVector totalSize = new PhysicsVector(_size.X, _size.Y, _size.Z);
  2545. // Inverse Inertia Matrix, set the X, Y, and/r Z inertia to 0 then invert it again.
  2546. d.Mass objMass;
  2547. d.MassSetZero(out objMass);
  2548. DMassCopy(ref pMass, ref objMass);
  2549. //m_log.DebugFormat("1-{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, ", objMass.I.M00, objMass.I.M01, objMass.I.M02, objMass.I.M10, objMass.I.M11, objMass.I.M12, objMass.I.M20, objMass.I.M21, objMass.I.M22);
  2550. Matrix4 dMassMat = FromDMass(objMass);
  2551. Matrix4 mathmat = Inverse(dMassMat);
  2552. /*
  2553. //m_log.DebugFormat("2-{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, ", mathmat[0, 0], mathmat[0, 1], mathmat[0, 2], mathmat[1, 0], mathmat[1, 1], mathmat[1, 2], mathmat[2, 0], mathmat[2, 1], mathmat[2, 2]);
  2554. mathmat = Inverse(mathmat);
  2555. objMass = FromMatrix4(mathmat, ref objMass);
  2556. //m_log.DebugFormat("3-{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, ", objMass.I.M00, objMass.I.M01, objMass.I.M02, objMass.I.M10, objMass.I.M11, objMass.I.M12, objMass.I.M20, objMass.I.M21, objMass.I.M22);
  2557. mathmat = Inverse(mathmat);
  2558. */
  2559. if (axis.X == 0)
  2560. {
  2561. mathmat.M33 = 50.0000001f;
  2562. //objMass.I.M22 = 0;
  2563. }
  2564. if (axis.Y == 0)
  2565. {
  2566. mathmat.M22 = 50.0000001f;
  2567. //objMass.I.M11 = 0;
  2568. }
  2569. if (axis.Z == 0)
  2570. {
  2571. mathmat.M11 = 50.0000001f;
  2572. //objMass.I.M00 = 0;
  2573. }
  2574. mathmat = Inverse(mathmat);
  2575. objMass = FromMatrix4(mathmat, ref objMass);
  2576. //m_log.DebugFormat("4-{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, ", objMass.I.M00, objMass.I.M01, objMass.I.M02, objMass.I.M10, objMass.I.M11, objMass.I.M12, objMass.I.M20, objMass.I.M21, objMass.I.M22);
  2577. //return;
  2578. if (d.MassCheck(ref objMass))
  2579. {
  2580. d.BodySetMass(Body, ref objMass);
  2581. }
  2582. else
  2583. {
  2584. //m_log.Debug("[PHYSICS]: Mass invalid, ignoring");
  2585. }
  2586. if (axisnum <= 0)
  2587. return;
  2588. // int dAMotorEuler = 1;
  2589. Amotor = d.JointCreateAMotor(_parent_scene.world, IntPtr.Zero);
  2590. d.JointAttach(Amotor, Body, IntPtr.Zero);
  2591. d.JointSetAMotorMode(Amotor, 0);
  2592. d.JointSetAMotorNumAxes(Amotor,(int)axisnum);
  2593. int i = 0;
  2594. if (axis.X == 0)
  2595. {
  2596. d.JointSetAMotorAxis(Amotor, i, 0, 1, 0, 0);
  2597. i++;
  2598. }
  2599. if (axis.Y == 0)
  2600. {
  2601. d.JointSetAMotorAxis(Amotor, i, 0, 0, 1, 0);
  2602. i++;
  2603. }
  2604. if (axis.Z == 0)
  2605. {
  2606. d.JointSetAMotorAxis(Amotor, i, 0, 0, 0, 1);
  2607. i++;
  2608. }
  2609. for (int j = 0; j < (int)axisnum; j++)
  2610. {
  2611. //d.JointSetAMotorAngle(Amotor, j, 0);
  2612. }
  2613. //d.JointSetAMotorAngle(Amotor, 1, 0);
  2614. //d.JointSetAMotorAngle(Amotor, 2, 0);
  2615. // These lowstops and high stops are effectively (no wiggle room)
  2616. d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, -0f);
  2617. d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0f);
  2618. d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, -0f);
  2619. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0f);
  2620. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f);
  2621. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0f);
  2622. //d.JointSetAMotorParam(Amotor, (int) dParam.Vel, 9000f);
  2623. d.JointSetAMotorParam(Amotor, (int)dParam.FudgeFactor, 0f);
  2624. d.JointSetAMotorParam(Amotor, (int)dParam.FMax, Mass * 50f);//
  2625. }
  2626. private Matrix4 FromDMass(d.Mass pMass)
  2627. {
  2628. Matrix4 obj;
  2629. obj.M11 = pMass.I.M00;
  2630. obj.M12 = pMass.I.M01;
  2631. obj.M13 = pMass.I.M02;
  2632. obj.M14 = 0;
  2633. obj.M21 = pMass.I.M10;
  2634. obj.M22 = pMass.I.M11;
  2635. obj.M23 = pMass.I.M12;
  2636. obj.M24 = 0;
  2637. obj.M31 = pMass.I.M20;
  2638. obj.M32 = pMass.I.M21;
  2639. obj.M33 = pMass.I.M22;
  2640. obj.M34 = 0;
  2641. obj.M41 = 0;
  2642. obj.M42 = 0;
  2643. obj.M43 = 0;
  2644. obj.M44 = 1;
  2645. return obj;
  2646. }
  2647. private d.Mass FromMatrix4(Matrix4 pMat, ref d.Mass obj)
  2648. {
  2649. obj.I.M00 = pMat[0, 0];
  2650. obj.I.M01 = pMat[0, 1];
  2651. obj.I.M02 = pMat[0, 2];
  2652. obj.I.M10 = pMat[1, 0];
  2653. obj.I.M11 = pMat[1, 1];
  2654. obj.I.M12 = pMat[1, 2];
  2655. obj.I.M20 = pMat[2, 0];
  2656. obj.I.M21 = pMat[2, 1];
  2657. obj.I.M22 = pMat[2, 2];
  2658. return obj;
  2659. }
  2660. public override void SubscribeEvents(int ms)
  2661. {
  2662. m_eventsubscription = ms;
  2663. _parent_scene.AddCollisionEventReporting(this);
  2664. }
  2665. public override void UnSubscribeEvents()
  2666. {
  2667. _parent_scene.RemoveCollisionEventReporting(this);
  2668. m_eventsubscription = 0;
  2669. }
  2670. public void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
  2671. {
  2672. CollisionEventsThisFrame.AddCollider(CollidedWith, contact);
  2673. }
  2674. public void SendCollisions()
  2675. {
  2676. if (m_collisionsOnPreviousFrame || CollisionEventsThisFrame.Count > 0)
  2677. {
  2678. base.SendCollisionUpdate(CollisionEventsThisFrame);
  2679. if (CollisionEventsThisFrame.Count > 0)
  2680. {
  2681. m_collisionsOnPreviousFrame = true;
  2682. CollisionEventsThisFrame.Clear();
  2683. }
  2684. else
  2685. {
  2686. m_collisionsOnPreviousFrame = false;
  2687. }
  2688. }
  2689. }
  2690. public override bool SubscribedEvents()
  2691. {
  2692. if (m_eventsubscription > 0)
  2693. return true;
  2694. return false;
  2695. }
  2696. public static Matrix4 Inverse(Matrix4 pMat)
  2697. {
  2698. if (determinant3x3(pMat) == 0)
  2699. {
  2700. return Matrix4.Identity; // should probably throw an error. singluar matrix inverse not possible
  2701. }
  2702. return (Adjoint(pMat) / determinant3x3(pMat));
  2703. }
  2704. public static Matrix4 Adjoint(Matrix4 pMat)
  2705. {
  2706. Matrix4 adjointMatrix = new Matrix4();
  2707. for (int i=0; i<4; i++)
  2708. {
  2709. for (int j=0; j<4; j++)
  2710. {
  2711. Matrix4SetValue(ref adjointMatrix, i, j, (float)(Math.Pow(-1, i + j) * (determinant3x3(Minor(pMat, i, j)))));
  2712. }
  2713. }
  2714. adjointMatrix = Transpose(adjointMatrix);
  2715. return adjointMatrix;
  2716. }
  2717. public static Matrix4 Minor(Matrix4 matrix, int iRow, int iCol)
  2718. {
  2719. Matrix4 minor = new Matrix4();
  2720. int m = 0, n = 0;
  2721. for (int i = 0; i < 4; i++)
  2722. {
  2723. if (i == iRow)
  2724. continue;
  2725. n = 0;
  2726. for (int j = 0; j < 4; j++)
  2727. {
  2728. if (j == iCol)
  2729. continue;
  2730. Matrix4SetValue(ref minor, m,n, matrix[i, j]);
  2731. n++;
  2732. }
  2733. m++;
  2734. }
  2735. return minor;
  2736. }
  2737. public static Matrix4 Transpose(Matrix4 pMat)
  2738. {
  2739. Matrix4 transposeMatrix = new Matrix4();
  2740. for (int i = 0; i < 4; i++)
  2741. for (int j = 0; j < 4; j++)
  2742. Matrix4SetValue(ref transposeMatrix, i, j, pMat[j, i]);
  2743. return transposeMatrix;
  2744. }
  2745. public static void Matrix4SetValue(ref Matrix4 pMat, int r, int c, float val)
  2746. {
  2747. switch (r)
  2748. {
  2749. case 0:
  2750. switch (c)
  2751. {
  2752. case 0:
  2753. pMat.M11 = val;
  2754. break;
  2755. case 1:
  2756. pMat.M12 = val;
  2757. break;
  2758. case 2:
  2759. pMat.M13 = val;
  2760. break;
  2761. case 3:
  2762. pMat.M14 = val;
  2763. break;
  2764. }
  2765. break;
  2766. case 1:
  2767. switch (c)
  2768. {
  2769. case 0:
  2770. pMat.M21 = val;
  2771. break;
  2772. case 1:
  2773. pMat.M22 = val;
  2774. break;
  2775. case 2:
  2776. pMat.M23 = val;
  2777. break;
  2778. case 3:
  2779. pMat.M24 = val;
  2780. break;
  2781. }
  2782. break;
  2783. case 2:
  2784. switch (c)
  2785. {
  2786. case 0:
  2787. pMat.M31 = val;
  2788. break;
  2789. case 1:
  2790. pMat.M32 = val;
  2791. break;
  2792. case 2:
  2793. pMat.M33 = val;
  2794. break;
  2795. case 3:
  2796. pMat.M34 = val;
  2797. break;
  2798. }
  2799. break;
  2800. case 3:
  2801. switch (c)
  2802. {
  2803. case 0:
  2804. pMat.M41 = val;
  2805. break;
  2806. case 1:
  2807. pMat.M42 = val;
  2808. break;
  2809. case 2:
  2810. pMat.M43 = val;
  2811. break;
  2812. case 3:
  2813. pMat.M44 = val;
  2814. break;
  2815. }
  2816. break;
  2817. }
  2818. }
  2819. private static float determinant3x3(Matrix4 pMat)
  2820. {
  2821. float det = 0;
  2822. float diag1 = pMat[0, 0]*pMat[1, 1]*pMat[2, 2];
  2823. float diag2 = pMat[0, 1]*pMat[2, 1]*pMat[2, 0];
  2824. float diag3 = pMat[0, 2]*pMat[1, 0]*pMat[2, 1];
  2825. float diag4 = pMat[2, 0]*pMat[1, 1]*pMat[0, 2];
  2826. float diag5 = pMat[2, 1]*pMat[1, 2]*pMat[0, 0];
  2827. float diag6 = pMat[2, 2]*pMat[1, 0]*pMat[0, 1];
  2828. det = diag1 + diag2 + diag3 - (diag4 + diag5 + diag6);
  2829. return det;
  2830. }
  2831. private static void DMassCopy(ref d.Mass src, ref d.Mass dst)
  2832. {
  2833. dst.c.W = src.c.W;
  2834. dst.c.X = src.c.X;
  2835. dst.c.Y = src.c.Y;
  2836. dst.c.Z = src.c.Z;
  2837. dst.mass = src.mass;
  2838. dst.I.M00 = src.I.M00;
  2839. dst.I.M01 = src.I.M01;
  2840. dst.I.M02 = src.I.M02;
  2841. dst.I.M10 = src.I.M10;
  2842. dst.I.M11 = src.I.M11;
  2843. dst.I.M12 = src.I.M12;
  2844. dst.I.M20 = src.I.M20;
  2845. dst.I.M21 = src.I.M21;
  2846. dst.I.M22 = src.I.M22;
  2847. }
  2848. public override void SetMaterial(int pMaterial)
  2849. {
  2850. m_material = pMaterial;
  2851. }
  2852. private void CheckMeshAsset()
  2853. {
  2854. if (_pbs.SculptEntry && !m_assetFailed && _pbs.SculptTexture != UUID.Zero)
  2855. {
  2856. m_assetFailed = true;
  2857. Util.FireAndForget(delegate
  2858. {
  2859. RequestAssetDelegate assetProvider = _parent_scene.RequestAssetMethod;
  2860. if (assetProvider != null)
  2861. assetProvider(_pbs.SculptTexture, MeshAssetReceived);
  2862. }, null, "ODEPrim.CheckMeshAsset");
  2863. }
  2864. }
  2865. private void MeshAssetReceived(AssetBase asset)
  2866. {
  2867. if (asset != null && asset.Data != null && asset.Data.Length > 0)
  2868. {
  2869. if (!_pbs.SculptEntry)
  2870. return;
  2871. if (_pbs.SculptTexture.ToString() != asset.ID)
  2872. return;
  2873. _pbs.SculptData = new byte[asset.Data.Length];
  2874. asset.Data.CopyTo(_pbs.SculptData, 0);
  2875. // m_assetFailed = false;
  2876. // m_log.DebugFormat(
  2877. // "[ODE PRIM]: Received mesh/sculpt data asset {0} with {1} bytes for {2} at {3} in {4}",
  2878. // _pbs.SculptTexture, _pbs.SculptData.Length, Name, _position, _parent_scene.Name);
  2879. m_taintshape = true;
  2880. _parent_scene.AddPhysicsActorTaint(this);
  2881. }
  2882. else
  2883. {
  2884. m_log.WarnFormat(
  2885. "[ODE PRIM]: Could not get mesh/sculpt asset {0} for {1} at {2} in {3}",
  2886. _pbs.SculptTexture, Name, _position, _parent_scene.PhysicsSceneName);
  2887. }
  2888. }
  2889. }
  2890. }