ODEPrim.cs 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387
  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.Zero, 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, prim.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. // The body doesn't already have a finite rotation mode set here
  992. if ((!m_angularlock.ApproxEquals(Vector3.Zero, 0f)) && _parent == null)
  993. {
  994. prm.createAMotor(m_angularlock);
  995. }
  996. prm.Body = Body;
  997. _parent_scene.ActivatePrim(prm);
  998. }
  999. m_collisionCategories |= CollisionCategories.Body;
  1000. m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind);
  1001. if (m_assetFailed)
  1002. {
  1003. d.GeomSetCategoryBits(prim_geom, 0);
  1004. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1005. }
  1006. else
  1007. {
  1008. //Console.WriteLine("GeomSetCategoryBits 2: " + prim_geom + " - " + (int)m_collisionCategories + " for " + Name);
  1009. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1010. //Console.WriteLine(" Post GeomSetCategoryBits 2");
  1011. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1012. }
  1013. d.Quaternion quat2 = new d.Quaternion();
  1014. quat2.W = _orientation.W;
  1015. quat2.X = _orientation.X;
  1016. quat2.Y = _orientation.Y;
  1017. quat2.Z = _orientation.Z;
  1018. d.Matrix3 mat2 = new d.Matrix3();
  1019. d.RfromQ(out mat2, ref quat2);
  1020. d.GeomSetBody(prim_geom, Body);
  1021. d.GeomSetOffsetWorldPosition(prim_geom, Position.X - pMass.c.X, Position.Y - pMass.c.Y, Position.Z - pMass.c.Z);
  1022. //d.GeomSetOffsetPosition(prim.prim_geom,
  1023. // (Position.X - prm.Position.X) - pMass.c.X,
  1024. // (Position.Y - prm.Position.Y) - pMass.c.Y,
  1025. // (Position.Z - prm.Position.Z) - pMass.c.Z);
  1026. //d.GeomSetOffsetRotation(prim_geom, ref mat2);
  1027. d.MassTranslate(ref pMass, -pMass.c.X, -pMass.c.Y, -pMass.c.Z);
  1028. d.BodySetMass(Body, ref pMass);
  1029. d.BodySetAutoDisableFlag(Body, true);
  1030. d.BodySetAutoDisableSteps(Body, body_autodisable_frames);
  1031. m_interpenetrationcount = 0;
  1032. m_collisionscore = 0;
  1033. m_disabled = false;
  1034. // The body doesn't already have a finite rotation mode set here
  1035. if ((!m_angularlock.ApproxEquals(Vector3.Zero, 0f)) && _parent == null)
  1036. {
  1037. createAMotor(m_angularlock);
  1038. }
  1039. d.BodySetPosition(Body, Position.X, Position.Y, Position.Z);
  1040. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1041. m_vehicle.Enable(Body, _parent_scene);
  1042. _parent_scene.ActivatePrim(this);
  1043. }
  1044. }
  1045. private void ChildSetGeom(OdePrim odePrim)
  1046. {
  1047. // m_log.DebugFormat(
  1048. // "[ODE PRIM]: ChildSetGeom {0} {1} for {2} {3}", odePrim.Name, odePrim.LocalID, Name, LocalID);
  1049. //if (IsPhysical && Body != IntPtr.Zero)
  1050. lock (childrenPrim)
  1051. {
  1052. foreach (OdePrim prm in childrenPrim)
  1053. {
  1054. //prm.childPrim = true;
  1055. prm.disableBody();
  1056. //prm.m_taintparent = null;
  1057. //prm._parent = null;
  1058. //prm.m_taintPhysics = false;
  1059. //prm.m_disabled = true;
  1060. //prm.childPrim = false;
  1061. }
  1062. }
  1063. disableBody();
  1064. // Spurious - Body == IntPtr.Zero after disableBody()
  1065. // if (Body != IntPtr.Zero)
  1066. // {
  1067. // _parent_scene.DeactivatePrim(this);
  1068. // }
  1069. lock (childrenPrim)
  1070. {
  1071. foreach (OdePrim prm in childrenPrim)
  1072. {
  1073. //Console.WriteLine("ChildSetGeom calls ParentPrim");
  1074. AddChildPrim(prm);
  1075. }
  1076. }
  1077. }
  1078. private void ChildDelink(OdePrim odePrim)
  1079. {
  1080. // m_log.DebugFormat(
  1081. // "[ODE PRIM]: Delinking prim {0} {1} from {2} {3}", odePrim.Name, odePrim.LocalID, Name, LocalID);
  1082. // Okay, we have a delinked child.. need to rebuild the body.
  1083. lock (childrenPrim)
  1084. {
  1085. foreach (OdePrim prm in childrenPrim)
  1086. {
  1087. prm.childPrim = true;
  1088. prm.disableBody();
  1089. //prm.m_taintparent = null;
  1090. //prm._parent = null;
  1091. //prm.m_taintPhysics = false;
  1092. //prm.m_disabled = true;
  1093. //prm.childPrim = false;
  1094. }
  1095. }
  1096. disableBody();
  1097. lock (childrenPrim)
  1098. {
  1099. //Console.WriteLine("childrenPrim.Remove " + odePrim);
  1100. childrenPrim.Remove(odePrim);
  1101. }
  1102. // Spurious - Body == IntPtr.Zero after disableBody()
  1103. // if (Body != IntPtr.Zero)
  1104. // {
  1105. // _parent_scene.DeactivatePrim(this);
  1106. // }
  1107. lock (childrenPrim)
  1108. {
  1109. foreach (OdePrim prm in childrenPrim)
  1110. {
  1111. //Console.WriteLine("ChildDelink calls ParentPrim");
  1112. AddChildPrim(prm);
  1113. }
  1114. }
  1115. }
  1116. /// <summary>
  1117. /// Change prim in response to a selection taint.
  1118. /// </summary>
  1119. private void changeSelectedStatus()
  1120. {
  1121. if (m_taintselected)
  1122. {
  1123. m_collisionCategories = CollisionCategories.Selected;
  1124. m_collisionFlags = (CollisionCategories.Sensor | CollisionCategories.Space);
  1125. // We do the body disable soft twice because 'in theory' a collision could have happened
  1126. // in between the disabling and the collision properties setting
  1127. // which would wake the physical body up from a soft disabling and potentially cause it to fall
  1128. // through the ground.
  1129. // NOTE FOR JOINTS: this doesn't always work for jointed assemblies because if you select
  1130. // just one part of the assembly, the rest of the assembly is non-selected and still simulating,
  1131. // so that causes the selected part to wake up and continue moving.
  1132. // even if you select all parts of a jointed assembly, it is not guaranteed that the entire
  1133. // assembly will stop simulating during the selection, because of the lack of atomicity
  1134. // of select operations (their processing could be interrupted by a thread switch, causing
  1135. // simulation to continue before all of the selected object notifications trickle down to
  1136. // the physics engine).
  1137. // e.g. we select 100 prims that are connected by joints. non-atomically, the first 50 are
  1138. // selected and disabled. then, due to a thread switch, the selection processing is
  1139. // interrupted and the physics engine continues to simulate, so the last 50 items, whose
  1140. // selection was not yet processed, continues to simulate. this wakes up ALL of the
  1141. // first 50 again. then the last 50 are disabled. then the first 50, which were just woken
  1142. // up, start simulating again, which in turn wakes up the last 50.
  1143. if (IsPhysical)
  1144. {
  1145. disableBodySoft();
  1146. }
  1147. if (m_assetFailed)
  1148. {
  1149. d.GeomSetCategoryBits(prim_geom, 0);
  1150. d.GeomSetCollideBits(prim_geom, 0);
  1151. }
  1152. else
  1153. {
  1154. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1155. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1156. }
  1157. if (IsPhysical)
  1158. {
  1159. disableBodySoft();
  1160. }
  1161. }
  1162. else
  1163. {
  1164. m_collisionCategories = CollisionCategories.Geom;
  1165. if (IsPhysical)
  1166. m_collisionCategories |= CollisionCategories.Body;
  1167. m_collisionFlags = m_default_collisionFlags;
  1168. if (m_collidesLand)
  1169. m_collisionFlags |= CollisionCategories.Land;
  1170. if (m_collidesWater)
  1171. m_collisionFlags |= CollisionCategories.Water;
  1172. if (m_assetFailed)
  1173. {
  1174. d.GeomSetCategoryBits(prim_geom, 0);
  1175. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1176. }
  1177. else
  1178. {
  1179. d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories);
  1180. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1181. }
  1182. if (IsPhysical)
  1183. {
  1184. if (Body != IntPtr.Zero)
  1185. {
  1186. d.BodySetLinearVel(Body, 0f, 0f, 0f);
  1187. d.BodySetForce(Body, 0, 0, 0);
  1188. enableBodySoft();
  1189. }
  1190. }
  1191. }
  1192. resetCollisionAccounting();
  1193. m_isSelected = m_taintselected;
  1194. }//end changeSelectedStatus
  1195. internal void ResetTaints()
  1196. {
  1197. m_taintposition = _position;
  1198. m_taintrot = _orientation;
  1199. m_taintPhysics = IsPhysical;
  1200. m_taintselected = m_isSelected;
  1201. m_taintsize = _size;
  1202. m_taintshape = false;
  1203. m_taintforce = false;
  1204. m_taintdisable = false;
  1205. m_taintVelocity = Vector3.Zero;
  1206. }
  1207. /// <summary>
  1208. /// Create a geometry for the given mesh in the given target space.
  1209. /// </summary>
  1210. /// <param name="m_targetSpace"></param>
  1211. /// <param name="mesh">If null, then a mesh is used that is based on the profile shape data.</param>
  1212. private void CreateGeom(IntPtr m_targetSpace, IMesh mesh)
  1213. {
  1214. #if SPAM
  1215. Console.WriteLine("CreateGeom:");
  1216. #endif
  1217. if (mesh != null)
  1218. {
  1219. setMesh(_parent_scene, mesh);
  1220. }
  1221. else
  1222. {
  1223. if (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1)
  1224. {
  1225. if (_size.X == _size.Y && _size.Y == _size.Z && _size.X == _size.Z)
  1226. {
  1227. if (((_size.X / 2f) > 0f))
  1228. {
  1229. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1230. try
  1231. {
  1232. //Console.WriteLine(" CreateGeom 1");
  1233. SetGeom(d.CreateSphere(m_targetSpace, _size.X / 2));
  1234. m_expectedCollisionContacts = 3;
  1235. }
  1236. catch (AccessViolationException)
  1237. {
  1238. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1239. return;
  1240. }
  1241. }
  1242. else
  1243. {
  1244. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1245. try
  1246. {
  1247. //Console.WriteLine(" CreateGeom 2");
  1248. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1249. m_expectedCollisionContacts = 4;
  1250. }
  1251. catch (AccessViolationException)
  1252. {
  1253. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1254. return;
  1255. }
  1256. }
  1257. }
  1258. else
  1259. {
  1260. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1261. try
  1262. {
  1263. //Console.WriteLine(" CreateGeom 3");
  1264. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1265. m_expectedCollisionContacts = 4;
  1266. }
  1267. catch (AccessViolationException)
  1268. {
  1269. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1270. return;
  1271. }
  1272. }
  1273. }
  1274. else
  1275. {
  1276. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1277. try
  1278. {
  1279. //Console.WriteLine(" CreateGeom 4");
  1280. SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z));
  1281. m_expectedCollisionContacts = 4;
  1282. }
  1283. catch (AccessViolationException)
  1284. {
  1285. m_log.WarnFormat("[PHYSICS]: Unable to create physics proxy for object {0}", Name);
  1286. return;
  1287. }
  1288. }
  1289. }
  1290. }
  1291. /// <summary>
  1292. /// Remove the existing geom from this prim.
  1293. /// </summary>
  1294. /// <param name="m_targetSpace"></param>
  1295. /// <param name="mesh">If null, then a mesh is used that is based on the profile shape data.</param>
  1296. /// <returns>true if the geom was successfully removed, false if it was already gone or the remove failed.</returns>
  1297. internal bool RemoveGeom()
  1298. {
  1299. if (prim_geom != IntPtr.Zero)
  1300. {
  1301. try
  1302. {
  1303. _parent_scene.geom_name_map.Remove(prim_geom);
  1304. _parent_scene.actor_name_map.Remove(prim_geom);
  1305. d.GeomDestroy(prim_geom);
  1306. m_expectedCollisionContacts = 0;
  1307. prim_geom = IntPtr.Zero;
  1308. }
  1309. catch (System.AccessViolationException)
  1310. {
  1311. prim_geom = IntPtr.Zero;
  1312. m_expectedCollisionContacts = 0;
  1313. m_log.ErrorFormat("[PHYSICS]: PrimGeom dead for {0}", Name);
  1314. return false;
  1315. }
  1316. return true;
  1317. }
  1318. else
  1319. {
  1320. m_log.WarnFormat(
  1321. "[ODE PRIM]: Called RemoveGeom() on {0} {1} where geometry was already null.", Name, LocalID);
  1322. return false;
  1323. }
  1324. }
  1325. /// <summary>
  1326. /// Add prim in response to an add taint.
  1327. /// </summary>
  1328. private void changeadd()
  1329. {
  1330. // m_log.DebugFormat("[ODE PRIM]: Adding prim {0}", Name);
  1331. int[] iprimspaceArrItem = _parent_scene.calculateSpaceArrayItemFromPos(_position);
  1332. IntPtr targetspace = _parent_scene.calculateSpaceForGeom(_position);
  1333. if (targetspace == IntPtr.Zero)
  1334. targetspace = _parent_scene.createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  1335. m_targetSpace = targetspace;
  1336. IMesh mesh = null;
  1337. if (_parent_scene.needsMeshing(_pbs))
  1338. {
  1339. // Don't need to re-enable body.. it's done in SetMesh
  1340. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, _parent_scene.meshSculptLOD, IsPhysical);
  1341. // createmesh returns null when it's a shape that isn't a cube.
  1342. // m_log.Debug(m_localID);
  1343. if (mesh == null)
  1344. CheckMeshAsset();
  1345. else
  1346. m_assetFailed = false;
  1347. }
  1348. #if SPAM
  1349. Console.WriteLine("changeadd 1");
  1350. #endif
  1351. CreateGeom(m_targetSpace, mesh);
  1352. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1353. d.Quaternion myrot = new d.Quaternion();
  1354. myrot.X = _orientation.X;
  1355. myrot.Y = _orientation.Y;
  1356. myrot.Z = _orientation.Z;
  1357. myrot.W = _orientation.W;
  1358. d.GeomSetQuaternion(prim_geom, ref myrot);
  1359. if (IsPhysical && Body == IntPtr.Zero)
  1360. enableBody();
  1361. changeSelectedStatus();
  1362. m_taintadd = false;
  1363. }
  1364. /// <summary>
  1365. /// Move prim in response to a move taint.
  1366. /// </summary>
  1367. private void changemove()
  1368. {
  1369. if (IsPhysical)
  1370. {
  1371. if (!m_disabled && !m_taintremove && !childPrim)
  1372. {
  1373. if (Body == IntPtr.Zero)
  1374. enableBody();
  1375. //Prim auto disable after 20 frames,
  1376. //if you move it, re-enable the prim manually.
  1377. if (_parent != null)
  1378. {
  1379. if (m_linkJoint != IntPtr.Zero)
  1380. {
  1381. d.JointDestroy(m_linkJoint);
  1382. m_linkJoint = IntPtr.Zero;
  1383. }
  1384. }
  1385. if (Body != IntPtr.Zero)
  1386. {
  1387. d.BodySetPosition(Body, _position.X, _position.Y, _position.Z);
  1388. if (_parent != null)
  1389. {
  1390. OdePrim odParent = (OdePrim)_parent;
  1391. if (Body != (IntPtr)0 && odParent.Body != (IntPtr)0 && Body != odParent.Body)
  1392. {
  1393. // KF: Fixed Joints were removed? Anyway - this Console.WriteLine does not show up, so routine is not used??
  1394. Console.WriteLine(" JointCreateFixed");
  1395. m_linkJoint = d.JointCreateFixed(_parent_scene.world, _linkJointGroup);
  1396. d.JointAttach(m_linkJoint, Body, odParent.Body);
  1397. d.JointSetFixed(m_linkJoint);
  1398. }
  1399. }
  1400. d.BodyEnable(Body);
  1401. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1402. {
  1403. m_vehicle.Enable(Body, _parent_scene);
  1404. }
  1405. }
  1406. else
  1407. {
  1408. m_log.WarnFormat("[PHYSICS]: Body for {0} still null after enableBody(). This is a crash scenario.", Name);
  1409. }
  1410. }
  1411. //else
  1412. // {
  1413. //m_log.Debug("[BUG]: race!");
  1414. //}
  1415. }
  1416. // string primScenAvatarIn = _parent_scene.whichspaceamIin(_position);
  1417. // int[] arrayitem = _parent_scene.calculateSpaceArrayItemFromPos(_position);
  1418. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1419. IntPtr tempspace = _parent_scene.recalculateSpaceForGeom(prim_geom, _position, m_targetSpace);
  1420. m_targetSpace = tempspace;
  1421. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1422. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1423. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1424. d.SpaceAdd(m_targetSpace, prim_geom);
  1425. changeSelectedStatus();
  1426. resetCollisionAccounting();
  1427. m_taintposition = _position;
  1428. }
  1429. internal void Move(float timestep)
  1430. {
  1431. float fx = 0;
  1432. float fy = 0;
  1433. float fz = 0;
  1434. if (IsPhysical && (Body != IntPtr.Zero) && !m_isSelected && !childPrim) // KF: Only move root prims.
  1435. {
  1436. if (m_vehicle.Type != Vehicle.TYPE_NONE)
  1437. {
  1438. // 'VEHICLES' are dealt with in ODEDynamics.cs
  1439. m_vehicle.Step(timestep, _parent_scene);
  1440. }
  1441. else
  1442. {
  1443. //Console.WriteLine("Move " + Name);
  1444. if (!d.BodyIsEnabled (Body)) d.BodyEnable (Body); // KF add 161009
  1445. // NON-'VEHICLES' are dealt with here
  1446. // if (d.BodyIsEnabled(Body) && !m_angularlock.ApproxEquals(Vector3.Zero, 0.003f))
  1447. // {
  1448. // d.Vector3 avel2 = d.BodyGetAngularVel(Body);
  1449. // /*
  1450. // if (m_angularlock.X == 1)
  1451. // avel2.X = 0;
  1452. // if (m_angularlock.Y == 1)
  1453. // avel2.Y = 0;
  1454. // if (m_angularlock.Z == 1)
  1455. // avel2.Z = 0;
  1456. // d.BodySetAngularVel(Body, avel2.X, avel2.Y, avel2.Z);
  1457. // */
  1458. // }
  1459. //float PID_P = 900.0f;
  1460. float m_mass = CalculateMass();
  1461. // fz = 0f;
  1462. //m_log.Info(m_collisionFlags.ToString());
  1463. //KF: m_buoyancy should be set by llSetBuoyancy() for non-vehicle.
  1464. // would come from SceneObjectPart.cs, public void SetBuoyancy(float fvalue) , PhysActor.Buoyancy = fvalue; ??
  1465. // m_buoyancy: (unlimited value) <0=Falls fast; 0=1g; 1=0g; >1 = floats up
  1466. // gravityz multiplier = 1 - m_buoyancy
  1467. fz = _parent_scene.gravityz * (1.0f - m_buoyancy) * m_mass;
  1468. if (PIDActive)
  1469. {
  1470. //Console.WriteLine("PID " + Name);
  1471. // KF - this is for object move? eg. llSetPos() ?
  1472. //if (!d.BodyIsEnabled(Body))
  1473. //d.BodySetForce(Body, 0f, 0f, 0f);
  1474. // If we're using the PID controller, then we have no gravity
  1475. //fz = (-1 * _parent_scene.gravityz) * m_mass; //KF: ?? Prims have no global gravity,so simply...
  1476. fz = 0f;
  1477. // no lock; for now it's only called from within Simulate()
  1478. // If the PID Controller isn't active then we set our force
  1479. // calculating base velocity to the current position
  1480. if ((m_PIDTau < 1) && (m_PIDTau != 0))
  1481. {
  1482. //PID_G = PID_G / m_PIDTau;
  1483. m_PIDTau = 1;
  1484. }
  1485. if ((PID_G - m_PIDTau) <= 0)
  1486. {
  1487. PID_G = m_PIDTau + 1;
  1488. }
  1489. //PidStatus = true;
  1490. // PhysicsVector vec = new PhysicsVector();
  1491. d.Vector3 vel = d.BodyGetLinearVel(Body);
  1492. d.Vector3 pos = d.BodyGetPosition(Body);
  1493. _target_velocity =
  1494. new Vector3(
  1495. (m_PIDTarget.X - pos.X) * ((PID_G - m_PIDTau) * timestep),
  1496. (m_PIDTarget.Y - pos.Y) * ((PID_G - m_PIDTau) * timestep),
  1497. (m_PIDTarget.Z - pos.Z) * ((PID_G - m_PIDTau) * timestep)
  1498. );
  1499. // if velocity is zero, use position control; otherwise, velocity control
  1500. if (_target_velocity.ApproxEquals(Vector3.Zero,0.1f))
  1501. {
  1502. // keep track of where we stopped. No more slippin' & slidin'
  1503. // We only want to deactivate the PID Controller if we think we want to have our surrogate
  1504. // react to the physics scene by moving it's position.
  1505. // Avatar to Avatar collisions
  1506. // Prim to avatar collisions
  1507. //fx = (_target_velocity.X - vel.X) * (PID_D) + (_zeroPosition.X - pos.X) * (PID_P * 2);
  1508. //fy = (_target_velocity.Y - vel.Y) * (PID_D) + (_zeroPosition.Y - pos.Y) * (PID_P * 2);
  1509. //fz = fz + (_target_velocity.Z - vel.Z) * (PID_D) + (_zeroPosition.Z - pos.Z) * PID_P;
  1510. d.BodySetPosition(Body, m_PIDTarget.X, m_PIDTarget.Y, m_PIDTarget.Z);
  1511. d.BodySetLinearVel(Body, 0, 0, 0);
  1512. d.BodyAddForce(Body, 0, 0, fz);
  1513. return;
  1514. }
  1515. else
  1516. {
  1517. _zeroFlag = false;
  1518. // We're flying and colliding with something
  1519. fx = ((_target_velocity.X) - vel.X) * (PID_D);
  1520. fy = ((_target_velocity.Y) - vel.Y) * (PID_D);
  1521. // vec.Z = (_target_velocity.Z - vel.Z) * PID_D + (_zeroPosition.Z - pos.Z) * PID_P;
  1522. fz = fz + ((_target_velocity.Z - vel.Z) * (PID_D) * m_mass);
  1523. }
  1524. } // end if (PIDActive)
  1525. // Hover PID Controller needs to be mutually exlusive to MoveTo PID controller
  1526. if (m_useHoverPID && !PIDActive)
  1527. {
  1528. //Console.WriteLine("Hover " + Name);
  1529. // If we're using the PID controller, then we have no gravity
  1530. fz = (-1 * _parent_scene.gravityz) * m_mass;
  1531. // no lock; for now it's only called from within Simulate()
  1532. // If the PID Controller isn't active then we set our force
  1533. // calculating base velocity to the current position
  1534. if ((m_PIDTau < 1))
  1535. {
  1536. PID_G = PID_G / m_PIDTau;
  1537. }
  1538. if ((PID_G - m_PIDTau) <= 0)
  1539. {
  1540. PID_G = m_PIDTau + 1;
  1541. }
  1542. // Where are we, and where are we headed?
  1543. d.Vector3 pos = d.BodyGetPosition(Body);
  1544. d.Vector3 vel = d.BodyGetLinearVel(Body);
  1545. // Non-Vehicles have a limited set of Hover options.
  1546. // determine what our target height really is based on HoverType
  1547. switch (m_PIDHoverType)
  1548. {
  1549. case PIDHoverType.Ground:
  1550. m_groundHeight = _parent_scene.GetTerrainHeightAtXY(pos.X, pos.Y);
  1551. m_targetHoverHeight = m_groundHeight + m_PIDHoverHeight;
  1552. break;
  1553. case PIDHoverType.GroundAndWater:
  1554. m_groundHeight = _parent_scene.GetTerrainHeightAtXY(pos.X, pos.Y);
  1555. m_waterHeight = _parent_scene.GetWaterLevel();
  1556. if (m_groundHeight > m_waterHeight)
  1557. {
  1558. m_targetHoverHeight = m_groundHeight + m_PIDHoverHeight;
  1559. }
  1560. else
  1561. {
  1562. m_targetHoverHeight = m_waterHeight + m_PIDHoverHeight;
  1563. }
  1564. break;
  1565. } // end switch (m_PIDHoverType)
  1566. _target_velocity =
  1567. new Vector3(0.0f, 0.0f,
  1568. (m_targetHoverHeight - pos.Z) * ((PID_G - m_PIDHoverTau) * timestep)
  1569. );
  1570. // if velocity is zero, use position control; otherwise, velocity control
  1571. if (_target_velocity.ApproxEquals(Vector3.Zero, 0.1f))
  1572. {
  1573. // keep track of where we stopped. No more slippin' & slidin'
  1574. // We only want to deactivate the PID Controller if we think we want to have our surrogate
  1575. // react to the physics scene by moving it's position.
  1576. // Avatar to Avatar collisions
  1577. // Prim to avatar collisions
  1578. d.BodySetPosition(Body, pos.X, pos.Y, m_targetHoverHeight);
  1579. d.BodySetLinearVel(Body, vel.X, vel.Y, 0);
  1580. d.BodyAddForce(Body, 0, 0, fz);
  1581. return;
  1582. }
  1583. else
  1584. {
  1585. _zeroFlag = false;
  1586. // We're flying and colliding with something
  1587. fz = fz + ((_target_velocity.Z - vel.Z) * (PID_D) * m_mass);
  1588. }
  1589. }
  1590. fx *= m_mass;
  1591. fy *= m_mass;
  1592. //fz *= m_mass;
  1593. fx += m_force.X;
  1594. fy += m_force.Y;
  1595. fz += m_force.Z;
  1596. //m_log.Info("[OBJPID]: X:" + fx.ToString() + " Y:" + fy.ToString() + " Z:" + fz.ToString());
  1597. if (fx != 0 || fy != 0 || fz != 0)
  1598. {
  1599. //m_taintdisable = true;
  1600. //base.RaiseOutOfBounds(Position);
  1601. //d.BodySetLinearVel(Body, fx, fy, 0f);
  1602. if (!d.BodyIsEnabled(Body))
  1603. {
  1604. // A physical body at rest on a surface will auto-disable after a while,
  1605. // this appears to re-enable it incase the surface it is upon vanishes,
  1606. // and the body should fall again.
  1607. d.BodySetLinearVel(Body, 0f, 0f, 0f);
  1608. d.BodySetForce(Body, 0, 0, 0);
  1609. enableBodySoft();
  1610. }
  1611. // 35x10 = 350n times the mass per second applied maximum.
  1612. float nmax = 35f * m_mass;
  1613. float nmin = -35f * m_mass;
  1614. if (fx > nmax)
  1615. fx = nmax;
  1616. if (fx < nmin)
  1617. fx = nmin;
  1618. if (fy > nmax)
  1619. fy = nmax;
  1620. if (fy < nmin)
  1621. fy = nmin;
  1622. d.BodyAddForce(Body, fx, fy, fz);
  1623. //Console.WriteLine("AddForce " + fx + "," + fy + "," + fz);
  1624. }
  1625. }
  1626. }
  1627. else
  1628. { // is not physical, or is not a body or is selected
  1629. // _zeroPosition = d.BodyGetPosition(Body);
  1630. return;
  1631. //Console.WriteLine("Nothing " + Name);
  1632. }
  1633. }
  1634. private void rotate()
  1635. {
  1636. d.Quaternion myrot = new d.Quaternion();
  1637. myrot.X = _orientation.X;
  1638. myrot.Y = _orientation.Y;
  1639. myrot.Z = _orientation.Z;
  1640. myrot.W = _orientation.W;
  1641. if (Body != IntPtr.Zero)
  1642. {
  1643. // KF: If this is a root prim do BodySet
  1644. d.BodySetQuaternion(Body, ref myrot);
  1645. if (IsPhysical)
  1646. {
  1647. if (!m_angularlock.ApproxEquals(Vector3.One, 0f))
  1648. createAMotor(m_angularlock);
  1649. }
  1650. }
  1651. else
  1652. {
  1653. // daughter prim, do Geom set
  1654. d.GeomSetQuaternion(prim_geom, ref myrot);
  1655. }
  1656. resetCollisionAccounting();
  1657. m_taintrot = _orientation;
  1658. }
  1659. private void resetCollisionAccounting()
  1660. {
  1661. m_collisionscore = 0;
  1662. m_interpenetrationcount = 0;
  1663. m_disabled = false;
  1664. }
  1665. /// <summary>
  1666. /// Change prim in response to a disable taint.
  1667. /// </summary>
  1668. private void changedisable()
  1669. {
  1670. m_disabled = true;
  1671. if (Body != IntPtr.Zero)
  1672. {
  1673. d.BodyDisable(Body);
  1674. Body = IntPtr.Zero;
  1675. }
  1676. m_taintdisable = false;
  1677. }
  1678. /// <summary>
  1679. /// Change prim in response to a physics status taint
  1680. /// </summary>
  1681. private void changePhysicsStatus()
  1682. {
  1683. if (IsPhysical)
  1684. {
  1685. if (Body == IntPtr.Zero)
  1686. {
  1687. if (_pbs.SculptEntry && _parent_scene.meshSculptedPrim)
  1688. {
  1689. changeshape();
  1690. }
  1691. else
  1692. {
  1693. enableBody();
  1694. }
  1695. }
  1696. }
  1697. else
  1698. {
  1699. if (Body != IntPtr.Zero)
  1700. {
  1701. if (_pbs.SculptEntry && _parent_scene.meshSculptedPrim)
  1702. {
  1703. RemoveGeom();
  1704. //Console.WriteLine("changePhysicsStatus for " + Name);
  1705. changeadd();
  1706. }
  1707. if (childPrim)
  1708. {
  1709. if (_parent != null)
  1710. {
  1711. OdePrim parent = (OdePrim)_parent;
  1712. parent.ChildDelink(this);
  1713. }
  1714. }
  1715. else
  1716. {
  1717. disableBody();
  1718. }
  1719. }
  1720. }
  1721. changeSelectedStatus();
  1722. resetCollisionAccounting();
  1723. m_taintPhysics = IsPhysical;
  1724. }
  1725. /// <summary>
  1726. /// Change prim in response to a size taint.
  1727. /// </summary>
  1728. private void changesize()
  1729. {
  1730. #if SPAM
  1731. m_log.DebugFormat("[ODE PRIM]: Called changesize");
  1732. #endif
  1733. if (_size.X <= 0) _size.X = 0.01f;
  1734. if (_size.Y <= 0) _size.Y = 0.01f;
  1735. if (_size.Z <= 0) _size.Z = 0.01f;
  1736. //kill body to rebuild
  1737. if (IsPhysical && Body != IntPtr.Zero)
  1738. {
  1739. if (childPrim)
  1740. {
  1741. if (_parent != null)
  1742. {
  1743. OdePrim parent = (OdePrim)_parent;
  1744. parent.ChildDelink(this);
  1745. }
  1746. }
  1747. else
  1748. {
  1749. disableBody();
  1750. }
  1751. }
  1752. if (d.SpaceQuery(m_targetSpace, prim_geom))
  1753. {
  1754. // _parent_scene.waitForSpaceUnlock(m_targetSpace);
  1755. d.SpaceRemove(m_targetSpace, prim_geom);
  1756. }
  1757. RemoveGeom();
  1758. // we don't need to do space calculation because the client sends a position update also.
  1759. IMesh mesh = null;
  1760. // Construction of new prim
  1761. if (_parent_scene.needsMeshing(_pbs))
  1762. {
  1763. float meshlod = _parent_scene.meshSculptLOD;
  1764. if (IsPhysical)
  1765. meshlod = _parent_scene.MeshSculptphysicalLOD;
  1766. // Don't need to re-enable body.. it's done in SetMesh
  1767. if (_parent_scene.needsMeshing(_pbs))
  1768. {
  1769. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical);
  1770. if (mesh == null)
  1771. CheckMeshAsset();
  1772. else
  1773. m_assetFailed = false;
  1774. }
  1775. }
  1776. CreateGeom(m_targetSpace, mesh);
  1777. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1778. d.Quaternion myrot = new d.Quaternion();
  1779. myrot.X = _orientation.X;
  1780. myrot.Y = _orientation.Y;
  1781. myrot.Z = _orientation.Z;
  1782. myrot.W = _orientation.W;
  1783. d.GeomSetQuaternion(prim_geom, ref myrot);
  1784. //d.GeomBoxSetLengths(prim_geom, _size.X, _size.Y, _size.Z);
  1785. if (IsPhysical && Body == IntPtr.Zero && !childPrim)
  1786. {
  1787. // Re creates body on size.
  1788. // EnableBody also does setMass()
  1789. enableBody();
  1790. d.BodyEnable(Body);
  1791. }
  1792. changeSelectedStatus();
  1793. if (childPrim)
  1794. {
  1795. if (_parent is OdePrim)
  1796. {
  1797. OdePrim parent = (OdePrim)_parent;
  1798. parent.ChildSetGeom(this);
  1799. }
  1800. }
  1801. resetCollisionAccounting();
  1802. m_taintsize = _size;
  1803. }
  1804. /// <summary>
  1805. /// Change prim in response to a float on water taint.
  1806. /// </summary>
  1807. /// <param name="timestep"></param>
  1808. private void changefloatonwater()
  1809. {
  1810. m_collidesWater = m_taintCollidesWater;
  1811. if (m_collidesWater)
  1812. {
  1813. m_collisionFlags |= CollisionCategories.Water;
  1814. }
  1815. else
  1816. {
  1817. m_collisionFlags &= ~CollisionCategories.Water;
  1818. }
  1819. if (m_assetFailed)
  1820. d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits);
  1821. else
  1822. d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags);
  1823. }
  1824. /// <summary>
  1825. /// Change prim in response to a shape taint.
  1826. /// </summary>
  1827. private void changeshape()
  1828. {
  1829. m_taintshape = false;
  1830. // Cleanup of old prim geometry and Bodies
  1831. if (IsPhysical && Body != IntPtr.Zero)
  1832. {
  1833. if (childPrim)
  1834. {
  1835. if (_parent != null)
  1836. {
  1837. OdePrim parent = (OdePrim)_parent;
  1838. parent.ChildDelink(this);
  1839. }
  1840. }
  1841. else
  1842. {
  1843. disableBody();
  1844. }
  1845. }
  1846. RemoveGeom();
  1847. // we don't need to do space calculation because the client sends a position update also.
  1848. if (_size.X <= 0) _size.X = 0.01f;
  1849. if (_size.Y <= 0) _size.Y = 0.01f;
  1850. if (_size.Z <= 0) _size.Z = 0.01f;
  1851. // Construction of new prim
  1852. IMesh mesh = null;
  1853. if (_parent_scene.needsMeshing(_pbs))
  1854. {
  1855. // Don't need to re-enable body.. it's done in CreateMesh
  1856. float meshlod = _parent_scene.meshSculptLOD;
  1857. if (IsPhysical)
  1858. meshlod = _parent_scene.MeshSculptphysicalLOD;
  1859. // createmesh returns null when it doesn't mesh.
  1860. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical);
  1861. if (mesh == null)
  1862. CheckMeshAsset();
  1863. else
  1864. m_assetFailed = false;
  1865. }
  1866. CreateGeom(m_targetSpace, mesh);
  1867. d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
  1868. d.Quaternion myrot = new d.Quaternion();
  1869. //myrot.W = _orientation.w;
  1870. myrot.W = _orientation.W;
  1871. myrot.X = _orientation.X;
  1872. myrot.Y = _orientation.Y;
  1873. myrot.Z = _orientation.Z;
  1874. d.GeomSetQuaternion(prim_geom, ref myrot);
  1875. //d.GeomBoxSetLengths(prim_geom, _size.X, _size.Y, _size.Z);
  1876. if (IsPhysical && Body == IntPtr.Zero)
  1877. {
  1878. // Re creates body on size.
  1879. // EnableBody also does setMass()
  1880. enableBody();
  1881. if (Body != IntPtr.Zero)
  1882. {
  1883. d.BodyEnable(Body);
  1884. }
  1885. }
  1886. changeSelectedStatus();
  1887. if (childPrim)
  1888. {
  1889. if (_parent is OdePrim)
  1890. {
  1891. OdePrim parent = (OdePrim)_parent;
  1892. parent.ChildSetGeom(this);
  1893. }
  1894. }
  1895. resetCollisionAccounting();
  1896. // m_taintshape = false;
  1897. }
  1898. /// <summary>
  1899. /// Change prim in response to an add force taint.
  1900. /// </summary>
  1901. private void changeAddForce()
  1902. {
  1903. if (!m_isSelected)
  1904. {
  1905. lock (m_forcelist)
  1906. {
  1907. //m_log.Info("[PHYSICS]: dequeing forcelist");
  1908. if (IsPhysical)
  1909. {
  1910. Vector3 iforce = Vector3.Zero;
  1911. int i = 0;
  1912. try
  1913. {
  1914. for (i = 0; i < m_forcelist.Count; i++)
  1915. {
  1916. iforce = iforce + (m_forcelist[i] * 100);
  1917. }
  1918. }
  1919. catch (IndexOutOfRangeException)
  1920. {
  1921. m_forcelist = new List<Vector3>();
  1922. m_collisionscore = 0;
  1923. m_interpenetrationcount = 0;
  1924. m_taintforce = false;
  1925. return;
  1926. }
  1927. catch (ArgumentOutOfRangeException)
  1928. {
  1929. m_forcelist = new List<Vector3>();
  1930. m_collisionscore = 0;
  1931. m_interpenetrationcount = 0;
  1932. m_taintforce = false;
  1933. return;
  1934. }
  1935. d.BodyEnable(Body);
  1936. d.BodyAddForce(Body, iforce.X, iforce.Y, iforce.Z);
  1937. }
  1938. m_forcelist.Clear();
  1939. }
  1940. m_collisionscore = 0;
  1941. m_interpenetrationcount = 0;
  1942. }
  1943. m_taintforce = false;
  1944. }
  1945. /// <summary>
  1946. /// Change prim in response to a torque taint.
  1947. /// </summary>
  1948. private void changeSetTorque()
  1949. {
  1950. if (!m_isSelected)
  1951. {
  1952. if (IsPhysical && Body != IntPtr.Zero)
  1953. {
  1954. d.BodySetTorque(Body, m_taintTorque.X, m_taintTorque.Y, m_taintTorque.Z);
  1955. }
  1956. }
  1957. m_taintTorque = Vector3.Zero;
  1958. }
  1959. /// <summary>
  1960. /// Change prim in response to an angular force taint.
  1961. /// </summary>
  1962. private void changeAddAngularForce()
  1963. {
  1964. if (!m_isSelected)
  1965. {
  1966. lock (m_angularforcelist)
  1967. {
  1968. //m_log.Info("[PHYSICS]: dequeing forcelist");
  1969. if (IsPhysical)
  1970. {
  1971. Vector3 iforce = Vector3.Zero;
  1972. for (int i = 0; i < m_angularforcelist.Count; i++)
  1973. {
  1974. iforce = iforce + (m_angularforcelist[i] * 100);
  1975. }
  1976. d.BodyEnable(Body);
  1977. d.BodyAddTorque(Body, iforce.X, iforce.Y, iforce.Z);
  1978. }
  1979. m_angularforcelist.Clear();
  1980. }
  1981. m_collisionscore = 0;
  1982. m_interpenetrationcount = 0;
  1983. }
  1984. m_taintaddangularforce = false;
  1985. }
  1986. /// <summary>
  1987. /// Change prim in response to a velocity taint.
  1988. /// </summary>
  1989. private void changevelocity()
  1990. {
  1991. if (!m_isSelected)
  1992. {
  1993. // Not sure exactly why this sleep is here, but from experimentation it appears to stop an avatar
  1994. // walking through a default rez size prim if it keeps kicking it around - justincc.
  1995. Thread.Sleep(20);
  1996. if (IsPhysical)
  1997. {
  1998. if (Body != IntPtr.Zero)
  1999. {
  2000. d.BodySetLinearVel(Body, m_taintVelocity.X, m_taintVelocity.Y, m_taintVelocity.Z);
  2001. }
  2002. }
  2003. //resetCollisionAccounting();
  2004. }
  2005. m_taintVelocity = Vector3.Zero;
  2006. }
  2007. internal void setPrimForRemoval()
  2008. {
  2009. m_taintremove = true;
  2010. }
  2011. public override bool Flying
  2012. {
  2013. // no flying prims for you
  2014. get { return false; }
  2015. set { }
  2016. }
  2017. public override bool IsColliding
  2018. {
  2019. get { return iscolliding; }
  2020. set { iscolliding = value; }
  2021. }
  2022. public override bool CollidingGround
  2023. {
  2024. get { return false; }
  2025. set { return; }
  2026. }
  2027. public override bool CollidingObj
  2028. {
  2029. get { return false; }
  2030. set { return; }
  2031. }
  2032. public override bool ThrottleUpdates
  2033. {
  2034. get { return m_throttleUpdates; }
  2035. set { m_throttleUpdates = value; }
  2036. }
  2037. public override bool Stopped
  2038. {
  2039. get { return _zeroFlag; }
  2040. }
  2041. public override Vector3 Position
  2042. {
  2043. get { return _position; }
  2044. set { _position = value;
  2045. //m_log.Info("[PHYSICS]: " + _position.ToString());
  2046. }
  2047. }
  2048. public override Vector3 Size
  2049. {
  2050. get { return _size; }
  2051. set
  2052. {
  2053. if (value.IsFinite())
  2054. {
  2055. _size = value;
  2056. // m_log.DebugFormat("[PHYSICS]: Set size on {0} to {1}", Name, value);
  2057. }
  2058. else
  2059. {
  2060. m_log.WarnFormat("[PHYSICS]: Got NaN Size on object {0}", Name);
  2061. }
  2062. }
  2063. }
  2064. public override float Mass
  2065. {
  2066. get { return CalculateMass(); }
  2067. }
  2068. public override Vector3 Force
  2069. {
  2070. //get { return Vector3.Zero; }
  2071. get { return m_force; }
  2072. set
  2073. {
  2074. if (value.IsFinite())
  2075. {
  2076. m_force = value;
  2077. }
  2078. else
  2079. {
  2080. m_log.WarnFormat("[PHYSICS]: NaN in Force Applied to an Object {0}", Name);
  2081. }
  2082. }
  2083. }
  2084. public override int VehicleType
  2085. {
  2086. get { return (int)m_vehicle.Type; }
  2087. set { m_vehicle.ProcessTypeChange((Vehicle)value); }
  2088. }
  2089. public override void VehicleFloatParam(int param, float value)
  2090. {
  2091. m_vehicle.ProcessFloatVehicleParam((Vehicle) param, value);
  2092. }
  2093. public override void VehicleVectorParam(int param, Vector3 value)
  2094. {
  2095. m_vehicle.ProcessVectorVehicleParam((Vehicle) param, value);
  2096. }
  2097. public override void VehicleRotationParam(int param, Quaternion rotation)
  2098. {
  2099. m_vehicle.ProcessRotationVehicleParam((Vehicle) param, rotation);
  2100. }
  2101. public override void VehicleFlags(int param, bool remove)
  2102. {
  2103. m_vehicle.ProcessVehicleFlags(param, remove);
  2104. }
  2105. public override void SetVolumeDetect(int param)
  2106. {
  2107. // We have to lock the scene here so that an entire simulate loop either uses volume detect for all
  2108. // possible collisions with this prim or for none of them.
  2109. lock (_parent_scene.OdeLock)
  2110. {
  2111. m_isVolumeDetect = (param != 0);
  2112. }
  2113. }
  2114. public override Vector3 CenterOfMass
  2115. {
  2116. get { return Vector3.Zero; }
  2117. }
  2118. public override Vector3 GeometricCenter
  2119. {
  2120. get { return Vector3.Zero; }
  2121. }
  2122. public override PrimitiveBaseShape Shape
  2123. {
  2124. set
  2125. {
  2126. _pbs = value;
  2127. m_assetFailed = false;
  2128. m_taintshape = true;
  2129. }
  2130. }
  2131. public override Vector3 Velocity
  2132. {
  2133. get
  2134. {
  2135. // Average previous velocity with the new one so
  2136. // client object interpolation works a 'little' better
  2137. if (_zeroFlag)
  2138. return Vector3.Zero;
  2139. Vector3 returnVelocity = Vector3.Zero;
  2140. returnVelocity.X = (m_lastVelocity.X + _velocity.X) * 0.5f; // 0.5f is mathematically equiv to '/ 2'
  2141. returnVelocity.Y = (m_lastVelocity.Y + _velocity.Y) * 0.5f;
  2142. returnVelocity.Z = (m_lastVelocity.Z + _velocity.Z) * 0.5f;
  2143. return returnVelocity;
  2144. }
  2145. set
  2146. {
  2147. if (value.IsFinite())
  2148. {
  2149. _velocity = value;
  2150. m_taintVelocity = value;
  2151. _parent_scene.AddPhysicsActorTaint(this);
  2152. }
  2153. else
  2154. {
  2155. m_log.WarnFormat("[PHYSICS]: Got NaN Velocity in Object {0}", Name);
  2156. }
  2157. }
  2158. }
  2159. public override Vector3 Torque
  2160. {
  2161. get
  2162. {
  2163. if (!IsPhysical || Body == IntPtr.Zero)
  2164. return Vector3.Zero;
  2165. return _torque;
  2166. }
  2167. set
  2168. {
  2169. if (value.IsFinite())
  2170. {
  2171. m_taintTorque = value;
  2172. _parent_scene.AddPhysicsActorTaint(this);
  2173. }
  2174. else
  2175. {
  2176. m_log.WarnFormat("[PHYSICS]: Got NaN Torque in Object {0}", Name);
  2177. }
  2178. }
  2179. }
  2180. public override float CollisionScore
  2181. {
  2182. get { return m_collisionscore; }
  2183. set { m_collisionscore = value; }
  2184. }
  2185. public override bool Kinematic
  2186. {
  2187. get { return false; }
  2188. set { }
  2189. }
  2190. public override Quaternion Orientation
  2191. {
  2192. get { return _orientation; }
  2193. set
  2194. {
  2195. if (QuaternionIsFinite(value))
  2196. _orientation = value;
  2197. else
  2198. m_log.WarnFormat("[PHYSICS]: Got NaN quaternion Orientation from Scene in Object {0}", Name);
  2199. }
  2200. }
  2201. private static bool QuaternionIsFinite(Quaternion q)
  2202. {
  2203. if (Single.IsNaN(q.X) || Single.IsInfinity(q.X))
  2204. return false;
  2205. if (Single.IsNaN(q.Y) || Single.IsInfinity(q.Y))
  2206. return false;
  2207. if (Single.IsNaN(q.Z) || Single.IsInfinity(q.Z))
  2208. return false;
  2209. if (Single.IsNaN(q.W) || Single.IsInfinity(q.W))
  2210. return false;
  2211. return true;
  2212. }
  2213. public override Vector3 Acceleration
  2214. {
  2215. get { return _acceleration; }
  2216. set { _acceleration = value; }
  2217. }
  2218. public override void AddForce(Vector3 force, bool pushforce)
  2219. {
  2220. if (force.IsFinite())
  2221. {
  2222. lock (m_forcelist)
  2223. m_forcelist.Add(force);
  2224. m_taintforce = true;
  2225. }
  2226. else
  2227. {
  2228. m_log.WarnFormat("[PHYSICS]: Got Invalid linear force vector from Scene in Object {0}", Name);
  2229. }
  2230. //m_log.Info("[PHYSICS]: Added Force:" + force.ToString() + " to prim at " + Position.ToString());
  2231. }
  2232. public override void AddAngularForce(Vector3 force, bool pushforce)
  2233. {
  2234. if (force.IsFinite())
  2235. {
  2236. m_angularforcelist.Add(force);
  2237. m_taintaddangularforce = true;
  2238. }
  2239. else
  2240. {
  2241. m_log.WarnFormat("[PHYSICS]: Got Invalid Angular force vector from Scene in Object {0}", Name);
  2242. }
  2243. }
  2244. public override Vector3 RotationalVelocity
  2245. {
  2246. get
  2247. {
  2248. Vector3 pv = Vector3.Zero;
  2249. if (_zeroFlag)
  2250. return pv;
  2251. m_lastUpdateSent = false;
  2252. if (m_rotationalVelocity.ApproxEquals(pv, 0.2f))
  2253. return pv;
  2254. return m_rotationalVelocity;
  2255. }
  2256. set
  2257. {
  2258. if (value.IsFinite())
  2259. {
  2260. m_rotationalVelocity = value;
  2261. setAngularVelocity(value.X, value.Y, value.Z);
  2262. }
  2263. else
  2264. {
  2265. m_log.WarnFormat("[PHYSICS]: Got NaN RotationalVelocity in Object {0}", Name);
  2266. }
  2267. }
  2268. }
  2269. public override void CrossingFailure()
  2270. {
  2271. m_crossingfailures++;
  2272. if (m_crossingfailures > _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2273. {
  2274. base.RaiseOutOfBounds(_position);
  2275. return;
  2276. }
  2277. else if (m_crossingfailures == _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2278. {
  2279. m_log.Warn("[PHYSICS]: Too many crossing failures for: " + Name);
  2280. }
  2281. }
  2282. public override float Buoyancy
  2283. {
  2284. get { return m_buoyancy; }
  2285. set { m_buoyancy = value; }
  2286. }
  2287. public override void link(PhysicsActor obj)
  2288. {
  2289. m_taintparent = obj;
  2290. }
  2291. public override void delink()
  2292. {
  2293. m_taintparent = null;
  2294. }
  2295. public override void LockAngularMotion(Vector3 axis)
  2296. {
  2297. // reverse the zero/non zero values for ODE.
  2298. if (axis.IsFinite())
  2299. {
  2300. axis.X = (axis.X > 0) ? 1f : 0f;
  2301. axis.Y = (axis.Y > 0) ? 1f : 0f;
  2302. axis.Z = (axis.Z > 0) ? 1f : 0f;
  2303. m_log.DebugFormat("[axislock]: <{0},{1},{2}>", axis.X, axis.Y, axis.Z);
  2304. m_taintAngularLock = axis;
  2305. }
  2306. else
  2307. {
  2308. m_log.WarnFormat("[PHYSICS]: Got NaN locking axis from Scene on Object {0}", Name);
  2309. }
  2310. }
  2311. internal void UpdatePositionAndVelocity()
  2312. {
  2313. // no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
  2314. if (_parent == null)
  2315. {
  2316. Vector3 pv = Vector3.Zero;
  2317. bool lastZeroFlag = _zeroFlag;
  2318. float m_minvelocity = 0;
  2319. if (Body != (IntPtr)0) // FIXME -> or if it is a joint
  2320. {
  2321. d.Vector3 vec = d.BodyGetPosition(Body);
  2322. d.Quaternion ori = d.BodyGetQuaternion(Body);
  2323. d.Vector3 vel = d.BodyGetLinearVel(Body);
  2324. d.Vector3 rotvel = d.BodyGetAngularVel(Body);
  2325. d.Vector3 torque = d.BodyGetTorque(Body);
  2326. _torque = new Vector3(torque.X, torque.Y, torque.Z);
  2327. Vector3 l_position = Vector3.Zero;
  2328. Quaternion l_orientation = Quaternion.Identity;
  2329. // kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
  2330. //if (vec.X < 0.0f) { vec.X = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2331. //if (vec.Y < 0.0f) { vec.Y = 0.0f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2332. //if (vec.X > 255.95f) { vec.X = 255.95f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2333. //if (vec.Y > 255.95f) { vec.Y = 255.95f; if (Body != (IntPtr)0) d.BodySetAngularVel(Body, 0, 0, 0); }
  2334. m_lastposition = _position;
  2335. m_lastorientation = _orientation;
  2336. l_position.X = vec.X;
  2337. l_position.Y = vec.Y;
  2338. l_position.Z = vec.Z;
  2339. l_orientation.X = ori.X;
  2340. l_orientation.Y = ori.Y;
  2341. l_orientation.Z = ori.Z;
  2342. l_orientation.W = ori.W;
  2343. 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)
  2344. {
  2345. //base.RaiseOutOfBounds(l_position);
  2346. if (m_crossingfailures < _parent_scene.geomCrossingFailuresBeforeOutofbounds)
  2347. {
  2348. _position = l_position;
  2349. //_parent_scene.remActivePrim(this);
  2350. if (_parent == null)
  2351. base.RequestPhysicsterseUpdate();
  2352. return;
  2353. }
  2354. else
  2355. {
  2356. if (_parent == null)
  2357. base.RaiseOutOfBounds(l_position);
  2358. return;
  2359. }
  2360. }
  2361. if (l_position.Z < 0)
  2362. {
  2363. // This is so prim that get lost underground don't fall forever and suck up
  2364. //
  2365. // Sim resources and memory.
  2366. // Disables the prim's movement physics....
  2367. // It's a hack and will generate a console message if it fails.
  2368. //IsPhysical = false;
  2369. if (_parent == null)
  2370. base.RaiseOutOfBounds(_position);
  2371. _acceleration.X = 0;
  2372. _acceleration.Y = 0;
  2373. _acceleration.Z = 0;
  2374. _velocity.X = 0;
  2375. _velocity.Y = 0;
  2376. _velocity.Z = 0;
  2377. m_rotationalVelocity.X = 0;
  2378. m_rotationalVelocity.Y = 0;
  2379. m_rotationalVelocity.Z = 0;
  2380. if (_parent == null)
  2381. base.RequestPhysicsterseUpdate();
  2382. m_throttleUpdates = false;
  2383. throttleCounter = 0;
  2384. _zeroFlag = true;
  2385. //outofBounds = true;
  2386. }
  2387. //float Adiff = 1.0f - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation));
  2388. //Console.WriteLine("Adiff " + Name + " = " + Adiff);
  2389. if ((Math.Abs(m_lastposition.X - l_position.X) < 0.02)
  2390. && (Math.Abs(m_lastposition.Y - l_position.Y) < 0.02)
  2391. && (Math.Abs(m_lastposition.Z - l_position.Z) < 0.02)
  2392. // && (1.0 - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation)) < 0.01))
  2393. && (1.0 - Math.Abs(Quaternion.Dot(m_lastorientation, l_orientation)) < 0.0001)) // KF 0.01 is far to large
  2394. {
  2395. _zeroFlag = true;
  2396. //Console.WriteLine("ZFT 2");
  2397. m_throttleUpdates = false;
  2398. }
  2399. else
  2400. {
  2401. //m_log.Debug(Math.Abs(m_lastposition.X - l_position.X).ToString());
  2402. _zeroFlag = false;
  2403. m_lastUpdateSent = false;
  2404. //m_throttleUpdates = false;
  2405. }
  2406. if (_zeroFlag)
  2407. {
  2408. _velocity.X = 0.0f;
  2409. _velocity.Y = 0.0f;
  2410. _velocity.Z = 0.0f;
  2411. _acceleration.X = 0;
  2412. _acceleration.Y = 0;
  2413. _acceleration.Z = 0;
  2414. //_orientation.w = 0f;
  2415. //_orientation.X = 0f;
  2416. //_orientation.Y = 0f;
  2417. //_orientation.Z = 0f;
  2418. m_rotationalVelocity.X = 0;
  2419. m_rotationalVelocity.Y = 0;
  2420. m_rotationalVelocity.Z = 0;
  2421. if (!m_lastUpdateSent)
  2422. {
  2423. m_throttleUpdates = false;
  2424. throttleCounter = 0;
  2425. m_rotationalVelocity = pv;
  2426. if (_parent == null)
  2427. {
  2428. base.RequestPhysicsterseUpdate();
  2429. }
  2430. m_lastUpdateSent = true;
  2431. }
  2432. }
  2433. else
  2434. {
  2435. if (lastZeroFlag != _zeroFlag)
  2436. {
  2437. if (_parent == null)
  2438. {
  2439. base.RequestPhysicsterseUpdate();
  2440. }
  2441. }
  2442. m_lastVelocity = _velocity;
  2443. _position = l_position;
  2444. _velocity.X = vel.X;
  2445. _velocity.Y = vel.Y;
  2446. _velocity.Z = vel.Z;
  2447. _acceleration = ((_velocity - m_lastVelocity) / 0.1f);
  2448. _acceleration = new Vector3(_velocity.X - m_lastVelocity.X / 0.1f, _velocity.Y - m_lastVelocity.Y / 0.1f, _velocity.Z - m_lastVelocity.Z / 0.1f);
  2449. //m_log.Info("[PHYSICS]: V1: " + _velocity + " V2: " + m_lastVelocity + " Acceleration: " + _acceleration.ToString());
  2450. // Note here that linearvelocity is affecting angular velocity... so I'm guessing this is a vehicle specific thing...
  2451. // it does make sense to do this for tiny little instabilities with physical prim, however 0.5m/frame is fairly large.
  2452. // 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
  2453. // adding these logical exclusion situations to maintain this where I think it was intended to be.
  2454. if (m_throttleUpdates || PIDActive || (m_vehicle != null && m_vehicle.Type != Vehicle.TYPE_NONE) || (Amotor != IntPtr.Zero))
  2455. {
  2456. m_minvelocity = 0.5f;
  2457. }
  2458. else
  2459. {
  2460. m_minvelocity = 0.02f;
  2461. }
  2462. if (_velocity.ApproxEquals(pv, m_minvelocity))
  2463. {
  2464. m_rotationalVelocity = pv;
  2465. }
  2466. else
  2467. {
  2468. m_rotationalVelocity = new Vector3(rotvel.X, rotvel.Y, rotvel.Z);
  2469. }
  2470. //m_log.Debug("ODE: " + m_rotationalVelocity.ToString());
  2471. _orientation.X = ori.X;
  2472. _orientation.Y = ori.Y;
  2473. _orientation.Z = ori.Z;
  2474. _orientation.W = ori.W;
  2475. m_lastUpdateSent = false;
  2476. if (!m_throttleUpdates || throttleCounter > _parent_scene.geomUpdatesPerThrottledUpdate)
  2477. {
  2478. if (_parent == null)
  2479. {
  2480. base.RequestPhysicsterseUpdate();
  2481. }
  2482. }
  2483. else
  2484. {
  2485. throttleCounter++;
  2486. }
  2487. }
  2488. m_lastposition = l_position;
  2489. }
  2490. else
  2491. {
  2492. // Not a body.. so Make sure the client isn't interpolating
  2493. _velocity.X = 0;
  2494. _velocity.Y = 0;
  2495. _velocity.Z = 0;
  2496. _acceleration.X = 0;
  2497. _acceleration.Y = 0;
  2498. _acceleration.Z = 0;
  2499. m_rotationalVelocity.X = 0;
  2500. m_rotationalVelocity.Y = 0;
  2501. m_rotationalVelocity.Z = 0;
  2502. _zeroFlag = true;
  2503. }
  2504. }
  2505. }
  2506. public override bool FloatOnWater
  2507. {
  2508. set {
  2509. m_taintCollidesWater = value;
  2510. _parent_scene.AddPhysicsActorTaint(this);
  2511. }
  2512. }
  2513. public override void SetMomentum(Vector3 momentum)
  2514. {
  2515. }
  2516. public override Vector3 PIDTarget
  2517. {
  2518. set
  2519. {
  2520. if (value.IsFinite())
  2521. {
  2522. m_PIDTarget = value;
  2523. }
  2524. else
  2525. m_log.WarnFormat("[PHYSICS]: Got NaN PIDTarget from Scene on Object {0}", Name);
  2526. }
  2527. }
  2528. public override bool PIDActive { get; set; }
  2529. public override float PIDTau { set { m_PIDTau = value; } }
  2530. public override float PIDHoverHeight { set { m_PIDHoverHeight = value; ; } }
  2531. public override bool PIDHoverActive { set { m_useHoverPID = value; } }
  2532. public override PIDHoverType PIDHoverType { set { m_PIDHoverType = value; } }
  2533. public override float PIDHoverTau { set { m_PIDHoverTau = value; } }
  2534. public override Quaternion APIDTarget{ set { return; } }
  2535. public override bool APIDActive{ set { return; } }
  2536. public override float APIDStrength{ set { return; } }
  2537. public override float APIDDamping{ set { return; } }
  2538. private void createAMotor(Vector3 axis)
  2539. {
  2540. if (Body == IntPtr.Zero)
  2541. return;
  2542. if (Amotor != IntPtr.Zero)
  2543. {
  2544. d.JointDestroy(Amotor);
  2545. Amotor = IntPtr.Zero;
  2546. }
  2547. float axisnum = 3;
  2548. axisnum = (axisnum - (axis.X + axis.Y + axis.Z));
  2549. // PhysicsVector totalSize = new PhysicsVector(_size.X, _size.Y, _size.Z);
  2550. // Inverse Inertia Matrix, set the X, Y, and/r Z inertia to 0 then invert it again.
  2551. d.Mass objMass;
  2552. d.MassSetZero(out objMass);
  2553. DMassCopy(ref pMass, ref objMass);
  2554. //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);
  2555. Matrix4 dMassMat = FromDMass(objMass);
  2556. Matrix4 mathmat = Inverse(dMassMat);
  2557. /*
  2558. //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]);
  2559. mathmat = Inverse(mathmat);
  2560. objMass = FromMatrix4(mathmat, ref objMass);
  2561. //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);
  2562. mathmat = Inverse(mathmat);
  2563. */
  2564. if (axis.X == 0)
  2565. {
  2566. mathmat.M33 = 50.0000001f;
  2567. //objMass.I.M22 = 0;
  2568. }
  2569. if (axis.Y == 0)
  2570. {
  2571. mathmat.M22 = 50.0000001f;
  2572. //objMass.I.M11 = 0;
  2573. }
  2574. if (axis.Z == 0)
  2575. {
  2576. mathmat.M11 = 50.0000001f;
  2577. //objMass.I.M00 = 0;
  2578. }
  2579. mathmat = Inverse(mathmat);
  2580. objMass = FromMatrix4(mathmat, ref objMass);
  2581. //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);
  2582. //return;
  2583. if (d.MassCheck(ref objMass))
  2584. {
  2585. d.BodySetMass(Body, ref objMass);
  2586. }
  2587. else
  2588. {
  2589. //m_log.Debug("[PHYSICS]: Mass invalid, ignoring");
  2590. }
  2591. if (axisnum <= 0)
  2592. return;
  2593. // int dAMotorEuler = 1;
  2594. Amotor = d.JointCreateAMotor(_parent_scene.world, IntPtr.Zero);
  2595. d.JointAttach(Amotor, Body, IntPtr.Zero);
  2596. d.JointSetAMotorMode(Amotor, 0);
  2597. d.JointSetAMotorNumAxes(Amotor,(int)axisnum);
  2598. int i = 0;
  2599. if (axis.X == 0)
  2600. {
  2601. d.JointSetAMotorAxis(Amotor, i, 0, 1, 0, 0);
  2602. i++;
  2603. }
  2604. if (axis.Y == 0)
  2605. {
  2606. d.JointSetAMotorAxis(Amotor, i, 0, 0, 1, 0);
  2607. i++;
  2608. }
  2609. if (axis.Z == 0)
  2610. {
  2611. d.JointSetAMotorAxis(Amotor, i, 0, 0, 0, 1);
  2612. i++;
  2613. }
  2614. for (int j = 0; j < (int)axisnum; j++)
  2615. {
  2616. //d.JointSetAMotorAngle(Amotor, j, 0);
  2617. }
  2618. //d.JointSetAMotorAngle(Amotor, 1, 0);
  2619. //d.JointSetAMotorAngle(Amotor, 2, 0);
  2620. // These lowstops and high stops are effectively (no wiggle room)
  2621. d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, -0f);
  2622. d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0f);
  2623. d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, -0f);
  2624. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0f);
  2625. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f);
  2626. d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0f);
  2627. //d.JointSetAMotorParam(Amotor, (int) dParam.Vel, 9000f);
  2628. d.JointSetAMotorParam(Amotor, (int)dParam.FudgeFactor, 0f);
  2629. d.JointSetAMotorParam(Amotor, (int)dParam.FMax, Mass * 50f);//
  2630. }
  2631. private Matrix4 FromDMass(d.Mass pMass)
  2632. {
  2633. Matrix4 obj;
  2634. obj.M11 = pMass.I.M00;
  2635. obj.M12 = pMass.I.M01;
  2636. obj.M13 = pMass.I.M02;
  2637. obj.M14 = 0;
  2638. obj.M21 = pMass.I.M10;
  2639. obj.M22 = pMass.I.M11;
  2640. obj.M23 = pMass.I.M12;
  2641. obj.M24 = 0;
  2642. obj.M31 = pMass.I.M20;
  2643. obj.M32 = pMass.I.M21;
  2644. obj.M33 = pMass.I.M22;
  2645. obj.M34 = 0;
  2646. obj.M41 = 0;
  2647. obj.M42 = 0;
  2648. obj.M43 = 0;
  2649. obj.M44 = 1;
  2650. return obj;
  2651. }
  2652. private d.Mass FromMatrix4(Matrix4 pMat, ref d.Mass obj)
  2653. {
  2654. obj.I.M00 = pMat[0, 0];
  2655. obj.I.M01 = pMat[0, 1];
  2656. obj.I.M02 = pMat[0, 2];
  2657. obj.I.M10 = pMat[1, 0];
  2658. obj.I.M11 = pMat[1, 1];
  2659. obj.I.M12 = pMat[1, 2];
  2660. obj.I.M20 = pMat[2, 0];
  2661. obj.I.M21 = pMat[2, 1];
  2662. obj.I.M22 = pMat[2, 2];
  2663. return obj;
  2664. }
  2665. public override void SubscribeEvents(int ms)
  2666. {
  2667. m_eventsubscription = ms;
  2668. _parent_scene.AddCollisionEventReporting(this);
  2669. }
  2670. public override void UnSubscribeEvents()
  2671. {
  2672. _parent_scene.RemoveCollisionEventReporting(this);
  2673. m_eventsubscription = 0;
  2674. }
  2675. public void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
  2676. {
  2677. CollisionEventsThisFrame.AddCollider(CollidedWith, contact);
  2678. }
  2679. public void SendCollisions()
  2680. {
  2681. if (m_collisionsOnPreviousFrame || CollisionEventsThisFrame.Count > 0)
  2682. {
  2683. base.SendCollisionUpdate(CollisionEventsThisFrame);
  2684. if (CollisionEventsThisFrame.Count > 0)
  2685. {
  2686. m_collisionsOnPreviousFrame = true;
  2687. CollisionEventsThisFrame.Clear();
  2688. }
  2689. else
  2690. {
  2691. m_collisionsOnPreviousFrame = false;
  2692. }
  2693. }
  2694. }
  2695. public override bool SubscribedEvents()
  2696. {
  2697. if (m_eventsubscription > 0)
  2698. return true;
  2699. return false;
  2700. }
  2701. public static Matrix4 Inverse(Matrix4 pMat)
  2702. {
  2703. if (determinant3x3(pMat) == 0)
  2704. {
  2705. return Matrix4.Identity; // should probably throw an error. singluar matrix inverse not possible
  2706. }
  2707. return (Adjoint(pMat) / determinant3x3(pMat));
  2708. }
  2709. public static Matrix4 Adjoint(Matrix4 pMat)
  2710. {
  2711. Matrix4 adjointMatrix = new Matrix4();
  2712. for (int i=0; i<4; i++)
  2713. {
  2714. for (int j=0; j<4; j++)
  2715. {
  2716. Matrix4SetValue(ref adjointMatrix, i, j, (float)(Math.Pow(-1, i + j) * (determinant3x3(Minor(pMat, i, j)))));
  2717. }
  2718. }
  2719. adjointMatrix = Transpose(adjointMatrix);
  2720. return adjointMatrix;
  2721. }
  2722. public static Matrix4 Minor(Matrix4 matrix, int iRow, int iCol)
  2723. {
  2724. Matrix4 minor = new Matrix4();
  2725. int m = 0, n = 0;
  2726. for (int i = 0; i < 4; i++)
  2727. {
  2728. if (i == iRow)
  2729. continue;
  2730. n = 0;
  2731. for (int j = 0; j < 4; j++)
  2732. {
  2733. if (j == iCol)
  2734. continue;
  2735. Matrix4SetValue(ref minor, m,n, matrix[i, j]);
  2736. n++;
  2737. }
  2738. m++;
  2739. }
  2740. return minor;
  2741. }
  2742. public static Matrix4 Transpose(Matrix4 pMat)
  2743. {
  2744. Matrix4 transposeMatrix = new Matrix4();
  2745. for (int i = 0; i < 4; i++)
  2746. for (int j = 0; j < 4; j++)
  2747. Matrix4SetValue(ref transposeMatrix, i, j, pMat[j, i]);
  2748. return transposeMatrix;
  2749. }
  2750. public static void Matrix4SetValue(ref Matrix4 pMat, int r, int c, float val)
  2751. {
  2752. switch (r)
  2753. {
  2754. case 0:
  2755. switch (c)
  2756. {
  2757. case 0:
  2758. pMat.M11 = val;
  2759. break;
  2760. case 1:
  2761. pMat.M12 = val;
  2762. break;
  2763. case 2:
  2764. pMat.M13 = val;
  2765. break;
  2766. case 3:
  2767. pMat.M14 = val;
  2768. break;
  2769. }
  2770. break;
  2771. case 1:
  2772. switch (c)
  2773. {
  2774. case 0:
  2775. pMat.M21 = val;
  2776. break;
  2777. case 1:
  2778. pMat.M22 = val;
  2779. break;
  2780. case 2:
  2781. pMat.M23 = val;
  2782. break;
  2783. case 3:
  2784. pMat.M24 = val;
  2785. break;
  2786. }
  2787. break;
  2788. case 2:
  2789. switch (c)
  2790. {
  2791. case 0:
  2792. pMat.M31 = val;
  2793. break;
  2794. case 1:
  2795. pMat.M32 = val;
  2796. break;
  2797. case 2:
  2798. pMat.M33 = val;
  2799. break;
  2800. case 3:
  2801. pMat.M34 = val;
  2802. break;
  2803. }
  2804. break;
  2805. case 3:
  2806. switch (c)
  2807. {
  2808. case 0:
  2809. pMat.M41 = val;
  2810. break;
  2811. case 1:
  2812. pMat.M42 = val;
  2813. break;
  2814. case 2:
  2815. pMat.M43 = val;
  2816. break;
  2817. case 3:
  2818. pMat.M44 = val;
  2819. break;
  2820. }
  2821. break;
  2822. }
  2823. }
  2824. private static float determinant3x3(Matrix4 pMat)
  2825. {
  2826. float det = 0;
  2827. float diag1 = pMat[0, 0]*pMat[1, 1]*pMat[2, 2];
  2828. float diag2 = pMat[0, 1]*pMat[2, 1]*pMat[2, 0];
  2829. float diag3 = pMat[0, 2]*pMat[1, 0]*pMat[2, 1];
  2830. float diag4 = pMat[2, 0]*pMat[1, 1]*pMat[0, 2];
  2831. float diag5 = pMat[2, 1]*pMat[1, 2]*pMat[0, 0];
  2832. float diag6 = pMat[2, 2]*pMat[1, 0]*pMat[0, 1];
  2833. det = diag1 + diag2 + diag3 - (diag4 + diag5 + diag6);
  2834. return det;
  2835. }
  2836. private static void DMassCopy(ref d.Mass src, ref d.Mass dst)
  2837. {
  2838. dst.c.W = src.c.W;
  2839. dst.c.X = src.c.X;
  2840. dst.c.Y = src.c.Y;
  2841. dst.c.Z = src.c.Z;
  2842. dst.mass = src.mass;
  2843. dst.I.M00 = src.I.M00;
  2844. dst.I.M01 = src.I.M01;
  2845. dst.I.M02 = src.I.M02;
  2846. dst.I.M10 = src.I.M10;
  2847. dst.I.M11 = src.I.M11;
  2848. dst.I.M12 = src.I.M12;
  2849. dst.I.M20 = src.I.M20;
  2850. dst.I.M21 = src.I.M21;
  2851. dst.I.M22 = src.I.M22;
  2852. }
  2853. public override void SetMaterial(int pMaterial)
  2854. {
  2855. m_material = pMaterial;
  2856. }
  2857. private void CheckMeshAsset()
  2858. {
  2859. if (_pbs.SculptEntry && !m_assetFailed && _pbs.SculptTexture != UUID.Zero)
  2860. {
  2861. m_assetFailed = true;
  2862. Util.FireAndForget(delegate
  2863. {
  2864. RequestAssetDelegate assetProvider = _parent_scene.RequestAssetMethod;
  2865. if (assetProvider != null)
  2866. assetProvider(_pbs.SculptTexture, MeshAssetReceived);
  2867. }, null, "ODEPrim.CheckMeshAsset");
  2868. }
  2869. }
  2870. private void MeshAssetReceived(AssetBase asset)
  2871. {
  2872. if (asset != null && asset.Data != null && asset.Data.Length > 0)
  2873. {
  2874. if (!_pbs.SculptEntry)
  2875. return;
  2876. if (_pbs.SculptTexture.ToString() != asset.ID)
  2877. return;
  2878. _pbs.SculptData = new byte[asset.Data.Length];
  2879. asset.Data.CopyTo(_pbs.SculptData, 0);
  2880. // m_assetFailed = false;
  2881. // m_log.DebugFormat(
  2882. // "[ODE PRIM]: Received mesh/sculpt data asset {0} with {1} bytes for {2} at {3} in {4}",
  2883. // _pbs.SculptTexture, _pbs.SculptData.Length, Name, _position, _parent_scene.Name);
  2884. m_taintshape = true;
  2885. _parent_scene.AddPhysicsActorTaint(this);
  2886. }
  2887. else
  2888. {
  2889. m_log.WarnFormat(
  2890. "[ODE PRIM]: Could not get mesh/sculpt asset {0} for {1} at {2} in {3}",
  2891. _pbs.SculptTexture, Name, _position, _parent_scene.PhysicsSceneName);
  2892. }
  2893. }
  2894. }
  2895. }