ScenePresence.cs 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797
  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. using System;
  28. using System.Collections.Generic;
  29. using System.Reflection;
  30. using OpenMetaverse;
  31. using log4net;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Client;
  34. using OpenSim.Framework.Communications.Cache;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenSim.Region.Framework.Scenes.Types;
  37. using OpenSim.Region.Physics.Manager;
  38. namespace OpenSim.Region.Framework.Scenes
  39. {
  40. enum ScriptControlled : uint
  41. {
  42. CONTROL_ZERO = 0,
  43. CONTROL_FWD = 1,
  44. CONTROL_BACK = 2,
  45. CONTROL_LEFT = 4,
  46. CONTROL_RIGHT = 8,
  47. CONTROL_UP = 16,
  48. CONTROL_DOWN = 32,
  49. CONTROL_ROT_LEFT = 256,
  50. CONTROL_ROT_RIGHT = 512,
  51. CONTROL_LBUTTON = 268435456,
  52. CONTROL_ML_LBUTTON = 1073741824
  53. }
  54. struct ScriptControllers
  55. {
  56. public UUID itemID;
  57. public uint objID;
  58. public ScriptControlled ignoreControls;
  59. public ScriptControlled eventControls;
  60. }
  61. public class ScenePresence : EntityBase
  62. {
  63. // ~ScenePresence()
  64. // {
  65. // m_log.Debug("[ScenePresence] Destructor called");
  66. // }
  67. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  68. public static byte[] DefaultTexture;
  69. public UUID currentParcelUUID = UUID.Zero;
  70. private ISceneViewer m_sceneViewer;
  71. private AnimationSet m_animations = new AnimationSet();
  72. private Dictionary<UUID, ScriptControllers> scriptedcontrols = new Dictionary<UUID, ScriptControllers>();
  73. private ScriptControlled IgnoredControls = ScriptControlled.CONTROL_ZERO;
  74. private ScriptControlled LastCommands = ScriptControlled.CONTROL_ZERO;
  75. private bool MouseDown = false;
  76. private SceneObjectGroup proxyObjectGroup;
  77. //private SceneObjectPart proxyObjectPart = null;
  78. public Vector3 lastKnownAllowedPosition;
  79. public bool sentMessageAboutRestrictedParcelFlyingDown;
  80. private bool m_updateflag;
  81. private byte m_movementflag;
  82. private readonly List<NewForce> m_forcesList = new List<NewForce>();
  83. private short m_updateCount;
  84. private uint m_requestedSitTargetID;
  85. private UUID m_requestedSitTargetUUID = UUID.Zero;
  86. private bool m_startAnimationSet;
  87. //private Vector3 m_requestedSitOffset = new Vector3();
  88. private Vector3 m_LastFinitePos;
  89. private float m_sitAvatarHeight = 2.0f;
  90. // experimentally determined "fudge factor" to make sit-target positions
  91. // the same as in SecondLife. Fudge factor was tested for 36 different
  92. // test cases including prims of type box, sphere, cylinder, and torus,
  93. // with varying parameters for sit target location, prim size, prim
  94. // rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
  95. // issue #1716
  96. private static readonly Vector3 m_sitTargetCorrectionOffset = new Vector3(0.1f, 0.0f, 0.3f);
  97. private float m_godlevel;
  98. private bool m_invulnerable = true;
  99. private Vector3 m_LastChildAgentUpdatePosition;
  100. private int m_perfMonMS;
  101. private bool m_setAlwaysRun;
  102. private bool m_updatesAllowed = true;
  103. private List<AgentUpdateArgs> m_agentUpdates = new List<AgentUpdateArgs>();
  104. private string m_movementAnimation = "DEFAULT";
  105. private long m_animPersistUntil = 0;
  106. private bool m_allowFalling = false;
  107. private bool m_useFlySlow = false;
  108. private bool m_usePreJump = false;
  109. private bool m_forceFly = false;
  110. private bool m_flyDisabled = false;
  111. private float m_speedModifier = 1.0f;
  112. private Quaternion m_bodyRot= Quaternion.Identity;
  113. public bool IsRestrictedToRegion;
  114. public string JID = string.Empty;
  115. // Agent moves with a PID controller causing a force to be exerted.
  116. private bool m_newForce;
  117. private bool m_newCoarseLocations = true;
  118. private float m_health = 100f;
  119. private Vector3 m_lastVelocity = Vector3.Zero;
  120. // Default AV Height
  121. private float m_avHeight = 127.0f;
  122. protected RegionInfo m_regionInfo;
  123. protected ulong crossingFromRegion;
  124. private readonly Vector3[] Dir_Vectors = new Vector3[6];
  125. /// <value>
  126. /// The avatar position last sent to clients
  127. /// </value>
  128. private Vector3 lastPhysPos = Vector3.Zero;
  129. /// <value>
  130. /// The avatar body rotation last sent to clients
  131. /// </value>
  132. private Quaternion lastPhysRot = Quaternion.Identity;
  133. // Position of agent's camera in world (region cordinates)
  134. protected Vector3 m_CameraCenter = Vector3.Zero;
  135. // Use these three vectors to figure out what the agent is looking at
  136. // Convert it to a Matrix and/or Quaternion
  137. protected Vector3 m_CameraAtAxis = Vector3.Zero;
  138. protected Vector3 m_CameraLeftAxis = Vector3.Zero;
  139. protected Vector3 m_CameraUpAxis = Vector3.Zero;
  140. private uint m_AgentControlFlags;
  141. private Quaternion m_headrotation = Quaternion.Identity;
  142. private byte m_state;
  143. //Reuse the Vector3 instead of creating a new one on the UpdateMovement method
  144. private Vector3 movementvector = Vector3.Zero;
  145. private bool m_autopilotMoving;
  146. private Vector3 m_autoPilotTarget = Vector3.Zero;
  147. private bool m_sitAtAutoTarget;
  148. private string m_nextSitAnimation = String.Empty;
  149. //PauPaw:Proper PID Controler for autopilot************
  150. private bool m_moveToPositionInProgress;
  151. private Vector3 m_moveToPositionTarget = Vector3.Zero;
  152. private bool m_followCamAuto = false;
  153. private int m_movementUpdateCount = 0;
  154. private const int NumMovementsBetweenRayCast = 5;
  155. private bool CameraConstraintActive = false;
  156. //private int m_moveToPositionStateStatus = 0;
  157. //*****************************************************
  158. // Agent's Draw distance.
  159. protected float m_DrawDistance;
  160. protected AvatarAppearance m_appearance;
  161. protected List<SceneObjectGroup> m_attachments = new List<SceneObjectGroup>();
  162. // neighbouring regions we have enabled a child agent in
  163. // holds the seed cap for the child agent in that region
  164. private Dictionary<ulong, string> m_knownChildRegions = new Dictionary<ulong, string>();
  165. /// <summary>
  166. /// Implemented Control Flags
  167. /// </summary>
  168. private enum Dir_ControlFlags
  169. {
  170. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  171. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  172. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  173. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  174. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  175. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  176. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  177. }
  178. protected enum Cardinals
  179. {
  180. N=1,NE,E,SE,S,SW,W,NW
  181. }
  182. /// <summary>
  183. /// Position at which a significant movement was made
  184. /// </summary>
  185. private Vector3 posLastSignificantMove;
  186. // For teleports and crossings callbacks
  187. string m_callbackURI;
  188. ulong m_rootRegionHandle;
  189. private IScriptModule[] m_scriptEngines;
  190. #region Properties
  191. /// <summary>
  192. /// Physical scene representation of this Avatar.
  193. /// </summary>
  194. public PhysicsActor PhysicsActor
  195. {
  196. set { m_physicsActor = value; }
  197. get { return m_physicsActor; }
  198. }
  199. public byte MovementFlag
  200. {
  201. set { m_movementflag = value; }
  202. get { return m_movementflag; }
  203. }
  204. public bool Updated
  205. {
  206. set { m_updateflag = value; }
  207. get { return m_updateflag; }
  208. }
  209. public bool Invulnerable
  210. {
  211. set { m_invulnerable = value; }
  212. get { return m_invulnerable; }
  213. }
  214. public float GodLevel
  215. {
  216. get { return m_godlevel; }
  217. }
  218. private readonly ulong m_regionHandle;
  219. public ulong RegionHandle
  220. {
  221. get { return m_regionHandle; }
  222. }
  223. public Vector3 CameraPosition
  224. {
  225. get { return m_CameraCenter; }
  226. }
  227. public Quaternion CameraRotation
  228. {
  229. get { return Util.Axes2Rot(m_CameraAtAxis, m_CameraLeftAxis, m_CameraUpAxis); }
  230. }
  231. public Vector3 Lookat
  232. {
  233. get
  234. {
  235. Vector3 a = new Vector3(m_CameraAtAxis.X, m_CameraAtAxis.Y, 0);
  236. if (a == Vector3.Zero)
  237. return a;
  238. return Util.GetNormalizedVector(a);
  239. }
  240. }
  241. private readonly string m_firstname;
  242. public string Firstname
  243. {
  244. get { return m_firstname; }
  245. }
  246. private readonly string m_lastname;
  247. public string Lastname
  248. {
  249. get { return m_lastname; }
  250. }
  251. private string m_grouptitle;
  252. public string Grouptitle
  253. {
  254. get { return m_grouptitle; }
  255. set { m_grouptitle = value; }
  256. }
  257. public float DrawDistance
  258. {
  259. get { return m_DrawDistance; }
  260. }
  261. protected bool m_allowMovement = true;
  262. public bool AllowMovement
  263. {
  264. get { return m_allowMovement; }
  265. set { m_allowMovement = value; }
  266. }
  267. public bool SetAlwaysRun
  268. {
  269. get
  270. {
  271. if (PhysicsActor != null)
  272. {
  273. return PhysicsActor.SetAlwaysRun;
  274. }
  275. else
  276. {
  277. return m_setAlwaysRun;
  278. }
  279. }
  280. set
  281. {
  282. m_setAlwaysRun = value;
  283. if (PhysicsActor != null)
  284. {
  285. PhysicsActor.SetAlwaysRun = value;
  286. }
  287. }
  288. }
  289. public byte State
  290. {
  291. get { return m_state; }
  292. set { m_state = value; }
  293. }
  294. public uint AgentControlFlags
  295. {
  296. get { return m_AgentControlFlags; }
  297. set { m_AgentControlFlags = value; }
  298. }
  299. /// <summary>
  300. /// This works out to be the ClientView object associated with this avatar, or it's client connection manager
  301. /// </summary>
  302. private IClientAPI m_controllingClient;
  303. protected PhysicsActor m_physicsActor;
  304. /// <value>
  305. /// The client controlling this presence
  306. /// </value>
  307. public IClientAPI ControllingClient
  308. {
  309. get { return m_controllingClient; }
  310. }
  311. public IClientCore ClientView
  312. {
  313. get { return (IClientCore) m_controllingClient; }
  314. }
  315. protected Vector3 m_parentPosition;
  316. public Vector3 ParentPosition
  317. {
  318. get { return m_parentPosition; }
  319. set { m_parentPosition = value; }
  320. }
  321. public int MaxPrimsPerFrame
  322. {
  323. get { return m_sceneViewer.MaxPrimsPerFrame; }
  324. set { m_sceneViewer.MaxPrimsPerFrame = value; }
  325. }
  326. /// <summary>
  327. /// Absolute position of this avatar in 'region cordinates'
  328. /// </summary>
  329. public override Vector3 AbsolutePosition
  330. {
  331. get
  332. {
  333. if (m_physicsActor != null)
  334. {
  335. m_pos.X = m_physicsActor.Position.X;
  336. m_pos.Y = m_physicsActor.Position.Y;
  337. m_pos.Z = m_physicsActor.Position.Z;
  338. }
  339. return m_parentPosition + m_pos;
  340. }
  341. set
  342. {
  343. if (m_physicsActor != null)
  344. {
  345. try
  346. {
  347. lock (m_scene.SyncRoot)
  348. {
  349. m_physicsActor.Position = new PhysicsVector(value.X, value.Y, value.Z);
  350. }
  351. }
  352. catch (Exception e)
  353. {
  354. m_log.Error("[SCENEPRESENCE]: ABSOLUTE POSITION " + e.Message);
  355. }
  356. }
  357. m_pos = value;
  358. m_parentPosition = new Vector3(0, 0, 0);
  359. }
  360. }
  361. /// <summary>
  362. /// Current velocity of the avatar.
  363. /// </summary>
  364. public override Vector3 Velocity
  365. {
  366. get
  367. {
  368. if (m_physicsActor != null)
  369. {
  370. m_velocity.X = m_physicsActor.Velocity.X;
  371. m_velocity.Y = m_physicsActor.Velocity.Y;
  372. m_velocity.Z = m_physicsActor.Velocity.Z;
  373. }
  374. return m_velocity;
  375. }
  376. set
  377. {
  378. //m_log.DebugFormat("In {0} setting velocity of {1} to {2}", m_scene.RegionInfo.RegionName, Name, value);
  379. if (m_physicsActor != null)
  380. {
  381. try
  382. {
  383. lock (m_scene.SyncRoot)
  384. {
  385. m_physicsActor.Velocity = new PhysicsVector(value.X, value.Y, value.Z);
  386. }
  387. }
  388. catch (Exception e)
  389. {
  390. m_log.Error("[SCENEPRESENCE]: VELOCITY " + e.Message);
  391. }
  392. }
  393. m_velocity = value;
  394. }
  395. }
  396. /// <summary>
  397. /// If this is true, agent doesn't have a representation in this scene.
  398. /// this is an agent 'looking into' this scene from a nearby scene(region)
  399. ///
  400. /// if False, this agent has a representation in this scene
  401. /// </summary>
  402. private bool m_isChildAgent = true;
  403. public bool IsChildAgent
  404. {
  405. get { return m_isChildAgent; }
  406. set { m_isChildAgent = value; }
  407. }
  408. private uint m_parentID;
  409. public uint ParentID
  410. {
  411. get { return m_parentID; }
  412. set { m_parentID = value; }
  413. }
  414. public float Health
  415. {
  416. get { return m_health; }
  417. set { m_health = value; }
  418. }
  419. /// <summary>
  420. /// These are the region handles known by the avatar.
  421. /// </summary>
  422. public List<ulong> KnownChildRegionHandles
  423. {
  424. get
  425. {
  426. if (m_knownChildRegions.Count == 0)
  427. return new List<ulong>();
  428. else
  429. return new List<ulong>(m_knownChildRegions.Keys);
  430. }
  431. }
  432. public Dictionary<ulong, string> KnownRegions
  433. {
  434. get { return m_knownChildRegions; }
  435. set
  436. {
  437. m_knownChildRegions = value;
  438. }
  439. }
  440. public ISceneViewer SceneViewer
  441. {
  442. get { return m_sceneViewer; }
  443. }
  444. public void AdjustKnownSeeds()
  445. {
  446. Dictionary<ulong, string> seeds;
  447. if (Scene.CapsModule != null)
  448. seeds = Scene.CapsModule.GetChildrenSeeds(UUID);
  449. else
  450. seeds = new Dictionary<ulong, string>();
  451. List<ulong> old = new List<ulong>();
  452. foreach (ulong handle in seeds.Keys)
  453. {
  454. uint x, y;
  455. Utils.LongToUInts(handle, out x, out y);
  456. x = x / Constants.RegionSize;
  457. y = y / Constants.RegionSize;
  458. if (Util.IsOutsideView(x, Scene.RegionInfo.RegionLocX, y, Scene.RegionInfo.RegionLocY))
  459. {
  460. old.Add(handle);
  461. }
  462. }
  463. DropOldNeighbours(old);
  464. if (Scene.CapsModule != null)
  465. Scene.CapsModule.SetChildrenSeed(UUID, seeds);
  466. KnownRegions = seeds;
  467. //m_log.Debug(" ++++++++++AFTER+++++++++++++ ");
  468. //DumpKnownRegions();
  469. }
  470. public void DumpKnownRegions()
  471. {
  472. m_log.Info("================ KnownRegions "+Scene.RegionInfo.RegionName+" ================");
  473. foreach (KeyValuePair<ulong, string> kvp in KnownRegions)
  474. {
  475. uint x, y;
  476. Utils.LongToUInts(kvp.Key, out x, out y);
  477. x = x / Constants.RegionSize;
  478. y = y / Constants.RegionSize;
  479. m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
  480. }
  481. }
  482. public AnimationSet Animations
  483. {
  484. get { return m_animations; }
  485. }
  486. private bool m_inTransit;
  487. private bool m_mouseLook;
  488. private bool m_leftButtonDown;
  489. public bool IsInTransit
  490. {
  491. get { return m_inTransit; }
  492. set { m_inTransit = value; }
  493. }
  494. public float SpeedModifier
  495. {
  496. get { return m_speedModifier; }
  497. set { m_speedModifier = value; }
  498. }
  499. public bool ForceFly
  500. {
  501. get { return m_forceFly; }
  502. set { m_forceFly = value; }
  503. }
  504. public bool FlyDisabled
  505. {
  506. get { return m_flyDisabled; }
  507. set { m_flyDisabled = value; }
  508. }
  509. #endregion
  510. #region Constructor(s)
  511. private ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo)
  512. {
  513. CreateSceneViewer();
  514. m_regionHandle = reginfo.RegionHandle;
  515. m_controllingClient = client;
  516. m_firstname = m_controllingClient.FirstName;
  517. m_lastname = m_controllingClient.LastName;
  518. m_name = String.Format("{0} {1}", m_firstname, m_lastname);
  519. m_scene = world;
  520. m_uuid = client.AgentId;
  521. m_regionInfo = reginfo;
  522. m_localId = m_scene.AllocateLocalId();
  523. m_useFlySlow = m_scene.m_useFlySlow;
  524. m_usePreJump = m_scene.m_usePreJump;
  525. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  526. if (gm != null)
  527. m_grouptitle = gm.GetGroupTitle(m_uuid);
  528. m_scriptEngines = m_scene.RequestModuleInterfaces<IScriptModule>();
  529. AbsolutePosition = m_controllingClient.StartPos;
  530. AdjustKnownSeeds();
  531. TrySetMovementAnimation("STAND"); // TODO: I think, this won't send anything, as we are still a child here...
  532. // we created a new ScenePresence (a new child agent) in a fresh region.
  533. // Request info about all the (root) agents in this region
  534. // Note: This won't send data *to* other clients in that region (children don't send)
  535. SendInitialFullUpdateToAllClients();
  536. RegisterToEvents();
  537. SetDirectionVectors();
  538. CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(m_uuid);
  539. if (userInfo != null)
  540. userInfo.OnItemReceived += ItemReceived;
  541. }
  542. public ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo, byte[] visualParams,
  543. AvatarWearable[] wearables)
  544. : this(client, world, reginfo)
  545. {
  546. CreateSceneViewer();
  547. m_appearance = new AvatarAppearance(m_uuid, wearables, visualParams);
  548. }
  549. public ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo, AvatarAppearance appearance)
  550. : this(client, world, reginfo)
  551. {
  552. CreateSceneViewer();
  553. m_appearance = appearance;
  554. }
  555. private void CreateSceneViewer()
  556. {
  557. m_sceneViewer = new SceneViewer(this);
  558. }
  559. public void RegisterToEvents()
  560. {
  561. m_controllingClient.OnRequestWearables += SendWearables;
  562. m_controllingClient.OnSetAppearance += SetAppearance;
  563. m_controllingClient.OnCompleteMovementToRegion += CompleteMovement;
  564. //m_controllingClient.OnCompleteMovementToRegion += SendInitialData;
  565. m_controllingClient.OnAgentUpdate += HandleAgentUpdate;
  566. m_controllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  567. m_controllingClient.OnAgentSit += HandleAgentSit;
  568. m_controllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  569. m_controllingClient.OnStartAnim += HandleStartAnim;
  570. m_controllingClient.OnStopAnim += HandleStopAnim;
  571. m_controllingClient.OnForceReleaseControls += HandleForceReleaseControls;
  572. m_controllingClient.OnAutoPilotGo += DoAutoPilot;
  573. m_controllingClient.AddGenericPacketHandler("autopilot", DoMoveToPosition);
  574. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  575. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  576. }
  577. private void SetDirectionVectors()
  578. {
  579. Dir_Vectors[0] = new Vector3(1, 0, 0); //FORWARD
  580. Dir_Vectors[1] = new Vector3(-1, 0, 0); //BACK
  581. Dir_Vectors[2] = new Vector3(0, 1, 0); //LEFT
  582. Dir_Vectors[3] = new Vector3(0, -1, 0); //RIGHT
  583. Dir_Vectors[4] = new Vector3(0, 0, 1); //UP
  584. Dir_Vectors[5] = new Vector3(0, 0, -1); //DOWN
  585. Dir_Vectors[5] = new Vector3(0, 0, -0.5f); //DOWN_Nudge
  586. }
  587. private Vector3[] GetWalkDirectionVectors()
  588. {
  589. Vector3[] vector = new Vector3[6];
  590. vector[0] = new Vector3(m_CameraUpAxis.Z, 0, -m_CameraAtAxis.Z); //FORWARD
  591. vector[1] = new Vector3(-m_CameraUpAxis.Z, 0, m_CameraAtAxis.Z); //BACK
  592. vector[2] = new Vector3(0, 1, 0); //LEFT
  593. vector[3] = new Vector3(0, -1, 0); //RIGHT
  594. vector[4] = new Vector3(m_CameraAtAxis.Z, 0, m_CameraUpAxis.Z); //UP
  595. vector[5] = new Vector3(-m_CameraAtAxis.Z, 0, -m_CameraUpAxis.Z); //DOWN
  596. vector[5] = new Vector3(-m_CameraAtAxis.Z, 0, -m_CameraUpAxis.Z); //DOWN_Nudge
  597. return vector;
  598. }
  599. #endregion
  600. /// <summary>
  601. /// Add the part to the queue of parts for which we need to send an update to the client
  602. /// </summary>
  603. /// <param name="part"></param>
  604. public void QueuePartForUpdate(SceneObjectPart part)
  605. {
  606. m_sceneViewer.QueuePartForUpdate(part);
  607. }
  608. public uint GenerateClientFlags(UUID ObjectID)
  609. {
  610. return m_scene.Permissions.GenerateClientFlags(m_uuid, ObjectID);
  611. }
  612. /// <summary>
  613. /// Send updates to the client about prims which have been placed on the update queue. We don't
  614. /// necessarily send updates for all the parts on the queue, e.g. if an updates with a more recent
  615. /// timestamp has already been sent.
  616. /// </summary>
  617. public void SendPrimUpdates()
  618. {
  619. m_perfMonMS = Environment.TickCount;
  620. m_sceneViewer.SendPrimUpdates();
  621. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  622. }
  623. #region Status Methods
  624. /// <summary>
  625. /// This turns a child agent, into a root agent
  626. /// This is called when an agent teleports into a region, or if an
  627. /// agent crosses into this region from a neighbor over the border
  628. /// </summary>
  629. public void MakeRootAgent(Vector3 pos, bool isFlying)
  630. {
  631. m_log.DebugFormat(
  632. "[SCENE]: Upgrading child to root agent for {0} in {1}",
  633. Name, m_scene.RegionInfo.RegionName);
  634. //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
  635. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  636. if (gm != null)
  637. m_grouptitle = gm.GetGroupTitle(m_uuid);
  638. m_scene.SetRootAgentScene(m_uuid);
  639. // Moved this from SendInitialData to ensure that m_appearance is initialized
  640. // before the inventory is processed in MakeRootAgent. This fixes a race condition
  641. // related to the handling of attachments
  642. //m_scene.GetAvatarAppearance(m_controllingClient, out m_appearance);
  643. if (pos.X < 0 || pos.X >= (int)Constants.RegionSize || pos.Y < 0 || pos.Y >= (int)Constants.RegionSize || pos.Z < 0)
  644. {
  645. Vector3 emergencyPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 128);
  646. m_log.WarnFormat(
  647. "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
  648. pos, Name, UUID, emergencyPos);
  649. pos = emergencyPos;
  650. }
  651. float localAVHeight = 1.56f;
  652. if (m_avHeight != 127.0f)
  653. {
  654. localAVHeight = m_avHeight;
  655. }
  656. float posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
  657. float newPosZ = posZLimit + localAVHeight / 2;
  658. if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  659. {
  660. pos.Z = newPosZ;
  661. }
  662. AbsolutePosition = pos;
  663. AddToPhysicalScene(isFlying);
  664. if (m_forceFly)
  665. {
  666. m_physicsActor.Flying = true;
  667. }
  668. else if (m_flyDisabled)
  669. {
  670. m_physicsActor.Flying = false;
  671. }
  672. if (m_appearance != null)
  673. {
  674. if (m_appearance.AvatarHeight > 0)
  675. SetHeight(m_appearance.AvatarHeight);
  676. }
  677. else
  678. {
  679. m_log.ErrorFormat("[SCENE PRESENCE]: null appearance in MakeRoot in {0}", Scene.RegionInfo.RegionName);
  680. // emergency; this really shouldn't happen
  681. m_appearance = new AvatarAppearance(UUID);
  682. }
  683. // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying
  684. // avatar to return to the standing position in mid-air. On login it looks like this is being sent
  685. // elsewhere anyway
  686. //SendAnimPack();
  687. m_scene.SwapRootAgentCount(false);
  688. CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(m_uuid);
  689. if (userInfo != null)
  690. userInfo.FetchInventory();
  691. else
  692. m_log.ErrorFormat("[SCENE]: Could not find user info for {0} when making it a root agent", m_uuid);
  693. // On the next prim update, all objects will be sent
  694. //
  695. m_sceneViewer.Reset();
  696. m_isChildAgent = false;
  697. List<ScenePresence> AnimAgents = m_scene.GetScenePresences();
  698. foreach (ScenePresence p in AnimAgents)
  699. {
  700. if (p != this)
  701. p.SendAnimPackToClient(ControllingClient);
  702. }
  703. m_scene.EventManager.TriggerOnMakeRootAgent(this);
  704. }
  705. /// <summary>
  706. /// This turns a root agent into a child agent
  707. /// when an agent departs this region for a neighbor, this gets called.
  708. ///
  709. /// It doesn't get called for a teleport. Reason being, an agent that
  710. /// teleports out may not end up anywhere near this region
  711. /// </summary>
  712. public void MakeChildAgent()
  713. {
  714. m_animations.Clear();
  715. // m_log.DebugFormat(
  716. // "[SCENEPRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
  717. // Name, UUID, m_scene.RegionInfo.RegionName);
  718. // Don't zero out the velocity since this can cause problems when an avatar is making a region crossing,
  719. // depending on the exact timing. This shouldn't matter anyway since child agent positions are not updated.
  720. //Velocity = new Vector3(0, 0, 0);
  721. m_isChildAgent = true;
  722. m_scene.SwapRootAgentCount(true);
  723. RemoveFromPhysicalScene();
  724. m_scene.EventManager.TriggerOnMakeChildAgent(this);
  725. }
  726. /// <summary>
  727. /// Removes physics plugin scene representation of this agent if it exists.
  728. /// </summary>
  729. private void RemoveFromPhysicalScene()
  730. {
  731. if (PhysicsActor != null)
  732. {
  733. m_physicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  734. m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
  735. m_physicsActor.UnSubscribeEvents();
  736. m_physicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
  737. PhysicsActor = null;
  738. }
  739. }
  740. /// <summary>
  741. ///
  742. /// </summary>
  743. /// <param name="pos"></param>
  744. public void Teleport(Vector3 pos)
  745. {
  746. bool isFlying = false;
  747. if (m_physicsActor != null)
  748. isFlying = m_physicsActor.Flying;
  749. RemoveFromPhysicalScene();
  750. Velocity = new Vector3(0, 0, 0);
  751. AbsolutePosition = pos;
  752. AddToPhysicalScene(isFlying);
  753. if (m_appearance != null)
  754. {
  755. if (m_appearance.AvatarHeight > 0)
  756. SetHeight(m_appearance.AvatarHeight);
  757. }
  758. SendTerseUpdateToAllClients();
  759. }
  760. public void TeleportWithMomentum(Vector3 pos)
  761. {
  762. bool isFlying = false;
  763. if (m_physicsActor != null)
  764. isFlying = m_physicsActor.Flying;
  765. RemoveFromPhysicalScene();
  766. AbsolutePosition = pos;
  767. AddToPhysicalScene(isFlying);
  768. if (m_appearance != null)
  769. {
  770. if (m_appearance.AvatarHeight > 0)
  771. SetHeight(m_appearance.AvatarHeight);
  772. }
  773. SendTerseUpdateToAllClients();
  774. }
  775. /// <summary>
  776. ///
  777. /// </summary>
  778. public void StopMovement()
  779. {
  780. }
  781. public void StopFlying()
  782. {
  783. // It turns out to get the agent to stop flying, you have to feed it stop flying velocities
  784. // and send a full object update.
  785. // There's no message to send the client to tell it to stop flying
  786. // Add 1/6 the avatar's height to it's position so it doesn't shoot into the air
  787. // when the avatar stands up
  788. if (m_avHeight != 127.0f)
  789. {
  790. AbsolutePosition = AbsolutePosition + new Vector3(0, 0, (m_avHeight / 6f));
  791. }
  792. else
  793. {
  794. AbsolutePosition = AbsolutePosition + new Vector3(0, 0, (1.56f / 6f));
  795. }
  796. TrySetMovementAnimation("LAND");
  797. SendFullUpdateToAllClients();
  798. }
  799. public void AddNeighbourRegion(ulong regionHandle, string cap)
  800. {
  801. lock (m_knownChildRegions)
  802. {
  803. if (!m_knownChildRegions.ContainsKey(regionHandle))
  804. {
  805. uint x, y;
  806. Utils.LongToUInts(regionHandle, out x, out y);
  807. m_knownChildRegions.Add(regionHandle, cap);
  808. }
  809. }
  810. }
  811. public void RemoveNeighbourRegion(ulong regionHandle)
  812. {
  813. lock (m_knownChildRegions)
  814. {
  815. if (m_knownChildRegions.ContainsKey(regionHandle))
  816. {
  817. m_knownChildRegions.Remove(regionHandle);
  818. //m_log.Debug(" !!! removing known region {0} in {1}. Count = {2}", regionHandle, Scene.RegionInfo.RegionName, m_knownChildRegions.Count);
  819. }
  820. }
  821. }
  822. public void DropOldNeighbours(List<ulong> oldRegions)
  823. {
  824. foreach (ulong handle in oldRegions)
  825. {
  826. RemoveNeighbourRegion(handle);
  827. Scene.CapsModule.DropChildSeed(UUID, handle);
  828. }
  829. }
  830. public List<ulong> GetKnownRegionList()
  831. {
  832. return new List<ulong>(m_knownChildRegions.Keys);
  833. }
  834. #endregion
  835. #region Event Handlers
  836. /// <summary>
  837. /// Sets avatar height in the phyiscs plugin
  838. /// </summary>
  839. internal void SetHeight(float height)
  840. {
  841. m_avHeight = height;
  842. if (PhysicsActor != null && !IsChildAgent)
  843. {
  844. PhysicsVector SetSize = new PhysicsVector(0.45f, 0.6f, m_avHeight);
  845. PhysicsActor.Size = SetSize;
  846. }
  847. }
  848. /// <summary>
  849. /// Complete Avatar's movement into the region
  850. /// </summary>
  851. public void CompleteMovement()
  852. {
  853. Vector3 look = Velocity;
  854. if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
  855. {
  856. look = new Vector3(0.99f, 0.042f, 0);
  857. }
  858. // Prevent teleporting to an underground location
  859. // (may crash client otherwise)
  860. //
  861. Vector3 pos = AbsolutePosition;
  862. float ground = m_scene.GetGroundHeight(pos.X, pos.Y);
  863. if (pos.Z < ground + 1.5f)
  864. {
  865. pos.Z = ground + 1.5f;
  866. AbsolutePosition = pos;
  867. }
  868. if (m_isChildAgent)
  869. {
  870. m_isChildAgent = false;
  871. bool m_flying = ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  872. MakeRootAgent(AbsolutePosition, m_flying);
  873. if ((m_callbackURI != null) && !m_callbackURI.Equals(""))
  874. {
  875. m_log.DebugFormat("[SCENE PRESENCE]: Releasing agent in URI {0}", m_callbackURI);
  876. Scene.SendReleaseAgent(m_rootRegionHandle, UUID, m_callbackURI);
  877. m_callbackURI = null;
  878. }
  879. //m_log.DebugFormat("Completed movement");
  880. }
  881. m_controllingClient.MoveAgentIntoRegion(m_regionInfo, AbsolutePosition, look);
  882. SendInitialData();
  883. }
  884. // These methods allow to queue up agent updates (like key presses)
  885. // until all attachment scripts are running and the animations from
  886. // AgentDataUpdate have been started. It is essential for combat
  887. // devices, weapons and AOs that keypresses are not processed
  888. // until scripts that are potentially interested in them are
  889. // up and running and that animations a script knows to be running
  890. // from before a crossing are running again
  891. //
  892. public void LockAgentUpdates()
  893. {
  894. m_updatesAllowed = false;
  895. }
  896. public void UnlockAgentUpdates()
  897. {
  898. lock (m_agentUpdates)
  899. {
  900. if (m_updatesAllowed == false)
  901. {
  902. foreach (AgentUpdateArgs a in m_agentUpdates)
  903. RealHandleAgentUpdate(ControllingClient, a);
  904. m_agentUpdates.Clear();
  905. m_updatesAllowed = true;
  906. }
  907. }
  908. }
  909. /// <summary>
  910. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  911. /// hitYN is true when there's something in the way.
  912. /// </summary>
  913. /// <param name="hitYN"></param>
  914. /// <param name="collisionPoint"></param>
  915. /// <param name="localid"></param>
  916. /// <param name="distance"></param>
  917. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance)
  918. {
  919. if (m_followCamAuto)
  920. {
  921. if (hitYN)
  922. {
  923. CameraConstraintActive = true;
  924. //m_log.DebugFormat("[RAYCASTRESULT]: {0}, {1}, {2}, {3}", hitYN, collisionPoint, localid, distance);
  925. Vector3 normal = Vector3.Normalize(new Vector3(0,0,collisionPoint.Z) - collisionPoint);
  926. ControllingClient.SendCameraConstraint(new Vector4(normal.X, normal.Y, normal.Z, -1 * Vector3.Distance(new Vector3(0,0,collisionPoint.Z),collisionPoint)));
  927. }
  928. else
  929. {
  930. if (((Util.GetDistanceTo(lastPhysPos, AbsolutePosition) > 0.02)
  931. || (Util.GetDistanceTo(m_lastVelocity, m_velocity) > 0.02)
  932. || lastPhysRot != m_bodyRot))
  933. {
  934. if (CameraConstraintActive)
  935. {
  936. ControllingClient.SendCameraConstraint(new Vector4(0, 0.5f, 0.9f, -3000f));
  937. CameraConstraintActive = false;
  938. }
  939. }
  940. }
  941. }
  942. }
  943. /// <summary>
  944. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  945. /// </summary>
  946. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  947. {
  948. lock (m_agentUpdates)
  949. {
  950. if (m_updatesAllowed)
  951. {
  952. RealHandleAgentUpdate(remoteClient, agentData);
  953. return;
  954. }
  955. m_agentUpdates.Add(agentData);
  956. }
  957. }
  958. private void RealHandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  959. {
  960. //if (m_isChildAgent)
  961. //{
  962. // // m_log.Debug("DEBUG: HandleAgentUpdate: child agent");
  963. // return;
  964. //}
  965. m_movementUpdateCount++;
  966. if (m_movementUpdateCount >= int.MaxValue)
  967. m_movementUpdateCount = 1;
  968. // Must check for standing up even when PhysicsActor is null,
  969. // since sitting currently removes avatar from physical scene
  970. //m_log.Debug("agentPos:" + AbsolutePosition.ToString());
  971. // This is irritating. Really.
  972. if (!AbsolutePosition.IsFinite())
  973. {
  974. RemoveFromPhysicalScene();
  975. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error# 9999902");
  976. m_pos = m_LastFinitePos;
  977. if (!m_pos.IsFinite())
  978. {
  979. m_pos.X = 127f;
  980. m_pos.Y = 127f;
  981. m_pos.Z = 127f;
  982. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error# 9999903");
  983. }
  984. AddToPhysicalScene(false);
  985. }
  986. else
  987. {
  988. m_LastFinitePos = m_pos;
  989. }
  990. //m_physicsActor.AddForce(new PhysicsVector(999999999, 99999999, 999999999999999), true);
  991. //ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  992. //if (land != null)
  993. //{
  994. //if (land.landData.landingType == (byte)1 && land.landData.userLocation != Vector3.Zero)
  995. //{
  996. // agent.startpos = land.landData.userLocation;
  997. //}
  998. //}
  999. m_perfMonMS = Environment.TickCount;
  1000. uint flags = agentData.ControlFlags;
  1001. Quaternion bodyRotation = agentData.BodyRotation;
  1002. // Camera location in world. We'll need to raytrace
  1003. // from this location from time to time.
  1004. m_CameraCenter = agentData.CameraCenter;
  1005. // Use these three vectors to figure out what the agent is looking at
  1006. // Convert it to a Matrix and/or Quaternion
  1007. m_CameraAtAxis = agentData.CameraAtAxis;
  1008. m_CameraLeftAxis = agentData.CameraLeftAxis;
  1009. m_CameraUpAxis = agentData.CameraUpAxis;
  1010. // The Agent's Draw distance setting
  1011. m_DrawDistance = agentData.Far;
  1012. if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  1013. {
  1014. StandUp();
  1015. }
  1016. // Check if Client has camera in 'follow cam' or 'build' mode.
  1017. Vector3 camdif = (Vector3.One * m_bodyRot - Vector3.One * CameraRotation);
  1018. m_followCamAuto = ((m_CameraUpAxis.Z > 0.959f && m_CameraUpAxis.Z < 0.98f)
  1019. && (Math.Abs(camdif.X) < 0.4f && Math.Abs(camdif.Y) < 0.4f)) ? true : false;
  1020. //m_log.DebugFormat("[FollowCam]: {0}", m_followCamAuto);
  1021. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  1022. if ((m_movementUpdateCount % NumMovementsBetweenRayCast) == 0 && m_scene.PhysicsScene.SupportsRayCast())
  1023. {
  1024. if (m_followCamAuto)
  1025. {
  1026. Vector3 headadjustment = new Vector3(0, 0, 0.3f);
  1027. m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(m_CameraCenter - (m_pos + headadjustment)), Vector3.Distance(m_CameraCenter, (m_pos + headadjustment)) + 0.3f, RayCastCameraCallback);
  1028. }
  1029. }
  1030. m_mouseLook = (flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  1031. m_leftButtonDown = (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  1032. lock (scriptedcontrols)
  1033. {
  1034. if (scriptedcontrols.Count > 0)
  1035. {
  1036. SendControlToScripts(flags);
  1037. flags = RemoveIgnoredControls(flags, IgnoredControls);
  1038. }
  1039. }
  1040. if (PhysicsActor == null)
  1041. {
  1042. return;
  1043. }
  1044. if (m_autopilotMoving)
  1045. CheckAtSitTarget();
  1046. if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  1047. {
  1048. // TODO: This doesn't prevent the user from walking yet.
  1049. // Setting parent ID would fix this, if we knew what value
  1050. // to use. Or we could add a m_isSitting variable.
  1051. TrySetMovementAnimation("SIT_GROUND_CONSTRAINED");
  1052. }
  1053. // In the future, these values might need to go global.
  1054. // Here's where you get them.
  1055. m_AgentControlFlags = flags;
  1056. m_headrotation = agentData.HeadRotation;
  1057. m_state = agentData.State;
  1058. if (m_allowMovement)
  1059. {
  1060. int i = 0;
  1061. bool update_movementflag = false;
  1062. bool update_rotation = false;
  1063. bool DCFlagKeyPressed = false;
  1064. Vector3 agent_control_v3 = new Vector3(0, 0, 0);
  1065. Quaternion q = bodyRotation;
  1066. if (PhysicsActor != null)
  1067. {
  1068. bool oldflying = PhysicsActor.Flying;
  1069. if (m_forceFly)
  1070. PhysicsActor.Flying = true;
  1071. else if (m_flyDisabled)
  1072. PhysicsActor.Flying = false;
  1073. else
  1074. PhysicsActor.Flying = ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1075. if (PhysicsActor.Flying != oldflying)
  1076. {
  1077. update_movementflag = true;
  1078. }
  1079. }
  1080. if (q != m_bodyRot)
  1081. {
  1082. m_bodyRot = q;
  1083. update_rotation = true;
  1084. }
  1085. if (m_parentID == 0)
  1086. {
  1087. bool bAllowUpdateMoveToPosition = false;
  1088. bool bResetMoveToPosition = false;
  1089. Vector3[] dirVectors;
  1090. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  1091. // this prevents 'jumping' in inappropriate situations.
  1092. if ((m_mouseLook && !m_physicsActor.Flying) || (m_leftButtonDown && !m_physicsActor.Flying))
  1093. dirVectors = GetWalkDirectionVectors();
  1094. else
  1095. dirVectors = Dir_Vectors;
  1096. foreach (Dir_ControlFlags DCF in Enum.GetValues(typeof (Dir_ControlFlags)))
  1097. {
  1098. if ((flags & (uint) DCF) != 0)
  1099. {
  1100. bResetMoveToPosition = true;
  1101. DCFlagKeyPressed = true;
  1102. try
  1103. {
  1104. agent_control_v3 += dirVectors[i];
  1105. }
  1106. catch (IndexOutOfRangeException)
  1107. {
  1108. // Why did I get this?
  1109. }
  1110. if ((m_movementflag & (uint) DCF) == 0)
  1111. {
  1112. m_movementflag += (byte) (uint) DCF;
  1113. update_movementflag = true;
  1114. }
  1115. }
  1116. else
  1117. {
  1118. if ((m_movementflag & (uint) DCF) != 0)
  1119. {
  1120. m_movementflag -= (byte) (uint) DCF;
  1121. update_movementflag = true;
  1122. }
  1123. else
  1124. {
  1125. bAllowUpdateMoveToPosition = true;
  1126. }
  1127. }
  1128. i++;
  1129. }
  1130. //Paupaw:Do Proper PID for Autopilot here
  1131. if (bResetMoveToPosition)
  1132. {
  1133. m_moveToPositionTarget = Vector3.Zero;
  1134. m_moveToPositionInProgress = false;
  1135. update_movementflag = true;
  1136. bAllowUpdateMoveToPosition = false;
  1137. }
  1138. if (bAllowUpdateMoveToPosition && (m_moveToPositionInProgress && !m_autopilotMoving))
  1139. {
  1140. //Check the error term of the current position in relation to the target position
  1141. if (Util.GetDistanceTo(AbsolutePosition, m_moveToPositionTarget) <= 1.5)
  1142. {
  1143. // we are close enough to the target
  1144. m_moveToPositionTarget = Vector3.Zero;
  1145. m_moveToPositionInProgress = false;
  1146. update_movementflag = true;
  1147. }
  1148. else
  1149. {
  1150. try
  1151. {
  1152. // move avatar in 2D at one meter/second towards target, in avatar coordinate frame.
  1153. // This movement vector gets added to the velocity through AddNewMovement().
  1154. // Theoretically we might need a more complex PID approach here if other
  1155. // unknown forces are acting on the avatar and we need to adaptively respond
  1156. // to such forces, but the following simple approach seems to works fine.
  1157. Vector3 LocalVectorToTarget3D =
  1158. (m_moveToPositionTarget - AbsolutePosition) // vector from cur. pos to target in global coords
  1159. * Matrix4.CreateFromQuaternion(Quaternion.Inverse(bodyRotation)); // change to avatar coords
  1160. // Ignore z component of vector
  1161. Vector3 LocalVectorToTarget2D = new Vector3((float)(LocalVectorToTarget3D.X), (float)(LocalVectorToTarget3D.Y), 0f);
  1162. LocalVectorToTarget2D.Normalize();
  1163. agent_control_v3 += LocalVectorToTarget2D;
  1164. // update avatar movement flags. the avatar coordinate system is as follows:
  1165. //
  1166. // +X (forward)
  1167. //
  1168. // ^
  1169. // |
  1170. // |
  1171. // |
  1172. // |
  1173. // (left) +Y <--------o--------> -Y
  1174. // avatar
  1175. // |
  1176. // |
  1177. // |
  1178. // |
  1179. // v
  1180. // -X
  1181. //
  1182. // based on the above avatar coordinate system, classify the movement into
  1183. // one of left/right/back/forward.
  1184. if (LocalVectorToTarget2D.Y > 0)//MoveLeft
  1185. {
  1186. m_movementflag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  1187. update_movementflag = true;
  1188. }
  1189. else if (LocalVectorToTarget2D.Y < 0) //MoveRight
  1190. {
  1191. m_movementflag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  1192. update_movementflag = true;
  1193. }
  1194. if (LocalVectorToTarget2D.X < 0) //MoveBack
  1195. {
  1196. m_movementflag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  1197. update_movementflag = true;
  1198. }
  1199. else if (LocalVectorToTarget2D.X > 0) //Move Forward
  1200. {
  1201. m_movementflag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  1202. update_movementflag = true;
  1203. }
  1204. }
  1205. catch (Exception)
  1206. {
  1207. //Avoid system crash, can be slower but...
  1208. }
  1209. }
  1210. }
  1211. }
  1212. // Cause the avatar to stop flying if it's colliding
  1213. // with something with the down arrow pressed.
  1214. // Only do this if we're flying
  1215. if (m_physicsActor != null && m_physicsActor.Flying && !m_forceFly)
  1216. {
  1217. // Are the landing controls requirements filled?
  1218. bool controlland = (((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  1219. ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  1220. // Are the collision requirements fulfilled?
  1221. bool colliding = (m_physicsActor.IsColliding == true);
  1222. if (m_physicsActor.Flying && colliding && controlland)
  1223. {
  1224. StopFlying();
  1225. }
  1226. }
  1227. if (update_movementflag || (update_rotation && DCFlagKeyPressed))
  1228. {
  1229. // m_log.DebugFormat("{0} {1}", update_movementflag, (update_rotation && DCFlagKeyPressed));
  1230. // m_log.DebugFormat(
  1231. // "In {0} adding velocity to {1} of {2}", m_scene.RegionInfo.RegionName, Name, agent_control_v3);
  1232. AddNewMovement(agent_control_v3, q);
  1233. if (update_movementflag)
  1234. UpdateMovementAnimations();
  1235. }
  1236. }
  1237. m_scene.EventManager.TriggerOnClientMovement(this);
  1238. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  1239. }
  1240. public void DoAutoPilot(uint not_used, Vector3 Pos, IClientAPI remote_client)
  1241. {
  1242. m_autopilotMoving = true;
  1243. m_autoPilotTarget = Pos;
  1244. m_sitAtAutoTarget = false;
  1245. PrimitiveBaseShape proxy = PrimitiveBaseShape.Default;
  1246. //proxy.PCode = (byte)PCode.ParticleSystem;
  1247. proxyObjectGroup = new SceneObjectGroup(UUID, Pos, Rotation, proxy);
  1248. proxyObjectGroup.AttachToScene(m_scene);
  1249. // Commented out this code since it could never have executed, but might still be informative.
  1250. // if (proxyObjectGroup != null)
  1251. // {
  1252. proxyObjectGroup.SendGroupFullUpdate();
  1253. remote_client.SendSitResponse(proxyObjectGroup.UUID, Vector3.Zero, Quaternion.Identity, true, Vector3.Zero, Vector3.Zero, false);
  1254. m_scene.DeleteSceneObject(proxyObjectGroup, false);
  1255. // }
  1256. // else
  1257. // {
  1258. // m_autopilotMoving = false;
  1259. // m_autoPilotTarget = Vector3.Zero;
  1260. // ControllingClient.SendAlertMessage("Autopilot cancelled");
  1261. // }
  1262. }
  1263. public void DoMoveToPosition(Object sender, string method, List<String> args)
  1264. {
  1265. try
  1266. {
  1267. float locx = 0f;
  1268. float locy = 0f;
  1269. float locz = 0f;
  1270. uint regionX = 0;
  1271. uint regionY = 0;
  1272. try
  1273. {
  1274. Utils.LongToUInts(Scene.RegionInfo.RegionHandle, out regionX, out regionY);
  1275. locx = Convert.ToSingle(args[0]) - (float)regionX;
  1276. locy = Convert.ToSingle(args[1]) - (float)regionY;
  1277. locz = Convert.ToSingle(args[2]);
  1278. }
  1279. catch (InvalidCastException)
  1280. {
  1281. m_log.Error("[CLIENT]: Invalid autopilot request");
  1282. return;
  1283. }
  1284. m_moveToPositionInProgress = true;
  1285. m_moveToPositionTarget = new Vector3(locx, locy, locz);
  1286. }
  1287. catch (Exception ex)
  1288. {
  1289. //Why did I get this error?
  1290. m_log.Error("[SCENEPRESENCE]: DoMoveToPosition" + ex);
  1291. }
  1292. }
  1293. private void CheckAtSitTarget()
  1294. {
  1295. //m_log.Debug("[AUTOPILOT]: " + Util.GetDistanceTo(AbsolutePosition, m_autoPilotTarget).ToString());
  1296. if (Util.GetDistanceTo(AbsolutePosition, m_autoPilotTarget) <= 1.5)
  1297. {
  1298. if (m_sitAtAutoTarget)
  1299. {
  1300. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetUUID);
  1301. if (part != null)
  1302. {
  1303. AbsolutePosition = part.AbsolutePosition;
  1304. Velocity = new Vector3(0, 0, 0);
  1305. SendFullUpdateToAllClients();
  1306. //HandleAgentSit(ControllingClient, m_requestedSitTargetUUID);
  1307. }
  1308. //ControllingClient.SendSitResponse(m_requestedSitTargetID, m_requestedSitOffset, Quaternion.Identity, false, Vector3.Zero, Vector3.Zero, false);
  1309. m_requestedSitTargetUUID = UUID.Zero;
  1310. }
  1311. /*
  1312. else
  1313. {
  1314. //ControllingClient.SendAlertMessage("Autopilot cancelled");
  1315. //SendTerseUpdateToAllClients();
  1316. //PrimitiveBaseShape proxy = PrimitiveBaseShape.Default;
  1317. //proxy.PCode = (byte)PCode.ParticleSystem;
  1318. ////uint nextUUID = m_scene.NextLocalId;
  1319. //proxyObjectGroup = new SceneObjectGroup(m_scene, m_scene.RegionInfo.RegionHandle, UUID, nextUUID, m_autoPilotTarget, Quaternion.Identity, proxy);
  1320. //if (proxyObjectGroup != null)
  1321. //{
  1322. //proxyObjectGroup.SendGroupFullUpdate();
  1323. //ControllingClient.SendSitResponse(UUID.Zero, m_autoPilotTarget, Quaternion.Identity, true, Vector3.Zero, Vector3.Zero, false);
  1324. //m_scene.DeleteSceneObject(proxyObjectGroup);
  1325. //}
  1326. }
  1327. */
  1328. m_autoPilotTarget = Vector3.Zero;
  1329. m_autopilotMoving = false;
  1330. }
  1331. }
  1332. /// <summary>
  1333. /// Perform the logic necessary to stand the client up. This method also executes
  1334. /// the stand animation.
  1335. /// </summary>
  1336. public void StandUp()
  1337. {
  1338. if (m_parentID != 0)
  1339. {
  1340. SceneObjectPart part = m_scene.GetSceneObjectPart(m_parentID);
  1341. if (part != null)
  1342. {
  1343. TaskInventoryDictionary taskIDict = part.TaskInventory;
  1344. if (taskIDict != null)
  1345. {
  1346. lock (taskIDict)
  1347. {
  1348. foreach (UUID taskID in taskIDict.Keys)
  1349. {
  1350. UnRegisterControlEventsToScript(LocalId, taskID);
  1351. taskIDict[taskID].PermsMask &= ~(
  1352. 2048 | //PERMISSION_CONTROL_CAMERA
  1353. 4); // PERMISSION_TAKE_CONTROLS
  1354. }
  1355. }
  1356. }
  1357. // Reset sit target.
  1358. if (part.GetAvatarOnSitTarget() == UUID)
  1359. part.SetAvatarOnSitTarget(UUID.Zero);
  1360. m_parentPosition = part.GetWorldPosition();
  1361. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  1362. }
  1363. if (m_physicsActor == null)
  1364. {
  1365. AddToPhysicalScene(false);
  1366. }
  1367. m_pos += m_parentPosition + new Vector3(0.0f, 0.0f, 2.0f*m_sitAvatarHeight);
  1368. m_parentPosition = new Vector3();
  1369. m_parentID = 0;
  1370. SendFullUpdateToAllClients();
  1371. m_requestedSitTargetID = 0;
  1372. if ((m_physicsActor != null) && (m_avHeight > 0))
  1373. {
  1374. SetHeight(m_avHeight);
  1375. }
  1376. }
  1377. TrySetMovementAnimation("STAND");
  1378. }
  1379. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  1380. {
  1381. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  1382. if (targetPart == null)
  1383. return null;
  1384. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  1385. // If the primitive the player clicked on has no sit target, and one or more other linked objects have sit targets that are not full, the sit target of the object with the lowest link number will be used.
  1386. // Get our own copy of the part array, and sort into the order we want to test
  1387. SceneObjectPart[] partArray = targetPart.ParentGroup.GetParts();
  1388. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  1389. {
  1390. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  1391. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  1392. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  1393. return linkNum1 - linkNum2;
  1394. }
  1395. );
  1396. //look for prims with explicit sit targets that are available
  1397. foreach (SceneObjectPart part in partArray)
  1398. {
  1399. // Is a sit target available?
  1400. Vector3 avSitOffSet = part.SitTargetPosition;
  1401. Quaternion avSitOrientation = part.SitTargetOrientation;
  1402. UUID avOnTargetAlready = part.GetAvatarOnSitTarget();
  1403. bool SitTargetUnOccupied = (!(avOnTargetAlready != UUID.Zero));
  1404. bool SitTargetisSet =
  1405. (!(avSitOffSet.X == 0f && avSitOffSet.Y == 0f && avSitOffSet.Z == 0f && avSitOrientation.W == 1f &&
  1406. avSitOrientation.X == 0f && avSitOrientation.Y == 0f && avSitOrientation.Z == 0f));
  1407. if (SitTargetisSet && SitTargetUnOccupied)
  1408. {
  1409. //switch the target to this prim
  1410. return part;
  1411. }
  1412. }
  1413. // no explicit sit target found - use original target
  1414. return targetPart;
  1415. }
  1416. private void SendSitResponse(IClientAPI remoteClient, UUID targetID, Vector3 offset)
  1417. {
  1418. bool autopilot = true;
  1419. Vector3 pos = new Vector3();
  1420. Quaternion sitOrientation = Quaternion.Identity;
  1421. Vector3 cameraEyeOffset = Vector3.Zero;
  1422. Vector3 cameraAtOffset = Vector3.Zero;
  1423. bool forceMouselook = false;
  1424. //SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  1425. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  1426. if (part != null)
  1427. {
  1428. // TODO: determine position to sit at based on scene geometry; don't trust offset from client
  1429. // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
  1430. // Is a sit target available?
  1431. Vector3 avSitOffSet = part.SitTargetPosition;
  1432. Quaternion avSitOrientation = part.SitTargetOrientation;
  1433. UUID avOnTargetAlready = part.GetAvatarOnSitTarget();
  1434. bool SitTargetUnOccupied = (!(avOnTargetAlready != UUID.Zero));
  1435. bool SitTargetisSet =
  1436. (!(avSitOffSet.X == 0f && avSitOffSet.Y == 0f && avSitOffSet.Z == 0f && avSitOrientation.W == 0f &&
  1437. avSitOrientation.X == 0f && avSitOrientation.Y == 0f && avSitOrientation.Z == 1f));
  1438. if (SitTargetisSet && SitTargetUnOccupied)
  1439. {
  1440. part.SetAvatarOnSitTarget(UUID);
  1441. offset = new Vector3(avSitOffSet.X, avSitOffSet.Y, avSitOffSet.Z);
  1442. sitOrientation = avSitOrientation;
  1443. autopilot = false;
  1444. }
  1445. pos = part.AbsolutePosition + offset;
  1446. //if (Math.Abs(part.AbsolutePosition.Z - AbsolutePosition.Z) > 1)
  1447. //{
  1448. // offset = pos;
  1449. //autopilot = false;
  1450. //}
  1451. if (m_physicsActor != null)
  1452. {
  1453. // If we're not using the client autopilot, we're immediately warping the avatar to the location
  1454. // We can remove the physicsActor until they stand up.
  1455. m_sitAvatarHeight = m_physicsActor.Size.Z;
  1456. if (autopilot)
  1457. {
  1458. if (Util.GetDistanceTo(AbsolutePosition, pos) < 4.5)
  1459. {
  1460. autopilot = false;
  1461. RemoveFromPhysicalScene();
  1462. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  1463. }
  1464. }
  1465. else
  1466. {
  1467. RemoveFromPhysicalScene();
  1468. }
  1469. }
  1470. cameraAtOffset = part.GetCameraAtOffset();
  1471. cameraEyeOffset = part.GetCameraEyeOffset();
  1472. forceMouselook = part.GetForceMouselook();
  1473. }
  1474. ControllingClient.SendSitResponse(targetID, offset, sitOrientation, autopilot, cameraAtOffset, cameraEyeOffset, forceMouselook);
  1475. m_requestedSitTargetUUID = targetID;
  1476. // This calls HandleAgentSit twice, once from here, and the client calls
  1477. // HandleAgentSit itself after it gets to the location
  1478. // It doesn't get to the location until we've moved them there though
  1479. // which happens in HandleAgentSit :P
  1480. m_autopilotMoving = autopilot;
  1481. m_autoPilotTarget = pos;
  1482. m_sitAtAutoTarget = autopilot;
  1483. if (!autopilot)
  1484. HandleAgentSit(remoteClient, UUID);
  1485. }
  1486. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  1487. {
  1488. if (m_parentID != 0)
  1489. {
  1490. StandUp();
  1491. }
  1492. m_nextSitAnimation = "SIT";
  1493. //SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  1494. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  1495. if (part != null)
  1496. {
  1497. if (!String.IsNullOrEmpty(part.SitAnimation))
  1498. {
  1499. m_nextSitAnimation = part.SitAnimation;
  1500. }
  1501. m_requestedSitTargetID = part.LocalId;
  1502. //m_requestedSitOffset = offset;
  1503. }
  1504. else
  1505. {
  1506. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  1507. }
  1508. SendSitResponse(remoteClient, targetID, offset);
  1509. }
  1510. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset, string sitAnimation)
  1511. {
  1512. if (m_parentID != 0)
  1513. {
  1514. StandUp();
  1515. }
  1516. if (!String.IsNullOrEmpty(sitAnimation))
  1517. {
  1518. m_nextSitAnimation = sitAnimation;
  1519. }
  1520. else
  1521. {
  1522. m_nextSitAnimation = "SIT";
  1523. }
  1524. //SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  1525. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  1526. if (part != null)
  1527. {
  1528. m_requestedSitTargetID = part.LocalId;
  1529. //m_requestedSitOffset = offset;
  1530. }
  1531. else
  1532. {
  1533. m_log.Warn("Sit requested on unknown object: " + targetID);
  1534. }
  1535. SendSitResponse(remoteClient, targetID, offset);
  1536. }
  1537. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  1538. {
  1539. if (!String.IsNullOrEmpty(m_nextSitAnimation))
  1540. {
  1541. HandleAgentSit(remoteClient, agentID, m_nextSitAnimation);
  1542. }
  1543. else
  1544. {
  1545. HandleAgentSit(remoteClient, agentID, "SIT");
  1546. }
  1547. }
  1548. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID, string sitAnimation)
  1549. {
  1550. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  1551. if (m_sitAtAutoTarget || !m_autopilotMoving)
  1552. {
  1553. if (part != null)
  1554. {
  1555. if (part.GetAvatarOnSitTarget() == UUID)
  1556. {
  1557. Vector3 sitTargetPos = part.SitTargetPosition;
  1558. Quaternion sitTargetOrient = part.SitTargetOrientation;
  1559. //Quaternion vq = new Quaternion(sitTargetPos.X, sitTargetPos.Y+0.2f, sitTargetPos.Z+0.2f, 0);
  1560. //Quaternion nq = new Quaternion(-sitTargetOrient.X, -sitTargetOrient.Y, -sitTargetOrient.Z, sitTargetOrient.w);
  1561. //Quaternion result = (sitTargetOrient * vq) * nq;
  1562. m_pos = new Vector3(sitTargetPos.X, sitTargetPos.Y, sitTargetPos.Z);
  1563. m_pos += m_sitTargetCorrectionOffset;
  1564. m_bodyRot = sitTargetOrient;
  1565. //Rotation = sitTargetOrient;
  1566. m_parentPosition = part.AbsolutePosition;
  1567. //SendTerseUpdateToAllClients();
  1568. }
  1569. else
  1570. {
  1571. m_pos -= part.AbsolutePosition;
  1572. m_parentPosition = part.AbsolutePosition;
  1573. }
  1574. }
  1575. else
  1576. {
  1577. return;
  1578. }
  1579. }
  1580. m_parentID = m_requestedSitTargetID;
  1581. Velocity = new Vector3(0, 0, 0);
  1582. RemoveFromPhysicalScene();
  1583. TrySetMovementAnimation(sitAnimation);
  1584. SendFullUpdateToAllClients();
  1585. // This may seem stupid, but Our Full updates don't send avatar rotation :P
  1586. // So we're also sending a terse update (which has avatar rotation)
  1587. // [Update] We do now.
  1588. //SendTerseUpdateToAllClients();
  1589. }
  1590. /// <summary>
  1591. /// Event handler for the 'Always run' setting on the client
  1592. /// Tells the physics plugin to increase speed of movement.
  1593. /// </summary>
  1594. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  1595. {
  1596. m_setAlwaysRun = pSetAlwaysRun;
  1597. if (PhysicsActor != null)
  1598. {
  1599. PhysicsActor.SetAlwaysRun = pSetAlwaysRun;
  1600. }
  1601. }
  1602. public BinBVHAnimation GenerateRandomAnimation()
  1603. {
  1604. int rnditerations = 3;
  1605. BinBVHAnimation anim = new BinBVHAnimation();
  1606. List<string> parts = new List<string>();
  1607. parts.Add("mPelvis");parts.Add("mHead");parts.Add("mTorso");
  1608. parts.Add("mHipLeft");parts.Add("mHipRight");parts.Add("mHipLeft");parts.Add("mKneeLeft");
  1609. parts.Add("mKneeRight");parts.Add("mCollarLeft");parts.Add("mCollarRight");parts.Add("mNeck");
  1610. parts.Add("mElbowLeft");parts.Add("mElbowRight");parts.Add("mWristLeft");parts.Add("mWristRight");
  1611. parts.Add("mShoulderLeft");parts.Add("mShoulderRight");parts.Add("mAnkleLeft");parts.Add("mAnkleRight");
  1612. parts.Add("mEyeRight");parts.Add("mChest");parts.Add("mToeLeft");parts.Add("mToeRight");
  1613. parts.Add("mFootLeft");parts.Add("mFootRight");parts.Add("mEyeLeft");
  1614. anim.HandPose = 1;
  1615. anim.InPoint = 0;
  1616. anim.OutPoint = (rnditerations * .10f);
  1617. anim.Priority = 7;
  1618. anim.Loop = false;
  1619. anim.Length = (rnditerations * .10f);
  1620. anim.ExpressionName = "afraid";
  1621. anim.EaseInTime = 0;
  1622. anim.EaseOutTime = 0;
  1623. string[] strjoints = parts.ToArray();
  1624. anim.Joints = new binBVHJoint[strjoints.Length];
  1625. for (int j = 0; j < strjoints.Length; j++)
  1626. {
  1627. anim.Joints[j] = new binBVHJoint();
  1628. anim.Joints[j].Name = strjoints[j];
  1629. anim.Joints[j].Priority = 7;
  1630. anim.Joints[j].positionkeys = new binBVHJointKey[rnditerations];
  1631. anim.Joints[j].rotationkeys = new binBVHJointKey[rnditerations];
  1632. Random rnd = new Random();
  1633. for (int i = 0; i < rnditerations; i++)
  1634. {
  1635. anim.Joints[j].rotationkeys[i] = new binBVHJointKey();
  1636. anim.Joints[j].rotationkeys[i].time = (i*.10f);
  1637. anim.Joints[j].rotationkeys[i].key_element.X = ((float) rnd.NextDouble()*2 - 1);
  1638. anim.Joints[j].rotationkeys[i].key_element.Y = ((float) rnd.NextDouble()*2 - 1);
  1639. anim.Joints[j].rotationkeys[i].key_element.Z = ((float) rnd.NextDouble()*2 - 1);
  1640. anim.Joints[j].positionkeys[i] = new binBVHJointKey();
  1641. anim.Joints[j].positionkeys[i].time = (i*.10f);
  1642. anim.Joints[j].positionkeys[i].key_element.X = 0;
  1643. anim.Joints[j].positionkeys[i].key_element.Y = 0;
  1644. anim.Joints[j].positionkeys[i].key_element.Z = 0;
  1645. }
  1646. }
  1647. AssetBase Animasset = new AssetBase();
  1648. Animasset.Data = anim.ToBytes();
  1649. Animasset.Temporary = true;
  1650. Animasset.Local = true;
  1651. Animasset.FullID = UUID.Random();
  1652. Animasset.ID = Animasset.FullID.ToString();
  1653. Animasset.Name = "Random Animation";
  1654. Animasset.Type = (sbyte)AssetType.Animation;
  1655. Animasset.Description = "dance";
  1656. //BinBVHAnimation bbvhanim = new BinBVHAnimation(Animasset.Data);
  1657. m_scene.AssetService.Store(Animasset);
  1658. AddAnimation(Animasset.FullID, UUID);
  1659. return anim;
  1660. }
  1661. public void AddAnimation(UUID animID, UUID objectID)
  1662. {
  1663. if (m_isChildAgent)
  1664. return;
  1665. if (m_animations.Add(animID, m_controllingClient.NextAnimationSequenceNumber, objectID))
  1666. SendAnimPack();
  1667. }
  1668. // Called from scripts
  1669. public void AddAnimation(string name, UUID objectID)
  1670. {
  1671. if (m_isChildAgent)
  1672. return;
  1673. UUID animID = m_controllingClient.GetDefaultAnimation(name);
  1674. if (animID == UUID.Zero)
  1675. return;
  1676. AddAnimation(animID, objectID);
  1677. }
  1678. public void RemoveAnimation(UUID animID)
  1679. {
  1680. if (m_isChildAgent)
  1681. return;
  1682. if (m_animations.Remove(animID))
  1683. SendAnimPack();
  1684. }
  1685. // Called from scripts
  1686. public void RemoveAnimation(string name)
  1687. {
  1688. if (m_isChildAgent)
  1689. return;
  1690. UUID animID = m_controllingClient.GetDefaultAnimation(name);
  1691. if (animID == UUID.Zero)
  1692. return;
  1693. RemoveAnimation(animID);
  1694. }
  1695. public UUID[] GetAnimationArray()
  1696. {
  1697. UUID[] animIDs;
  1698. int[] sequenceNums;
  1699. UUID[] objectIDs;
  1700. m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs);
  1701. return animIDs;
  1702. }
  1703. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  1704. {
  1705. AddAnimation(animID, UUID.Zero);
  1706. }
  1707. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  1708. {
  1709. RemoveAnimation(animID);
  1710. }
  1711. /// <summary>
  1712. /// The movement animation is reserved for "main" animations
  1713. /// that are mutually exclusive, e.g. flying and sitting.
  1714. /// </summary>
  1715. protected void TrySetMovementAnimation(string anim)
  1716. {
  1717. //m_log.DebugFormat("Updating movement animation to {0}", anim);
  1718. if (!m_isChildAgent)
  1719. {
  1720. if (m_animations.TrySetDefaultAnimation(anim, m_controllingClient.NextAnimationSequenceNumber, UUID.Zero))
  1721. {
  1722. if (m_scriptEngines != null)
  1723. {
  1724. lock (m_attachments)
  1725. {
  1726. foreach (SceneObjectGroup grp in m_attachments)
  1727. {
  1728. // 16384 is CHANGED_ANIMATION
  1729. //
  1730. // Send this to all attachment root prims
  1731. //
  1732. foreach (IScriptModule m in m_scriptEngines)
  1733. {
  1734. if (m == null) // No script engine loaded
  1735. continue;
  1736. m.PostObjectEvent(grp.RootPart.UUID, "changed", new Object[] { 16384 });
  1737. }
  1738. }
  1739. }
  1740. }
  1741. SendAnimPack();
  1742. }
  1743. }
  1744. }
  1745. /// <summary>
  1746. /// This method determines the proper movement related animation
  1747. /// </summary>
  1748. public string GetMovementAnimation()
  1749. {
  1750. if ((m_animPersistUntil > 0) && (m_animPersistUntil > DateTime.Now.Ticks))
  1751. {
  1752. //We don't want our existing state to end yet.
  1753. return m_movementAnimation;
  1754. }
  1755. else if (m_movementflag != 0)
  1756. {
  1757. //We're moving
  1758. m_allowFalling = true;
  1759. if (PhysicsActor != null && PhysicsActor.IsColliding)
  1760. {
  1761. //And colliding. Can you guess what it is yet?
  1762. if ((m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0)
  1763. {
  1764. //Down key is being pressed.
  1765. if ((m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) + (m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0)
  1766. {
  1767. return "CROUCHWALK";
  1768. }
  1769. else
  1770. {
  1771. return "CROUCH";
  1772. }
  1773. }
  1774. else if (m_setAlwaysRun)
  1775. {
  1776. return "RUN";
  1777. }
  1778. else
  1779. {
  1780. //If we're prejumping then inhibit this, it's a problem
  1781. //caused by a false positive on IsColliding
  1782. if (m_movementAnimation == "PREJUMP")
  1783. {
  1784. return "PREJUMP";
  1785. }
  1786. else
  1787. {
  1788. return "WALK";
  1789. }
  1790. }
  1791. }
  1792. else
  1793. {
  1794. //We're not colliding. Colliding isn't cool these days.
  1795. if (PhysicsActor != null && PhysicsActor.Flying)
  1796. {
  1797. //Are we moving forwards or backwards?
  1798. if ((m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0)
  1799. {
  1800. //Then we really are flying
  1801. if (m_setAlwaysRun)
  1802. {
  1803. return "FLY";
  1804. }
  1805. else
  1806. {
  1807. if (m_useFlySlow == false)
  1808. {
  1809. return "FLY";
  1810. }
  1811. else
  1812. {
  1813. return "FLYSLOW";
  1814. }
  1815. }
  1816. }
  1817. else
  1818. {
  1819. if ((m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0)
  1820. {
  1821. return "HOVER_UP";
  1822. }
  1823. else
  1824. {
  1825. return "HOVER_DOWN";
  1826. }
  1827. }
  1828. }
  1829. else if (m_movementAnimation == "JUMP")
  1830. {
  1831. //If we were already jumping, continue to jump until we collide
  1832. return "JUMP";
  1833. }
  1834. else if (m_movementAnimation == "PREJUMP" && (m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) == 0)
  1835. {
  1836. //If we were in a prejump, and the UP key is no longer being held down
  1837. //then we're not going to fly, so we're jumping
  1838. return "JUMP";
  1839. }
  1840. else if ((m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0)
  1841. {
  1842. //They're pressing up, so we're either going to fly or jump
  1843. return "PREJUMP";
  1844. }
  1845. else
  1846. {
  1847. //If we're moving and not flying and not jumping and not colliding..
  1848. if (m_movementAnimation == "WALK" || m_movementAnimation == "RUN")
  1849. {
  1850. //Let's not enter a FALLDOWN state here, since we're probably
  1851. //not colliding because we're going down hill.
  1852. return m_movementAnimation;
  1853. }
  1854. //Record the time we enter this state so we know whether to "land" or not
  1855. m_animPersistUntil = DateTime.Now.Ticks;
  1856. return "FALLDOWN";
  1857. }
  1858. }
  1859. }
  1860. else
  1861. {
  1862. //We're not moving.
  1863. if (PhysicsActor != null && PhysicsActor.IsColliding)
  1864. {
  1865. //But we are colliding.
  1866. if (m_movementAnimation == "FALLDOWN")
  1867. {
  1868. //We're re-using the m_animPersistUntil value here to see how long we've been falling
  1869. if ((DateTime.Now.Ticks - m_animPersistUntil) > TimeSpan.TicksPerSecond)
  1870. {
  1871. //Make sure we don't change state for a bit
  1872. m_animPersistUntil = DateTime.Now.Ticks + TimeSpan.TicksPerSecond;
  1873. return "LAND";
  1874. }
  1875. else
  1876. {
  1877. //We haven't been falling very long, we were probably just walking down hill
  1878. return "STAND";
  1879. }
  1880. }
  1881. else if (m_movementAnimation == "JUMP" || m_movementAnimation == "HOVER_DOWN")
  1882. {
  1883. //Make sure we don't change state for a bit
  1884. m_animPersistUntil = DateTime.Now.Ticks + (1 * TimeSpan.TicksPerSecond);
  1885. return "SOFT_LAND";
  1886. }
  1887. else if ((m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0)
  1888. {
  1889. return "PREJUMP";
  1890. }
  1891. else if (PhysicsActor != null && PhysicsActor.Flying)
  1892. {
  1893. m_allowFalling = true;
  1894. if ((m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0)
  1895. {
  1896. return "HOVER_UP";
  1897. }
  1898. else if ((m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0)
  1899. {
  1900. return "HOVER_DOWN";
  1901. }
  1902. else
  1903. {
  1904. return "HOVER";
  1905. }
  1906. }
  1907. else
  1908. {
  1909. return "STAND";
  1910. }
  1911. }
  1912. else
  1913. {
  1914. //We're not colliding.
  1915. if (PhysicsActor != null && PhysicsActor.Flying)
  1916. {
  1917. return "HOVER";
  1918. }
  1919. else if ((m_movementAnimation == "JUMP" || m_movementAnimation == "PREJUMP") && (m_movementflag & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) == 0)
  1920. {
  1921. return "JUMP";
  1922. }
  1923. else
  1924. {
  1925. //Record the time we enter this state so we know whether to "land" or not
  1926. m_animPersistUntil = DateTime.Now.Ticks;
  1927. return "FALLDOWN";
  1928. }
  1929. }
  1930. }
  1931. }
  1932. /// <summary>
  1933. /// Update the movement animation of this avatar according to its current state
  1934. /// </summary>
  1935. protected void UpdateMovementAnimations()
  1936. {
  1937. string movementAnimation = GetMovementAnimation();
  1938. if (movementAnimation == "FALLDOWN" && m_allowFalling == false)
  1939. {
  1940. movementAnimation = m_movementAnimation;
  1941. }
  1942. else
  1943. {
  1944. m_movementAnimation = movementAnimation;
  1945. }
  1946. if (movementAnimation == "PREJUMP" && m_usePreJump == false)
  1947. {
  1948. //This was the previous behavior before PREJUMP
  1949. TrySetMovementAnimation("JUMP");
  1950. }
  1951. else
  1952. {
  1953. TrySetMovementAnimation(movementAnimation);
  1954. }
  1955. }
  1956. /// <summary>
  1957. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  1958. /// </summary>
  1959. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  1960. /// <param name="rotation">The direction in which this avatar should now face.
  1961. public void AddNewMovement(Vector3 vec, Quaternion rotation)
  1962. {
  1963. if (m_isChildAgent)
  1964. {
  1965. m_log.Debug("DEBUG: AddNewMovement: child agent, Making root agent!");
  1966. // we have to reset the user's child agent connections.
  1967. // Likely, here they've lost the eventqueue for other regions so border
  1968. // crossings will fail at this point unless we reset them.
  1969. List<ulong> regions = new List<ulong>(KnownChildRegionHandles);
  1970. regions.Remove(m_scene.RegionInfo.RegionHandle);
  1971. MakeRootAgent(new Vector3(127, 127, 127), true);
  1972. // Async command
  1973. if (m_scene.SceneGridService != null)
  1974. {
  1975. m_scene.SceneGridService.SendCloseChildAgentConnections(UUID, regions);
  1976. // Give the above command some time to try and close the connections.
  1977. // this is really an emergency.. so sleep, or we'll get all discombobulated.
  1978. System.Threading.Thread.Sleep(500);
  1979. }
  1980. if (m_scene.SceneGridService != null)
  1981. {
  1982. m_scene.SceneGridService.EnableNeighbourChildAgents(this, new List<RegionInfo>());
  1983. }
  1984. return;
  1985. }
  1986. m_perfMonMS = Environment.TickCount;
  1987. m_rotation = rotation;
  1988. NewForce newVelocity = new NewForce();
  1989. Vector3 direc = vec * rotation;
  1990. direc.Normalize();
  1991. direc *= 0.03f * 128f * m_speedModifier;
  1992. if (m_physicsActor.Flying)
  1993. {
  1994. direc *= 4;
  1995. //bool controlland = (((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  1996. //bool colliding = (m_physicsActor.IsColliding==true);
  1997. //if (controlland)
  1998. // m_log.Info("[AGENT]: landCommand");
  1999. //if (colliding)
  2000. // m_log.Info("[AGENT]: colliding");
  2001. //if (m_physicsActor.Flying && colliding && controlland)
  2002. //{
  2003. // StopFlying();
  2004. // m_log.Info("[AGENT]: Stop FLying");
  2005. //}
  2006. }
  2007. else
  2008. {
  2009. if (!m_physicsActor.Flying && m_physicsActor.IsColliding)
  2010. {
  2011. if (direc.Z > 2.0f)
  2012. {
  2013. direc.Z *= 3;
  2014. // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
  2015. TrySetMovementAnimation("PREJUMP");
  2016. TrySetMovementAnimation("JUMP");
  2017. }
  2018. }
  2019. }
  2020. newVelocity.X = direc.X;
  2021. newVelocity.Y = direc.Y;
  2022. newVelocity.Z = direc.Z;
  2023. m_forcesList.Add(newVelocity);
  2024. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  2025. }
  2026. #endregion
  2027. #region Overridden Methods
  2028. public override void Update()
  2029. {
  2030. SendPrimUpdates();
  2031. if (m_newCoarseLocations)
  2032. {
  2033. SendCoarseLocations();
  2034. m_newCoarseLocations = false;
  2035. }
  2036. if (m_isChildAgent == false)
  2037. {
  2038. if (m_newForce) // user movement 'forces' (ie commands to move)
  2039. {
  2040. SendTerseUpdateToAllClients();
  2041. m_updateCount = 0;
  2042. }
  2043. else if (m_movementflag != 0) // scripted movement (?)
  2044. {
  2045. m_updateCount++;
  2046. if (m_updateCount > 3)
  2047. {
  2048. SendTerseUpdateToAllClients();
  2049. m_updateCount = 0;
  2050. }
  2051. }
  2052. else if ((Util.GetDistanceTo(lastPhysPos, AbsolutePosition) > 0.02)
  2053. || (Util.GetDistanceTo(m_lastVelocity, m_velocity) > 0.02)
  2054. || lastPhysRot != m_bodyRot)
  2055. {
  2056. // Send Terse Update to all clients updates lastPhysPos and m_lastVelocity
  2057. // doing the above assures us that we know what we sent the clients last
  2058. SendTerseUpdateToAllClients();
  2059. m_updateCount = 0;
  2060. }
  2061. // followed suggestion from mic bowman. reversed the two lines below.
  2062. CheckForBorderCrossing();
  2063. CheckForSignificantMovement(); // sends update to the modules.
  2064. }
  2065. }
  2066. #endregion
  2067. #region Update Client(s)
  2068. /// <summary>
  2069. /// Sends a location update to the client connected to this scenePresence
  2070. /// </summary>
  2071. /// <param name="remoteClient"></param>
  2072. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  2073. {
  2074. // If the client is inactive, it's getting its updates from another
  2075. // server.
  2076. if (remoteClient.IsActive)
  2077. {
  2078. m_perfMonMS = Environment.TickCount;
  2079. Vector3 pos = m_pos;
  2080. Vector3 vel = Velocity;
  2081. Quaternion rot = m_bodyRot;
  2082. pos.Z -= m_appearance.HipOffset;
  2083. remoteClient.SendAvatarTerseUpdate(m_regionHandle, (ushort)(m_scene.TimeDilation * ushort.MaxValue), LocalId, new Vector3(pos.X, pos.Y, pos.Z),
  2084. new Vector3(vel.X, vel.Y, vel.Z), rot, m_uuid);
  2085. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  2086. m_scene.StatsReporter.AddAgentUpdates(1);
  2087. }
  2088. }
  2089. /// <summary>
  2090. /// Send a location/velocity/accelleration update to all agents in scene
  2091. /// </summary>
  2092. public void SendTerseUpdateToAllClients()
  2093. {
  2094. m_perfMonMS = Environment.TickCount;
  2095. m_scene.Broadcast(SendTerseUpdateToClient);
  2096. m_lastVelocity = m_velocity;
  2097. lastPhysPos = AbsolutePosition;
  2098. lastPhysRot = m_bodyRot;
  2099. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  2100. }
  2101. public void SendCoarseLocations()
  2102. {
  2103. m_perfMonMS = Environment.TickCount;
  2104. List<Vector3> CoarseLocations = new List<Vector3>();
  2105. List<UUID> AvatarUUIDs = new List<UUID>();
  2106. List<ScenePresence> avatars = m_scene.GetAvatars();
  2107. for (int i = 0; i < avatars.Count; i++)
  2108. {
  2109. if (avatars[i] != this)
  2110. {
  2111. if (avatars[i].ParentID != 0)
  2112. {
  2113. // sitting avatar
  2114. SceneObjectPart sop = m_scene.GetSceneObjectPart(avatars[i].ParentID);
  2115. if (sop != null)
  2116. {
  2117. CoarseLocations.Add(sop.AbsolutePosition + avatars[i].m_pos);
  2118. AvatarUUIDs.Add(avatars[i].UUID);
  2119. }
  2120. else
  2121. {
  2122. // we can't find the parent.. ! arg!
  2123. CoarseLocations.Add(avatars[i].m_pos);
  2124. AvatarUUIDs.Add(avatars[i].UUID);
  2125. }
  2126. }
  2127. else
  2128. {
  2129. CoarseLocations.Add(avatars[i].m_pos);
  2130. AvatarUUIDs.Add(avatars[i].UUID);
  2131. }
  2132. }
  2133. }
  2134. m_controllingClient.SendCoarseLocationUpdate(AvatarUUIDs, CoarseLocations);
  2135. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  2136. }
  2137. public void CoarseLocationChange()
  2138. {
  2139. m_newCoarseLocations = true;
  2140. }
  2141. /// <summary>
  2142. /// Tell other client about this avatar (The client previously didn't know or had outdated details about this avatar)
  2143. /// </summary>
  2144. /// <param name="remoteAvatar"></param>
  2145. public void SendFullUpdateToOtherClient(ScenePresence remoteAvatar)
  2146. {
  2147. // 2 stage check is needed.
  2148. if (remoteAvatar == null)
  2149. return;
  2150. IClientAPI cl=remoteAvatar.ControllingClient;
  2151. if (cl == null)
  2152. return;
  2153. if (m_appearance.Texture == null)
  2154. return;
  2155. // Note: because Quaternion is a struct, it can't be null
  2156. Quaternion rot = m_bodyRot;
  2157. Vector3 pos = m_pos;
  2158. pos.Z -= m_appearance.HipOffset;
  2159. remoteAvatar.m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_grouptitle, m_uuid,
  2160. LocalId, m_pos, m_appearance.Texture.GetBytes(),
  2161. m_parentID, rot);
  2162. m_scene.StatsReporter.AddAgentUpdates(1);
  2163. }
  2164. /// <summary>
  2165. /// Tell *ALL* agents about this agent
  2166. /// </summary>
  2167. public void SendInitialFullUpdateToAllClients()
  2168. {
  2169. m_perfMonMS = Environment.TickCount;
  2170. List<ScenePresence> avatars = m_scene.GetScenePresences();
  2171. foreach (ScenePresence avatar in avatars)
  2172. {
  2173. // only send if this is the root (children are only "listening posts" in a foreign region)
  2174. if (!IsChildAgent)
  2175. {
  2176. SendFullUpdateToOtherClient(avatar);
  2177. }
  2178. if (avatar.LocalId != LocalId)
  2179. {
  2180. if (!avatar.IsChildAgent)
  2181. {
  2182. avatar.SendFullUpdateToOtherClient(this);
  2183. avatar.SendAppearanceToOtherAgent(this);
  2184. avatar.SendAnimPackToClient(ControllingClient);
  2185. }
  2186. }
  2187. }
  2188. m_scene.StatsReporter.AddAgentUpdates(avatars.Count);
  2189. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  2190. //SendAnimPack();
  2191. }
  2192. public void SendFullUpdateToAllClients()
  2193. {
  2194. m_perfMonMS = Environment.TickCount;
  2195. // only send update from root agents to other clients; children are only "listening posts"
  2196. List<ScenePresence> avatars = m_scene.GetAvatars();
  2197. foreach (ScenePresence avatar in avatars)
  2198. {
  2199. SendFullUpdateToOtherClient(avatar);
  2200. }
  2201. m_scene.StatsReporter.AddAgentUpdates(avatars.Count);
  2202. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  2203. SendAnimPack();
  2204. }
  2205. /// <summary>
  2206. /// Do everything required once a client completes its movement into a region
  2207. /// </summary>
  2208. public void SendInitialData()
  2209. {
  2210. // Moved this into CompleteMovement to ensure that m_appearance is initialized before
  2211. // the inventory arrives
  2212. // m_scene.GetAvatarAppearance(m_controllingClient, out m_appearance);
  2213. // Note: because Quaternion is a struct, it can't be null
  2214. Quaternion rot = m_bodyRot;
  2215. Vector3 pos = m_pos;
  2216. pos.Z -= m_appearance.HipOffset;
  2217. m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_grouptitle, m_uuid, LocalId,
  2218. m_pos, m_appearance.Texture.GetBytes(), m_parentID, rot);
  2219. if (!m_isChildAgent)
  2220. {
  2221. m_scene.InformClientOfNeighbours(this);
  2222. }
  2223. SendInitialFullUpdateToAllClients();
  2224. SendAppearanceToAllOtherAgents();
  2225. }
  2226. /// <summary>
  2227. /// Tell the client for this scene presence what items it should be wearing now
  2228. /// </summary>
  2229. public void SendWearables()
  2230. {
  2231. ControllingClient.SendWearables(m_appearance.Wearables, m_appearance.Serial++);
  2232. }
  2233. /// <summary>
  2234. ///
  2235. /// </summary>
  2236. public void SendAppearanceToAllOtherAgents()
  2237. {
  2238. m_perfMonMS = Environment.TickCount;
  2239. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  2240. {
  2241. if (scenePresence.UUID != UUID)
  2242. {
  2243. SendAppearanceToOtherAgent(scenePresence);
  2244. }
  2245. });
  2246. m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
  2247. }
  2248. /// <summary>
  2249. /// Send appearance data to an agent that isn't this one.
  2250. /// </summary>
  2251. /// <param name="avatar"></param>
  2252. public void SendAppearanceToOtherAgent(ScenePresence avatar)
  2253. {
  2254. avatar.ControllingClient.SendAppearance(
  2255. m_appearance.Owner, m_appearance.VisualParams, m_appearance.Texture.GetBytes());
  2256. }
  2257. /// <summary>
  2258. /// Set appearance data (textureentry and slider settings) received from the client
  2259. /// </summary>
  2260. /// <param name="texture"></param>
  2261. /// <param name="visualParam"></param>
  2262. public void SetAppearance(byte[] texture, List<byte> visualParam)
  2263. {
  2264. if (m_physicsActor != null)
  2265. {
  2266. if (!IsChildAgent)
  2267. {
  2268. // This may seem like it's redundant, remove the avatar from the physics scene
  2269. // just to add it back again, but it saves us from having to update
  2270. // 3 variables 10 times a second.
  2271. bool flyingTemp = m_physicsActor.Flying;
  2272. RemoveFromPhysicalScene();
  2273. //m_scene.PhysicsScene.RemoveAvatar(m_physicsActor);
  2274. //PhysicsActor = null;
  2275. AddToPhysicalScene(flyingTemp);
  2276. }
  2277. }
  2278. m_appearance.SetAppearance(texture, visualParam);
  2279. if (m_appearance.AvatarHeight > 0)
  2280. SetHeight(m_appearance.AvatarHeight);
  2281. m_scene.CommsManager.AvatarService.UpdateUserAppearance(m_controllingClient.AgentId, m_appearance);
  2282. SendAppearanceToAllOtherAgents();
  2283. if (!m_startAnimationSet)
  2284. {
  2285. UpdateMovementAnimations();
  2286. m_startAnimationSet = true;
  2287. }
  2288. Quaternion rot = m_bodyRot;
  2289. m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_grouptitle, m_uuid, LocalId,
  2290. m_pos, m_appearance.Texture.GetBytes(), m_parentID, rot);
  2291. }
  2292. public void SetWearable(int wearableId, AvatarWearable wearable)
  2293. {
  2294. m_appearance.SetWearable(wearableId, wearable);
  2295. m_scene.CommsManager.AvatarService.UpdateUserAppearance(m_controllingClient.AgentId, m_appearance);
  2296. m_controllingClient.SendWearables(m_appearance.Wearables, m_appearance.Serial++);
  2297. }
  2298. // Because appearance setting is in a module, we actually need
  2299. // to give it access to our appearance directly, otherwise we
  2300. // get a synchronization issue.
  2301. public AvatarAppearance Appearance
  2302. {
  2303. get { return m_appearance; }
  2304. set { m_appearance = value; }
  2305. }
  2306. /// <summary>
  2307. ///
  2308. /// </summary>
  2309. /// <param name="animations"></param>
  2310. /// <param name="seqs"></param>
  2311. /// <param name="objectIDs"></param>
  2312. public void SendAnimPack(UUID[] animations, int[] seqs, UUID[] objectIDs)
  2313. {
  2314. if (m_isChildAgent)
  2315. return;
  2316. m_scene.Broadcast(
  2317. delegate(IClientAPI client) { client.SendAnimations(animations, seqs, m_controllingClient.AgentId, objectIDs); });
  2318. }
  2319. public void SendAnimPackToClient(IClientAPI client)
  2320. {
  2321. if (m_isChildAgent)
  2322. return;
  2323. UUID[] animIDs;
  2324. int[] sequenceNums;
  2325. UUID[] objectIDs;
  2326. m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs);
  2327. client.SendAnimations(animIDs, sequenceNums, m_controllingClient.AgentId, objectIDs);
  2328. }
  2329. /// <summary>
  2330. /// Send animation information about this avatar to all clients.
  2331. /// </summary>
  2332. public void SendAnimPack()
  2333. {
  2334. //m_log.Debug("Sending animation pack to all");
  2335. if (m_isChildAgent)
  2336. return;
  2337. UUID[] animIDs;
  2338. int[] sequenceNums;
  2339. UUID[] objectIDs;
  2340. m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs);
  2341. SendAnimPack(animIDs, sequenceNums, objectIDs);
  2342. }
  2343. #endregion
  2344. #region Significant Movement Method
  2345. /// <summary>
  2346. /// This checks for a significant movement and sends a courselocationchange update
  2347. /// </summary>
  2348. protected void CheckForSignificantMovement()
  2349. {
  2350. if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > 0.5)
  2351. {
  2352. posLastSignificantMove = AbsolutePosition;
  2353. m_scene.EventManager.TriggerSignificantClientMovement(m_controllingClient);
  2354. m_scene.NotifyMyCoarseLocationChange();
  2355. }
  2356. // Minimum Draw distance is 64 meters, the Radius of the draw distance sphere is 32m
  2357. if (Util.GetDistanceTo(AbsolutePosition,m_LastChildAgentUpdatePosition) > 32)
  2358. {
  2359. ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
  2360. cadu.ActiveGroupID = UUID.Zero.Guid;
  2361. cadu.AgentID = UUID.Guid;
  2362. cadu.alwaysrun = m_setAlwaysRun;
  2363. cadu.AVHeight = m_avHeight;
  2364. sLLVector3 tempCameraCenter = new sLLVector3(new Vector3(m_CameraCenter.X, m_CameraCenter.Y, m_CameraCenter.Z));
  2365. cadu.cameraPosition = tempCameraCenter;
  2366. cadu.drawdistance = m_DrawDistance;
  2367. if (m_scene.Permissions.IsGod(new UUID(cadu.AgentID)))
  2368. cadu.godlevel = m_godlevel;
  2369. cadu.GroupAccess = 0;
  2370. cadu.Position = new sLLVector3(AbsolutePosition);
  2371. cadu.regionHandle = m_scene.RegionInfo.RegionHandle;
  2372. float multiplier = 1;
  2373. int innacurateNeighbors = m_scene.GetInaccurateNeighborCount();
  2374. if (innacurateNeighbors != 0)
  2375. {
  2376. multiplier = 1f / (float)innacurateNeighbors;
  2377. }
  2378. if (multiplier <= 0f)
  2379. {
  2380. multiplier = 0.25f;
  2381. }
  2382. //m_log.Info("[NeighborThrottle]: " + m_scene.GetInaccurateNeighborCount().ToString() + " - m: " + multiplier.ToString());
  2383. cadu.throttles = ControllingClient.GetThrottlesPacked(multiplier);
  2384. cadu.Velocity = new sLLVector3(Velocity);
  2385. AgentPosition agentpos = new AgentPosition();
  2386. agentpos.CopyFrom(cadu);
  2387. m_scene.SendOutChildAgentUpdates(agentpos, this);
  2388. m_LastChildAgentUpdatePosition.X = AbsolutePosition.X;
  2389. m_LastChildAgentUpdatePosition.Y = AbsolutePosition.Y;
  2390. m_LastChildAgentUpdatePosition.Z = AbsolutePosition.Z;
  2391. }
  2392. }
  2393. #endregion
  2394. #region Border Crossing Methods
  2395. /// <summary>
  2396. /// Checks to see if the avatar is in range of a border and calls CrossToNewRegion
  2397. /// </summary>
  2398. protected void CheckForBorderCrossing()
  2399. {
  2400. if (IsChildAgent)
  2401. return;
  2402. Vector3 pos2 = AbsolutePosition;
  2403. Vector3 vel = Velocity;
  2404. int neighbor = 0;
  2405. int[] fix = new int[2];
  2406. float timeStep = 0.1f;
  2407. pos2.X = pos2.X + (vel.X*timeStep);
  2408. pos2.Y = pos2.Y + (vel.Y*timeStep);
  2409. pos2.Z = pos2.Z + (vel.Z*timeStep);
  2410. if (!IsInTransit)
  2411. {
  2412. // Checks if where it's headed exists a region
  2413. if (pos2.X < 0)
  2414. {
  2415. if (pos2.Y < 0)
  2416. neighbor = HaveNeighbor(Cardinals.SW, ref fix);
  2417. else if (pos2.Y > Constants.RegionSize)
  2418. neighbor = HaveNeighbor(Cardinals.NW, ref fix);
  2419. else
  2420. neighbor = HaveNeighbor(Cardinals.W, ref fix);
  2421. }
  2422. else if (pos2.X > Constants.RegionSize)
  2423. {
  2424. if (pos2.Y < 0)
  2425. neighbor = HaveNeighbor(Cardinals.SE, ref fix);
  2426. else if (pos2.Y > Constants.RegionSize)
  2427. neighbor = HaveNeighbor(Cardinals.NE, ref fix);
  2428. else
  2429. neighbor = HaveNeighbor(Cardinals.E, ref fix);
  2430. }
  2431. else if (pos2.Y < 0)
  2432. neighbor = HaveNeighbor(Cardinals.S, ref fix);
  2433. else if (pos2.Y > Constants.RegionSize)
  2434. neighbor = HaveNeighbor(Cardinals.N, ref fix);
  2435. // Makes sure avatar does not end up outside region
  2436. if (neighbor < 0)
  2437. AbsolutePosition = new Vector3(
  2438. AbsolutePosition.X + 3*fix[0],
  2439. AbsolutePosition.Y + 3*fix[1],
  2440. AbsolutePosition.Z);
  2441. else if (neighbor > 0)
  2442. CrossToNewRegion();
  2443. }
  2444. else
  2445. {
  2446. RemoveFromPhysicalScene();
  2447. // This constant has been inferred from experimentation
  2448. // I'm not sure what this value should be, so I tried a few values.
  2449. timeStep = 0.04f;
  2450. pos2 = AbsolutePosition;
  2451. pos2.X = pos2.X + (vel.X * timeStep);
  2452. pos2.Y = pos2.Y + (vel.Y * timeStep);
  2453. pos2.Z = pos2.Z + (vel.Z * timeStep);
  2454. m_pos = pos2;
  2455. }
  2456. }
  2457. protected int HaveNeighbor(Cardinals car, ref int[] fix)
  2458. {
  2459. uint neighbourx = m_regionInfo.RegionLocX;
  2460. uint neighboury = m_regionInfo.RegionLocY;
  2461. int dir = (int)car;
  2462. if (dir > 1 && dir < 5) //Heading East
  2463. neighbourx++;
  2464. else if (dir > 5) // Heading West
  2465. neighbourx--;
  2466. if (dir < 3 || dir == 8) // Heading North
  2467. neighboury++;
  2468. else if (dir > 3 && dir < 7) // Heading Sout
  2469. neighboury--;
  2470. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  2471. SimpleRegionInfo neighbourRegion = m_scene.RequestNeighbouringRegionInfo(neighbourHandle);
  2472. if (neighbourRegion == null)
  2473. {
  2474. fix[0] = (int)(m_regionInfo.RegionLocX - neighbourx);
  2475. fix[1] = (int)(m_regionInfo.RegionLocY - neighboury);
  2476. return dir * (-1);
  2477. }
  2478. else
  2479. return dir;
  2480. }
  2481. /// <summary>
  2482. /// Moves the agent outside the region bounds
  2483. /// Tells neighbor region that we're crossing to it
  2484. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  2485. /// set them to a child agent.
  2486. /// </summary>
  2487. protected void CrossToNewRegion()
  2488. {
  2489. InTransit();
  2490. m_scene.CrossAgentToNewRegion(this, m_physicsActor.Flying);
  2491. }
  2492. public void InTransit()
  2493. {
  2494. m_inTransit = true;
  2495. if ((m_physicsActor != null) && m_physicsActor.Flying)
  2496. m_AgentControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  2497. else if ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0)
  2498. m_AgentControlFlags &= ~(uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  2499. }
  2500. public void NotInTransit()
  2501. {
  2502. m_inTransit = false;
  2503. }
  2504. public void RestoreInCurrentScene()
  2505. {
  2506. AddToPhysicalScene(false); // not exactly false
  2507. }
  2508. public void Reset()
  2509. {
  2510. // Put the child agent back at the center
  2511. AbsolutePosition = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 70);
  2512. ResetAnimations();
  2513. }
  2514. public void ResetAnimations()
  2515. {
  2516. m_animations.Clear();
  2517. }
  2518. /// <summary>
  2519. /// Computes which child agents to close when the scene presence moves to another region.
  2520. /// Removes those regions from m_knownRegions.
  2521. /// </summary>
  2522. /// <param name="newRegionX">The new region's x on the map</param>
  2523. /// <param name="newRegionY">The new region's y on the map</param>
  2524. /// <returns></returns>
  2525. public void CloseChildAgents(uint newRegionX, uint newRegionY)
  2526. {
  2527. List<ulong> byebyeRegions = new List<ulong>();
  2528. m_log.DebugFormat(
  2529. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  2530. m_knownChildRegions.Keys.Count, Scene.RegionInfo.RegionName);
  2531. //DumpKnownRegions();
  2532. lock (m_knownChildRegions)
  2533. {
  2534. foreach (ulong handle in m_knownChildRegions.Keys)
  2535. {
  2536. // Don't close the agent on this region yet
  2537. if (handle != Scene.RegionInfo.RegionHandle)
  2538. {
  2539. uint x, y;
  2540. Utils.LongToUInts(handle, out x, out y);
  2541. x = x / Constants.RegionSize;
  2542. y = y / Constants.RegionSize;
  2543. //m_log.Debug("---> x: " + x + "; newx:" + newRegionX + "; Abs:" + (int)Math.Abs((int)(x - newRegionX)));
  2544. //m_log.Debug("---> y: " + y + "; newy:" + newRegionY + "; Abs:" + (int)Math.Abs((int)(y - newRegionY)));
  2545. if (Util.IsOutsideView(x, newRegionX, y, newRegionY))
  2546. {
  2547. byebyeRegions.Add(handle);
  2548. }
  2549. }
  2550. }
  2551. }
  2552. if (byebyeRegions.Count > 0)
  2553. {
  2554. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  2555. m_scene.SceneGridService.SendCloseChildAgentConnections(m_controllingClient.AgentId, byebyeRegions);
  2556. }
  2557. foreach (ulong handle in byebyeRegions)
  2558. {
  2559. RemoveNeighbourRegion(handle);
  2560. }
  2561. }
  2562. #endregion
  2563. /// <summary>
  2564. /// This allows the Sim owner the abiility to kick users from their sim currently.
  2565. /// It tells the client that the agent has permission to do so.
  2566. /// </summary>
  2567. public void GrantGodlikePowers(UUID agentID, UUID sessionID, UUID token, bool godStatus)
  2568. {
  2569. if (godStatus)
  2570. {
  2571. // For now, assign god level 200 to anyone
  2572. // who is granted god powers, but has no god level set.
  2573. //
  2574. CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID);
  2575. if (profile.UserProfile.GodLevel > 0)
  2576. m_godlevel = profile.UserProfile.GodLevel;
  2577. else
  2578. m_godlevel = 200;
  2579. }
  2580. else
  2581. {
  2582. m_godlevel = 0;
  2583. }
  2584. ControllingClient.SendAdminResponse(token, (uint)m_godlevel);
  2585. }
  2586. #region Child Agent Updates
  2587. public void ChildAgentDataUpdate(AgentData cAgentData)
  2588. {
  2589. //m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  2590. if (!IsChildAgent)
  2591. return;
  2592. CopyFrom(cAgentData);
  2593. }
  2594. /// <summary>
  2595. /// This updates important decision making data about a child agent
  2596. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  2597. /// </summary>
  2598. public void ChildAgentDataUpdate(AgentPosition cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY)
  2599. {
  2600. if (!IsChildAgent)
  2601. return;
  2602. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  2603. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  2604. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  2605. m_DrawDistance = cAgentData.Far;
  2606. if (cAgentData.Position != new Vector3(-1, -1, -1)) // UGH!!
  2607. m_pos = new Vector3(cAgentData.Position.X + shiftx, cAgentData.Position.Y + shifty, cAgentData.Position.Z);
  2608. // It's hard to say here.. We can't really tell where the camera position is unless it's in world cordinates from the sending region
  2609. m_CameraCenter = cAgentData.Center;
  2610. m_avHeight = cAgentData.Size.Z;
  2611. //SetHeight(cAgentData.AVHeight);
  2612. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  2613. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles);
  2614. // Sends out the objects in the user's draw distance if m_sendTasksToChild is true.
  2615. if (m_scene.m_seeIntoRegionFromNeighbor)
  2616. m_sceneViewer.Reset();
  2617. //cAgentData.AVHeight;
  2618. //cAgentData.regionHandle;
  2619. //m_velocity = cAgentData.Velocity;
  2620. }
  2621. public void CopyTo(AgentData cAgent)
  2622. {
  2623. cAgent.AgentID = UUID;
  2624. cAgent.RegionHandle = m_scene.RegionInfo.RegionHandle;
  2625. cAgent.Position = m_pos;
  2626. cAgent.Velocity = m_velocity;
  2627. cAgent.Center = m_CameraCenter;
  2628. // Don't copy the size; it is inferred from apearance parameters
  2629. //cAgent.Size = new Vector3(0, 0, m_avHeight);
  2630. cAgent.AtAxis = m_CameraAtAxis;
  2631. cAgent.LeftAxis = m_CameraLeftAxis;
  2632. cAgent.UpAxis = m_CameraUpAxis;
  2633. cAgent.Far = m_DrawDistance;
  2634. // Throttles
  2635. float multiplier = 1;
  2636. int innacurateNeighbors = m_scene.GetInaccurateNeighborCount();
  2637. if (innacurateNeighbors != 0)
  2638. {
  2639. multiplier = 1f / innacurateNeighbors;
  2640. }
  2641. if (multiplier <= 0f)
  2642. {
  2643. multiplier = 0.25f;
  2644. }
  2645. //m_log.Info("[NeighborThrottle]: " + m_scene.GetInaccurateNeighborCount().ToString() + " - m: " + multiplier.ToString());
  2646. cAgent.Throttles = ControllingClient.GetThrottlesPacked(multiplier);
  2647. cAgent.HeadRotation = m_headrotation;
  2648. cAgent.BodyRotation = m_bodyRot;
  2649. cAgent.ControlFlags = m_AgentControlFlags;
  2650. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  2651. cAgent.GodLevel = (byte)m_godlevel;
  2652. else
  2653. cAgent.GodLevel = (byte) 0;
  2654. cAgent.AlwaysRun = m_setAlwaysRun;
  2655. try
  2656. {
  2657. // We might not pass the Wearables in all cases...
  2658. // They're only needed so that persistent changes to the appearance
  2659. // are preserved in the new region where the user is moving to.
  2660. // But in Hypergrid we might not let this happen.
  2661. int i = 0;
  2662. UUID[] wears = new UUID[m_appearance.Wearables.Length * 2];
  2663. foreach (AvatarWearable aw in m_appearance.Wearables)
  2664. {
  2665. if (aw != null)
  2666. {
  2667. wears[i++] = aw.ItemID;
  2668. wears[i++] = aw.AssetID;
  2669. }
  2670. else
  2671. {
  2672. wears[i++] = UUID.Zero;
  2673. wears[i++] = UUID.Zero;
  2674. }
  2675. }
  2676. cAgent.Wearables = wears;
  2677. cAgent.VisualParams = m_appearance.VisualParams;
  2678. if (m_appearance.Texture != null)
  2679. cAgent.AgentTextures = m_appearance.Texture.GetBytes();
  2680. }
  2681. catch (Exception e)
  2682. {
  2683. m_log.Warn("[SCENE PRESENCE]: exception in CopyTo " + e.Message);
  2684. }
  2685. // Animations
  2686. try
  2687. {
  2688. cAgent.Anims = m_animations.ToArray();
  2689. }
  2690. catch { }
  2691. // cAgent.GroupID = ??
  2692. // Groups???
  2693. }
  2694. public void CopyFrom(AgentData cAgent)
  2695. {
  2696. m_rootRegionHandle= cAgent.RegionHandle;
  2697. m_callbackURI = cAgent.CallbackURI;
  2698. m_pos = cAgent.Position;
  2699. m_velocity = cAgent.Velocity;
  2700. m_CameraCenter = cAgent.Center;
  2701. //m_avHeight = cAgent.Size.Z;
  2702. m_CameraAtAxis = cAgent.AtAxis;
  2703. m_CameraLeftAxis = cAgent.LeftAxis;
  2704. m_CameraUpAxis = cAgent.UpAxis;
  2705. m_DrawDistance = cAgent.Far;
  2706. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  2707. ControllingClient.SetChildAgentThrottle(cAgent.Throttles);
  2708. m_headrotation = cAgent.HeadRotation;
  2709. m_bodyRot = cAgent.BodyRotation;
  2710. m_AgentControlFlags = cAgent.ControlFlags;
  2711. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  2712. m_godlevel = cAgent.GodLevel;
  2713. m_setAlwaysRun = cAgent.AlwaysRun;
  2714. uint i = 0;
  2715. try
  2716. {
  2717. if (cAgent.Wearables == null)
  2718. cAgent.Wearables = new UUID[0];
  2719. AvatarWearable[] wears = new AvatarWearable[cAgent.Wearables.Length / 2];
  2720. for (uint n = 0; n < cAgent.Wearables.Length; n += 2)
  2721. {
  2722. UUID itemId = cAgent.Wearables[n];
  2723. UUID assetId = cAgent.Wearables[n + 1];
  2724. wears[i++] = new AvatarWearable(itemId, assetId);
  2725. }
  2726. m_appearance.Wearables = wears;
  2727. byte[] te = null;
  2728. if (cAgent.AgentTextures != null)
  2729. te = cAgent.AgentTextures;
  2730. else
  2731. te = AvatarAppearance.GetDefaultTexture().GetBytes();
  2732. if ((cAgent.VisualParams == null) || (cAgent.VisualParams.Length < AvatarAppearance.VISUALPARAM_COUNT))
  2733. cAgent.VisualParams = AvatarAppearance.GetDefaultVisualParams();
  2734. m_appearance.SetAppearance(te, new List<byte>(cAgent.VisualParams));
  2735. }
  2736. catch (Exception e)
  2737. {
  2738. m_log.Warn("[SCENE PRESENCE]: exception in CopyFrom " + e.Message);
  2739. }
  2740. // Animations
  2741. try
  2742. {
  2743. m_animations.Clear();
  2744. m_animations.FromArray(cAgent.Anims);
  2745. }
  2746. catch { }
  2747. //cAgent.GroupID = ??
  2748. //Groups???
  2749. }
  2750. public bool CopyAgent(out IAgentData agent)
  2751. {
  2752. agent = new CompleteAgentData();
  2753. CopyTo((AgentData)agent);
  2754. return true;
  2755. }
  2756. #endregion Child Agent Updates
  2757. /// <summary>
  2758. /// Handles part of the PID controller function for moving an avatar.
  2759. /// </summary>
  2760. public override void UpdateMovement()
  2761. {
  2762. m_newForce = false;
  2763. lock (m_forcesList)
  2764. {
  2765. if (m_forcesList.Count > 0)
  2766. {
  2767. //we are only interested in the last velocity added to the list [Although they are called forces, they are actually velocities]
  2768. NewForce force = m_forcesList[m_forcesList.Count - 1];
  2769. m_updateflag = true;
  2770. try
  2771. {
  2772. movementvector.X = force.X;
  2773. movementvector.Y = force.Y;
  2774. movementvector.Z = force.Z;
  2775. Velocity = movementvector;
  2776. }
  2777. catch (NullReferenceException)
  2778. {
  2779. // Under extreme load, this returns a NullReference Exception that we can ignore.
  2780. // Ignoring this causes no movement to be sent to the physics engine...
  2781. // which when the scene is moving at 1 frame every 10 seconds, it doesn't really matter!
  2782. }
  2783. m_newForce = true;
  2784. m_forcesList.Clear();
  2785. }
  2786. }
  2787. }
  2788. static ScenePresence()
  2789. {
  2790. Primitive.TextureEntry textu = AvatarAppearance.GetDefaultTexture();
  2791. DefaultTexture = textu.GetBytes();
  2792. }
  2793. public class NewForce
  2794. {
  2795. public float X;
  2796. public float Y;
  2797. public float Z;
  2798. }
  2799. public override void SetText(string text, Vector3 color, double alpha)
  2800. {
  2801. throw new Exception("Can't set Text on avatar.");
  2802. }
  2803. /// <summary>
  2804. /// Adds a physical representation of the avatar to the Physics plugin
  2805. /// </summary>
  2806. public void AddToPhysicalScene(bool isFlying)
  2807. {
  2808. PhysicsScene scene = m_scene.PhysicsScene;
  2809. PhysicsVector pVec =
  2810. new PhysicsVector(AbsolutePosition.X, AbsolutePosition.Y,
  2811. AbsolutePosition.Z);
  2812. // Old bug where the height was in centimeters instead of meters
  2813. if (m_avHeight == 127.0f)
  2814. {
  2815. m_physicsActor = scene.AddAvatar(Firstname + "." + Lastname, pVec, new PhysicsVector(0, 0, 1.56f),
  2816. isFlying);
  2817. }
  2818. else
  2819. {
  2820. m_physicsActor = scene.AddAvatar(Firstname + "." + Lastname, pVec,
  2821. new PhysicsVector(0, 0, m_avHeight), isFlying);
  2822. }
  2823. scene.AddPhysicsActorTaint(m_physicsActor);
  2824. //m_physicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  2825. m_physicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
  2826. m_physicsActor.SubscribeEvents(1000);
  2827. m_physicsActor.LocalID = LocalId;
  2828. }
  2829. // Event called by the physics plugin to tell the avatar about a collision.
  2830. private void PhysicsCollisionUpdate(EventArgs e)
  2831. {
  2832. if ((e == null) || m_invulnerable)
  2833. return;
  2834. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  2835. Dictionary<uint, float> coldata = collisionData.m_objCollisionList;
  2836. float starthealth = Health;
  2837. uint killerObj = 0;
  2838. foreach (uint localid in coldata.Keys)
  2839. {
  2840. if (coldata[localid] <= 0.10f || m_invulnerable)
  2841. continue;
  2842. //if (localid == 0)
  2843. //continue;
  2844. SceneObjectPart part = m_scene.GetSceneObjectPart(localid);
  2845. if (part != null && part.ParentGroup.Damage != -1.0f)
  2846. Health -= part.ParentGroup.Damage;
  2847. else
  2848. Health -= coldata[localid] * 5;
  2849. if (Health <= 0)
  2850. {
  2851. if (localid != 0)
  2852. killerObj = localid;
  2853. }
  2854. //m_log.Debug("[AVATAR]: Collision with localid: " + localid.ToString() + " at depth: " + coldata[localid].ToString());
  2855. }
  2856. //Health = 100;
  2857. if (!m_invulnerable)
  2858. {
  2859. if (starthealth != Health)
  2860. {
  2861. ControllingClient.SendHealth(Health);
  2862. }
  2863. if (m_health <= 0)
  2864. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  2865. }
  2866. if (Velocity.X > 0 || Velocity.Y > 0)
  2867. UpdateMovementAnimations();
  2868. }
  2869. public void setHealthWithUpdate(float health)
  2870. {
  2871. Health = health;
  2872. ControllingClient.SendHealth(Health);
  2873. }
  2874. public void Close()
  2875. {
  2876. lock (m_attachments)
  2877. {
  2878. // Delete attachments from scene
  2879. // Don't try to save, as this thread won't live long
  2880. // enough to complete the save. This would cause no copy
  2881. // attachments to poof!
  2882. //
  2883. foreach (SceneObjectGroup grp in m_attachments)
  2884. {
  2885. m_scene.DeleteSceneObject(grp, false);
  2886. }
  2887. m_attachments.Clear();
  2888. }
  2889. lock (m_knownChildRegions)
  2890. {
  2891. m_knownChildRegions.Clear();
  2892. }
  2893. m_sceneViewer.Close();
  2894. RemoveFromPhysicalScene();
  2895. GC.Collect();
  2896. }
  2897. public ScenePresence()
  2898. {
  2899. if (DefaultTexture == null)
  2900. {
  2901. Primitive.TextureEntry textu = AvatarAppearance.GetDefaultTexture();
  2902. DefaultTexture = textu.GetBytes();
  2903. }
  2904. CreateSceneViewer();
  2905. }
  2906. public void AddAttachment(SceneObjectGroup gobj)
  2907. {
  2908. lock (m_attachments)
  2909. {
  2910. m_attachments.Add(gobj);
  2911. }
  2912. }
  2913. public bool HasAttachments()
  2914. {
  2915. return m_attachments.Count > 0;
  2916. }
  2917. public bool HasScriptedAttachments()
  2918. {
  2919. lock (m_attachments)
  2920. {
  2921. foreach (SceneObjectGroup gobj in m_attachments)
  2922. {
  2923. if (gobj != null)
  2924. {
  2925. if (gobj.RootPart.Inventory.ContainsScripts())
  2926. return true;
  2927. }
  2928. }
  2929. }
  2930. return false;
  2931. }
  2932. public void RemoveAttachment(SceneObjectGroup gobj)
  2933. {
  2934. lock (m_attachments)
  2935. {
  2936. if (m_attachments.Contains(gobj))
  2937. {
  2938. m_attachments.Remove(gobj);
  2939. }
  2940. }
  2941. }
  2942. public bool ValidateAttachments()
  2943. {
  2944. lock (m_attachments)
  2945. {
  2946. // Validate
  2947. foreach (SceneObjectGroup gobj in m_attachments)
  2948. {
  2949. if (gobj == null)
  2950. return false;
  2951. if (gobj.IsDeleted)
  2952. return false;
  2953. }
  2954. }
  2955. return true;
  2956. }
  2957. public bool CrossAttachmentsIntoNewRegion(ulong regionHandle, bool silent)
  2958. {
  2959. lock (m_attachments)
  2960. {
  2961. // Validate
  2962. foreach (SceneObjectGroup gobj in m_attachments)
  2963. {
  2964. if (gobj == null || gobj.IsDeleted)
  2965. return false;
  2966. }
  2967. foreach (SceneObjectGroup gobj in m_attachments)
  2968. {
  2969. // If the prim group is null then something must have happened to it!
  2970. if (gobj != null && gobj.RootPart != null)
  2971. {
  2972. // Set the parent localID to 0 so it transfers over properly.
  2973. gobj.RootPart.SetParentLocalId(0);
  2974. gobj.RootPart.IsAttachment = false;
  2975. gobj.AbsolutePosition = gobj.RootPart.AttachedPos;
  2976. //gobj.RootPart.LastOwnerID = gobj.GetFromAssetID();
  2977. m_log.DebugFormat("[ATTACHMENT]: Sending attachment {0} to region {1}", gobj.UUID, regionHandle);
  2978. m_scene.CrossPrimGroupIntoNewRegion(regionHandle, gobj, silent);
  2979. }
  2980. }
  2981. m_attachments.Clear();
  2982. return true;
  2983. }
  2984. }
  2985. public void initializeScenePresence(IClientAPI client, RegionInfo region, Scene scene)
  2986. {
  2987. m_controllingClient = client;
  2988. m_regionInfo = region;
  2989. m_scene = scene;
  2990. RegisterToEvents();
  2991. /*
  2992. AbsolutePosition = client.StartPos;
  2993. Animations = new AvatarAnimations();
  2994. Animations.LoadAnims();
  2995. m_animations = new List<UUID>();
  2996. m_animations.Add(Animations.AnimsUUID["STAND"]);
  2997. m_animationSeqs.Add(m_controllingClient.NextAnimationSequenceNumber);
  2998. SetDirectionVectors();
  2999. */
  3000. }
  3001. internal void PushForce(PhysicsVector impulse)
  3002. {
  3003. if (PhysicsActor != null)
  3004. {
  3005. PhysicsActor.AddForce(impulse,true);
  3006. }
  3007. }
  3008. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  3009. {
  3010. ScriptControllers obj = new ScriptControllers();
  3011. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  3012. obj.eventControls = ScriptControlled.CONTROL_ZERO;
  3013. obj.itemID = Script_item_UUID;
  3014. obj.objID = Obj_localID;
  3015. if (pass_on == 0 && accept == 0)
  3016. {
  3017. IgnoredControls |= (ScriptControlled)controls;
  3018. obj.ignoreControls = (ScriptControlled)controls;
  3019. }
  3020. if (pass_on == 0 && accept == 1)
  3021. {
  3022. IgnoredControls |= (ScriptControlled)controls;
  3023. obj.ignoreControls = (ScriptControlled)controls;
  3024. obj.eventControls = (ScriptControlled)controls;
  3025. }
  3026. if (pass_on == 1 && accept == 1)
  3027. {
  3028. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3029. obj.eventControls = (ScriptControlled)controls;
  3030. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  3031. }
  3032. lock (scriptedcontrols)
  3033. {
  3034. if (pass_on == 1 && accept == 0)
  3035. {
  3036. IgnoredControls &= ~(ScriptControlled)controls;
  3037. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  3038. scriptedcontrols.Remove(Script_item_UUID);
  3039. }
  3040. else
  3041. {
  3042. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  3043. {
  3044. scriptedcontrols[Script_item_UUID] = obj;
  3045. }
  3046. else
  3047. {
  3048. scriptedcontrols.Add(Script_item_UUID, obj);
  3049. }
  3050. }
  3051. }
  3052. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  3053. }
  3054. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  3055. {
  3056. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3057. lock (scriptedcontrols)
  3058. {
  3059. scriptedcontrols.Clear();
  3060. }
  3061. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  3062. }
  3063. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  3064. {
  3065. lock (scriptedcontrols)
  3066. {
  3067. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  3068. {
  3069. ScriptControllers takecontrolls = scriptedcontrols[Script_item_UUID];
  3070. ScriptControlled sctc = takecontrolls.eventControls;
  3071. ControllingClient.SendTakeControls((int)sctc, false, false);
  3072. ControllingClient.SendTakeControls((int)sctc, true, false);
  3073. scriptedcontrols.Remove(Script_item_UUID);
  3074. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3075. foreach (ScriptControllers scData in scriptedcontrols.Values)
  3076. {
  3077. IgnoredControls |= scData.ignoreControls;
  3078. }
  3079. }
  3080. }
  3081. }
  3082. internal void SendControlToScripts(uint flags)
  3083. {
  3084. ScriptControlled allflags = ScriptControlled.CONTROL_ZERO;
  3085. if (MouseDown)
  3086. {
  3087. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  3088. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 || (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  3089. {
  3090. allflags = ScriptControlled.CONTROL_ZERO;
  3091. MouseDown = true;
  3092. }
  3093. }
  3094. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  3095. {
  3096. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  3097. MouseDown = true;
  3098. }
  3099. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  3100. {
  3101. allflags |= ScriptControlled.CONTROL_LBUTTON;
  3102. MouseDown = true;
  3103. }
  3104. // find all activated controls, whether the scripts are interested in them or not
  3105. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  3106. {
  3107. allflags |= ScriptControlled.CONTROL_FWD;
  3108. }
  3109. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  3110. {
  3111. allflags |= ScriptControlled.CONTROL_BACK;
  3112. }
  3113. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  3114. {
  3115. allflags |= ScriptControlled.CONTROL_UP;
  3116. }
  3117. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  3118. {
  3119. allflags |= ScriptControlled.CONTROL_DOWN;
  3120. }
  3121. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  3122. {
  3123. allflags |= ScriptControlled.CONTROL_LEFT;
  3124. }
  3125. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  3126. {
  3127. allflags |= ScriptControlled.CONTROL_RIGHT;
  3128. }
  3129. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  3130. {
  3131. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  3132. }
  3133. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  3134. {
  3135. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  3136. }
  3137. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  3138. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  3139. {
  3140. lock (scriptedcontrols)
  3141. {
  3142. foreach (UUID scriptUUID in scriptedcontrols.Keys)
  3143. {
  3144. ScriptControllers scriptControlData = scriptedcontrols[scriptUUID];
  3145. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  3146. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  3147. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  3148. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  3149. {
  3150. // only send if still pressed or just changed
  3151. m_scene.EventManager.TriggerControlEvent(scriptControlData.objID, scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  3152. }
  3153. }
  3154. }
  3155. }
  3156. LastCommands = allflags;
  3157. }
  3158. internal static uint RemoveIgnoredControls(uint flags, ScriptControlled Ignored)
  3159. {
  3160. if (Ignored == ScriptControlled.CONTROL_ZERO)
  3161. return flags;
  3162. if ((Ignored & ScriptControlled.CONTROL_BACK) != 0)
  3163. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  3164. if ((Ignored & ScriptControlled.CONTROL_FWD) != 0)
  3165. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  3166. if ((Ignored & ScriptControlled.CONTROL_DOWN) != 0)
  3167. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  3168. if ((Ignored & ScriptControlled.CONTROL_UP) != 0)
  3169. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  3170. if ((Ignored & ScriptControlled.CONTROL_LEFT) != 0)
  3171. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  3172. if ((Ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  3173. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  3174. if ((Ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  3175. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  3176. if ((Ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  3177. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  3178. if ((Ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  3179. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  3180. if ((Ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  3181. flags &= ~((uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  3182. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  3183. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  3184. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  3185. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  3186. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  3187. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  3188. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  3189. return flags;
  3190. }
  3191. private void ItemReceived(UUID itemID)
  3192. {
  3193. if (IsChildAgent)
  3194. return;
  3195. if (null == m_appearance)
  3196. {
  3197. m_log.Warn("[ATTACHMENT] Appearance has not been initialized");
  3198. return;
  3199. }
  3200. int attachpoint = m_appearance.GetAttachpoint(itemID);
  3201. if (attachpoint == 0)
  3202. return;
  3203. UUID asset = m_appearance.GetAttachedAsset(attachpoint);
  3204. if (UUID.Zero == asset) // We have just logged in
  3205. {
  3206. try
  3207. {
  3208. // Rez from inventory
  3209. asset = m_scene.RezSingleAttachment(ControllingClient,
  3210. itemID, (uint)attachpoint);
  3211. // Corner case: We are not yet a Scene Entity
  3212. // Setting attachment info in RezSingleAttachment will fail
  3213. // Set it here
  3214. //
  3215. m_appearance.SetAttachment((int)attachpoint, itemID,
  3216. asset);
  3217. m_log.InfoFormat("[ATTACHMENT] Rezzed attachment {0}, inworld asset {1}",
  3218. itemID.ToString(), asset);
  3219. }
  3220. catch (Exception e)
  3221. {
  3222. m_log.ErrorFormat("[ATTACHMENT] Unable to rez attachment: {0}", e.ToString());
  3223. }
  3224. return;
  3225. }
  3226. SceneObjectPart att = m_scene.GetSceneObjectPart(asset);
  3227. // If this is null, then the asset has not yet appeared in world
  3228. // so we revisit this when it does
  3229. //
  3230. if (att != null && att.UUID != asset) // Yes. It's really needed
  3231. {
  3232. m_log.DebugFormat("[ATTACHMENT]: Attach from in world: ItemID {0}, Asset ID {1}, Attachment inworld: {2}", itemID.ToString(), asset.ToString(), att.UUID.ToString());
  3233. // This will throw if crossing katty-korner
  3234. // So catch it here to avoid the noid
  3235. //
  3236. try
  3237. {
  3238. // Attach from world, if not already attached
  3239. if (att.ParentGroup != null && !att.IsAttachment)
  3240. m_scene.AttachObject(ControllingClient, att.ParentGroup.LocalId, 0, Quaternion.Identity, att.ParentGroup.AbsolutePosition, false);
  3241. }
  3242. catch (NullReferenceException)
  3243. {
  3244. }
  3245. }
  3246. }
  3247. }
  3248. }