1
0

ODEPrim.cs 122 KB

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