OdeScene.cs 176 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117
  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. // changes for varsize regions
  28. // note that raycasts need to have limited range
  29. // (even in normal regions)
  30. // or application thread stack may just blowup
  31. // see RayCast(ODERayCastRequest req)
  32. //#define USE_DRAWSTUFF
  33. //#define SPAM
  34. using System;
  35. using System.Collections.Generic;
  36. using System.Diagnostics;
  37. using System.IO;
  38. using System.Linq;
  39. using System.Reflection;
  40. using System.Runtime.InteropServices;
  41. using System.Threading;
  42. using log4net;
  43. using Nini.Config;
  44. using Mono.Addins;
  45. using Ode.NET;
  46. using OpenMetaverse;
  47. #if USE_DRAWSTUFF
  48. using Drawstuff.NET;
  49. #endif
  50. using OpenSim.Framework;
  51. using OpenSim.Region.PhysicsModules.SharedBase;
  52. using OpenSim.Region.Framework.Scenes;
  53. using OpenSim.Region.Framework.Interfaces;
  54. namespace OpenSim.Region.PhysicsModule.ODE
  55. {
  56. public enum StatusIndicators : int
  57. {
  58. Generic = 0,
  59. Start = 1,
  60. End = 2
  61. }
  62. // public struct sCollisionData
  63. // {
  64. // public uint ColliderLocalId;
  65. // public uint CollidedWithLocalId;
  66. // public int NumberOfCollisions;
  67. // public int CollisionType;
  68. // public int StatusIndicator;
  69. // public int lastframe;
  70. // }
  71. [Flags]
  72. public enum CollisionCategories : int
  73. {
  74. Disabled = 0,
  75. Geom = 0x00000001,
  76. Body = 0x00000002,
  77. Space = 0x00000004,
  78. Character = 0x00000008,
  79. Land = 0x00000010,
  80. Water = 0x00000020,
  81. Wind = 0x00000040,
  82. Sensor = 0x00000080,
  83. Selected = 0x00000100
  84. }
  85. /// <summary>
  86. /// Material type for a primitive
  87. /// </summary>
  88. public enum Material : int
  89. {
  90. /// <summary></summary>
  91. Stone = 0,
  92. /// <summary></summary>
  93. Metal = 1,
  94. /// <summary></summary>
  95. Glass = 2,
  96. /// <summary></summary>
  97. Wood = 3,
  98. /// <summary></summary>
  99. Flesh = 4,
  100. /// <summary></summary>
  101. Plastic = 5,
  102. /// <summary></summary>
  103. Rubber = 6
  104. }
  105. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ODEPhysicsScene")]
  106. public class OdeScene : PhysicsScene, INonSharedRegionModule
  107. {
  108. private readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.ToString());
  109. private bool m_Enabled = false;
  110. // private Dictionary<string, sCollisionData> m_storedCollisions = new Dictionary<string, sCollisionData>();
  111. /// <summary>
  112. /// Provide a sync object so that only one thread calls d.Collide() at a time across all OdeScene instances.
  113. /// </summary>
  114. /// <remarks>
  115. /// With ODE as of r1755 (though also tested on r1860), only one thread can call d.Collide() at a
  116. /// time, even where physics objects are in entirely different ODE worlds. This is because generating contacts
  117. /// uses a static cache at the ODE level.
  118. ///
  119. /// Without locking, simulators running multiple regions will eventually crash with a native stack trace similar
  120. /// to
  121. ///
  122. /// mono() [0x489171]
  123. /// mono() [0x4d154f]
  124. /// /lib/x86_64-linux-gnu/libpthread.so.0(+0xfc60) [0x7f6ded592c60]
  125. /// .../opensim/bin/libode-x86_64.so(_ZN6Opcode11OBBCollider8_CollideEPKNS_14AABBNoLeafNodeE+0xd7a) [0x7f6dd822628a]
  126. ///
  127. /// ODE provides an experimental option to cache in thread local storage but compiling ODE with this option
  128. /// causes OpenSimulator to immediately crash with a native stack trace similar to
  129. ///
  130. /// mono() [0x489171]
  131. /// mono() [0x4d154f]
  132. /// /lib/x86_64-linux-gnu/libpthread.so.0(+0xfc60) [0x7f03c9849c60]
  133. /// .../opensim/bin/libode-x86_64.so(_Z12dCollideCCTLP6dxGeomS0_iP12dContactGeomi+0x92) [0x7f03b44bcf82]
  134. /// </remarks>
  135. internal static Object UniversalColliderSyncObject = new Object();
  136. /// <summary>
  137. /// Is stats collecting enabled for this ODE scene?
  138. /// </summary>
  139. public bool CollectStats { get; set; }
  140. /// <summary>
  141. /// Statistics for this scene.
  142. /// </summary>
  143. private Dictionary<string, float> m_stats = new Dictionary<string, float>();
  144. /// <summary>
  145. /// Stat name for total number of avatars in this ODE scene.
  146. /// </summary>
  147. public const string ODETotalAvatarsStatName = "ODETotalAvatars";
  148. /// <summary>
  149. /// Stat name for total number of prims in this ODE scene.
  150. /// </summary>
  151. public const string ODETotalPrimsStatName = "ODETotalPrims";
  152. /// <summary>
  153. /// Stat name for total number of prims with active physics in this ODE scene.
  154. /// </summary>
  155. public const string ODEActivePrimsStatName = "ODEActivePrims";
  156. /// <summary>
  157. /// Stat name for the total time spent in ODE frame processing.
  158. /// </summary>
  159. /// <remarks>
  160. /// A sanity check for the main scene loop physics time.
  161. /// </remarks>
  162. public const string ODETotalFrameMsStatName = "ODETotalFrameMS";
  163. /// <summary>
  164. /// Stat name for time spent processing avatar taints per frame
  165. /// </summary>
  166. public const string ODEAvatarTaintMsStatName = "ODEAvatarTaintFrameMS";
  167. /// <summary>
  168. /// Stat name for time spent processing prim taints per frame
  169. /// </summary>
  170. public const string ODEPrimTaintMsStatName = "ODEPrimTaintFrameMS";
  171. /// <summary>
  172. /// Stat name for time spent calculating avatar forces per frame.
  173. /// </summary>
  174. public const string ODEAvatarForcesFrameMsStatName = "ODEAvatarForcesFrameMS";
  175. /// <summary>
  176. /// Stat name for time spent calculating prim forces per frame
  177. /// </summary>
  178. public const string ODEPrimForcesFrameMsStatName = "ODEPrimForcesFrameMS";
  179. /// <summary>
  180. /// Stat name for time spent fulfilling raycasting requests per frame
  181. /// </summary>
  182. public const string ODERaycastingFrameMsStatName = "ODERaycastingFrameMS";
  183. /// <summary>
  184. /// Stat name for time spent in native code that actually steps through the simulation.
  185. /// </summary>
  186. public const string ODENativeStepFrameMsStatName = "ODENativeStepFrameMS";
  187. /// <summary>
  188. /// Stat name for the number of milliseconds that ODE spends in native space collision code.
  189. /// </summary>
  190. public const string ODENativeSpaceCollisionFrameMsStatName = "ODENativeSpaceCollisionFrameMS";
  191. /// <summary>
  192. /// Stat name for milliseconds that ODE spends in native geom collision code.
  193. /// </summary>
  194. public const string ODENativeGeomCollisionFrameMsStatName = "ODENativeGeomCollisionFrameMS";
  195. /// <summary>
  196. /// Time spent in collision processing that is not spent in native space or geom collision code.
  197. /// </summary>
  198. public const string ODEOtherCollisionFrameMsStatName = "ODEOtherCollisionFrameMS";
  199. /// <summary>
  200. /// Stat name for time spent notifying listeners of collisions
  201. /// </summary>
  202. public const string ODECollisionNotificationFrameMsStatName = "ODECollisionNotificationFrameMS";
  203. /// <summary>
  204. /// Stat name for milliseconds spent updating avatar position and velocity
  205. /// </summary>
  206. public const string ODEAvatarUpdateFrameMsStatName = "ODEAvatarUpdateFrameMS";
  207. /// <summary>
  208. /// Stat name for the milliseconds spent updating prim position and velocity
  209. /// </summary>
  210. public const string ODEPrimUpdateFrameMsStatName = "ODEPrimUpdateFrameMS";
  211. /// <summary>
  212. /// Stat name for avatar collisions with another entity.
  213. /// </summary>
  214. public const string ODEAvatarContactsStatsName = "ODEAvatarContacts";
  215. /// <summary>
  216. /// Stat name for prim collisions with another entity.
  217. /// </summary>
  218. public const string ODEPrimContactsStatName = "ODEPrimContacts";
  219. /// <summary>
  220. /// Used to hold tick numbers for stat collection purposes.
  221. /// </summary>
  222. private int m_nativeCollisionStartTick;
  223. /// <summary>
  224. /// A messy way to tell if we need to avoid adding a collision time because this was already done in the callback.
  225. /// </summary>
  226. private bool m_inCollisionTiming;
  227. /// <summary>
  228. /// A temporary holder for the number of avatar collisions in a frame, so we can work out how many object
  229. /// collisions occured using the _perloopcontact if stats collection is enabled.
  230. /// </summary>
  231. private int m_tempAvatarCollisionsThisFrame;
  232. /// <summary>
  233. /// Used in calculating physics frame time dilation
  234. /// </summary>
  235. private int tickCountFrameRun;
  236. /// <summary>
  237. /// Used in calculating physics frame time dilation
  238. /// </summary>
  239. private int latertickcount;
  240. private Random fluidRandomizer = new Random(Environment.TickCount);
  241. public bool m_suportCombine = true;
  242. private uint m_regionWidth = Constants.RegionSize;
  243. private uint m_regionHeight = Constants.RegionSize;
  244. private float ODE_STEPSIZE = 0.0178f;
  245. private float metersInSpace = 29.9f;
  246. private float m_timeDilation = 1.0f;
  247. public float gravityx = 0f;
  248. public float gravityy = 0f;
  249. public float gravityz = -9.8f;
  250. public float AvatarTerminalVelocity { get; set; }
  251. private float contactsurfacelayer = 0.001f;
  252. private int worldHashspaceLow = -4;
  253. private int worldHashspaceHigh = 128;
  254. private int smallHashspaceLow = -4;
  255. private int smallHashspaceHigh = 66;
  256. private float waterlevel = 0f;
  257. private int framecount = 0;
  258. //private int m_returncollisions = 10;
  259. private IntPtr contactgroup;
  260. // internal IntPtr WaterGeom;
  261. private float nmTerrainContactFriction = 255.0f;
  262. private float nmTerrainContactBounce = 0.1f;
  263. private float nmTerrainContactERP = 0.1025f;
  264. private float mTerrainContactFriction = 75f;
  265. private float mTerrainContactBounce = 0.1f;
  266. private float mTerrainContactERP = 0.05025f;
  267. private float nmAvatarObjectContactFriction = 250f;
  268. private float nmAvatarObjectContactBounce = 0.1f;
  269. private float mAvatarObjectContactFriction = 75f;
  270. private float mAvatarObjectContactBounce = 0.1f;
  271. private float avPIDD = 3200f;
  272. private float avPIDP = 1400f;
  273. private float avCapRadius = 0.37f;
  274. private float avStandupTensor = 2000000f;
  275. /// <summary>
  276. /// true = old compatibility mode with leaning capsule; false = new corrected mode
  277. /// </summary>
  278. /// <remarks>
  279. /// Even when set to false, the capsule still tilts but this is done in a different way.
  280. /// </remarks>
  281. public bool IsAvCapsuleTilted { get; private set; }
  282. private float avDensity = 80f;
  283. // private float avHeightFudgeFactor = 0.52f;
  284. private float avMovementDivisorWalk = 1.3f;
  285. private float avMovementDivisorRun = 0.8f;
  286. private float minimumGroundFlightOffset = 3f;
  287. public float maximumMassObject = 10000.01f;
  288. public bool meshSculptedPrim = true;
  289. public bool forceSimplePrimMeshing = false;
  290. public float meshSculptLOD = 32;
  291. public float MeshSculptphysicalLOD = 16;
  292. public float geomDefaultDensity = 10.000006836f;
  293. public int geomContactPointsStartthrottle = 3;
  294. public int geomUpdatesPerThrottledUpdate = 15;
  295. private const int avatarExpectedContacts = 3;
  296. public float bodyPIDD = 35f;
  297. public float bodyPIDG = 25;
  298. public int geomCrossingFailuresBeforeOutofbounds = 5;
  299. public float bodyMotorJointMaxforceTensor = 2;
  300. public int bodyFramesAutoDisable = 20;
  301. private float[] _watermap;
  302. private bool m_filterCollisions = true;
  303. private d.NearCallback nearCallback;
  304. public d.TriCallback triCallback;
  305. public d.TriArrayCallback triArrayCallback;
  306. /// <summary>
  307. /// Avatars in the physics scene.
  308. /// </summary>
  309. private readonly HashSet<OdeCharacter> _characters = new HashSet<OdeCharacter>();
  310. /// <summary>
  311. /// Prims in the physics scene.
  312. /// </summary>
  313. private readonly HashSet<OdePrim> _prims = new HashSet<OdePrim>();
  314. /// <summary>
  315. /// Prims in the physics scene that are subject to physics, not just collisions.
  316. /// </summary>
  317. private readonly HashSet<OdePrim> _activeprims = new HashSet<OdePrim>();
  318. /// <summary>
  319. /// Prims that the simulator has created/deleted/updated and so need updating in ODE.
  320. /// </summary>
  321. private readonly HashSet<OdePrim> _taintedPrims = new HashSet<OdePrim>();
  322. /// <summary>
  323. /// Record a character that has taints to be processed.
  324. /// </summary>
  325. private readonly HashSet<OdeCharacter> _taintedActors = new HashSet<OdeCharacter>();
  326. /// <summary>
  327. /// Keep record of contacts in the physics loop so that we can remove duplicates.
  328. /// </summary>
  329. private readonly List<d.ContactGeom> _perloopContact = new List<d.ContactGeom>();
  330. /// <summary>
  331. /// A dictionary of actors that should receive collision events.
  332. /// </summary>
  333. private readonly Dictionary<uint, PhysicsActor> m_collisionEventActors = new Dictionary<uint, PhysicsActor>();
  334. /// <summary>
  335. /// A dictionary of collision event changes that are waiting to be processed.
  336. /// </summary>
  337. private readonly Dictionary<uint, PhysicsActor> m_collisionEventActorsChanges = new Dictionary<uint, PhysicsActor>();
  338. /// <summary>
  339. /// Maps a unique geometry id (a memory location) to a physics actor name.
  340. /// </summary>
  341. /// <remarks>
  342. /// Only actors participating in collisions have geometries. This has to be maintained separately from
  343. /// actor_name_map because terrain and water currently don't conceptually have a physics actor of their own
  344. /// apart from the singleton PANull
  345. /// </remarks>
  346. public Dictionary<IntPtr, String> geom_name_map = new Dictionary<IntPtr, String>();
  347. /// <summary>
  348. /// Maps a unique geometry id (a memory location) to a physics actor.
  349. /// </summary>
  350. /// <remarks>
  351. /// Only actors participating in collisions have geometries.
  352. /// </remarks>
  353. public Dictionary<IntPtr, PhysicsActor> actor_name_map = new Dictionary<IntPtr, PhysicsActor>();
  354. /// <summary>
  355. /// Defects list to remove characters that no longer have finite positions due to some other bug.
  356. /// </summary>
  357. /// <remarks>
  358. /// Used repeatedly in Simulate() but initialized once here.
  359. /// </remarks>
  360. private readonly List<OdeCharacter> defects = new List<OdeCharacter>();
  361. private bool m_NINJA_physics_joints_enabled = false;
  362. //private Dictionary<String, IntPtr> jointpart_name_map = new Dictionary<String,IntPtr>();
  363. private readonly Dictionary<String, List<PhysicsJoint>> joints_connecting_actor = new Dictionary<String, List<PhysicsJoint>>();
  364. private d.ContactGeom[] contacts;
  365. /// <summary>
  366. /// Lock only briefly. accessed by external code (to request new joints) and by OdeScene.Simulate() to move those joints into pending/active
  367. /// </summary>
  368. private readonly List<PhysicsJoint> requestedJointsToBeCreated = new List<PhysicsJoint>();
  369. /// <summary>
  370. /// can lock for longer. accessed only by OdeScene.
  371. /// </summary>
  372. private readonly List<PhysicsJoint> pendingJoints = new List<PhysicsJoint>();
  373. /// <summary>
  374. /// can lock for longer. accessed only by OdeScene.
  375. /// </summary>
  376. private readonly List<PhysicsJoint> activeJoints = new List<PhysicsJoint>();
  377. /// <summary>
  378. /// lock only briefly. accessed by external code (to request deletion of joints) and by OdeScene.Simulate() to move those joints out of pending/active
  379. /// </summary>
  380. private readonly List<string> requestedJointsToBeDeleted = new List<string>();
  381. private Object externalJointRequestsLock = new Object();
  382. private readonly Dictionary<String, PhysicsJoint> SOPName_to_activeJoint = new Dictionary<String, PhysicsJoint>();
  383. private readonly Dictionary<String, PhysicsJoint> SOPName_to_pendingJoint = new Dictionary<String, PhysicsJoint>();
  384. private readonly DoubleDictionary<Vector3, IntPtr, IntPtr> RegionTerrain = new DoubleDictionary<Vector3, IntPtr, IntPtr>();
  385. private readonly Dictionary<IntPtr,float[]> TerrainHeightFieldHeights = new Dictionary<IntPtr, float[]>();
  386. private d.Contact contact;
  387. private d.Contact TerrainContact;
  388. private d.Contact AvatarMovementprimContact;
  389. private d.Contact AvatarMovementTerrainContact;
  390. private d.Contact WaterContact;
  391. private d.Contact[,] m_materialContacts;
  392. //Ckrinke: Comment out until used. We declare it, initialize it, but do not use it
  393. //Ckrinke private int m_randomizeWater = 200;
  394. private int m_physicsiterations = 10;
  395. private const float m_SkipFramesAtms = 0.40f; // Drop frames gracefully at a 400 ms lag
  396. private readonly PhysicsActor PANull = new NullPhysicsActor();
  397. // private float step_time = 0.0f;
  398. //Ckrinke: Comment out until used. We declare it, initialize it, but do not use it
  399. //Ckrinke private int ms = 0;
  400. public IntPtr world;
  401. //private bool returncollisions = false;
  402. // private uint obj1LocalID = 0;
  403. private uint obj2LocalID = 0;
  404. //private int ctype = 0;
  405. private OdeCharacter cc1;
  406. private OdePrim cp1;
  407. private OdeCharacter cc2;
  408. private OdePrim cp2;
  409. private int p1ExpectedPoints = 0;
  410. private int p2ExpectedPoints = 0;
  411. //private int cStartStop = 0;
  412. //private string cDictKey = "";
  413. public IntPtr space;
  414. //private IntPtr tmpSpace;
  415. // split static geometry collision handling into spaces of 30 meters
  416. public IntPtr[,] staticPrimspace;
  417. /// <summary>
  418. /// Used to lock the entire physics scene. Locked during the main part of Simulate()
  419. /// </summary>
  420. internal Object OdeLock = new Object();
  421. private bool _worldInitialized = false;
  422. public IMesher mesher;
  423. private IConfigSource m_config;
  424. public bool physics_logging = false;
  425. public int physics_logging_interval = 0;
  426. public bool physics_logging_append_existing_logfile = false;
  427. private bool avplanted = false;
  428. private bool av_av_collisions_off = false;
  429. public d.Vector3 xyz = new d.Vector3(128.1640f, 128.3079f, 25.7600f);
  430. public d.Vector3 hpr = new d.Vector3(125.5000f, -17.0000f, 0.0000f);
  431. private volatile int m_global_contactcount = 0;
  432. private Vector3 m_worldOffset = Vector3.Zero;
  433. public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize);
  434. private PhysicsScene m_parentScene = null;
  435. float spacesPerMeterX;
  436. float spacesPerMeterY;
  437. int spaceGridMaxX;
  438. int spaceGridMaxY;
  439. private ODERayCastRequestManager m_rayCastManager;
  440. #region INonSharedRegionModule
  441. public string Name
  442. {
  443. get { return "OpenDynamicsEngine"; }
  444. }
  445. public Type ReplaceableInterface
  446. {
  447. get { return null; }
  448. }
  449. public void Initialise(IConfigSource source)
  450. {
  451. // TODO: Move this out of Startup
  452. IConfig config = source.Configs["Startup"];
  453. if (config != null)
  454. {
  455. string physics = config.GetString("physics", string.Empty);
  456. if (physics == Name)
  457. {
  458. m_Enabled = true;
  459. m_config = source;
  460. // We do this so that OpenSimulator on Windows loads the correct native ODE library depending on whether
  461. // it's running as a 32-bit process or a 64-bit one. By invoking LoadLibary here, later DLLImports
  462. // will find it already loaded later on.
  463. //
  464. // This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
  465. // controlled in Ode.NET.dll.config
  466. if (Util.IsWindows())
  467. Util.LoadArchSpecificWindowsDll("ode.dll");
  468. // Initializing ODE only when a scene is created allows alternative ODE plugins to co-habit (according to
  469. // http://opensimulator.org/mantis/view.php?id=2750).
  470. d.InitODE();
  471. }
  472. }
  473. }
  474. public void Close()
  475. {
  476. }
  477. public void AddRegion(Scene scene)
  478. {
  479. if (!m_Enabled)
  480. return;
  481. EngineType = Name;
  482. PhysicsSceneName = EngineType + "/" + scene.RegionInfo.RegionName;
  483. scene.RegisterModuleInterface<PhysicsScene>(this);
  484. Vector3 extent = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, scene.RegionInfo.RegionSizeZ);
  485. Initialise(extent);
  486. InitialiseFromConfig(m_config);
  487. // This may not be that good since terrain may not be avaiable at this point
  488. base.Initialise(scene.PhysicsRequestAsset,
  489. (scene.Heightmap != null ? scene.Heightmap.GetFloatsSerialised() : new float[(int)(extent.X * extent.Y)]),
  490. (float)scene.RegionInfo.RegionSettings.WaterHeight);
  491. }
  492. public void RemoveRegion(Scene scene)
  493. {
  494. if (!m_Enabled)
  495. return;
  496. }
  497. public void RegionLoaded(Scene scene)
  498. {
  499. if (!m_Enabled)
  500. return;
  501. mesher = scene.RequestModuleInterface<IMesher>();
  502. if (mesher == null)
  503. m_log.WarnFormat("[ODE SCENE]: No mesher in {0}. Things will not work well.", PhysicsSceneName);
  504. }
  505. #endregion
  506. /// <summary>
  507. /// Initiailizes the scene
  508. /// Sets many properties that ODE requires to be stable
  509. /// These settings need to be tweaked 'exactly' right or weird stuff happens.
  510. /// </summary>
  511. private void Initialise(Vector3 regionExtent)
  512. {
  513. WorldExtents.X = regionExtent.X;
  514. m_regionWidth = (uint)regionExtent.X;
  515. WorldExtents.Y = regionExtent.Y;
  516. m_regionHeight = (uint)regionExtent.Y;
  517. m_suportCombine = false;
  518. nearCallback = near;
  519. triCallback = TriCallback;
  520. triArrayCallback = TriArrayCallback;
  521. m_rayCastManager = new ODERayCastRequestManager(this);
  522. // Create the world and the first space
  523. world = d.WorldCreate();
  524. space = d.HashSpaceCreate(IntPtr.Zero);
  525. contactgroup = d.JointGroupCreate(0);
  526. d.WorldSetAutoDisableFlag(world, false);
  527. #if USE_DRAWSTUFF
  528. Thread viewthread = new Thread(new ParameterizedThreadStart(startvisualization));
  529. viewthread.Start();
  530. #endif
  531. // _watermap = new float[258 * 258];
  532. // Zero out the prim spaces array (we split our space into smaller spaces so
  533. // we can hit test less.
  534. }
  535. #if USE_DRAWSTUFF
  536. public void startvisualization(object o)
  537. {
  538. ds.Functions fn;
  539. fn.version = ds.VERSION;
  540. fn.start = new ds.CallbackFunction(start);
  541. fn.step = new ds.CallbackFunction(step);
  542. fn.command = new ds.CallbackFunction(command);
  543. fn.stop = null;
  544. fn.path_to_textures = "./textures";
  545. string[] args = new string[0];
  546. ds.SimulationLoop(args.Length, args, 352, 288, ref fn);
  547. }
  548. #endif
  549. // Initialize from configs
  550. private void InitialiseFromConfig(IConfigSource config)
  551. {
  552. InitializeExtraStats();
  553. m_config = config;
  554. // Defaults
  555. if (Environment.OSVersion.Platform == PlatformID.Unix)
  556. {
  557. avPIDD = 3200.0f;
  558. avPIDP = 1400.0f;
  559. avStandupTensor = 2000000f;
  560. }
  561. else
  562. {
  563. avPIDD = 2200.0f;
  564. avPIDP = 900.0f;
  565. avStandupTensor = 550000f;
  566. }
  567. int contactsPerCollision = 80;
  568. if (m_config != null)
  569. {
  570. IConfig physicsconfig = m_config.Configs["ODEPhysicsSettings"];
  571. if (physicsconfig != null)
  572. {
  573. CollectStats = physicsconfig.GetBoolean("collect_stats", false);
  574. gravityx = physicsconfig.GetFloat("world_gravityx", 0f);
  575. gravityy = physicsconfig.GetFloat("world_gravityy", 0f);
  576. gravityz = physicsconfig.GetFloat("world_gravityz", -9.8f);
  577. float avatarTerminalVelocity = physicsconfig.GetFloat("avatar_terminal_velocity", 54f);
  578. AvatarTerminalVelocity = Util.Clamp<float>(avatarTerminalVelocity, 0, 255f);
  579. if (AvatarTerminalVelocity != avatarTerminalVelocity)
  580. {
  581. m_log.WarnFormat(
  582. "[ODE SCENE]: avatar_terminal_velocity of {0} is invalid. Clamping to {1}",
  583. avatarTerminalVelocity, AvatarTerminalVelocity);
  584. }
  585. worldHashspaceLow = physicsconfig.GetInt("world_hashspace_size_low", -4);
  586. worldHashspaceHigh = physicsconfig.GetInt("world_hashspace_size_high", 128);
  587. metersInSpace = physicsconfig.GetFloat("meters_in_small_space", 29.9f);
  588. smallHashspaceLow = physicsconfig.GetInt("small_hashspace_size_low", -4);
  589. smallHashspaceHigh = physicsconfig.GetInt("small_hashspace_size_high", 66);
  590. contactsurfacelayer = physicsconfig.GetFloat("world_contact_surface_layer", 0.001f);
  591. nmTerrainContactFriction = physicsconfig.GetFloat("nm_terraincontact_friction", 255.0f);
  592. nmTerrainContactBounce = physicsconfig.GetFloat("nm_terraincontact_bounce", 0.1f);
  593. nmTerrainContactERP = physicsconfig.GetFloat("nm_terraincontact_erp", 0.1025f);
  594. mTerrainContactFriction = physicsconfig.GetFloat("m_terraincontact_friction", 75f);
  595. mTerrainContactBounce = physicsconfig.GetFloat("m_terraincontact_bounce", 0.05f);
  596. mTerrainContactERP = physicsconfig.GetFloat("m_terraincontact_erp", 0.05025f);
  597. nmAvatarObjectContactFriction = physicsconfig.GetFloat("objectcontact_friction", 250f);
  598. nmAvatarObjectContactBounce = physicsconfig.GetFloat("objectcontact_bounce", 0.2f);
  599. mAvatarObjectContactFriction = physicsconfig.GetFloat("m_avatarobjectcontact_friction", 75f);
  600. mAvatarObjectContactBounce = physicsconfig.GetFloat("m_avatarobjectcontact_bounce", 0.1f);
  601. ODE_STEPSIZE = physicsconfig.GetFloat("world_stepsize", ODE_STEPSIZE);
  602. m_physicsiterations = physicsconfig.GetInt("world_internal_steps_without_collisions", 10);
  603. avDensity = physicsconfig.GetFloat("av_density", 80f);
  604. // avHeightFudgeFactor = physicsconfig.GetFloat("av_height_fudge_factor", 0.52f);
  605. avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", 1.3f);
  606. avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", 0.8f);
  607. avCapRadius = physicsconfig.GetFloat("av_capsule_radius", 0.37f);
  608. avplanted = physicsconfig.GetBoolean("av_planted", false);
  609. av_av_collisions_off = physicsconfig.GetBoolean("av_av_collisions_off", false);
  610. IsAvCapsuleTilted = physicsconfig.GetBoolean("av_capsule_tilted", false);
  611. contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80);
  612. geomContactPointsStartthrottle = physicsconfig.GetInt("geom_contactpoints_start_throttling", 5);
  613. geomUpdatesPerThrottledUpdate = physicsconfig.GetInt("geom_updates_before_throttled_update", 15);
  614. geomCrossingFailuresBeforeOutofbounds = physicsconfig.GetInt("geom_crossing_failures_before_outofbounds", 5);
  615. geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", 10.000006836f);
  616. bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", 20);
  617. bodyPIDD = physicsconfig.GetFloat("body_pid_derivative", 35f);
  618. bodyPIDG = physicsconfig.GetFloat("body_pid_gain", 25f);
  619. forceSimplePrimMeshing = physicsconfig.GetBoolean("force_simple_prim_meshing", forceSimplePrimMeshing);
  620. meshSculptedPrim = physicsconfig.GetBoolean("mesh_sculpted_prim", true);
  621. meshSculptLOD = physicsconfig.GetFloat("mesh_lod", 32f);
  622. MeshSculptphysicalLOD = physicsconfig.GetFloat("mesh_physical_lod", 16f);
  623. m_filterCollisions = physicsconfig.GetBoolean("filter_collisions", false);
  624. if (Environment.OSVersion.Platform == PlatformID.Unix)
  625. {
  626. avPIDD = physicsconfig.GetFloat("av_pid_derivative_linux", 2200.0f);
  627. avPIDP = physicsconfig.GetFloat("av_pid_proportional_linux", 900.0f);
  628. avStandupTensor = physicsconfig.GetFloat("av_capsule_standup_tensor_linux", 550000f);
  629. bodyMotorJointMaxforceTensor = physicsconfig.GetFloat("body_motor_joint_maxforce_tensor_linux", 5f);
  630. }
  631. else
  632. {
  633. avPIDD = physicsconfig.GetFloat("av_pid_derivative_win", 2200.0f);
  634. avPIDP = physicsconfig.GetFloat("av_pid_proportional_win", 900.0f);
  635. avStandupTensor = physicsconfig.GetFloat("av_capsule_standup_tensor_win", 550000f);
  636. bodyMotorJointMaxforceTensor = physicsconfig.GetFloat("body_motor_joint_maxforce_tensor_win", 5f);
  637. }
  638. physics_logging = physicsconfig.GetBoolean("physics_logging", false);
  639. physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
  640. physics_logging_append_existing_logfile = physicsconfig.GetBoolean("physics_logging_append_existing_logfile", false);
  641. m_NINJA_physics_joints_enabled = physicsconfig.GetBoolean("use_NINJA_physics_joints", false);
  642. minimumGroundFlightOffset = physicsconfig.GetFloat("minimum_ground_flight_offset", 3f);
  643. maximumMassObject = physicsconfig.GetFloat("maximum_mass_object", 10000.01f);
  644. }
  645. }
  646. contacts = new d.ContactGeom[contactsPerCollision];
  647. spacesPerMeterX = 1.0f / metersInSpace;
  648. spacesPerMeterY = 1.0f / metersInSpace;
  649. spaceGridMaxX = (int)(WorldExtents.X * spacesPerMeterX);
  650. spaceGridMaxY = (int)(WorldExtents.Y * spacesPerMeterY);
  651. // note: limit number of spaces
  652. if (spaceGridMaxX > 24)
  653. {
  654. spaceGridMaxX = 24;
  655. spacesPerMeterX = spaceGridMaxX / WorldExtents.X;
  656. }
  657. if (spaceGridMaxY > 24)
  658. {
  659. spaceGridMaxY = 24;
  660. spacesPerMeterY = spaceGridMaxY / WorldExtents.Y ;
  661. }
  662. staticPrimspace = new IntPtr[spaceGridMaxX, spaceGridMaxY];
  663. // make this index limits
  664. spaceGridMaxX--;
  665. spaceGridMaxY--;
  666. // Centeral contact friction and bounce
  667. // ckrinke 11/10/08 Enabling soft_erp but not soft_cfm until I figure out why
  668. // an avatar falls through in Z but not in X or Y when walking on a prim.
  669. contact.surface.mode |= d.ContactFlags.SoftERP;
  670. contact.surface.mu = nmAvatarObjectContactFriction;
  671. contact.surface.bounce = nmAvatarObjectContactBounce;
  672. contact.surface.soft_cfm = 0.010f;
  673. contact.surface.soft_erp = 0.010f;
  674. // Terrain contact friction and Bounce
  675. // This is the *non* moving version. Use this when an avatar
  676. // isn't moving to keep it in place better
  677. TerrainContact.surface.mode |= d.ContactFlags.SoftERP;
  678. TerrainContact.surface.mu = nmTerrainContactFriction;
  679. TerrainContact.surface.bounce = nmTerrainContactBounce;
  680. TerrainContact.surface.soft_erp = nmTerrainContactERP;
  681. WaterContact.surface.mode |= (d.ContactFlags.SoftERP | d.ContactFlags.SoftCFM);
  682. WaterContact.surface.mu = 0f; // No friction
  683. WaterContact.surface.bounce = 0.0f; // No bounce
  684. WaterContact.surface.soft_cfm = 0.010f;
  685. WaterContact.surface.soft_erp = 0.010f;
  686. // Prim contact friction and bounce
  687. // THis is the *non* moving version of friction and bounce
  688. // Use this when an avatar comes in contact with a prim
  689. // and is moving
  690. AvatarMovementprimContact.surface.mu = mAvatarObjectContactFriction;
  691. AvatarMovementprimContact.surface.bounce = mAvatarObjectContactBounce;
  692. // Terrain contact friction bounce and various error correcting calculations
  693. // Use this when an avatar is in contact with the terrain and moving.
  694. AvatarMovementTerrainContact.surface.mode |= d.ContactFlags.SoftERP;
  695. AvatarMovementTerrainContact.surface.mu = mTerrainContactFriction;
  696. AvatarMovementTerrainContact.surface.bounce = mTerrainContactBounce;
  697. AvatarMovementTerrainContact.surface.soft_erp = mTerrainContactERP;
  698. /*
  699. <summary></summary>
  700. Stone = 0,
  701. /// <summary></summary>
  702. Metal = 1,
  703. /// <summary></summary>
  704. Glass = 2,
  705. /// <summary></summary>
  706. Wood = 3,
  707. /// <summary></summary>
  708. Flesh = 4,
  709. /// <summary></summary>
  710. Plastic = 5,
  711. /// <summary></summary>
  712. Rubber = 6
  713. */
  714. m_materialContacts = new d.Contact[7,2];
  715. m_materialContacts[(int)Material.Stone, 0] = new d.Contact();
  716. m_materialContacts[(int)Material.Stone, 0].surface.mode |= d.ContactFlags.SoftERP;
  717. m_materialContacts[(int)Material.Stone, 0].surface.mu = nmAvatarObjectContactFriction;
  718. m_materialContacts[(int)Material.Stone, 0].surface.bounce = nmAvatarObjectContactBounce;
  719. m_materialContacts[(int)Material.Stone, 0].surface.soft_cfm = 0.010f;
  720. m_materialContacts[(int)Material.Stone, 0].surface.soft_erp = 0.010f;
  721. m_materialContacts[(int)Material.Stone, 1] = new d.Contact();
  722. m_materialContacts[(int)Material.Stone, 1].surface.mode |= d.ContactFlags.SoftERP;
  723. m_materialContacts[(int)Material.Stone, 1].surface.mu = mAvatarObjectContactFriction;
  724. m_materialContacts[(int)Material.Stone, 1].surface.bounce = mAvatarObjectContactBounce;
  725. m_materialContacts[(int)Material.Stone, 1].surface.soft_cfm = 0.010f;
  726. m_materialContacts[(int)Material.Stone, 1].surface.soft_erp = 0.010f;
  727. m_materialContacts[(int)Material.Metal, 0] = new d.Contact();
  728. m_materialContacts[(int)Material.Metal, 0].surface.mode |= d.ContactFlags.SoftERP;
  729. m_materialContacts[(int)Material.Metal, 0].surface.mu = nmAvatarObjectContactFriction;
  730. m_materialContacts[(int)Material.Metal, 0].surface.bounce = nmAvatarObjectContactBounce;
  731. m_materialContacts[(int)Material.Metal, 0].surface.soft_cfm = 0.010f;
  732. m_materialContacts[(int)Material.Metal, 0].surface.soft_erp = 0.010f;
  733. m_materialContacts[(int)Material.Metal, 1] = new d.Contact();
  734. m_materialContacts[(int)Material.Metal, 1].surface.mode |= d.ContactFlags.SoftERP;
  735. m_materialContacts[(int)Material.Metal, 1].surface.mu = mAvatarObjectContactFriction;
  736. m_materialContacts[(int)Material.Metal, 1].surface.bounce = mAvatarObjectContactBounce;
  737. m_materialContacts[(int)Material.Metal, 1].surface.soft_cfm = 0.010f;
  738. m_materialContacts[(int)Material.Metal, 1].surface.soft_erp = 0.010f;
  739. m_materialContacts[(int)Material.Glass, 0] = new d.Contact();
  740. m_materialContacts[(int)Material.Glass, 0].surface.mode |= d.ContactFlags.SoftERP;
  741. m_materialContacts[(int)Material.Glass, 0].surface.mu = 1f;
  742. m_materialContacts[(int)Material.Glass, 0].surface.bounce = 0.5f;
  743. m_materialContacts[(int)Material.Glass, 0].surface.soft_cfm = 0.010f;
  744. m_materialContacts[(int)Material.Glass, 0].surface.soft_erp = 0.010f;
  745. /*
  746. private float nmAvatarObjectContactFriction = 250f;
  747. private float nmAvatarObjectContactBounce = 0.1f;
  748. private float mAvatarObjectContactFriction = 75f;
  749. private float mAvatarObjectContactBounce = 0.1f;
  750. */
  751. m_materialContacts[(int)Material.Glass, 1] = new d.Contact();
  752. m_materialContacts[(int)Material.Glass, 1].surface.mode |= d.ContactFlags.SoftERP;
  753. m_materialContacts[(int)Material.Glass, 1].surface.mu = 1f;
  754. m_materialContacts[(int)Material.Glass, 1].surface.bounce = 0.5f;
  755. m_materialContacts[(int)Material.Glass, 1].surface.soft_cfm = 0.010f;
  756. m_materialContacts[(int)Material.Glass, 1].surface.soft_erp = 0.010f;
  757. m_materialContacts[(int)Material.Wood, 0] = new d.Contact();
  758. m_materialContacts[(int)Material.Wood, 0].surface.mode |= d.ContactFlags.SoftERP;
  759. m_materialContacts[(int)Material.Wood, 0].surface.mu = nmAvatarObjectContactFriction;
  760. m_materialContacts[(int)Material.Wood, 0].surface.bounce = nmAvatarObjectContactBounce;
  761. m_materialContacts[(int)Material.Wood, 0].surface.soft_cfm = 0.010f;
  762. m_materialContacts[(int)Material.Wood, 0].surface.soft_erp = 0.010f;
  763. m_materialContacts[(int)Material.Wood, 1] = new d.Contact();
  764. m_materialContacts[(int)Material.Wood, 1].surface.mode |= d.ContactFlags.SoftERP;
  765. m_materialContacts[(int)Material.Wood, 1].surface.mu = mAvatarObjectContactFriction;
  766. m_materialContacts[(int)Material.Wood, 1].surface.bounce = mAvatarObjectContactBounce;
  767. m_materialContacts[(int)Material.Wood, 1].surface.soft_cfm = 0.010f;
  768. m_materialContacts[(int)Material.Wood, 1].surface.soft_erp = 0.010f;
  769. m_materialContacts[(int)Material.Flesh, 0] = new d.Contact();
  770. m_materialContacts[(int)Material.Flesh, 0].surface.mode |= d.ContactFlags.SoftERP;
  771. m_materialContacts[(int)Material.Flesh, 0].surface.mu = nmAvatarObjectContactFriction;
  772. m_materialContacts[(int)Material.Flesh, 0].surface.bounce = nmAvatarObjectContactBounce;
  773. m_materialContacts[(int)Material.Flesh, 0].surface.soft_cfm = 0.010f;
  774. m_materialContacts[(int)Material.Flesh, 0].surface.soft_erp = 0.010f;
  775. m_materialContacts[(int)Material.Flesh, 1] = new d.Contact();
  776. m_materialContacts[(int)Material.Flesh, 1].surface.mode |= d.ContactFlags.SoftERP;
  777. m_materialContacts[(int)Material.Flesh, 1].surface.mu = mAvatarObjectContactFriction;
  778. m_materialContacts[(int)Material.Flesh, 1].surface.bounce = mAvatarObjectContactBounce;
  779. m_materialContacts[(int)Material.Flesh, 1].surface.soft_cfm = 0.010f;
  780. m_materialContacts[(int)Material.Flesh, 1].surface.soft_erp = 0.010f;
  781. m_materialContacts[(int)Material.Plastic, 0] = new d.Contact();
  782. m_materialContacts[(int)Material.Plastic, 0].surface.mode |= d.ContactFlags.SoftERP;
  783. m_materialContacts[(int)Material.Plastic, 0].surface.mu = nmAvatarObjectContactFriction;
  784. m_materialContacts[(int)Material.Plastic, 0].surface.bounce = nmAvatarObjectContactBounce;
  785. m_materialContacts[(int)Material.Plastic, 0].surface.soft_cfm = 0.010f;
  786. m_materialContacts[(int)Material.Plastic, 0].surface.soft_erp = 0.010f;
  787. m_materialContacts[(int)Material.Plastic, 1] = new d.Contact();
  788. m_materialContacts[(int)Material.Plastic, 1].surface.mode |= d.ContactFlags.SoftERP;
  789. m_materialContacts[(int)Material.Plastic, 1].surface.mu = mAvatarObjectContactFriction;
  790. m_materialContacts[(int)Material.Plastic, 1].surface.bounce = mAvatarObjectContactBounce;
  791. m_materialContacts[(int)Material.Plastic, 1].surface.soft_cfm = 0.010f;
  792. m_materialContacts[(int)Material.Plastic, 1].surface.soft_erp = 0.010f;
  793. m_materialContacts[(int)Material.Rubber, 0] = new d.Contact();
  794. m_materialContacts[(int)Material.Rubber, 0].surface.mode |= d.ContactFlags.SoftERP;
  795. m_materialContacts[(int)Material.Rubber, 0].surface.mu = nmAvatarObjectContactFriction;
  796. m_materialContacts[(int)Material.Rubber, 0].surface.bounce = nmAvatarObjectContactBounce;
  797. m_materialContacts[(int)Material.Rubber, 0].surface.soft_cfm = 0.010f;
  798. m_materialContacts[(int)Material.Rubber, 0].surface.soft_erp = 0.010f;
  799. m_materialContacts[(int)Material.Rubber, 1] = new d.Contact();
  800. m_materialContacts[(int)Material.Rubber, 1].surface.mode |= d.ContactFlags.SoftERP;
  801. m_materialContacts[(int)Material.Rubber, 1].surface.mu = mAvatarObjectContactFriction;
  802. m_materialContacts[(int)Material.Rubber, 1].surface.bounce = mAvatarObjectContactBounce;
  803. m_materialContacts[(int)Material.Rubber, 1].surface.soft_cfm = 0.010f;
  804. m_materialContacts[(int)Material.Rubber, 1].surface.soft_erp = 0.010f;
  805. d.HashSpaceSetLevels(space, worldHashspaceLow, worldHashspaceHigh);
  806. // Set the gravity,, don't disable things automatically (we set it explicitly on some things)
  807. d.WorldSetGravity(world, gravityx, gravityy, gravityz);
  808. d.WorldSetContactSurfaceLayer(world, contactsurfacelayer);
  809. d.WorldSetLinearDamping(world, 256f);
  810. d.WorldSetAngularDamping(world, 256f);
  811. d.WorldSetAngularDampingThreshold(world, 256f);
  812. d.WorldSetLinearDampingThreshold(world, 256f);
  813. d.WorldSetMaxAngularSpeed(world, 256f);
  814. // Set how many steps we go without running collision testing
  815. // This is in addition to the step size.
  816. // Essentially Steps * m_physicsiterations
  817. d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  818. //d.WorldSetContactMaxCorrectingVel(world, 1000.0f);
  819. for (int i = 0; i < staticPrimspace.GetLength(0); i++)
  820. {
  821. for (int j = 0; j < staticPrimspace.GetLength(1); j++)
  822. {
  823. staticPrimspace[i, j] = IntPtr.Zero;
  824. }
  825. }
  826. _worldInitialized = true;
  827. }
  828. // internal void waitForSpaceUnlock(IntPtr space)
  829. // {
  830. // //if (space != IntPtr.Zero)
  831. // //while (d.SpaceLockQuery(space)) { } // Wait and do nothing
  832. // }
  833. // /// <summary>
  834. // /// Debug space message for printing the space that a prim/avatar is in.
  835. // /// </summary>
  836. // /// <param name="pos"></param>
  837. // /// <returns>Returns which split up space the given position is in.</returns>
  838. // public string whichspaceamIin(Vector3 pos)
  839. // {
  840. // return calculateSpaceForGeom(pos).ToString();
  841. // }
  842. #region Collision Detection
  843. /// <summary>
  844. /// Collides two geometries.
  845. /// </summary>
  846. /// <returns></returns>
  847. /// <param name='geom1'></param>
  848. /// <param name='geom2'>/param>
  849. /// <param name='maxContacts'></param>
  850. /// <param name='contactsArray'></param>
  851. /// <param name='contactGeomSize'></param>
  852. private int CollideGeoms(
  853. IntPtr geom1, IntPtr geom2, int maxContacts, Ode.NET.d.ContactGeom[] contactsArray, int contactGeomSize)
  854. {
  855. int count;
  856. lock (OdeScene.UniversalColliderSyncObject)
  857. {
  858. // We do this inside the lock so that we don't count any delay in acquiring it
  859. if (CollectStats)
  860. m_nativeCollisionStartTick = Util.EnvironmentTickCount();
  861. count = d.Collide(geom1, geom2, maxContacts, contactsArray, contactGeomSize);
  862. }
  863. // We do this outside the lock so that any waiting threads aren't held up, though the effect is probably
  864. // negligable
  865. if (CollectStats)
  866. m_stats[ODENativeGeomCollisionFrameMsStatName]
  867. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  868. return count;
  869. }
  870. /// <summary>
  871. /// Collide two spaces or a space and a geometry.
  872. /// </summary>
  873. /// <param name='space1'></param>
  874. /// <param name='space2'>/param>
  875. /// <param name='data'></param>
  876. private void CollideSpaces(IntPtr space1, IntPtr space2, IntPtr data)
  877. {
  878. if (CollectStats)
  879. {
  880. m_inCollisionTiming = true;
  881. m_nativeCollisionStartTick = Util.EnvironmentTickCount();
  882. }
  883. d.SpaceCollide2(space1, space2, data, nearCallback);
  884. if (CollectStats && m_inCollisionTiming)
  885. {
  886. m_stats[ODENativeSpaceCollisionFrameMsStatName]
  887. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  888. m_inCollisionTiming = false;
  889. }
  890. }
  891. /// <summary>
  892. /// This is our near callback. A geometry is near a body
  893. /// </summary>
  894. /// <param name="space">The space that contains the geoms. Remember, spaces are also geoms</param>
  895. /// <param name="g1">a geometry or space</param>
  896. /// <param name="g2">another geometry or space</param>
  897. private void near(IntPtr space, IntPtr g1, IntPtr g2)
  898. {
  899. if (CollectStats && m_inCollisionTiming)
  900. {
  901. m_stats[ODENativeSpaceCollisionFrameMsStatName]
  902. += Util.EnvironmentTickCountSubtract(m_nativeCollisionStartTick);
  903. m_inCollisionTiming = false;
  904. }
  905. // m_log.DebugFormat("[PHYSICS]: Colliding {0} and {1} in {2}", g1, g2, space);
  906. // no lock here! It's invoked from within Simulate(), which is thread-locked
  907. // Test if we're colliding a geom with a space.
  908. // If so we have to drill down into the space recursively
  909. if (d.GeomIsSpace(g1) || d.GeomIsSpace(g2))
  910. {
  911. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  912. return;
  913. // Separating static prim geometry spaces.
  914. // We'll be calling near recursivly if one
  915. // of them is a space to find all of the
  916. // contact points in the space
  917. try
  918. {
  919. CollideSpaces(g1, g2, IntPtr.Zero);
  920. }
  921. catch (AccessViolationException)
  922. {
  923. m_log.Error("[ODE SCENE]: Unable to collide test a space");
  924. return;
  925. }
  926. //Colliding a space or a geom with a space or a geom. so drill down
  927. //Collide all geoms in each space..
  928. //if (d.GeomIsSpace(g1)) d.SpaceCollide(g1, IntPtr.Zero, nearCallback);
  929. //if (d.GeomIsSpace(g2)) d.SpaceCollide(g2, IntPtr.Zero, nearCallback);
  930. return;
  931. }
  932. if (g1 == IntPtr.Zero || g2 == IntPtr.Zero)
  933. return;
  934. IntPtr b1 = d.GeomGetBody(g1);
  935. IntPtr b2 = d.GeomGetBody(g2);
  936. // d.GeomClassID id = d.GeomGetClass(g1);
  937. String name1 = null;
  938. String name2 = null;
  939. if (!geom_name_map.TryGetValue(g1, out name1))
  940. {
  941. name1 = "null";
  942. }
  943. if (!geom_name_map.TryGetValue(g2, out name2))
  944. {
  945. name2 = "null";
  946. }
  947. //if (id == d.GeomClassId.TriMeshClass)
  948. //{
  949. // m_log.InfoFormat("near: A collision was detected between {1} and {2}", 0, name1, name2);
  950. //m_log.Debug("near: A collision was detected between {1} and {2}", 0, name1, name2);
  951. //}
  952. // Figure out how many contact points we have
  953. int count = 0;
  954. try
  955. {
  956. // Colliding Geom To Geom
  957. // This portion of the function 'was' blatantly ripped off from BoxStack.cs
  958. if (g1 == g2)
  959. return; // Can't collide with yourself
  960. if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
  961. return;
  962. count = CollideGeoms(g1, g2, contacts.Length, contacts, d.ContactGeom.SizeOf);
  963. // All code after this is only relevant if we have any collisions
  964. if (count <= 0)
  965. return;
  966. if (count > contacts.Length)
  967. m_log.Error("[ODE SCENE]: Got " + count + " contacts when we asked for a maximum of " + contacts.Length);
  968. }
  969. catch (SEHException)
  970. {
  971. m_log.Error(
  972. "[ODE SCENE]: The Operating system shut down ODE because of corrupt memory. This could be a result of really irregular terrain. If this repeats continuously, restart using Basic Physics and terrain fill your terrain. Restarting the sim.");
  973. base.TriggerPhysicsBasedRestart();
  974. }
  975. catch (Exception e)
  976. {
  977. m_log.ErrorFormat("[ODE SCENE]: Unable to collide test an object: {0}", e.Message);
  978. return;
  979. }
  980. PhysicsActor p1;
  981. PhysicsActor p2;
  982. p1ExpectedPoints = 0;
  983. p2ExpectedPoints = 0;
  984. if (!actor_name_map.TryGetValue(g1, out p1))
  985. {
  986. p1 = PANull;
  987. }
  988. if (!actor_name_map.TryGetValue(g2, out p2))
  989. {
  990. p2 = PANull;
  991. }
  992. ContactPoint maxDepthContact = new ContactPoint();
  993. if (p1.CollisionScore + count >= float.MaxValue)
  994. p1.CollisionScore = 0;
  995. p1.CollisionScore += count;
  996. if (p2.CollisionScore + count >= float.MaxValue)
  997. p2.CollisionScore = 0;
  998. p2.CollisionScore += count;
  999. for (int i = 0; i < count; i++)
  1000. {
  1001. d.ContactGeom curContact = contacts[i];
  1002. if (curContact.depth > maxDepthContact.PenetrationDepth)
  1003. {
  1004. maxDepthContact = new ContactPoint(
  1005. new Vector3(curContact.pos.X, curContact.pos.Y, curContact.pos.Z),
  1006. new Vector3(curContact.normal.X, curContact.normal.Y, curContact.normal.Z),
  1007. curContact.depth
  1008. );
  1009. }
  1010. //m_log.Warn("[CCOUNT]: " + count);
  1011. IntPtr joint;
  1012. // If we're colliding with terrain, use 'TerrainContact' instead of contact.
  1013. // allows us to have different settings
  1014. // We only need to test p2 for 'jump crouch purposes'
  1015. if (p2 is OdeCharacter && p1.PhysicsActorType == (int)ActorTypes.Prim)
  1016. {
  1017. // Testing if the collision is at the feet of the avatar
  1018. //m_log.DebugFormat("[PHYSICS]: {0} - {1} - {2} - {3}", curContact.pos.Z, p2.Position.Z, (p2.Position.Z - curContact.pos.Z), (p2.Size.Z * 0.6f));
  1019. if ((p2.Position.Z - curContact.pos.Z) > (p2.Size.Z * 0.6f))
  1020. p2.IsColliding = true;
  1021. }
  1022. else
  1023. {
  1024. p2.IsColliding = true;
  1025. }
  1026. //if ((framecount % m_returncollisions) == 0)
  1027. switch (p1.PhysicsActorType)
  1028. {
  1029. case (int)ActorTypes.Agent:
  1030. p1ExpectedPoints = avatarExpectedContacts;
  1031. p2.CollidingObj = true;
  1032. break;
  1033. case (int)ActorTypes.Prim:
  1034. if (p1 != null && p1 is OdePrim)
  1035. p1ExpectedPoints = ((OdePrim) p1).ExpectedCollisionContacts;
  1036. if (p2.Velocity.LengthSquared() > 0.0f)
  1037. p2.CollidingObj = true;
  1038. break;
  1039. case (int)ActorTypes.Unknown:
  1040. p2.CollidingGround = true;
  1041. break;
  1042. default:
  1043. p2.CollidingGround = true;
  1044. break;
  1045. }
  1046. // we don't want prim or avatar to explode
  1047. #region InterPenetration Handling - Unintended physics explosions
  1048. # region disabled code1
  1049. if (curContact.depth >= 0.08f)
  1050. {
  1051. //This is disabled at the moment only because it needs more tweaking
  1052. //It will eventually be uncommented
  1053. /*
  1054. if (contact.depth >= 1.00f)
  1055. {
  1056. //m_log.Debug("[PHYSICS]: " + contact.depth.ToString());
  1057. }
  1058. //If you interpenetrate a prim with an agent
  1059. if ((p2.PhysicsActorType == (int) ActorTypes.Agent &&
  1060. p1.PhysicsActorType == (int) ActorTypes.Prim) ||
  1061. (p1.PhysicsActorType == (int) ActorTypes.Agent &&
  1062. p2.PhysicsActorType == (int) ActorTypes.Prim))
  1063. {
  1064. //contact.depth = contact.depth * 4.15f;
  1065. /*
  1066. if (p2.PhysicsActorType == (int) ActorTypes.Agent)
  1067. {
  1068. p2.CollidingObj = true;
  1069. contact.depth = 0.003f;
  1070. p2.Velocity = p2.Velocity + new PhysicsVector(0, 0, 2.5f);
  1071. OdeCharacter character = (OdeCharacter) p2;
  1072. character.SetPidStatus(true);
  1073. contact.pos = new d.Vector3(contact.pos.X + (p1.Size.X / 2), contact.pos.Y + (p1.Size.Y / 2), contact.pos.Z + (p1.Size.Z / 2));
  1074. }
  1075. else
  1076. {
  1077. //contact.depth = 0.0000000f;
  1078. }
  1079. if (p1.PhysicsActorType == (int) ActorTypes.Agent)
  1080. {
  1081. p1.CollidingObj = true;
  1082. contact.depth = 0.003f;
  1083. p1.Velocity = p1.Velocity + new PhysicsVector(0, 0, 2.5f);
  1084. contact.pos = new d.Vector3(contact.pos.X + (p2.Size.X / 2), contact.pos.Y + (p2.Size.Y / 2), contact.pos.Z + (p2.Size.Z / 2));
  1085. OdeCharacter character = (OdeCharacter)p1;
  1086. character.SetPidStatus(true);
  1087. }
  1088. else
  1089. {
  1090. //contact.depth = 0.0000000f;
  1091. }
  1092. }
  1093. */
  1094. // If you interpenetrate a prim with another prim
  1095. /*
  1096. if (p1.PhysicsActorType == (int) ActorTypes.Prim && p2.PhysicsActorType == (int) ActorTypes.Prim)
  1097. {
  1098. #region disabledcode2
  1099. //OdePrim op1 = (OdePrim)p1;
  1100. //OdePrim op2 = (OdePrim)p2;
  1101. //op1.m_collisionscore++;
  1102. //op2.m_collisionscore++;
  1103. //if (op1.m_collisionscore > 8000 || op2.m_collisionscore > 8000)
  1104. //{
  1105. //op1.m_taintdisable = true;
  1106. //AddPhysicsActorTaint(p1);
  1107. //op2.m_taintdisable = true;
  1108. //AddPhysicsActorTaint(p2);
  1109. //}
  1110. //if (contact.depth >= 0.25f)
  1111. //{
  1112. // Don't collide, one or both prim will expld.
  1113. //op1.m_interpenetrationcount++;
  1114. //op2.m_interpenetrationcount++;
  1115. //interpenetrations_before_disable = 200;
  1116. //if (op1.m_interpenetrationcount >= interpenetrations_before_disable)
  1117. //{
  1118. //op1.m_taintdisable = true;
  1119. //AddPhysicsActorTaint(p1);
  1120. //}
  1121. //if (op2.m_interpenetrationcount >= interpenetrations_before_disable)
  1122. //{
  1123. // op2.m_taintdisable = true;
  1124. //AddPhysicsActorTaint(p2);
  1125. //}
  1126. //contact.depth = contact.depth / 8f;
  1127. //contact.normal = new d.Vector3(0, 0, 1);
  1128. //}
  1129. //if (op1.m_disabled || op2.m_disabled)
  1130. //{
  1131. //Manually disabled objects stay disabled
  1132. //contact.depth = 0f;
  1133. //}
  1134. #endregion
  1135. }
  1136. */
  1137. #endregion
  1138. if (curContact.depth >= 1.00f)
  1139. {
  1140. //m_log.Info("[P]: " + contact.depth.ToString());
  1141. if ((p2.PhysicsActorType == (int) ActorTypes.Agent &&
  1142. p1.PhysicsActorType == (int) ActorTypes.Unknown) ||
  1143. (p1.PhysicsActorType == (int) ActorTypes.Agent &&
  1144. p2.PhysicsActorType == (int) ActorTypes.Unknown))
  1145. {
  1146. if (p2.PhysicsActorType == (int) ActorTypes.Agent)
  1147. {
  1148. if (p2 is OdeCharacter)
  1149. {
  1150. OdeCharacter character = (OdeCharacter) p2;
  1151. //p2.CollidingObj = true;
  1152. curContact.depth = 0.00000003f;
  1153. p2.Velocity = p2.Velocity + new Vector3(0f, 0f, 0.5f);
  1154. curContact.pos =
  1155. new d.Vector3(curContact.pos.X + (p1.Size.X/2),
  1156. curContact.pos.Y + (p1.Size.Y/2),
  1157. curContact.pos.Z + (p1.Size.Z/2));
  1158. character.SetPidStatus(true);
  1159. }
  1160. }
  1161. if (p1.PhysicsActorType == (int) ActorTypes.Agent)
  1162. {
  1163. if (p1 is OdeCharacter)
  1164. {
  1165. OdeCharacter character = (OdeCharacter) p1;
  1166. //p2.CollidingObj = true;
  1167. curContact.depth = 0.00000003f;
  1168. p1.Velocity = p1.Velocity + new Vector3(0f, 0f, 0.5f);
  1169. curContact.pos =
  1170. new d.Vector3(curContact.pos.X + (p1.Size.X/2),
  1171. curContact.pos.Y + (p1.Size.Y/2),
  1172. curContact.pos.Z + (p1.Size.Z/2));
  1173. character.SetPidStatus(true);
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. #endregion
  1180. // Logic for collision handling
  1181. // Note, that if *all* contacts are skipped (VolumeDetect)
  1182. // The prim still detects (and forwards) collision events but
  1183. // appears to be phantom for the world
  1184. Boolean skipThisContact = false;
  1185. if ((p1 is OdePrim) && (((OdePrim)p1).m_isVolumeDetect))
  1186. skipThisContact = true; // No collision on volume detect prims
  1187. if (av_av_collisions_off)
  1188. if ((p1 is OdeCharacter) && (p2 is OdeCharacter))
  1189. skipThisContact = true;
  1190. if (!skipThisContact && (p2 is OdePrim) && (((OdePrim)p2).m_isVolumeDetect))
  1191. skipThisContact = true; // No collision on volume detect prims
  1192. if (!skipThisContact && curContact.depth < 0f)
  1193. skipThisContact = true;
  1194. if (!skipThisContact && checkDupe(curContact, p2.PhysicsActorType))
  1195. skipThisContact = true;
  1196. const int maxContactsbeforedeath = 4000;
  1197. joint = IntPtr.Zero;
  1198. if (!skipThisContact)
  1199. {
  1200. _perloopContact.Add(curContact);
  1201. if (name1 == "Terrain" || name2 == "Terrain")
  1202. {
  1203. if ((p2.PhysicsActorType == (int) ActorTypes.Agent) &&
  1204. (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  1205. {
  1206. p2ExpectedPoints = avatarExpectedContacts;
  1207. // Avatar is moving on terrain, use the movement terrain contact
  1208. AvatarMovementTerrainContact.geom = curContact;
  1209. if (m_global_contactcount < maxContactsbeforedeath)
  1210. {
  1211. joint = d.JointCreateContact(world, contactgroup, ref AvatarMovementTerrainContact);
  1212. m_global_contactcount++;
  1213. }
  1214. }
  1215. else
  1216. {
  1217. if (p2.PhysicsActorType == (int)ActorTypes.Agent)
  1218. {
  1219. p2ExpectedPoints = avatarExpectedContacts;
  1220. // Avatar is standing on terrain, use the non moving terrain contact
  1221. TerrainContact.geom = curContact;
  1222. if (m_global_contactcount < maxContactsbeforedeath)
  1223. {
  1224. joint = d.JointCreateContact(world, contactgroup, ref TerrainContact);
  1225. m_global_contactcount++;
  1226. }
  1227. }
  1228. else
  1229. {
  1230. if (p2.PhysicsActorType == (int)ActorTypes.Prim && p1.PhysicsActorType == (int)ActorTypes.Prim)
  1231. {
  1232. // prim prim contact
  1233. // int pj294950 = 0;
  1234. int movintYN = 0;
  1235. int material = (int) Material.Wood;
  1236. // prim terrain contact
  1237. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  1238. {
  1239. movintYN = 1;
  1240. }
  1241. if (p2 is OdePrim)
  1242. {
  1243. material = ((OdePrim) p2).m_material;
  1244. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1245. }
  1246. // Unnessesary because p1 is defined above
  1247. //if (p1 is OdePrim)
  1248. // {
  1249. // p1ExpectedPoints = ((OdePrim)p1).ExpectedCollisionContacts;
  1250. // }
  1251. //m_log.DebugFormat("Material: {0}", material);
  1252. m_materialContacts[material, movintYN].geom = curContact;
  1253. if (m_global_contactcount < maxContactsbeforedeath)
  1254. {
  1255. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  1256. m_global_contactcount++;
  1257. }
  1258. }
  1259. else
  1260. {
  1261. int movintYN = 0;
  1262. // prim terrain contact
  1263. if (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)
  1264. {
  1265. movintYN = 1;
  1266. }
  1267. int material = (int)Material.Wood;
  1268. if (p2 is OdePrim)
  1269. {
  1270. material = ((OdePrim)p2).m_material;
  1271. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1272. }
  1273. //m_log.DebugFormat("Material: {0}", material);
  1274. m_materialContacts[material, movintYN].geom = curContact;
  1275. if (m_global_contactcount < maxContactsbeforedeath)
  1276. {
  1277. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, movintYN]);
  1278. m_global_contactcount++;
  1279. }
  1280. }
  1281. }
  1282. }
  1283. //if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1284. //{
  1285. //m_log.Debug("[PHYSICS]: prim contacting with ground");
  1286. //}
  1287. }
  1288. else if (name1 == "Water" || name2 == "Water")
  1289. {
  1290. /*
  1291. if ((p2.PhysicsActorType == (int) ActorTypes.Prim))
  1292. {
  1293. }
  1294. else
  1295. {
  1296. }
  1297. */
  1298. //WaterContact.surface.soft_cfm = 0.0000f;
  1299. //WaterContact.surface.soft_erp = 0.00000f;
  1300. if (curContact.depth > 0.1f)
  1301. {
  1302. curContact.depth *= 52;
  1303. //contact.normal = new d.Vector3(0, 0, 1);
  1304. //contact.pos = new d.Vector3(0, 0, contact.pos.Z - 5f);
  1305. }
  1306. WaterContact.geom = curContact;
  1307. if (m_global_contactcount < maxContactsbeforedeath)
  1308. {
  1309. joint = d.JointCreateContact(world, contactgroup, ref WaterContact);
  1310. m_global_contactcount++;
  1311. }
  1312. //m_log.Info("[PHYSICS]: Prim Water Contact" + contact.depth);
  1313. }
  1314. else
  1315. {
  1316. if ((p2.PhysicsActorType == (int)ActorTypes.Agent))
  1317. {
  1318. p2ExpectedPoints = avatarExpectedContacts;
  1319. if ((Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f))
  1320. {
  1321. // Avatar is moving on a prim, use the Movement prim contact
  1322. AvatarMovementprimContact.geom = curContact;
  1323. if (m_global_contactcount < maxContactsbeforedeath)
  1324. {
  1325. joint = d.JointCreateContact(world, contactgroup, ref AvatarMovementprimContact);
  1326. m_global_contactcount++;
  1327. }
  1328. }
  1329. else
  1330. {
  1331. // Avatar is standing still on a prim, use the non movement contact
  1332. contact.geom = curContact;
  1333. if (m_global_contactcount < maxContactsbeforedeath)
  1334. {
  1335. joint = d.JointCreateContact(world, contactgroup, ref contact);
  1336. m_global_contactcount++;
  1337. }
  1338. }
  1339. }
  1340. else if (p2.PhysicsActorType == (int)ActorTypes.Prim)
  1341. {
  1342. //p1.PhysicsActorType
  1343. int material = (int)Material.Wood;
  1344. if (p2 is OdePrim)
  1345. {
  1346. material = ((OdePrim)p2).m_material;
  1347. p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts;
  1348. }
  1349. //m_log.DebugFormat("Material: {0}", material);
  1350. m_materialContacts[material, 0].geom = curContact;
  1351. if (m_global_contactcount < maxContactsbeforedeath)
  1352. {
  1353. joint = d.JointCreateContact(world, contactgroup, ref m_materialContacts[material, 0]);
  1354. m_global_contactcount++;
  1355. }
  1356. }
  1357. }
  1358. if (m_global_contactcount < maxContactsbeforedeath && joint != IntPtr.Zero) // stack collide!
  1359. {
  1360. d.JointAttach(joint, b1, b2);
  1361. m_global_contactcount++;
  1362. }
  1363. }
  1364. collision_accounting_events(p1, p2, maxDepthContact);
  1365. if (count > ((p1ExpectedPoints + p2ExpectedPoints) * 0.25) + (geomContactPointsStartthrottle))
  1366. {
  1367. // If there are more then 3 contact points, it's likely
  1368. // that we've got a pile of objects, so ...
  1369. // We don't want to send out hundreds of terse updates over and over again
  1370. // so lets throttle them and send them again after it's somewhat sorted out.
  1371. p2.ThrottleUpdates = true;
  1372. }
  1373. //m_log.Debug(count.ToString());
  1374. //m_log.Debug("near: A collision was detected between {1} and {2}", 0, name1, name2);
  1375. }
  1376. }
  1377. private bool checkDupe(d.ContactGeom contactGeom, int atype)
  1378. {
  1379. if (!m_filterCollisions)
  1380. return false;
  1381. bool result = false;
  1382. ActorTypes at = (ActorTypes)atype;
  1383. foreach (d.ContactGeom contact in _perloopContact)
  1384. {
  1385. //if ((contact.g1 == contactGeom.g1 && contact.g2 == contactGeom.g2))
  1386. //{
  1387. // || (contact.g2 == contactGeom.g1 && contact.g1 == contactGeom.g2)
  1388. if (at == ActorTypes.Agent)
  1389. {
  1390. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f)
  1391. && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f)
  1392. && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)))
  1393. {
  1394. if (Math.Abs(contact.depth - contactGeom.depth) < 0.052f)
  1395. {
  1396. //contactGeom.depth *= .00005f;
  1397. //m_log.DebugFormat("[Collsion]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1398. // m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1399. result = true;
  1400. break;
  1401. }
  1402. // else
  1403. // {
  1404. // //m_log.DebugFormat("[Collsion]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1405. // }
  1406. }
  1407. // else
  1408. // {
  1409. // //m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1410. // //int i = 0;
  1411. // }
  1412. }
  1413. else if (at == ActorTypes.Prim)
  1414. {
  1415. //d.AABB aabb1 = new d.AABB();
  1416. //d.AABB aabb2 = new d.AABB();
  1417. //d.GeomGetAABB(contactGeom.g2, out aabb2);
  1418. //d.GeomGetAABB(contactGeom.g1, out aabb1);
  1419. //aabb1.
  1420. if (((Math.Abs(contactGeom.normal.X - contact.normal.X) < 1.026f) && (Math.Abs(contactGeom.normal.Y - contact.normal.Y) < 0.303f) && (Math.Abs(contactGeom.normal.Z - contact.normal.Z) < 0.065f)))
  1421. {
  1422. if (contactGeom.normal.X == contact.normal.X && contactGeom.normal.Y == contact.normal.Y && contactGeom.normal.Z == contact.normal.Z)
  1423. {
  1424. if (Math.Abs(contact.depth - contactGeom.depth) < 0.272f)
  1425. {
  1426. result = true;
  1427. break;
  1428. }
  1429. }
  1430. //m_log.DebugFormat("[Collision]: Depth {0}", Math.Abs(contact.depth - contactGeom.depth));
  1431. //m_log.DebugFormat("[Collision]: <{0},{1},{2}>", Math.Abs(contactGeom.normal.X - contact.normal.X), Math.Abs(contactGeom.normal.Y - contact.normal.Y), Math.Abs(contactGeom.normal.Z - contact.normal.Z));
  1432. }
  1433. }
  1434. }
  1435. return result;
  1436. }
  1437. private void collision_accounting_events(PhysicsActor p1, PhysicsActor p2, ContactPoint contact)
  1438. {
  1439. // obj1LocalID = 0;
  1440. //returncollisions = false;
  1441. obj2LocalID = 0;
  1442. //ctype = 0;
  1443. //cStartStop = 0;
  1444. if (!p2.SubscribedEvents() && !p1.SubscribedEvents())
  1445. return;
  1446. switch ((ActorTypes)p2.PhysicsActorType)
  1447. {
  1448. case ActorTypes.Agent:
  1449. cc2 = (OdeCharacter)p2;
  1450. // obj1LocalID = cc2.m_localID;
  1451. switch ((ActorTypes)p1.PhysicsActorType)
  1452. {
  1453. case ActorTypes.Agent:
  1454. cc1 = (OdeCharacter)p1;
  1455. obj2LocalID = cc1.LocalID;
  1456. cc1.AddCollisionEvent(cc2.LocalID, contact);
  1457. //ctype = (int)CollisionCategories.Character;
  1458. //if (cc1.CollidingObj)
  1459. //cStartStop = (int)StatusIndicators.Generic;
  1460. //else
  1461. //cStartStop = (int)StatusIndicators.Start;
  1462. //returncollisions = true;
  1463. break;
  1464. case ActorTypes.Prim:
  1465. if (p1 is OdePrim)
  1466. {
  1467. cp1 = (OdePrim) p1;
  1468. obj2LocalID = cp1.LocalID;
  1469. cp1.AddCollisionEvent(cc2.LocalID, contact);
  1470. }
  1471. //ctype = (int)CollisionCategories.Geom;
  1472. //if (cp1.CollidingObj)
  1473. //cStartStop = (int)StatusIndicators.Generic;
  1474. //else
  1475. //cStartStop = (int)StatusIndicators.Start;
  1476. //returncollisions = true;
  1477. break;
  1478. case ActorTypes.Ground:
  1479. case ActorTypes.Unknown:
  1480. obj2LocalID = 0;
  1481. //ctype = (int)CollisionCategories.Land;
  1482. //returncollisions = true;
  1483. break;
  1484. }
  1485. cc2.AddCollisionEvent(obj2LocalID, contact);
  1486. break;
  1487. case ActorTypes.Prim:
  1488. if (p2 is OdePrim)
  1489. {
  1490. cp2 = (OdePrim) p2;
  1491. // obj1LocalID = cp2.m_localID;
  1492. switch ((ActorTypes) p1.PhysicsActorType)
  1493. {
  1494. case ActorTypes.Agent:
  1495. if (p1 is OdeCharacter)
  1496. {
  1497. cc1 = (OdeCharacter) p1;
  1498. obj2LocalID = cc1.LocalID;
  1499. cc1.AddCollisionEvent(cp2.LocalID, contact);
  1500. //ctype = (int)CollisionCategories.Character;
  1501. //if (cc1.CollidingObj)
  1502. //cStartStop = (int)StatusIndicators.Generic;
  1503. //else
  1504. //cStartStop = (int)StatusIndicators.Start;
  1505. //returncollisions = true;
  1506. }
  1507. break;
  1508. case ActorTypes.Prim:
  1509. if (p1 is OdePrim)
  1510. {
  1511. cp1 = (OdePrim) p1;
  1512. obj2LocalID = cp1.LocalID;
  1513. cp1.AddCollisionEvent(cp2.LocalID, contact);
  1514. //ctype = (int)CollisionCategories.Geom;
  1515. //if (cp1.CollidingObj)
  1516. //cStartStop = (int)StatusIndicators.Generic;
  1517. //else
  1518. //cStartStop = (int)StatusIndicators.Start;
  1519. //returncollisions = true;
  1520. }
  1521. break;
  1522. case ActorTypes.Ground:
  1523. case ActorTypes.Unknown:
  1524. obj2LocalID = 0;
  1525. //ctype = (int)CollisionCategories.Land;
  1526. //returncollisions = true;
  1527. break;
  1528. }
  1529. cp2.AddCollisionEvent(obj2LocalID, contact);
  1530. }
  1531. break;
  1532. }
  1533. //if (returncollisions)
  1534. //{
  1535. //lock (m_storedCollisions)
  1536. //{
  1537. //cDictKey = obj1LocalID.ToString() + obj2LocalID.ToString() + cStartStop.ToString() + ctype.ToString();
  1538. //if (m_storedCollisions.ContainsKey(cDictKey))
  1539. //{
  1540. //sCollisionData objd = m_storedCollisions[cDictKey];
  1541. //objd.NumberOfCollisions += 1;
  1542. //objd.lastframe = framecount;
  1543. //m_storedCollisions[cDictKey] = objd;
  1544. //}
  1545. //else
  1546. //{
  1547. //sCollisionData objd = new sCollisionData();
  1548. //objd.ColliderLocalId = obj1LocalID;
  1549. //objd.CollidedWithLocalId = obj2LocalID;
  1550. //objd.CollisionType = ctype;
  1551. //objd.NumberOfCollisions = 1;
  1552. //objd.lastframe = framecount;
  1553. //objd.StatusIndicator = cStartStop;
  1554. //m_storedCollisions.Add(cDictKey, objd);
  1555. //}
  1556. //}
  1557. // }
  1558. }
  1559. private int TriArrayCallback(IntPtr trimesh, IntPtr refObject, int[] triangleIndex, int triCount)
  1560. {
  1561. /* String name1 = null;
  1562. String name2 = null;
  1563. if (!geom_name_map.TryGetValue(trimesh, out name1))
  1564. {
  1565. name1 = "null";
  1566. }
  1567. if (!geom_name_map.TryGetValue(refObject, out name2))
  1568. {
  1569. name2 = "null";
  1570. }
  1571. m_log.InfoFormat("TriArrayCallback: A collision was detected between {1} and {2}", 0, name1, name2);
  1572. */
  1573. return 1;
  1574. }
  1575. private int TriCallback(IntPtr trimesh, IntPtr refObject, int triangleIndex)
  1576. {
  1577. // String name1 = null;
  1578. // String name2 = null;
  1579. //
  1580. // if (!geom_name_map.TryGetValue(trimesh, out name1))
  1581. // {
  1582. // name1 = "null";
  1583. // }
  1584. //
  1585. // if (!geom_name_map.TryGetValue(refObject, out name2))
  1586. // {
  1587. // name2 = "null";
  1588. // }
  1589. // m_log.InfoFormat("TriCallback: A collision was detected between {1} and {2}. Index was {3}", 0, name1, name2, triangleIndex);
  1590. d.Vector3 v0 = new d.Vector3();
  1591. d.Vector3 v1 = new d.Vector3();
  1592. d.Vector3 v2 = new d.Vector3();
  1593. d.GeomTriMeshGetTriangle(trimesh, 0, ref v0, ref v1, ref v2);
  1594. // m_log.DebugFormat("Triangle {0} is <{1},{2},{3}>, <{4},{5},{6}>, <{7},{8},{9}>", triangleIndex, v0.X, v0.Y, v0.Z, v1.X, v1.Y, v1.Z, v2.X, v2.Y, v2.Z);
  1595. return 1;
  1596. }
  1597. /// <summary>
  1598. /// This is our collision testing routine in ODE
  1599. /// </summary>
  1600. private void collision_optimized()
  1601. {
  1602. _perloopContact.Clear();
  1603. foreach (OdeCharacter chr in _characters)
  1604. {
  1605. // Reset the collision values to false
  1606. // since we don't know if we're colliding yet
  1607. if (chr.Shell == IntPtr.Zero || chr.Body == IntPtr.Zero)
  1608. continue;
  1609. chr.IsColliding = false;
  1610. chr.CollidingGround = false;
  1611. chr.CollidingObj = false;
  1612. // Test the avatar's geometry for collision with the space
  1613. // This will return near and the space that they are the closest to
  1614. // And we'll run this again against the avatar and the space segment
  1615. // This will return with a bunch of possible objects in the space segment
  1616. // and we'll run it again on all of them.
  1617. try
  1618. {
  1619. CollideSpaces(space, chr.Shell, IntPtr.Zero);
  1620. }
  1621. catch (AccessViolationException)
  1622. {
  1623. m_log.ErrorFormat("[ODE SCENE]: Unable to space collide {0}", PhysicsSceneName);
  1624. }
  1625. //float terrainheight = GetTerrainHeightAtXY(chr.Position.X, chr.Position.Y);
  1626. //if (chr.Position.Z + (chr.Velocity.Z * timeStep) < terrainheight + 10)
  1627. //{
  1628. //chr.Position.Z = terrainheight + 10.0f;
  1629. //forcedZ = true;
  1630. //}
  1631. }
  1632. if (CollectStats)
  1633. {
  1634. m_tempAvatarCollisionsThisFrame = _perloopContact.Count;
  1635. m_stats[ODEAvatarContactsStatsName] += m_tempAvatarCollisionsThisFrame;
  1636. }
  1637. List<OdePrim> removeprims = null;
  1638. foreach (OdePrim chr in _activeprims)
  1639. {
  1640. if (chr.Body != IntPtr.Zero && d.BodyIsEnabled(chr.Body) && (!chr.m_disabled))
  1641. {
  1642. try
  1643. {
  1644. lock (chr)
  1645. {
  1646. if (space != IntPtr.Zero && chr.prim_geom != IntPtr.Zero && chr.m_taintremove == false)
  1647. {
  1648. CollideSpaces(space, chr.prim_geom, IntPtr.Zero);
  1649. }
  1650. else
  1651. {
  1652. if (removeprims == null)
  1653. {
  1654. removeprims = new List<OdePrim>();
  1655. }
  1656. removeprims.Add(chr);
  1657. m_log.Error(
  1658. "[ODE SCENE]: unable to collide test active prim against space. The space was zero, the geom was zero or it was in the process of being removed. Removed it from the active prim list. This needs to be fixed!");
  1659. }
  1660. }
  1661. }
  1662. catch (AccessViolationException)
  1663. {
  1664. m_log.Error("[ODE SCENE]: Unable to space collide");
  1665. }
  1666. }
  1667. }
  1668. if (CollectStats)
  1669. m_stats[ODEPrimContactsStatName] += _perloopContact.Count - m_tempAvatarCollisionsThisFrame;
  1670. if (removeprims != null)
  1671. {
  1672. foreach (OdePrim chr in removeprims)
  1673. {
  1674. _activeprims.Remove(chr);
  1675. }
  1676. }
  1677. }
  1678. #endregion
  1679. public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
  1680. {
  1681. if (!m_suportCombine)
  1682. return;
  1683. m_worldOffset = offset;
  1684. WorldExtents = new Vector2(extents.X, extents.Y);
  1685. m_parentScene = pScene;
  1686. }
  1687. // Recovered for use by fly height. Kitto Flora
  1688. internal float GetTerrainHeightAtXY(float x, float y)
  1689. {
  1690. IntPtr heightFieldGeom = IntPtr.Zero;
  1691. int offsetX = 0;
  1692. int offsetY = 0;
  1693. if (m_suportCombine)
  1694. {
  1695. offsetX = ((int)(x / (int)Constants.RegionSize)) * (int)Constants.RegionSize;
  1696. offsetY = ((int)(y / (int)Constants.RegionSize)) * (int)Constants.RegionSize;
  1697. }
  1698. if(RegionTerrain.TryGetValue(new Vector3(offsetX,offsetY,0), out heightFieldGeom))
  1699. {
  1700. if (heightFieldGeom != IntPtr.Zero)
  1701. {
  1702. if (TerrainHeightFieldHeights.ContainsKey(heightFieldGeom))
  1703. {
  1704. int index;
  1705. if ((int)x > WorldExtents.X || (int)y > WorldExtents.Y ||
  1706. (int)x < 0.001f || (int)y < 0.001f)
  1707. return 0;
  1708. x = x - offsetX + 1f;
  1709. y = y - offsetY + 1f;
  1710. index = (int)((int)x * ((int)m_regionHeight +3) + (int)y);
  1711. if (index < TerrainHeightFieldHeights[heightFieldGeom].Length)
  1712. {
  1713. //m_log.DebugFormat("x{0} y{1} = {2}", x, y, (float)TerrainHeightFieldHeights[heightFieldGeom][index]);
  1714. return (float)TerrainHeightFieldHeights[heightFieldGeom][index];
  1715. }
  1716. else
  1717. return 0f;
  1718. }
  1719. else
  1720. {
  1721. return 0f;
  1722. }
  1723. }
  1724. else
  1725. {
  1726. return 0f;
  1727. }
  1728. }
  1729. else
  1730. {
  1731. return 0f;
  1732. }
  1733. }
  1734. // End recovered. Kitto Flora
  1735. /// <summary>
  1736. /// Add actor to the list that should receive collision events in the simulate loop.
  1737. /// </summary>
  1738. /// <param name="obj"></param>
  1739. internal void AddCollisionEventReporting(PhysicsActor obj)
  1740. {
  1741. // m_log.DebugFormat("[PHYSICS]: Adding {0} {1} to collision event reporting", obj.SOPName, obj.LocalID);
  1742. lock (m_collisionEventActorsChanges)
  1743. m_collisionEventActorsChanges[obj.LocalID] = obj;
  1744. }
  1745. /// <summary>
  1746. /// Remove actor from the list that should receive collision events in the simulate loop.
  1747. /// </summary>
  1748. /// <param name="obj"></param>
  1749. internal void RemoveCollisionEventReporting(PhysicsActor obj)
  1750. {
  1751. // m_log.DebugFormat("[PHYSICS]: Removing {0} {1} from collision event reporting", obj.SOPName, obj.LocalID);
  1752. lock (m_collisionEventActorsChanges)
  1753. m_collisionEventActorsChanges[obj.LocalID] = null;
  1754. }
  1755. #region Add/Remove Entities
  1756. public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
  1757. {
  1758. OdeCharacter newAv
  1759. = new OdeCharacter(
  1760. avName, this, position, velocity, size, avPIDD, avPIDP,
  1761. avCapRadius, avStandupTensor, avDensity,
  1762. avMovementDivisorWalk, avMovementDivisorRun);
  1763. newAv.Flying = isFlying;
  1764. newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset;
  1765. newAv.m_avatarplanted = avplanted;
  1766. return newAv;
  1767. }
  1768. public override void RemoveAvatar(PhysicsActor actor)
  1769. {
  1770. // m_log.DebugFormat(
  1771. // "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2}",
  1772. // actor.Name, actor.LocalID, Name);
  1773. ((OdeCharacter) actor).Destroy();
  1774. }
  1775. internal void AddCharacter(OdeCharacter chr)
  1776. {
  1777. chr.m_avatarplanted = avplanted;
  1778. if (!_characters.Contains(chr))
  1779. {
  1780. _characters.Add(chr);
  1781. // m_log.DebugFormat(
  1782. // "[ODE SCENE]: Adding physics character {0} {1} to physics scene {2}. Count now {3}",
  1783. // chr.Name, chr.LocalID, Name, _characters.Count);
  1784. if (chr.bad)
  1785. m_log.ErrorFormat("[ODE SCENE]: Added BAD actor {0} to characters list", chr.m_uuid);
  1786. }
  1787. else
  1788. {
  1789. m_log.ErrorFormat(
  1790. "[ODE SCENE]: Tried to add character {0} {1} but they are already in the set!",
  1791. chr.Name, chr.LocalID);
  1792. }
  1793. }
  1794. internal void RemoveCharacter(OdeCharacter chr)
  1795. {
  1796. if (_characters.Contains(chr))
  1797. {
  1798. _characters.Remove(chr);
  1799. // m_log.DebugFormat(
  1800. // "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2}. Count now {3}",
  1801. // chr.Name, chr.LocalID, Name, _characters.Count);
  1802. }
  1803. else
  1804. {
  1805. m_log.ErrorFormat(
  1806. "[ODE SCENE]: Tried to remove character {0} {1} but they are not in the list!",
  1807. chr.Name, chr.LocalID);
  1808. }
  1809. }
  1810. private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation,
  1811. PrimitiveBaseShape pbs, bool isphysical, uint localID)
  1812. {
  1813. Vector3 pos = position;
  1814. Vector3 siz = size;
  1815. Quaternion rot = rotation;
  1816. OdePrim newPrim;
  1817. lock (OdeLock)
  1818. {
  1819. newPrim = new OdePrim(name, this, pos, siz, rot, pbs, isphysical);
  1820. lock (_prims)
  1821. _prims.Add(newPrim);
  1822. }
  1823. newPrim.LocalID = localID;
  1824. return newPrim;
  1825. }
  1826. /// <summary>
  1827. /// Make this prim subject to physics.
  1828. /// </summary>
  1829. /// <param name="prim"></param>
  1830. internal void ActivatePrim(OdePrim prim)
  1831. {
  1832. // adds active prim.. (ones that should be iterated over in collisions_optimized
  1833. if (!_activeprims.Contains(prim))
  1834. _activeprims.Add(prim);
  1835. //else
  1836. // m_log.Warn("[PHYSICS]: Double Entry in _activeprims detected, potential crash immenent");
  1837. }
  1838. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
  1839. Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
  1840. {
  1841. // m_log.DebugFormat("[ODE SCENE]: Adding physics prim {0} {1} to physics scene {2}", primName, localid, Name);
  1842. return AddPrim(primName, position, size, rotation, pbs, isPhysical, localid);
  1843. }
  1844. public override float TimeDilation
  1845. {
  1846. get { return m_timeDilation; }
  1847. }
  1848. public override bool SupportsNINJAJoints
  1849. {
  1850. get { return m_NINJA_physics_joints_enabled; }
  1851. }
  1852. // internal utility function: must be called within a lock (OdeLock)
  1853. private void InternalAddActiveJoint(PhysicsJoint joint)
  1854. {
  1855. activeJoints.Add(joint);
  1856. SOPName_to_activeJoint.Add(joint.ObjectNameInScene, joint);
  1857. }
  1858. // internal utility function: must be called within a lock (OdeLock)
  1859. private void InternalAddPendingJoint(OdePhysicsJoint joint)
  1860. {
  1861. pendingJoints.Add(joint);
  1862. SOPName_to_pendingJoint.Add(joint.ObjectNameInScene, joint);
  1863. }
  1864. // internal utility function: must be called within a lock (OdeLock)
  1865. private void InternalRemovePendingJoint(PhysicsJoint joint)
  1866. {
  1867. pendingJoints.Remove(joint);
  1868. SOPName_to_pendingJoint.Remove(joint.ObjectNameInScene);
  1869. }
  1870. // internal utility function: must be called within a lock (OdeLock)
  1871. private void InternalRemoveActiveJoint(PhysicsJoint joint)
  1872. {
  1873. activeJoints.Remove(joint);
  1874. SOPName_to_activeJoint.Remove(joint.ObjectNameInScene);
  1875. }
  1876. public override void DumpJointInfo()
  1877. {
  1878. string hdr = "[NINJA] JOINTINFO: ";
  1879. foreach (PhysicsJoint j in pendingJoints)
  1880. {
  1881. m_log.Debug(hdr + " pending joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1882. }
  1883. m_log.Debug(hdr + pendingJoints.Count + " total pending joints");
  1884. foreach (string jointName in SOPName_to_pendingJoint.Keys)
  1885. {
  1886. m_log.Debug(hdr + " pending joints dict contains Name: " + jointName);
  1887. }
  1888. m_log.Debug(hdr + SOPName_to_pendingJoint.Keys.Count + " total pending joints dict entries");
  1889. foreach (PhysicsJoint j in activeJoints)
  1890. {
  1891. m_log.Debug(hdr + " active joint, Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1892. }
  1893. m_log.Debug(hdr + activeJoints.Count + " total active joints");
  1894. foreach (string jointName in SOPName_to_activeJoint.Keys)
  1895. {
  1896. m_log.Debug(hdr + " active joints dict contains Name: " + jointName);
  1897. }
  1898. m_log.Debug(hdr + SOPName_to_activeJoint.Keys.Count + " total active joints dict entries");
  1899. m_log.Debug(hdr + " Per-body joint connectivity information follows.");
  1900. m_log.Debug(hdr + joints_connecting_actor.Keys.Count + " bodies are connected by joints.");
  1901. foreach (string actorName in joints_connecting_actor.Keys)
  1902. {
  1903. m_log.Debug(hdr + " Actor " + actorName + " has the following joints connecting it");
  1904. foreach (PhysicsJoint j in joints_connecting_actor[actorName])
  1905. {
  1906. m_log.Debug(hdr + " * joint Name: " + j.ObjectNameInScene + " raw parms:" + j.RawParams);
  1907. }
  1908. m_log.Debug(hdr + joints_connecting_actor[actorName].Count + " connecting joints total for this actor");
  1909. }
  1910. }
  1911. public override void RequestJointDeletion(string ObjectNameInScene)
  1912. {
  1913. lock (externalJointRequestsLock)
  1914. {
  1915. if (!requestedJointsToBeDeleted.Contains(ObjectNameInScene)) // forbid same deletion request from entering twice to prevent spurious deletions processed asynchronously
  1916. {
  1917. requestedJointsToBeDeleted.Add(ObjectNameInScene);
  1918. }
  1919. }
  1920. }
  1921. private void DeleteRequestedJoints()
  1922. {
  1923. List<string> myRequestedJointsToBeDeleted;
  1924. lock (externalJointRequestsLock)
  1925. {
  1926. // make a local copy of the shared list for processing (threading issues)
  1927. myRequestedJointsToBeDeleted = new List<string>(requestedJointsToBeDeleted);
  1928. }
  1929. foreach (string jointName in myRequestedJointsToBeDeleted)
  1930. {
  1931. lock (OdeLock)
  1932. {
  1933. //m_log.Debug("[NINJA] trying to deleting requested joint " + jointName);
  1934. if (SOPName_to_activeJoint.ContainsKey(jointName) || SOPName_to_pendingJoint.ContainsKey(jointName))
  1935. {
  1936. OdePhysicsJoint joint = null;
  1937. if (SOPName_to_activeJoint.ContainsKey(jointName))
  1938. {
  1939. joint = SOPName_to_activeJoint[jointName] as OdePhysicsJoint;
  1940. InternalRemoveActiveJoint(joint);
  1941. }
  1942. else if (SOPName_to_pendingJoint.ContainsKey(jointName))
  1943. {
  1944. joint = SOPName_to_pendingJoint[jointName] as OdePhysicsJoint;
  1945. InternalRemovePendingJoint(joint);
  1946. }
  1947. if (joint != null)
  1948. {
  1949. //m_log.Debug("joint.BodyNames.Count is " + joint.BodyNames.Count + " and contents " + joint.BodyNames);
  1950. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  1951. {
  1952. string bodyName = joint.BodyNames[iBodyName];
  1953. if (bodyName != "NULL")
  1954. {
  1955. joints_connecting_actor[bodyName].Remove(joint);
  1956. if (joints_connecting_actor[bodyName].Count == 0)
  1957. {
  1958. joints_connecting_actor.Remove(bodyName);
  1959. }
  1960. }
  1961. }
  1962. DoJointDeactivated(joint);
  1963. if (joint.jointID != IntPtr.Zero)
  1964. {
  1965. d.JointDestroy(joint.jointID);
  1966. joint.jointID = IntPtr.Zero;
  1967. //DoJointErrorMessage(joint, "successfully destroyed joint " + jointName);
  1968. }
  1969. else
  1970. {
  1971. //m_log.Warn("[NINJA] Ignoring re-request to destroy joint " + jointName);
  1972. }
  1973. }
  1974. else
  1975. {
  1976. // DoJointErrorMessage(joint, "coult not find joint to destroy based on name " + jointName);
  1977. }
  1978. }
  1979. else
  1980. {
  1981. // DoJointErrorMessage(joint, "WARNING - joint removal failed, joint " + jointName);
  1982. }
  1983. }
  1984. }
  1985. // remove processed joints from the shared list
  1986. lock (externalJointRequestsLock)
  1987. {
  1988. foreach (string jointName in myRequestedJointsToBeDeleted)
  1989. {
  1990. requestedJointsToBeDeleted.Remove(jointName);
  1991. }
  1992. }
  1993. }
  1994. // for pending joints we don't know if their associated bodies exist yet or not.
  1995. // the joint is actually created during processing of the taints
  1996. private void CreateRequestedJoints()
  1997. {
  1998. List<PhysicsJoint> myRequestedJointsToBeCreated;
  1999. lock (externalJointRequestsLock)
  2000. {
  2001. // make a local copy of the shared list for processing (threading issues)
  2002. myRequestedJointsToBeCreated = new List<PhysicsJoint>(requestedJointsToBeCreated);
  2003. }
  2004. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  2005. {
  2006. lock (OdeLock)
  2007. {
  2008. if (SOPName_to_pendingJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_pendingJoint[joint.ObjectNameInScene] != null)
  2009. {
  2010. DoJointErrorMessage(joint, "WARNING: ignoring request to re-add already pending joint Name:" + joint.ObjectNameInScene + " type:" + joint.Type + " parms: " + joint.RawParams + " pos: " + joint.Position + " rot:" + joint.Rotation);
  2011. continue;
  2012. }
  2013. if (SOPName_to_activeJoint.ContainsKey(joint.ObjectNameInScene) && SOPName_to_activeJoint[joint.ObjectNameInScene] != null)
  2014. {
  2015. DoJointErrorMessage(joint, "WARNING: ignoring request to re-add already active joint Name:" + joint.ObjectNameInScene + " type:" + joint.Type + " parms: " + joint.RawParams + " pos: " + joint.Position + " rot:" + joint.Rotation);
  2016. continue;
  2017. }
  2018. InternalAddPendingJoint(joint as OdePhysicsJoint);
  2019. if (joint.BodyNames.Count >= 2)
  2020. {
  2021. for (int iBodyName = 0; iBodyName < 2; iBodyName++)
  2022. {
  2023. string bodyName = joint.BodyNames[iBodyName];
  2024. if (bodyName != "NULL")
  2025. {
  2026. if (!joints_connecting_actor.ContainsKey(bodyName))
  2027. {
  2028. joints_connecting_actor.Add(bodyName, new List<PhysicsJoint>());
  2029. }
  2030. joints_connecting_actor[bodyName].Add(joint);
  2031. }
  2032. }
  2033. }
  2034. }
  2035. }
  2036. // remove processed joints from shared list
  2037. lock (externalJointRequestsLock)
  2038. {
  2039. foreach (PhysicsJoint joint in myRequestedJointsToBeCreated)
  2040. {
  2041. requestedJointsToBeCreated.Remove(joint);
  2042. }
  2043. }
  2044. }
  2045. /// <summary>
  2046. /// Add a request for joint creation.
  2047. /// </summary>
  2048. /// <remarks>
  2049. /// this joint will just be added to a waiting list that is NOT processed during the main
  2050. /// Simulate() loop (to avoid deadlocks). After Simulate() is finished, we handle unprocessed joint requests.
  2051. /// </remarks>
  2052. /// <param name="objectNameInScene"></param>
  2053. /// <param name="jointType"></param>
  2054. /// <param name="position"></param>
  2055. /// <param name="rotation"></param>
  2056. /// <param name="parms"></param>
  2057. /// <param name="bodyNames"></param>
  2058. /// <param name="trackedBodyName"></param>
  2059. /// <param name="localRotation"></param>
  2060. /// <returns></returns>
  2061. public override PhysicsJoint RequestJointCreation(
  2062. string objectNameInScene, PhysicsJointType jointType, Vector3 position,
  2063. Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation)
  2064. {
  2065. OdePhysicsJoint joint = new OdePhysicsJoint();
  2066. joint.ObjectNameInScene = objectNameInScene;
  2067. joint.Type = jointType;
  2068. joint.Position = position;
  2069. joint.Rotation = rotation;
  2070. joint.RawParams = parms;
  2071. joint.BodyNames = new List<string>(bodyNames);
  2072. joint.TrackedBodyName = trackedBodyName;
  2073. joint.LocalRotation = localRotation;
  2074. joint.jointID = IntPtr.Zero;
  2075. joint.ErrorMessageCount = 0;
  2076. lock (externalJointRequestsLock)
  2077. {
  2078. if (!requestedJointsToBeCreated.Contains(joint)) // forbid same creation request from entering twice
  2079. {
  2080. requestedJointsToBeCreated.Add(joint);
  2081. }
  2082. }
  2083. return joint;
  2084. }
  2085. private void RemoveAllJointsConnectedToActor(PhysicsActor actor)
  2086. {
  2087. //m_log.Debug("RemoveAllJointsConnectedToActor: start");
  2088. if (actor.SOPName != null && joints_connecting_actor.ContainsKey(actor.SOPName) && joints_connecting_actor[actor.SOPName] != null)
  2089. {
  2090. List<PhysicsJoint> jointsToRemove = new List<PhysicsJoint>();
  2091. //TODO: merge these 2 loops (originally it was needed to avoid altering a list being iterated over, but it is no longer needed due to the joint request queue mechanism)
  2092. foreach (PhysicsJoint j in joints_connecting_actor[actor.SOPName])
  2093. {
  2094. jointsToRemove.Add(j);
  2095. }
  2096. foreach (PhysicsJoint j in jointsToRemove)
  2097. {
  2098. //m_log.Debug("RemoveAllJointsConnectedToActor: about to request deletion of " + j.ObjectNameInScene);
  2099. RequestJointDeletion(j.ObjectNameInScene);
  2100. //m_log.Debug("RemoveAllJointsConnectedToActor: done request deletion of " + j.ObjectNameInScene);
  2101. j.TrackedBodyName = null; // *IMMEDIATELY* prevent any further movement of this joint (else a deleted actor might cause spurious tracking motion of the joint for a few frames, leading to the joint proxy object disappearing)
  2102. }
  2103. }
  2104. }
  2105. public override void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor)
  2106. {
  2107. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: start");
  2108. lock (OdeLock)
  2109. {
  2110. //m_log.Debug("RemoveAllJointsConnectedToActorThreadLocked: got lock");
  2111. RemoveAllJointsConnectedToActor(actor);
  2112. }
  2113. }
  2114. // normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  2115. public override Vector3 GetJointAnchor(PhysicsJoint joint)
  2116. {
  2117. Debug.Assert(joint.IsInPhysicsEngine);
  2118. d.Vector3 pos = new d.Vector3();
  2119. if (!(joint is OdePhysicsJoint))
  2120. {
  2121. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  2122. }
  2123. else
  2124. {
  2125. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  2126. switch (odeJoint.Type)
  2127. {
  2128. case PhysicsJointType.Ball:
  2129. d.JointGetBallAnchor(odeJoint.jointID, out pos);
  2130. break;
  2131. case PhysicsJointType.Hinge:
  2132. d.JointGetHingeAnchor(odeJoint.jointID, out pos);
  2133. break;
  2134. }
  2135. }
  2136. return new Vector3(pos.X, pos.Y, pos.Z);
  2137. }
  2138. /// <summary>
  2139. /// Get joint axis.
  2140. /// </summary>
  2141. /// <remarks>
  2142. /// normally called from within OnJointMoved, which is called from within a lock (OdeLock)
  2143. /// WARNING: ODE sometimes returns <0,0,0> as the joint axis! Therefore this function
  2144. /// appears to be unreliable. Fortunately we can compute the joint axis ourselves by
  2145. /// keeping track of the joint's original orientation relative to one of the involved bodies.
  2146. /// </remarks>
  2147. /// <param name="joint"></param>
  2148. /// <returns></returns>
  2149. public override Vector3 GetJointAxis(PhysicsJoint joint)
  2150. {
  2151. Debug.Assert(joint.IsInPhysicsEngine);
  2152. d.Vector3 axis = new d.Vector3();
  2153. if (!(joint is OdePhysicsJoint))
  2154. {
  2155. DoJointErrorMessage(joint, "warning: non-ODE joint requesting anchor: " + joint.ObjectNameInScene);
  2156. }
  2157. else
  2158. {
  2159. OdePhysicsJoint odeJoint = (OdePhysicsJoint)joint;
  2160. switch (odeJoint.Type)
  2161. {
  2162. case PhysicsJointType.Ball:
  2163. DoJointErrorMessage(joint, "warning - axis requested for ball joint: " + joint.ObjectNameInScene);
  2164. break;
  2165. case PhysicsJointType.Hinge:
  2166. d.JointGetHingeAxis(odeJoint.jointID, out axis);
  2167. break;
  2168. }
  2169. }
  2170. return new Vector3(axis.X, axis.Y, axis.Z);
  2171. }
  2172. /// <summary>
  2173. /// Stop this prim being subject to physics
  2174. /// </summary>
  2175. /// <param name="prim"></param>
  2176. internal void DeactivatePrim(OdePrim prim)
  2177. {
  2178. _activeprims.Remove(prim);
  2179. }
  2180. public override void RemovePrim(PhysicsActor prim)
  2181. {
  2182. // As with all ODE physics operations, we don't remove the prim immediately but signal that it should be
  2183. // removed in the next physics simulate pass.
  2184. if (prim is OdePrim)
  2185. {
  2186. lock (OdeLock)
  2187. {
  2188. OdePrim p = (OdePrim) prim;
  2189. p.setPrimForRemoval();
  2190. AddPhysicsActorTaint(prim);
  2191. }
  2192. }
  2193. }
  2194. /// <summary>
  2195. /// This is called from within simulate but outside the locked portion
  2196. /// We need to do our own locking here
  2197. /// (Note: As of 20110801 this no longer appears to be true - this is being called within lock (odeLock) in
  2198. /// Simulate() -- justincc).
  2199. ///
  2200. /// Essentially, we need to remove the prim from our space segment, whatever segment it's in.
  2201. ///
  2202. /// If there are no more prim in the segment, we need to empty (spacedestroy)the segment and reclaim memory
  2203. /// that the space was using.
  2204. /// </summary>
  2205. /// <param name="prim"></param>
  2206. internal void RemovePrimThreadLocked(OdePrim prim)
  2207. {
  2208. // m_log.DebugFormat("[ODE SCENE]: Removing physical prim {0} {1}", prim.Name, prim.LocalID);
  2209. lock (prim)
  2210. {
  2211. RemoveCollisionEventReporting(prim);
  2212. if (prim.prim_geom != IntPtr.Zero)
  2213. {
  2214. prim.ResetTaints();
  2215. if (prim.IsPhysical)
  2216. {
  2217. prim.disableBody();
  2218. if (prim.childPrim)
  2219. {
  2220. prim.childPrim = false;
  2221. prim.Body = IntPtr.Zero;
  2222. prim.m_disabled = true;
  2223. prim.IsPhysical = false;
  2224. }
  2225. }
  2226. // we don't want to remove the main space
  2227. // If the geometry is in the targetspace, remove it from the target space
  2228. //m_log.Warn(prim.m_targetSpace);
  2229. //if (prim.m_targetSpace != IntPtr.Zero)
  2230. //{
  2231. //if (d.SpaceQuery(prim.m_targetSpace, prim.prim_geom))
  2232. //{
  2233. //if (d.GeomIsSpace(prim.m_targetSpace))
  2234. //{
  2235. //waitForSpaceUnlock(prim.m_targetSpace);
  2236. //d.SpaceRemove(prim.m_targetSpace, prim.prim_geom);
  2237. prim.m_targetSpace = IntPtr.Zero;
  2238. //}
  2239. //else
  2240. //{
  2241. // m_log.Info("[Physics]: Invalid Scene passed to 'removeprim from scene':" +
  2242. //((OdePrim)prim).m_targetSpace.ToString());
  2243. //}
  2244. //}
  2245. //}
  2246. //m_log.Warn(prim.prim_geom);
  2247. if (!prim.RemoveGeom())
  2248. m_log.Warn("[ODE SCENE]: Unable to remove prim from physics scene");
  2249. lock (_prims)
  2250. _prims.Remove(prim);
  2251. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  2252. //if (d.SpaceGetNumGeoms(prim.m_targetSpace) == 0)
  2253. //{
  2254. //if (prim.m_targetSpace != null)
  2255. //{
  2256. //if (d.GeomIsSpace(prim.m_targetSpace))
  2257. //{
  2258. //waitForSpaceUnlock(prim.m_targetSpace);
  2259. //d.SpaceRemove(space, prim.m_targetSpace);
  2260. // free up memory used by the space.
  2261. //d.SpaceDestroy(prim.m_targetSpace);
  2262. //int[] xyspace = calculateSpaceArrayItemFromPos(prim.Position);
  2263. //resetSpaceArrayItemToZero(xyspace[0], xyspace[1]);
  2264. //}
  2265. //else
  2266. //{
  2267. //m_log.Info("[Physics]: Invalid Scene passed to 'removeprim from scene':" +
  2268. //((OdePrim) prim).m_targetSpace.ToString());
  2269. //}
  2270. //}
  2271. //}
  2272. if (SupportsNINJAJoints)
  2273. RemoveAllJointsConnectedToActorThreadLocked(prim);
  2274. }
  2275. }
  2276. }
  2277. #endregion
  2278. #region Space Separation Calculation
  2279. /// <summary>
  2280. /// Takes a space pointer and zeros out the array we're using to hold the spaces
  2281. /// </summary>
  2282. /// <param name="pSpace"></param>
  2283. private void resetSpaceArrayItemToZero(IntPtr pSpace)
  2284. {
  2285. for (int x = 0; x < staticPrimspace.GetLength(0); x++)
  2286. {
  2287. for (int y = 0; y < staticPrimspace.GetLength(1); y++)
  2288. {
  2289. if (staticPrimspace[x, y] == pSpace)
  2290. staticPrimspace[x, y] = IntPtr.Zero;
  2291. }
  2292. }
  2293. }
  2294. // private void resetSpaceArrayItemToZero(int arrayitemX, int arrayitemY)
  2295. // {
  2296. // staticPrimspace[arrayitemX, arrayitemY] = IntPtr.Zero;
  2297. // }
  2298. /// <summary>
  2299. /// Called when a static prim moves. Allocates a space for the prim based on its position
  2300. /// </summary>
  2301. /// <param name="geom">the pointer to the geom that moved</param>
  2302. /// <param name="pos">the position that the geom moved to</param>
  2303. /// <param name="currentspace">a pointer to the space it was in before it was moved.</param>
  2304. /// <returns>a pointer to the new space it's in</returns>
  2305. internal IntPtr recalculateSpaceForGeom(IntPtr geom, Vector3 pos, IntPtr currentspace)
  2306. {
  2307. // Called from setting the Position and Size of an ODEPrim so
  2308. // it's already in locked space.
  2309. // we don't want to remove the main space
  2310. // we don't need to test physical here because this function should
  2311. // never be called if the prim is physical(active)
  2312. // All physical prim end up in the root space
  2313. //Thread.Sleep(20);
  2314. if (currentspace != space)
  2315. {
  2316. //m_log.Info("[SPACE]: C:" + currentspace.ToString() + " g:" + geom.ToString());
  2317. //if (currentspace == IntPtr.Zero)
  2318. //{
  2319. //int adfadf = 0;
  2320. //}
  2321. if (d.SpaceQuery(currentspace, geom) && currentspace != IntPtr.Zero)
  2322. {
  2323. if (d.GeomIsSpace(currentspace))
  2324. {
  2325. // waitForSpaceUnlock(currentspace);
  2326. d.SpaceRemove(currentspace, geom);
  2327. }
  2328. else
  2329. {
  2330. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" + currentspace +
  2331. " Geom:" + geom);
  2332. }
  2333. }
  2334. else
  2335. {
  2336. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  2337. if (sGeomIsIn != IntPtr.Zero)
  2338. {
  2339. if (d.GeomIsSpace(currentspace))
  2340. {
  2341. // waitForSpaceUnlock(sGeomIsIn);
  2342. d.SpaceRemove(sGeomIsIn, geom);
  2343. }
  2344. else
  2345. {
  2346. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2347. sGeomIsIn + " Geom:" + geom);
  2348. }
  2349. }
  2350. }
  2351. //If there are no more geometries in the sub-space, we don't need it in the main space anymore
  2352. if (d.SpaceGetNumGeoms(currentspace) == 0)
  2353. {
  2354. if (currentspace != IntPtr.Zero)
  2355. {
  2356. if (d.GeomIsSpace(currentspace))
  2357. {
  2358. // waitForSpaceUnlock(currentspace);
  2359. // waitForSpaceUnlock(space);
  2360. d.SpaceRemove(space, currentspace);
  2361. // free up memory used by the space.
  2362. //d.SpaceDestroy(currentspace);
  2363. resetSpaceArrayItemToZero(currentspace);
  2364. }
  2365. else
  2366. {
  2367. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2368. currentspace + " Geom:" + geom);
  2369. }
  2370. }
  2371. }
  2372. }
  2373. else
  2374. {
  2375. // this is a physical object that got disabled. ;.;
  2376. if (currentspace != IntPtr.Zero && geom != IntPtr.Zero)
  2377. {
  2378. if (d.SpaceQuery(currentspace, geom))
  2379. {
  2380. if (d.GeomIsSpace(currentspace))
  2381. {
  2382. // waitForSpaceUnlock(currentspace);
  2383. d.SpaceRemove(currentspace, geom);
  2384. }
  2385. else
  2386. {
  2387. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2388. currentspace + " Geom:" + geom);
  2389. }
  2390. }
  2391. else
  2392. {
  2393. IntPtr sGeomIsIn = d.GeomGetSpace(geom);
  2394. if (sGeomIsIn != IntPtr.Zero)
  2395. {
  2396. if (d.GeomIsSpace(sGeomIsIn))
  2397. {
  2398. // waitForSpaceUnlock(sGeomIsIn);
  2399. d.SpaceRemove(sGeomIsIn, geom);
  2400. }
  2401. else
  2402. {
  2403. m_log.Info("[ODE SCENE]: Invalid Scene passed to 'recalculatespace':" +
  2404. sGeomIsIn + " Geom:" + geom);
  2405. }
  2406. }
  2407. }
  2408. }
  2409. }
  2410. // The routines in the Position and Size sections do the 'inserting' into the space,
  2411. // so all we have to do is make sure that the space that we're putting the prim into
  2412. // is in the 'main' space.
  2413. int[] iprimspaceArrItem = calculateSpaceArrayItemFromPos(pos);
  2414. IntPtr newspace = calculateSpaceForGeom(pos);
  2415. if (newspace == IntPtr.Zero)
  2416. {
  2417. newspace = createprimspace(iprimspaceArrItem[0], iprimspaceArrItem[1]);
  2418. d.HashSpaceSetLevels(newspace, smallHashspaceLow, smallHashspaceHigh);
  2419. }
  2420. return newspace;
  2421. }
  2422. /// <summary>
  2423. /// Creates a new space at X Y
  2424. /// </summary>
  2425. /// <param name="iprimspaceArrItemX"></param>
  2426. /// <param name="iprimspaceArrItemY"></param>
  2427. /// <returns>A pointer to the created space</returns>
  2428. internal IntPtr createprimspace(int iprimspaceArrItemX, int iprimspaceArrItemY)
  2429. {
  2430. // creating a new space for prim and inserting it into main space.
  2431. staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY] = d.HashSpaceCreate(IntPtr.Zero);
  2432. d.GeomSetCategoryBits(staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY], (int)CollisionCategories.Space);
  2433. // waitForSpaceUnlock(space);
  2434. d.SpaceSetSublevel(space, 1);
  2435. d.SpaceAdd(space, staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY]);
  2436. return staticPrimspace[iprimspaceArrItemX, iprimspaceArrItemY];
  2437. }
  2438. /// <summary>
  2439. /// Calculates the space the prim should be in by its position
  2440. /// </summary>
  2441. /// <param name="pos"></param>
  2442. /// <returns>a pointer to the space. This could be a new space or reused space.</returns>
  2443. internal IntPtr calculateSpaceForGeom(Vector3 pos)
  2444. {
  2445. int[] xyspace = calculateSpaceArrayItemFromPos(pos);
  2446. //m_log.Info("[Physics]: Attempting to use arrayItem: " + xyspace[0].ToString() + "," + xyspace[1].ToString());
  2447. return staticPrimspace[xyspace[0], xyspace[1]];
  2448. }
  2449. /// <summary>
  2450. /// Holds the space allocation logic
  2451. /// </summary>
  2452. /// <param name="pos"></param>
  2453. /// <returns>an array item based on the position</returns>
  2454. internal int[] calculateSpaceArrayItemFromPos(Vector3 pos)
  2455. {
  2456. int[] returnint = new int[2];
  2457. returnint[0] = (int) (pos.X * spacesPerMeterX);
  2458. if (returnint[0] > spaceGridMaxX)
  2459. returnint[0] = spaceGridMaxX;
  2460. if (returnint[0] < 0)
  2461. returnint[0] = 0;
  2462. returnint[1] = (int)(pos.Y * spacesPerMeterY);
  2463. if (returnint[1] > spaceGridMaxY)
  2464. returnint[1] = spaceGridMaxY;
  2465. if (returnint[1] < 0)
  2466. returnint[1] = 0;
  2467. return returnint;
  2468. }
  2469. #endregion
  2470. /// <summary>
  2471. /// Routine to figure out if we need to mesh this prim with our mesher
  2472. /// </summary>
  2473. /// <param name="pbs"></param>
  2474. /// <returns></returns>
  2475. internal bool needsMeshing(PrimitiveBaseShape pbs)
  2476. {
  2477. // most of this is redundant now as the mesher will return null if it cant mesh a prim
  2478. // but we still need to check for sculptie meshing being enabled so this is the most
  2479. // convenient place to do it for now...
  2480. // //if (pbs.PathCurve == (byte)Primitive.PathCurve.Circle && pbs.ProfileCurve == (byte)Primitive.ProfileCurve.Circle && pbs.PathScaleY <= 0.75f)
  2481. // //m_log.Debug("needsMeshing: " + " pathCurve: " + pbs.PathCurve.ToString() + " profileCurve: " + pbs.ProfileCurve.ToString() + " pathScaleY: " + Primitive.UnpackPathScale(pbs.PathScaleY).ToString());
  2482. int iPropertiesNotSupportedDefault = 0;
  2483. if (pbs.SculptEntry && !meshSculptedPrim)
  2484. {
  2485. #if SPAM
  2486. m_log.Warn("NonMesh");
  2487. #endif
  2488. return false;
  2489. }
  2490. // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since ODE can use an internal representation for the prim
  2491. if (!forceSimplePrimMeshing && !pbs.SculptEntry)
  2492. {
  2493. if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  2494. || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1
  2495. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z))
  2496. {
  2497. if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  2498. && pbs.ProfileHollow == 0
  2499. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  2500. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  2501. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  2502. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  2503. && pbs.PathShearX == 0 && pbs.PathShearY == 0)
  2504. {
  2505. #if SPAM
  2506. m_log.Warn("NonMesh");
  2507. #endif
  2508. return false;
  2509. }
  2510. }
  2511. }
  2512. if (pbs.ProfileHollow != 0)
  2513. iPropertiesNotSupportedDefault++;
  2514. if ((pbs.PathBegin != 0) || pbs.PathEnd != 0)
  2515. iPropertiesNotSupportedDefault++;
  2516. if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0))
  2517. iPropertiesNotSupportedDefault++;
  2518. if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0)
  2519. iPropertiesNotSupportedDefault++;
  2520. if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100))
  2521. iPropertiesNotSupportedDefault++;
  2522. if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0))
  2523. iPropertiesNotSupportedDefault++;
  2524. if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight)
  2525. iPropertiesNotSupportedDefault++;
  2526. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X))
  2527. iPropertiesNotSupportedDefault++;
  2528. if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1)
  2529. iPropertiesNotSupportedDefault++;
  2530. // test for torus
  2531. if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
  2532. {
  2533. if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2534. {
  2535. iPropertiesNotSupportedDefault++;
  2536. }
  2537. }
  2538. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  2539. {
  2540. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2541. {
  2542. iPropertiesNotSupportedDefault++;
  2543. }
  2544. // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
  2545. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2546. {
  2547. iPropertiesNotSupportedDefault++;
  2548. }
  2549. }
  2550. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  2551. {
  2552. if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2)
  2553. {
  2554. iPropertiesNotSupportedDefault++;
  2555. }
  2556. }
  2557. else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  2558. {
  2559. if (pbs.PathCurve == (byte)Extrusion.Straight)
  2560. {
  2561. iPropertiesNotSupportedDefault++;
  2562. }
  2563. else if (pbs.PathCurve == (byte)Extrusion.Curve1)
  2564. {
  2565. iPropertiesNotSupportedDefault++;
  2566. }
  2567. }
  2568. if (pbs.SculptEntry && meshSculptedPrim)
  2569. iPropertiesNotSupportedDefault++;
  2570. if (iPropertiesNotSupportedDefault == 0)
  2571. {
  2572. #if SPAM
  2573. m_log.Warn("NonMesh");
  2574. #endif
  2575. return false;
  2576. }
  2577. #if SPAM
  2578. m_log.Debug("Mesh");
  2579. #endif
  2580. return true;
  2581. }
  2582. /// <summary>
  2583. /// Called after our prim properties are set Scale, position etc.
  2584. /// </summary>
  2585. /// <remarks>
  2586. /// We use this event queue like method to keep changes to the physical scene occuring in the threadlocked mutex
  2587. /// This assures us that we have no race conditions
  2588. /// </remarks>
  2589. /// <param name="actor"></param>
  2590. public override void AddPhysicsActorTaint(PhysicsActor actor)
  2591. {
  2592. if (actor is OdePrim)
  2593. {
  2594. OdePrim taintedprim = ((OdePrim)actor);
  2595. lock (_taintedPrims)
  2596. _taintedPrims.Add(taintedprim);
  2597. }
  2598. else if (actor is OdeCharacter)
  2599. {
  2600. OdeCharacter taintedchar = ((OdeCharacter)actor);
  2601. lock (_taintedActors)
  2602. {
  2603. _taintedActors.Add(taintedchar);
  2604. if (taintedchar.bad)
  2605. m_log.ErrorFormat("[ODE SCENE]: Added BAD actor {0} to tainted actors", taintedchar.m_uuid);
  2606. }
  2607. }
  2608. }
  2609. /// <summary>
  2610. /// This is our main simulate loop
  2611. /// </summary>
  2612. /// <remarks>
  2613. /// It's thread locked by a Mutex in the scene.
  2614. /// It holds Collisions, it instructs ODE to step through the physical reactions
  2615. /// It moves the objects around in memory
  2616. /// It calls the methods that report back to the object owners.. (scenepresence, SceneObjectGroup)
  2617. /// </remarks>
  2618. /// <param name="timeStep"></param>
  2619. /// <returns>The number of frames simulated over that period.</returns>
  2620. public override float Simulate(float timeStep)
  2621. {
  2622. if (!_worldInitialized) return 11f;
  2623. int startFrameTick = CollectStats ? Util.EnvironmentTickCount() : 0;
  2624. int tempTick = 0, tempTick2 = 0;
  2625. if (framecount >= int.MaxValue)
  2626. framecount = 0;
  2627. framecount++;
  2628. float fps = 0;
  2629. float timeLeft = timeStep;
  2630. //m_log.Info(timeStep.ToString());
  2631. // step_time += timeSte
  2632. //
  2633. // // If We're loaded down by something else,
  2634. // // or debugging with the Visual Studio project on pause
  2635. // // skip a few frames to catch up gracefully.
  2636. // // without shooting the physicsactors all over the place
  2637. //
  2638. // if (step_time >= m_SkipFramesAtms)
  2639. // {
  2640. // // Instead of trying to catch up, it'll do 5 physics frames only
  2641. // step_time = ODE_STEPSIZE;
  2642. // m_physicsiterations = 5;
  2643. // }
  2644. // else
  2645. // {
  2646. // m_physicsiterations = 10;
  2647. // }
  2648. // We change _collisionEventPrimChanges to avoid locking _collisionEventPrim itself and causing potential
  2649. // deadlock if the collision event tries to lock something else later on which is already locked by a
  2650. // caller that is adding or removing the collision event.
  2651. lock (m_collisionEventActorsChanges)
  2652. {
  2653. foreach (KeyValuePair<uint, PhysicsActor> kvp in m_collisionEventActorsChanges)
  2654. {
  2655. if (kvp.Value == null)
  2656. m_collisionEventActors.Remove(kvp.Key);
  2657. else
  2658. m_collisionEventActors[kvp.Key] = kvp.Value;
  2659. }
  2660. m_collisionEventActorsChanges.Clear();
  2661. }
  2662. if (SupportsNINJAJoints)
  2663. {
  2664. DeleteRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2665. CreateRequestedJoints(); // this must be outside of the lock (OdeLock) to avoid deadlocks
  2666. }
  2667. lock (OdeLock)
  2668. {
  2669. // Process 10 frames if the sim is running normal..
  2670. // process 5 frames if the sim is running slow
  2671. //try
  2672. //{
  2673. //d.WorldSetQuickStepNumIterations(world, m_physicsiterations);
  2674. //}
  2675. //catch (StackOverflowException)
  2676. //{
  2677. // m_log.Error("[PHYSICS]: The operating system wasn't able to allocate enough memory for the simulation. Restarting the sim.");
  2678. // ode.drelease(world);
  2679. //base.TriggerPhysicsBasedRestart();
  2680. //}
  2681. // Figure out the Frames Per Second we're going at.
  2682. //(step_time == 0.004f, there's 250 of those per second. Times the step time/step size
  2683. fps = (timeStep / ODE_STEPSIZE) * 1000;
  2684. // HACK: Using a time dilation of 1.0 to debug rubberbanding issues
  2685. //m_timeDilation = Math.Min((step_time / ODE_STEPSIZE) / (0.09375f / ODE_STEPSIZE), 1.0f);
  2686. while (timeLeft > 0.0f)
  2687. {
  2688. try
  2689. {
  2690. if (CollectStats)
  2691. tempTick = Util.EnvironmentTickCount();
  2692. lock (_taintedActors)
  2693. {
  2694. foreach (OdeCharacter character in _taintedActors)
  2695. character.ProcessTaints();
  2696. _taintedActors.Clear();
  2697. }
  2698. if (CollectStats)
  2699. {
  2700. tempTick2 = Util.EnvironmentTickCount();
  2701. m_stats[ODEAvatarTaintMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2702. tempTick = tempTick2;
  2703. }
  2704. lock (_taintedPrims)
  2705. {
  2706. foreach (OdePrim prim in _taintedPrims)
  2707. {
  2708. if (prim.m_taintremove)
  2709. {
  2710. // Console.WriteLine("Simulate calls RemovePrimThreadLocked for {0}", prim.Name);
  2711. RemovePrimThreadLocked(prim);
  2712. }
  2713. else
  2714. {
  2715. // Console.WriteLine("Simulate calls ProcessTaints for {0}", prim.Name);
  2716. prim.ProcessTaints();
  2717. }
  2718. prim.m_collisionscore = 0;
  2719. // This loop can block up the Heartbeat for a very long time on large regions.
  2720. // We need to let the Watchdog know that the Heartbeat is not dead
  2721. // NOTE: This is currently commented out, but if things like OAR loading are
  2722. // timing the heartbeat out we will need to uncomment it
  2723. //Watchdog.UpdateThread();
  2724. }
  2725. if (SupportsNINJAJoints)
  2726. SimulatePendingNINJAJoints();
  2727. _taintedPrims.Clear();
  2728. }
  2729. if (CollectStats)
  2730. {
  2731. tempTick2 = Util.EnvironmentTickCount();
  2732. m_stats[ODEPrimTaintMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2733. tempTick = tempTick2;
  2734. }
  2735. // Move characters
  2736. foreach (OdeCharacter actor in _characters)
  2737. actor.Move(defects);
  2738. if (defects.Count != 0)
  2739. {
  2740. foreach (OdeCharacter actor in defects)
  2741. {
  2742. m_log.ErrorFormat(
  2743. "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2} due to defect found when moving",
  2744. actor.Name, actor.LocalID, PhysicsSceneName);
  2745. RemoveCharacter(actor);
  2746. actor.DestroyOdeStructures();
  2747. }
  2748. defects.Clear();
  2749. }
  2750. if (CollectStats)
  2751. {
  2752. tempTick2 = Util.EnvironmentTickCount();
  2753. m_stats[ODEAvatarForcesFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2754. tempTick = tempTick2;
  2755. }
  2756. // Move other active objects
  2757. foreach (OdePrim prim in _activeprims)
  2758. {
  2759. prim.m_collisionscore = 0;
  2760. prim.Move(timeStep);
  2761. }
  2762. if (CollectStats)
  2763. {
  2764. tempTick2 = Util.EnvironmentTickCount();
  2765. m_stats[ODEPrimForcesFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2766. tempTick = tempTick2;
  2767. }
  2768. //if ((framecount % m_randomizeWater) == 0)
  2769. // randomizeWater(waterlevel);
  2770. //int RayCastTimeMS = m_rayCastManager.ProcessQueuedRequests();
  2771. m_rayCastManager.ProcessQueuedRequests();
  2772. if (CollectStats)
  2773. {
  2774. tempTick2 = Util.EnvironmentTickCount();
  2775. m_stats[ODERaycastingFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2776. tempTick = tempTick2;
  2777. }
  2778. collision_optimized();
  2779. if (CollectStats)
  2780. {
  2781. tempTick2 = Util.EnvironmentTickCount();
  2782. m_stats[ODEOtherCollisionFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2783. tempTick = tempTick2;
  2784. }
  2785. foreach (PhysicsActor obj in m_collisionEventActors.Values)
  2786. {
  2787. // m_log.DebugFormat("[PHYSICS]: Assessing {0} {1} for collision events", obj.SOPName, obj.LocalID);
  2788. switch ((ActorTypes)obj.PhysicsActorType)
  2789. {
  2790. case ActorTypes.Agent:
  2791. OdeCharacter cobj = (OdeCharacter)obj;
  2792. cobj.AddCollisionFrameTime(100);
  2793. cobj.SendCollisions();
  2794. break;
  2795. case ActorTypes.Prim:
  2796. OdePrim pobj = (OdePrim)obj;
  2797. pobj.SendCollisions();
  2798. break;
  2799. }
  2800. }
  2801. // if (m_global_contactcount > 0)
  2802. // m_log.DebugFormat(
  2803. // "[PHYSICS]: Collision contacts to process this frame = {0}", m_global_contactcount);
  2804. m_global_contactcount = 0;
  2805. if (CollectStats)
  2806. {
  2807. tempTick2 = Util.EnvironmentTickCount();
  2808. m_stats[ODECollisionNotificationFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2809. tempTick = tempTick2;
  2810. }
  2811. d.WorldQuickStep(world, ODE_STEPSIZE);
  2812. if (CollectStats)
  2813. m_stats[ODENativeStepFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick);
  2814. d.JointGroupEmpty(contactgroup);
  2815. }
  2816. catch (Exception e)
  2817. {
  2818. m_log.ErrorFormat("[ODE SCENE]: {0}, {1}, {2}", e.Message, e.TargetSite, e);
  2819. }
  2820. timeLeft -= ODE_STEPSIZE;
  2821. }
  2822. if (CollectStats)
  2823. tempTick = Util.EnvironmentTickCount();
  2824. foreach (OdeCharacter actor in _characters)
  2825. {
  2826. if (actor.bad)
  2827. m_log.ErrorFormat("[ODE SCENE]: BAD Actor {0} in _characters list was not removed?", actor.m_uuid);
  2828. actor.UpdatePositionAndVelocity(defects);
  2829. }
  2830. if (defects.Count != 0)
  2831. {
  2832. foreach (OdeCharacter actor in defects)
  2833. {
  2834. m_log.ErrorFormat(
  2835. "[ODE SCENE]: Removing physics character {0} {1} from physics scene {2} due to defect found when updating position and velocity",
  2836. actor.Name, actor.LocalID, PhysicsSceneName);
  2837. RemoveCharacter(actor);
  2838. actor.DestroyOdeStructures();
  2839. }
  2840. defects.Clear();
  2841. }
  2842. if (CollectStats)
  2843. {
  2844. tempTick2 = Util.EnvironmentTickCount();
  2845. m_stats[ODEAvatarUpdateFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick2, tempTick);
  2846. tempTick = tempTick2;
  2847. }
  2848. //if (timeStep < 0.2f)
  2849. foreach (OdePrim prim in _activeprims)
  2850. {
  2851. if (prim.IsPhysical && (d.BodyIsEnabled(prim.Body) || !prim._zeroFlag))
  2852. {
  2853. prim.UpdatePositionAndVelocity();
  2854. if (SupportsNINJAJoints)
  2855. SimulateActorPendingJoints(prim);
  2856. }
  2857. }
  2858. if (CollectStats)
  2859. m_stats[ODEPrimUpdateFrameMsStatName] += Util.EnvironmentTickCountSubtract(tempTick);
  2860. //DumpJointInfo();
  2861. // Finished with all sim stepping. If requested, dump world state to file for debugging.
  2862. // TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
  2863. // TODO: This overwrites all dump files in-place. Should this be a growing logfile, or separate snapshots?
  2864. if (physics_logging && (physics_logging_interval > 0) && (framecount % physics_logging_interval == 0))
  2865. {
  2866. string fname = "state-" + world.ToString() + ".DIF"; // give each physics world a separate filename
  2867. string prefix = "world" + world.ToString(); // prefix for variable names in exported .DIF file
  2868. if (physics_logging_append_existing_logfile)
  2869. {
  2870. string header = "-------------- START OF PHYSICS FRAME " + framecount.ToString() + " --------------";
  2871. TextWriter fwriter = File.AppendText(fname);
  2872. fwriter.WriteLine(header);
  2873. fwriter.Close();
  2874. }
  2875. d.WorldExportDIF(world, fname, physics_logging_append_existing_logfile, prefix);
  2876. }
  2877. latertickcount = Util.EnvironmentTickCountSubtract(tickCountFrameRun);
  2878. // OpenSimulator above does 10 fps. 10 fps = means that the main thread loop and physics
  2879. // has a max of 100 ms to run theoretically.
  2880. // If the main loop stalls, it calls Simulate later which makes the tick count ms larger.
  2881. // If Physics stalls, it takes longer which makes the tick count ms larger.
  2882. if (latertickcount < 100)
  2883. {
  2884. m_timeDilation = 1.0f;
  2885. }
  2886. else
  2887. {
  2888. m_timeDilation = 100f / latertickcount;
  2889. //m_timeDilation = Math.Min((Math.Max(100 - (Util.EnvironmentTickCount() - tickCountFrameRun), 1) / 100f), 1.0f);
  2890. }
  2891. tickCountFrameRun = Util.EnvironmentTickCount();
  2892. if (CollectStats)
  2893. m_stats[ODETotalFrameMsStatName] += Util.EnvironmentTickCountSubtract(startFrameTick);
  2894. }
  2895. return fps;
  2896. }
  2897. /// <summary>
  2898. /// Simulate pending NINJA joints.
  2899. /// </summary>
  2900. /// <remarks>
  2901. /// Called by the main Simulate() loop if NINJA joints are active. Should not be called from anywhere else.
  2902. /// </remarks>
  2903. private void SimulatePendingNINJAJoints()
  2904. {
  2905. // Create pending joints, if possible
  2906. // joints can only be processed after ALL bodies are processed (and exist in ODE), since creating
  2907. // a joint requires specifying the body id of both involved bodies
  2908. if (pendingJoints.Count > 0)
  2909. {
  2910. List<PhysicsJoint> successfullyProcessedPendingJoints = new List<PhysicsJoint>();
  2911. //DoJointErrorMessage(joints_connecting_actor, "taint: " + pendingJoints.Count + " pending joints");
  2912. foreach (PhysicsJoint joint in pendingJoints)
  2913. {
  2914. //DoJointErrorMessage(joint, "taint: time to create joint with parms: " + joint.RawParams);
  2915. string[] jointParams = joint.RawParams.Split(" ".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries);
  2916. List<IntPtr> jointBodies = new List<IntPtr>();
  2917. bool allJointBodiesAreReady = true;
  2918. foreach (string jointParam in jointParams)
  2919. {
  2920. if (jointParam == "NULL")
  2921. {
  2922. //DoJointErrorMessage(joint, "attaching NULL joint to world");
  2923. jointBodies.Add(IntPtr.Zero);
  2924. }
  2925. else
  2926. {
  2927. //DoJointErrorMessage(joint, "looking for prim name: " + jointParam);
  2928. bool foundPrim = false;
  2929. lock (_prims)
  2930. {
  2931. foreach (OdePrim prim in _prims) // FIXME: inefficient
  2932. {
  2933. if (prim.SOPName == jointParam)
  2934. {
  2935. //DoJointErrorMessage(joint, "found for prim name: " + jointParam);
  2936. if (prim.IsPhysical && prim.Body != IntPtr.Zero)
  2937. {
  2938. jointBodies.Add(prim.Body);
  2939. foundPrim = true;
  2940. break;
  2941. }
  2942. else
  2943. {
  2944. DoJointErrorMessage(joint, "prim name " + jointParam +
  2945. " exists but is not (yet) physical; deferring joint creation. " +
  2946. "IsPhysical property is " + prim.IsPhysical +
  2947. " and body is " + prim.Body);
  2948. foundPrim = false;
  2949. break;
  2950. }
  2951. }
  2952. }
  2953. }
  2954. if (foundPrim)
  2955. {
  2956. // all is fine
  2957. }
  2958. else
  2959. {
  2960. allJointBodiesAreReady = false;
  2961. break;
  2962. }
  2963. }
  2964. }
  2965. if (allJointBodiesAreReady)
  2966. {
  2967. //DoJointErrorMessage(joint, "allJointBodiesAreReady for " + joint.ObjectNameInScene + " with parms " + joint.RawParams);
  2968. if (jointBodies[0] == jointBodies[1])
  2969. {
  2970. DoJointErrorMessage(joint, "ERROR: joint cannot be created; the joint bodies are the same, body1==body2. Raw body is " + jointBodies[0] + ". raw parms: " + joint.RawParams);
  2971. }
  2972. else
  2973. {
  2974. switch (joint.Type)
  2975. {
  2976. case PhysicsJointType.Ball:
  2977. {
  2978. IntPtr odeJoint;
  2979. //DoJointErrorMessage(joint, "ODE creating ball joint ");
  2980. odeJoint = d.JointCreateBall(world, IntPtr.Zero);
  2981. //DoJointErrorMessage(joint, "ODE attaching ball joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  2982. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  2983. //DoJointErrorMessage(joint, "ODE setting ball anchor: " + odeJoint + " to vec:" + joint.Position);
  2984. d.JointSetBallAnchor(odeJoint,
  2985. joint.Position.X,
  2986. joint.Position.Y,
  2987. joint.Position.Z);
  2988. //DoJointErrorMessage(joint, "ODE joint setting OK");
  2989. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b0: ");
  2990. //DoJointErrorMessage(joint, "" + (jointBodies[0] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[0]) : "fixed environment"));
  2991. //DoJointErrorMessage(joint, "The ball joint's bodies are here: b1: ");
  2992. //DoJointErrorMessage(joint, "" + (jointBodies[1] != IntPtr.Zero ? "" + d.BodyGetPosition(jointBodies[1]) : "fixed environment"));
  2993. if (joint is OdePhysicsJoint)
  2994. {
  2995. ((OdePhysicsJoint)joint).jointID = odeJoint;
  2996. }
  2997. else
  2998. {
  2999. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  3000. }
  3001. }
  3002. break;
  3003. case PhysicsJointType.Hinge:
  3004. {
  3005. IntPtr odeJoint;
  3006. //DoJointErrorMessage(joint, "ODE creating hinge joint ");
  3007. odeJoint = d.JointCreateHinge(world, IntPtr.Zero);
  3008. //DoJointErrorMessage(joint, "ODE attaching hinge joint: " + odeJoint + " with b1:" + jointBodies[0] + " b2:" + jointBodies[1]);
  3009. d.JointAttach(odeJoint, jointBodies[0], jointBodies[1]);
  3010. //DoJointErrorMessage(joint, "ODE setting hinge anchor: " + odeJoint + " to vec:" + joint.Position);
  3011. d.JointSetHingeAnchor(odeJoint,
  3012. joint.Position.X,
  3013. joint.Position.Y,
  3014. joint.Position.Z);
  3015. // We use the orientation of the x-axis of the joint's coordinate frame
  3016. // as the axis for the hinge.
  3017. // Therefore, we must get the joint's coordinate frame based on the
  3018. // joint.Rotation field, which originates from the orientation of the
  3019. // joint's proxy object in the scene.
  3020. // The joint's coordinate frame is defined as the transformation matrix
  3021. // that converts a vector from joint-local coordinates into world coordinates.
  3022. // World coordinates are defined as the XYZ coordinate system of the sim,
  3023. // as shown in the top status-bar of the viewer.
  3024. // Once we have the joint's coordinate frame, we extract its X axis (AtAxis)
  3025. // and use that as the hinge axis.
  3026. //joint.Rotation.Normalize();
  3027. Matrix4 proxyFrame = Matrix4.CreateFromQuaternion(joint.Rotation);
  3028. // Now extract the X axis of the joint's coordinate frame.
  3029. // Do not try to use proxyFrame.AtAxis or you will become mired in the
  3030. // tar pit of transposed, inverted, and generally messed-up orientations.
  3031. // (In other words, Matrix4.AtAxis() is borked.)
  3032. // Vector3 jointAxis = proxyFrame.AtAxis; <--- this path leadeth to madness
  3033. // Instead, compute the X axis of the coordinate frame by transforming
  3034. // the (1,0,0) vector. At least that works.
  3035. //m_log.Debug("PHY: making axis: complete matrix is " + proxyFrame);
  3036. Vector3 jointAxis = Vector3.Transform(Vector3.UnitX, proxyFrame);
  3037. //m_log.Debug("PHY: making axis: hinge joint axis is " + jointAxis);
  3038. //DoJointErrorMessage(joint, "ODE setting hinge axis: " + odeJoint + " to vec:" + jointAxis);
  3039. d.JointSetHingeAxis(odeJoint,
  3040. jointAxis.X,
  3041. jointAxis.Y,
  3042. jointAxis.Z);
  3043. //d.JointSetHingeParam(odeJoint, (int)dParam.CFM, 0.1f);
  3044. if (joint is OdePhysicsJoint)
  3045. {
  3046. ((OdePhysicsJoint)joint).jointID = odeJoint;
  3047. }
  3048. else
  3049. {
  3050. DoJointErrorMessage(joint, "WARNING: non-ode joint in ODE!");
  3051. }
  3052. }
  3053. break;
  3054. }
  3055. successfullyProcessedPendingJoints.Add(joint);
  3056. }
  3057. }
  3058. else
  3059. {
  3060. DoJointErrorMessage(joint, "joint could not yet be created; still pending");
  3061. }
  3062. }
  3063. foreach (PhysicsJoint successfullyProcessedJoint in successfullyProcessedPendingJoints)
  3064. {
  3065. //DoJointErrorMessage(successfullyProcessedJoint, "finalizing succesfully procsssed joint " + successfullyProcessedJoint.ObjectNameInScene + " parms " + successfullyProcessedJoint.RawParams);
  3066. //DoJointErrorMessage(successfullyProcessedJoint, "removing from pending");
  3067. InternalRemovePendingJoint(successfullyProcessedJoint);
  3068. //DoJointErrorMessage(successfullyProcessedJoint, "adding to active");
  3069. InternalAddActiveJoint(successfullyProcessedJoint);
  3070. //DoJointErrorMessage(successfullyProcessedJoint, "done");
  3071. }
  3072. }
  3073. }
  3074. /// <summary>
  3075. /// Simulate the joint proxies of a NINJA actor.
  3076. /// </summary>
  3077. /// <remarks>
  3078. /// Called as part of the Simulate() loop if NINJA physics is active. Must only be called from there.
  3079. /// </remarks>
  3080. /// <param name="actor"></param>
  3081. private void SimulateActorPendingJoints(OdePrim actor)
  3082. {
  3083. // If an actor moved, move its joint proxy objects as well.
  3084. // There seems to be an event PhysicsActor.OnPositionUpdate that could be used
  3085. // for this purpose but it is never called! So we just do the joint
  3086. // movement code here.
  3087. if (actor.SOPName != null &&
  3088. joints_connecting_actor.ContainsKey(actor.SOPName) &&
  3089. joints_connecting_actor[actor.SOPName] != null &&
  3090. joints_connecting_actor[actor.SOPName].Count > 0)
  3091. {
  3092. foreach (PhysicsJoint affectedJoint in joints_connecting_actor[actor.SOPName])
  3093. {
  3094. if (affectedJoint.IsInPhysicsEngine)
  3095. {
  3096. DoJointMoved(affectedJoint);
  3097. }
  3098. else
  3099. {
  3100. DoJointErrorMessage(affectedJoint, "a body connected to a joint was moved, but the joint doesn't exist yet! this will lead to joint error. joint was: " + affectedJoint.ObjectNameInScene + " parms:" + affectedJoint.RawParams);
  3101. }
  3102. }
  3103. }
  3104. }
  3105. public override void GetResults()
  3106. {
  3107. }
  3108. public override bool IsThreaded
  3109. {
  3110. // for now we won't be multithreaded
  3111. get { return false; }
  3112. }
  3113. public override void SetTerrain(float[] heightMap)
  3114. {
  3115. if (m_worldOffset != Vector3.Zero && m_parentScene != null)
  3116. {
  3117. if (m_parentScene is OdeScene)
  3118. {
  3119. ((OdeScene)m_parentScene).SetTerrain(heightMap, m_worldOffset);
  3120. }
  3121. }
  3122. else
  3123. {
  3124. SetTerrain(heightMap, m_worldOffset);
  3125. }
  3126. }
  3127. private void SetTerrain(float[] heightMap, Vector3 pOffset)
  3128. {
  3129. int startTime = Util.EnvironmentTickCount();
  3130. m_log.DebugFormat("[ODE SCENE]: Setting terrain for {0} with offset {1}", PhysicsSceneName, pOffset);
  3131. float[] _heightmap;
  3132. // ok im lasy this are just a aliases
  3133. uint regionsizeX = m_regionWidth;
  3134. uint regionsizeY = m_regionHeight;
  3135. // map is rotated
  3136. uint heightmapWidth = regionsizeY + 2;
  3137. uint heightmapHeight = regionsizeX + 2;
  3138. uint heightmapWidthSamples = heightmapWidth + 1;
  3139. uint heightmapHeightSamples = heightmapHeight + 1;
  3140. _heightmap = new float[heightmapWidthSamples * heightmapHeightSamples];
  3141. const float scale = 1.0f;
  3142. const float offset = 0.0f;
  3143. const float thickness = 10f;
  3144. const int wrap = 0;
  3145. float hfmin = float.MaxValue;
  3146. float hfmax = float.MinValue;
  3147. float val;
  3148. uint xx;
  3149. uint yy;
  3150. uint maxXX = regionsizeX - 1;
  3151. uint maxYY = regionsizeY - 1;
  3152. // flipping map adding one margin all around so things don't fall in edges
  3153. uint xt = 0;
  3154. xx = 0;
  3155. for (uint x = 0; x < heightmapWidthSamples; x++)
  3156. {
  3157. if (x > 1 && xx < maxXX)
  3158. xx++;
  3159. yy = 0;
  3160. for (uint y = 0; y < heightmapHeightSamples; y++)
  3161. {
  3162. if (y > 1 && y < maxYY)
  3163. yy += regionsizeX;
  3164. val = heightMap[yy + xx];
  3165. if (val < 0.0f)
  3166. val = 0.0f;
  3167. _heightmap[xt + y] = val;
  3168. if (hfmin > val)
  3169. hfmin = val;
  3170. if (hfmax < val)
  3171. hfmax = val;
  3172. }
  3173. xt += heightmapHeightSamples;
  3174. }
  3175. lock (OdeLock)
  3176. {
  3177. IntPtr GroundGeom = IntPtr.Zero;
  3178. if (RegionTerrain.TryGetValue(pOffset, out GroundGeom))
  3179. {
  3180. RegionTerrain.Remove(pOffset);
  3181. if (GroundGeom != IntPtr.Zero)
  3182. {
  3183. if (TerrainHeightFieldHeights.ContainsKey(GroundGeom))
  3184. {
  3185. TerrainHeightFieldHeights.Remove(GroundGeom);
  3186. }
  3187. d.SpaceRemove(space, GroundGeom);
  3188. d.GeomDestroy(GroundGeom);
  3189. }
  3190. }
  3191. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  3192. d.GeomHeightfieldDataBuildSingle(HeightmapData, _heightmap, 0,
  3193. heightmapWidth, heightmapHeight,
  3194. (int)heightmapWidthSamples, (int)heightmapHeightSamples,
  3195. scale, offset, thickness, wrap);
  3196. d.GeomHeightfieldDataSetBounds(HeightmapData, hfmin - 1, hfmax + 1);
  3197. GroundGeom = d.CreateHeightfield(space, HeightmapData, 1);
  3198. if (GroundGeom != IntPtr.Zero)
  3199. {
  3200. d.GeomSetCategoryBits(GroundGeom, (int)(CollisionCategories.Land));
  3201. d.GeomSetCollideBits(GroundGeom, (int)(CollisionCategories.Space));
  3202. }
  3203. geom_name_map[GroundGeom] = "Terrain";
  3204. d.Matrix3 R = new d.Matrix3();
  3205. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  3206. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  3207. q1 = q1 * q2;
  3208. Vector3 v3;
  3209. float angle;
  3210. q1.GetAxisAngle(out v3, out angle);
  3211. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  3212. d.GeomSetRotation(GroundGeom, ref R);
  3213. d.GeomSetPosition(GroundGeom, pOffset.X + regionsizeX * 0.5f, pOffset.Y + regionsizeY * 0.5f, 0f);
  3214. IntPtr testGround = IntPtr.Zero;
  3215. if (RegionTerrain.TryGetValue(pOffset, out testGround))
  3216. {
  3217. RegionTerrain.Remove(pOffset);
  3218. }
  3219. RegionTerrain.Add(pOffset, GroundGeom, GroundGeom);
  3220. TerrainHeightFieldHeights.Add(GroundGeom,_heightmap);
  3221. }
  3222. m_log.DebugFormat(
  3223. "[ODE SCENE]: Setting terrain for {0} took {1}ms", PhysicsSceneName, Util.EnvironmentTickCountSubtract(startTime));
  3224. }
  3225. public override void DeleteTerrain()
  3226. {
  3227. }
  3228. internal float GetWaterLevel()
  3229. {
  3230. return waterlevel;
  3231. }
  3232. public override bool SupportsCombining()
  3233. {
  3234. return m_suportCombine;
  3235. }
  3236. public override void SetWaterLevel(float baseheight)
  3237. {
  3238. waterlevel = baseheight;
  3239. // randomizeWater(waterlevel);
  3240. }
  3241. /*
  3242. private void randomizeWater(float baseheight)
  3243. {
  3244. uint heightmapWidth = m_regionWidth + 2;
  3245. uint heightmapHeight = m_regionHeight + 2;
  3246. uint heightmapWidthSamples = m_regionWidth + 2;
  3247. uint heightmapHeightSamples = m_regionHeight + 2;
  3248. float scale = 1.0f;
  3249. float offset = 0.0f;
  3250. float thickness = 2.9f;
  3251. int wrap = 0;
  3252. for (int i = 0; i < (258 * 258); i++)
  3253. {
  3254. _watermap[i] = (baseheight-0.1f) + ((float)fluidRandomizer.Next(1,9) / 10f);
  3255. // m_log.Info((baseheight - 0.1f) + ((float)fluidRandomizer.Next(1, 9) / 10f));
  3256. }
  3257. lock (OdeLock)
  3258. {
  3259. if (WaterGeom != IntPtr.Zero)
  3260. {
  3261. d.SpaceRemove(space, WaterGeom);
  3262. }
  3263. IntPtr HeightmapData = d.GeomHeightfieldDataCreate();
  3264. d.GeomHeightfieldDataBuildSingle(HeightmapData, _watermap, 0, heightmapWidth, heightmapHeight,
  3265. (int)heightmapWidthSamples, (int)heightmapHeightSamples, scale,
  3266. offset, thickness, wrap);
  3267. d.GeomHeightfieldDataSetBounds(HeightmapData, m_regionWidth, m_regionHeight);
  3268. WaterGeom = d.CreateHeightfield(space, HeightmapData, 1);
  3269. if (WaterGeom != IntPtr.Zero)
  3270. {
  3271. d.GeomSetCategoryBits(WaterGeom, (int)(CollisionCategories.Water));
  3272. d.GeomSetCollideBits(WaterGeom, (int)(CollisionCategories.Space));
  3273. }
  3274. geom_name_map[WaterGeom] = "Water";
  3275. d.Matrix3 R = new d.Matrix3();
  3276. Quaternion q1 = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 1.5707f);
  3277. Quaternion q2 = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), 1.5707f);
  3278. //Axiom.Math.Quaternion q3 = Axiom.Math.Quaternion.FromAngleAxis(3.14f, new Axiom.Math.Vector3(0, 0, 1));
  3279. q1 = q1 * q2;
  3280. //q1 = q1 * q3;
  3281. Vector3 v3;
  3282. float angle;
  3283. q1.GetAxisAngle(out v3, out angle);
  3284. d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
  3285. d.GeomSetRotation(WaterGeom, ref R);
  3286. d.GeomSetPosition(WaterGeom, 128, 128, 0);
  3287. }
  3288. }
  3289. */
  3290. public override void Dispose()
  3291. {
  3292. _worldInitialized = false;
  3293. m_rayCastManager.Dispose();
  3294. m_rayCastManager = null;
  3295. lock (OdeLock)
  3296. {
  3297. lock (_prims)
  3298. {
  3299. foreach (OdePrim prm in _prims)
  3300. {
  3301. RemovePrim(prm);
  3302. }
  3303. }
  3304. //foreach (OdeCharacter act in _characters)
  3305. //{
  3306. //RemoveAvatar(act);
  3307. //}
  3308. d.WorldDestroy(world);
  3309. //d.CloseODE();
  3310. }
  3311. }
  3312. public override Dictionary<uint, float> GetTopColliders()
  3313. {
  3314. Dictionary<uint, float> topColliders;
  3315. lock (_prims)
  3316. {
  3317. List<OdePrim> orderedPrims = new List<OdePrim>(_prims);
  3318. orderedPrims.OrderByDescending(p => p.CollisionScore);
  3319. topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
  3320. foreach (OdePrim p in _prims)
  3321. p.CollisionScore = 0;
  3322. }
  3323. return topColliders;
  3324. }
  3325. public override bool SupportsRayCast()
  3326. {
  3327. return true;
  3328. }
  3329. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
  3330. {
  3331. if (retMethod != null)
  3332. {
  3333. m_rayCastManager.QueueRequest(position, direction, length, retMethod);
  3334. }
  3335. }
  3336. public override void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
  3337. {
  3338. if (retMethod != null)
  3339. {
  3340. m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
  3341. }
  3342. }
  3343. public override List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
  3344. {
  3345. ContactResult[] ourResults = null;
  3346. RayCallback retMethod = delegate(List<ContactResult> results)
  3347. {
  3348. ourResults = new ContactResult[results.Count];
  3349. results.CopyTo(ourResults, 0);
  3350. };
  3351. int waitTime = 0;
  3352. m_rayCastManager.QueueRequest(position, direction, length, Count, retMethod);
  3353. while (ourResults == null && waitTime < 1000)
  3354. {
  3355. Thread.Sleep(1);
  3356. waitTime++;
  3357. }
  3358. if (ourResults == null)
  3359. return new List<ContactResult> ();
  3360. return new List<ContactResult>(ourResults);
  3361. }
  3362. #if USE_DRAWSTUFF
  3363. // Keyboard callback
  3364. public void command(int cmd)
  3365. {
  3366. IntPtr geom;
  3367. d.Mass mass;
  3368. d.Vector3 sides = new d.Vector3(d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f, d.RandReal() * 0.5f + 0.1f);
  3369. Char ch = Char.ToLower((Char)cmd);
  3370. switch ((Char)ch)
  3371. {
  3372. case 'w':
  3373. try
  3374. {
  3375. Vector3 rotate = (new Vector3(1, 0, 0) * Quaternion.CreateFromEulers(hpr.Z * Utils.DEG_TO_RAD, hpr.Y * Utils.DEG_TO_RAD, hpr.X * Utils.DEG_TO_RAD));
  3376. xyz.X += rotate.X; xyz.Y += rotate.Y; xyz.Z += rotate.Z;
  3377. ds.SetViewpoint(ref xyz, ref hpr);
  3378. }
  3379. catch (ArgumentException)
  3380. { hpr.X = 0; }
  3381. break;
  3382. case 'a':
  3383. hpr.X++;
  3384. ds.SetViewpoint(ref xyz, ref hpr);
  3385. break;
  3386. case 's':
  3387. try
  3388. {
  3389. Vector3 rotate2 = (new Vector3(-1, 0, 0) * Quaternion.CreateFromEulers(hpr.Z * Utils.DEG_TO_RAD, hpr.Y * Utils.DEG_TO_RAD, hpr.X * Utils.DEG_TO_RAD));
  3390. xyz.X += rotate2.X; xyz.Y += rotate2.Y; xyz.Z += rotate2.Z;
  3391. ds.SetViewpoint(ref xyz, ref hpr);
  3392. }
  3393. catch (ArgumentException)
  3394. { hpr.X = 0; }
  3395. break;
  3396. case 'd':
  3397. hpr.X--;
  3398. ds.SetViewpoint(ref xyz, ref hpr);
  3399. break;
  3400. case 'r':
  3401. xyz.Z++;
  3402. ds.SetViewpoint(ref xyz, ref hpr);
  3403. break;
  3404. case 'f':
  3405. xyz.Z--;
  3406. ds.SetViewpoint(ref xyz, ref hpr);
  3407. break;
  3408. case 'e':
  3409. xyz.Y++;
  3410. ds.SetViewpoint(ref xyz, ref hpr);
  3411. break;
  3412. case 'q':
  3413. xyz.Y--;
  3414. ds.SetViewpoint(ref xyz, ref hpr);
  3415. break;
  3416. }
  3417. }
  3418. public void step(int pause)
  3419. {
  3420. ds.SetColor(1.0f, 1.0f, 0.0f);
  3421. ds.SetTexture(ds.Texture.Wood);
  3422. lock (_prims)
  3423. {
  3424. foreach (OdePrim prm in _prims)
  3425. {
  3426. //IntPtr body = d.GeomGetBody(prm.prim_geom);
  3427. if (prm.prim_geom != IntPtr.Zero)
  3428. {
  3429. d.Vector3 pos;
  3430. d.GeomCopyPosition(prm.prim_geom, out pos);
  3431. //d.BodyCopyPosition(body, out pos);
  3432. d.Matrix3 R;
  3433. d.GeomCopyRotation(prm.prim_geom, out R);
  3434. //d.BodyCopyRotation(body, out R);
  3435. d.Vector3 sides = new d.Vector3();
  3436. sides.X = prm.Size.X;
  3437. sides.Y = prm.Size.Y;
  3438. sides.Z = prm.Size.Z;
  3439. ds.DrawBox(ref pos, ref R, ref sides);
  3440. }
  3441. }
  3442. }
  3443. ds.SetColor(1.0f, 0.0f, 0.0f);
  3444. foreach (OdeCharacter chr in _characters)
  3445. {
  3446. if (chr.Shell != IntPtr.Zero)
  3447. {
  3448. IntPtr body = d.GeomGetBody(chr.Shell);
  3449. d.Vector3 pos;
  3450. d.GeomCopyPosition(chr.Shell, out pos);
  3451. //d.BodyCopyPosition(body, out pos);
  3452. d.Matrix3 R;
  3453. d.GeomCopyRotation(chr.Shell, out R);
  3454. //d.BodyCopyRotation(body, out R);
  3455. ds.DrawCapsule(ref pos, ref R, chr.Size.Z, 0.35f);
  3456. d.Vector3 sides = new d.Vector3();
  3457. sides.X = 0.5f;
  3458. sides.Y = 0.5f;
  3459. sides.Z = 0.5f;
  3460. ds.DrawBox(ref pos, ref R, ref sides);
  3461. }
  3462. }
  3463. }
  3464. public void start(int unused)
  3465. {
  3466. ds.SetViewpoint(ref xyz, ref hpr);
  3467. }
  3468. #endif
  3469. public override Dictionary<string, float> GetStats()
  3470. {
  3471. if (!CollectStats)
  3472. return null;
  3473. Dictionary<string, float> returnStats;
  3474. lock (OdeLock)
  3475. {
  3476. returnStats = new Dictionary<string, float>(m_stats);
  3477. // FIXME: This is a SUPER DUMB HACK until we can establish stats that aren't subject to a division by
  3478. // 3 from the SimStatsReporter.
  3479. returnStats[ODETotalAvatarsStatName] = _characters.Count * 3;
  3480. returnStats[ODETotalPrimsStatName] = _prims.Count * 3;
  3481. returnStats[ODEActivePrimsStatName] = _activeprims.Count * 3;
  3482. InitializeExtraStats();
  3483. }
  3484. returnStats[ODEOtherCollisionFrameMsStatName]
  3485. = returnStats[ODEOtherCollisionFrameMsStatName]
  3486. - returnStats[ODENativeSpaceCollisionFrameMsStatName]
  3487. - returnStats[ODENativeGeomCollisionFrameMsStatName];
  3488. return returnStats;
  3489. }
  3490. private void InitializeExtraStats()
  3491. {
  3492. m_stats[ODETotalFrameMsStatName] = 0;
  3493. m_stats[ODEAvatarTaintMsStatName] = 0;
  3494. m_stats[ODEPrimTaintMsStatName] = 0;
  3495. m_stats[ODEAvatarForcesFrameMsStatName] = 0;
  3496. m_stats[ODEPrimForcesFrameMsStatName] = 0;
  3497. m_stats[ODERaycastingFrameMsStatName] = 0;
  3498. m_stats[ODENativeStepFrameMsStatName] = 0;
  3499. m_stats[ODENativeSpaceCollisionFrameMsStatName] = 0;
  3500. m_stats[ODENativeGeomCollisionFrameMsStatName] = 0;
  3501. m_stats[ODEOtherCollisionFrameMsStatName] = 0;
  3502. m_stats[ODECollisionNotificationFrameMsStatName] = 0;
  3503. m_stats[ODEAvatarContactsStatsName] = 0;
  3504. m_stats[ODEPrimContactsStatName] = 0;
  3505. m_stats[ODEAvatarUpdateFrameMsStatName] = 0;
  3506. m_stats[ODEPrimUpdateFrameMsStatName] = 0;
  3507. }
  3508. }
  3509. }