ScenePresence.cs 155 KB

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