OdeScene.cs 185 KB

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