1
0

ScenePresence.cs 142 KB

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