コード例 #1
0
ファイル: Movement.cs プロジェクト: dachidahu/AutoFollow
        /// <summary>
        /// Moves to a world position 
        /// (naive, blocks execution, avoid using while in combat)
        /// </summary>
        /// <param name="location">where to move to</param>
        /// <param name="destinationName">name of location for debugging purposes</param>
        /// <param name="range">how close it should get</param>
        public static async Task<bool> MoveTo(Vector3 location, string destinationName = "", float range = 10f, Func<bool> stopCondition = null)
        {
            var distance = 0f;
            var name = string.IsNullOrEmpty(destinationName) ? location.ToString() : destinationName;

            Navigator.PlayerMover.MoveTowards(location);

            while (ZetaDia.IsInGame && (distance = location.Distance(ZetaDia.Me.Position)) >= range)
            {
                if (stopCondition != null && stopCondition())
                    break;

                if (ZetaDia.Me.IsDead || Navigator.StuckHandler.IsStuck)
                    break;

                if (Navigation.IsBlocked)
                {
                    Log.Verbose("Movement Failed, It looks like we're blocked!", name, distance);
                    break;
                }
                    
                Log.Verbose("Moving to {0} Distance={1}", name, distance);
                await Navigator.MoveTo(location, name);
                await Coroutine.Yield();
            }

            if (distance <= range)
                Navigator.PlayerMover.MoveStop();

            Log.Verbose("MoveTo Finished. Distance={0}", distance);
            return true;
        }
コード例 #2
0
 public string CacheName(Vector3 addr)
 {
     byte[] data = UnicodeEncoding.Unicode.GetBytes(addr.ToString() + m_map.Name);
     byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(data);
     StringBuilder hex = new StringBuilder(hash.Length);
     foreach (byte b in data)
     {
         hex.Append(b.ToString("X2"));
     }
     return hex.ToString();
 }
コード例 #3
0
ファイル: Program.cs プロジェクト: Dyno1990/TelerikAcademy-1
        static void Main(string[] args)
        {
            //3d vectors are necessary, because crossproduct creates a 
            //perpendicular vector, which doesnt exist in 2d space
            Vector3 a = new Vector3(1f, 1f, 0f);
            Vector3 b = new Vector3(3f, 1f, 0f);
            Vector3 c = new Vector3(2f, 3f, 0f);

            Vector3 x = new Vector3(2f, 2f, 0f);

            bool result = PointInTriangle(x, a, b, c);

            if (result)
            {
                Console.WriteLine("{0}is in triangle", x.ToString());
            }
            else
            {
                Console.WriteLine("{0}is NOT in triangle", x.ToString());
            }
        }
コード例 #4
0
        public void teleport(string sim,Vector3 pos)
        {
            Gtk.Application.Invoke(delegate {
                this.label_sim.Text=sim;
                this.label_loc.Text=pos.ToString();
                this.tppos=pos;
                this.tpsim=sim;
                this.QueueDraw();
            });

                Thread tpRunner= new Thread(new ThreadStart(this.tpthread));
                tpRunner.Start();
        }
コード例 #5
0
ファイル: LuaAPI.cs プロジェクト: Keldyn/BattleOfTheClans
 public String PositionToString(Vector3 p)
 {
     return p.ToString();
 }
コード例 #6
0
 public AbstractPage Wake(Vector3 addr)
 {
     Console.WriteLine("Waking " + addr.ToString());
     string path = Game.PathTo("cache/" + CacheName(addr) + ".dat");
     FileStream file = new FileStream(path, FileMode.Open);
     BinaryFormatter f = new BinaryFormatter();
     AbstractPage page = (AbstractPage)f.Deserialize(file);
     file.Close();
     File.Delete(path);
     return page;
 }
コード例 #7
0
        /// <summary>
        /// </summary>
        public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string version, out string reason)
        {
            reason = "Failed to contact destination";
            version = "Unknown";

            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position);

            IPEndPoint ext = destination.ExternalEndPoint;
            if (ext == null) return false;

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + id + "/" + destination.RegionID.ToString() + "/";

            OSDMap request = new OSDMap();
            request.Add("position", OSD.FromString(position.ToString()));

            try
            {
                OSDMap result = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 10000, false);
                bool success = result["success"].AsBoolean();
                if (result.ContainsKey("_Result"))
                {
                    OSDMap data = (OSDMap)result["_Result"];

                    reason = data["reason"].AsString();
                    if (data["version"] != null && data["version"].AsString() != string.Empty)
                        version = data["version"].AsString();

                    m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1} version {2} ({3})", uri, success, version, data["version"].AsString());
                }

                if (!success)
                {
                    if (result.ContainsKey("Message"))
                    {
                        string message = result["Message"].AsString();
                        if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region
                        {
                            m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored");
                            return true;
                        }

                        reason = result["Message"];
                    }
                    else
                    {
                        reason = "Communications failure";
                    }

                    return false;
                }

                return success;
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcess failed with exception; {0}",e.ToString());
            }
            
            return false;
        }
コード例 #8
0
ファイル: PlayerMover.cs プロジェクト: FalseApple/d3db
        // Actually deal with a stuck - find an unstuck point etc.
        public static Vector3 UnstuckHandler(Vector3 vMyCurrentPosition, Vector3 vOriginalDestination)
        {
            if (Trinity.Settings.Advanced.DisableAllMovement)
                return Vector3.Zero;

            // Update the last time we generated a path
            LastGeneratedStuckPosition = DateTime.UtcNow;
            Navigator.Clear();

            // If we got stuck on a 2nd/3rd/4th "chained" anti-stuck route, then return the old move to target to keep movement of some kind going
            if (TimesReachedStuckPoint > 0)
            {
                vSafeMovementLocation = Vector3.Zero;

                // Reset the path and allow a whole "New" unstuck generation next cycle
                TimesReachedStuckPoint = 0;
                // And cancel unstucking for 9 seconds so DB can try to navigate
                CancelUnstuckerForSeconds = (9 * TotalAntiStuckAttempts);
                if (CancelUnstuckerForSeconds < 20)
                    CancelUnstuckerForSeconds = 20;
                LastCancelledUnstucker = DateTime.UtcNow;
                Logger.Log(TrinityLogLevel.Verbose, LogCategory.UserInformation, "Clearing old route and trying new path find to: " + LastMoveToTarget.ToString());
                NavigateTo(LastMoveToTarget, "original destination");
                return vSafeMovementLocation;
            }
            // Only try an unstuck 10 times maximum in XXX period of time
            if (Vector3.Distance(vOriginalDestination, vMyCurrentPosition) >= V.F("Unstucker.MaxDistance"))
            {
                Logger.Log(TrinityLogLevel.Verbose, LogCategory.UserInformation, "You are " + Vector3.Distance(vOriginalDestination, vMyCurrentPosition).ToString() + " distance away from your destination.");
                Logger.Log(TrinityLogLevel.Verbose, LogCategory.UserInformation, "This is too far for the unstucker, and is likely a sign of ending up in the wrong map zone.");
                TotalAntiStuckAttempts = 20;
            }

            if (TotalAntiStuckAttempts <= 10)
            {
                Logger.Log(TrinityLogLevel.Info, LogCategory.UserInformation, "Your bot got stuck! Trying to unstuck (attempt #{0} of 10 attempts) {1} {2} {3} {4}",
                    TotalAntiStuckAttempts.ToString(),
                    "Act=\"" + ZetaDia.CurrentAct + "\"",
                    "questId=\"" + ZetaDia.CurrentQuest.QuestSNO + "\"",
                    "stepId=\"" + ZetaDia.CurrentQuest.StepId + "\"",
                    "worldId=\"" + ZetaDia.CurrentWorldId + "\""
                );

                Logger.Log(TrinityLogLevel.Verbose, LogCategory.UserInformation, "(destination=" + vOriginalDestination.ToString() + ", which is " + Vector3.Distance(vOriginalDestination, vMyCurrentPosition).ToString() + " distance away)");

                /*
                 * Unstucker position
                 */
                //vSafeMovementLocation = NavHelper.FindSafeZone(true, TotalAntiStuckAttempts, vMyCurrentPosition);
                vSafeMovementLocation = NavHelper.SimpleUnstucker();

                // Temporarily log stuff
                if (TotalAntiStuckAttempts == 1 && Trinity.Settings.Advanced.LogStuckLocation)
                {
                    FileStream LogStream = File.Open(Path.Combine(FileManager.LoggingPath, "Stucks - " + Trinity.Player.ActorClass.ToString() + ".log"), FileMode.Append, FileAccess.Write, FileShare.Read);
                    using (StreamWriter LogWriter = new StreamWriter(LogStream))
                    {
                        LogWriter.WriteLine(DateTime.UtcNow.ToString() + ": Original Destination=" + LastMoveToTarget.ToString() + ". Current player position when stuck=" + vMyCurrentPosition.ToString());
                        LogWriter.WriteLine("Profile Name=" + ProfileManager.CurrentProfile.Name);
                    }
                    LogStream.Close();
                }
                // Now count up our stuck attempt generations
                TotalAntiStuckAttempts++;
                return vSafeMovementLocation;
            }

            TimesReachedMaxUnstucks++;
            TotalAntiStuckAttempts = 1;
            vSafeMovementLocation = Vector3.Zero;
            LastPosition = Vector3.Zero;
            TimesReachedStuckPoint = 0;
            TimeLastRecordedPosition = DateTime.MinValue;
            LastGeneratedStuckPosition = DateTime.MinValue;
            // int iSafetyLoops = 0;
            if (TimesReachedMaxUnstucks == 1)
            {
                Navigator.Clear();
                GridSegmentation.Reset();
                Logger.Log(TrinityLogLevel.Info, LogCategory.Movement, "Anti-stuck measures now attempting to kickstart DB's path-finder into action.");
                var result = NavigateTo(vOriginalDestination, "original destination");
                //Navigator.MoveTo(vOriginalDestination, "original destination");
                CancelUnstuckerForSeconds = 40;
                LastCancelledUnstucker = DateTime.UtcNow;
                return vSafeMovementLocation;
            }
            if (TimesReachedMaxUnstucks == 2)
            {
                Logger.Log(TrinityLogLevel.Info, LogCategory.Movement, "Anti-stuck measures failed. Now attempting to reload current profile.");

                Navigator.Clear();

                ProfileManager.Load(Zeta.Bot.ProfileManager.CurrentProfile.Path);
                Logger.Log(TrinityLogLevel.Info, LogCategory.UserInformation, "Anti-stuck successfully reloaded current profile, DemonBuddy now navigating again.");
                return vSafeMovementLocation;

                // Didn't make it to town, so skip instantly to the exit game system
                //iTimesReachedMaxUnstucks = 3;
            }
            // Exit the game and reload the profile
            if (Trinity.Settings.Advanced.AllowRestartGame && DateTime.UtcNow.Subtract(LastRestartedGame).TotalMinutes >= 5)
            {
                LastRestartedGame = DateTime.UtcNow;
                string sUseProfile = Trinity.FirstProfile;
                Logger.Log(TrinityLogLevel.Info, LogCategory.UserInformation, "Anti-stuck measures exiting current game.");
                // Load the first profile seen last run
                ProfileManager.Load(!string.IsNullOrEmpty(sUseProfile)
                                        ? sUseProfile
                                        : Zeta.Bot.ProfileManager.CurrentProfile.Path);
                Thread.Sleep(1000);
                Trinity.ResetEverythingNewGame();
                ZetaDia.Service.Party.LeaveGame(true);
                // Wait for 10 second log out timer if not in town
                if (!ZetaDia.IsInTown)
                {
                    Thread.Sleep(15000);
                }
            }
            else
            {
                Logger.Log(TrinityLogLevel.Info, LogCategory.UserInformation, "Unstucking measures failed. Now stopping Trinity unstucker for 12 minutes to inactivity timers to kick in or DB to auto-fix.");
                CancelUnstuckerForSeconds = 720;
                LastCancelledUnstucker = DateTime.UtcNow;
                return vSafeMovementLocation;
            }
            return vSafeMovementLocation;
        }
コード例 #9
0
ファイル: PlayerMover.cs プロジェクト: FalseApple/d3db
 private static Vector3 WarnAndLogLongPath(Vector3 vMoveToTarget)
 {
     // The below code is to help profile/routine makers avoid waypoints with a long distance between them.
     // Long-distances between waypoints is bad - it increases stucks, and forces the DB nav-server to be called.
     if (Trinity.Settings.Advanced.LogStuckLocation)
     {
         if (vLastMoveTo == Vector3.Zero)
             vLastMoveTo = vMoveToTarget;
         if (vMoveToTarget != vLastMoveTo)
         {
             float fDistance = Vector3.Distance(vMoveToTarget, vLastMoveTo);
             // Log if not in town, last waypoint wasn't FROM town, and the distance is >200 but <2000 (cos 2000+ probably means we changed map zones!)
             if (!Trinity.Player.IsInTown && !bLastWaypointWasTown && fDistance >= 200 & fDistance <= 2000)
             {
                 if (!hashDoneThisVector.Contains(vMoveToTarget))
                 {
                     // Log it
                     FileStream LogStream = File.Open(Path.Combine(FileManager.LoggingPath, "LongPaths - " + ZetaDia.Me.ActorClass.ToString() + ".log"), FileMode.Append, FileAccess.Write, FileShare.Read);
                     using (StreamWriter LogWriter = new StreamWriter(LogStream))
                     {
                         LogWriter.WriteLine(DateTime.UtcNow.ToString() + ":");
                         LogWriter.WriteLine("Profile Name=" + ProfileManager.CurrentProfile.Name);
                         LogWriter.WriteLine("'From' Waypoint=" + vLastMoveTo.ToString() + ". 'To' Waypoint=" + vMoveToTarget.ToString() + ". Distance=" + fDistance.ToString());
                     }
                     LogStream.Close();
                     hashDoneThisVector.Add(vMoveToTarget);
                 }
             }
             vLastMoveTo = vMoveToTarget;
             bLastWaypointWasTown = false;
             if (Trinity.Player.IsInTown)
                 bLastWaypointWasTown = true;
         }
     }
     return vMoveToTarget;
 }
コード例 #10
0
ファイル: SceneObjectPart.cs プロジェクト: kf6kjg/halcyon
        // Internal function that has all the logic but also allows the operation to be forced (even if in transit)
        public bool SetGroupPosition(Vector3 value, bool forced, bool physicsTriggered)
        {
            if ((!forced) && (ParentGroup != null) && ParentGroup.InTransit) // it's null at startup time
            {
                m_log.WarnFormat("[SCENEOBJECTPART]: GroupPosition update for {0} to {1} ignored while in transit.", ParentGroup.Name, value.ToString());
                return false;
            }

            //check for nan and inf for x y and z.  refuse to set position
            //in these cases
            if (Single.IsNaN(value.X) || Single.IsInfinity(value.X) ||
                Single.IsNaN(value.Y) || Single.IsInfinity(value.Y) ||
                Single.IsNaN(value.Z) || Single.IsInfinity(value.Z))
            {
                return false;
            }

            SetGroupPositionDirect(value);

            if (!physicsTriggered)
            {
                PhysicsActor physActor = PhysActor;
                if (physActor != null)
                {
                    try
                    {
                        // Root prim actually goes at Position
                        if (IsRootPart())
                        {
                            physActor.Position = value;
                        }
                    }
                    catch (Exception e)
                    {
                        m_log.Error("[SCENEOBJECTPART]: GROUP POSITION. " + e.Message);
                    }
                }
            }

            return true;
        }
コード例 #11
0
        private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
        {
            // Save our current location as session data
            NameValueCollection requestArgs = new NameValueCollection
                {
                        { "RequestMethod", "UpdateSession" },
                        { "SessionID", sessionID.ToString() },
                        { "SceneID", regionID.ToString() },
                        { "ScenePosition", lastPosition.ToString() },
                        { "SceneLookAt", lastLookAt.ToString() }
                };

            OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
            bool success = response["Success"].AsBoolean();

            if (!success)
                m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString());

            return success;
        }
コード例 #12
0
ファイル: Meshmerizer.cs プロジェクト: HGExchange/opensim
        public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
        {
#if SPAM
            m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
#endif

            Mesh mesh = null;
            ulong key = 0;

            // If this mesh has been created already, return it instead of creating another copy
            // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
            key = GetMeshKey(primShape, size, lod);
            if (m_uniqueMeshes.TryGetValue(key, out mesh))
                return mesh;

            if (size.X < 0.01f) size.X = 0.01f;
            if (size.Y < 0.01f) size.Y = 0.01f;
            if (size.Z < 0.01f) size.Z = 0.01f;

            mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);

            if (mesh != null)
            {
                if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
                {
#if SPAM
                m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " + 
                            minSizeForComplexMesh.ToString() + " - creating simple bounding box");
#endif
                    mesh = CreateBoundingBoxMesh(mesh);
                    mesh.DumpRaw(baseDir, primName, "Z extruded");
                }

                // trim the vertex and triangle lists to free up memory
                mesh.TrimExcess();

                m_uniqueMeshes.Add(key, mesh);
            }

            return mesh;
        }
コード例 #13
0
ファイル: LSL_Api.cs プロジェクト: mugginsm/Aurora-Sim
        public LSL_Key llRequestInventoryData(string name)
        {
            ScriptProtection.CheckThreatLevel(ThreatLevel.None, "LSL", m_host, "LSL");
            

            TaskInventoryDictionary itemDictionary = (TaskInventoryDictionary)m_host.TaskInventory.Clone();

            foreach (TaskInventoryItem item in itemDictionary.Values)
            {
                if (item.Type == 3 && item.Name == name)
                {
                    DataserverPlugin dataserverPlugin = (DataserverPlugin)m_ScriptEngine.GetScriptPlugin("Dataserver");

                    UUID tid = dataserverPlugin.RegisterRequest(m_host.UUID,
                                                     m_itemID, item.AssetID.ToString());

                    Vector3 region = new Vector3(
                        World.RegionInfo.RegionLocX,
                        World.RegionInfo.RegionLocY,
                        0);

                    World.AssetService.Get(item.AssetID.ToString(), this,
                        delegate(string i, object sender, AssetBase a)
                        {
                            AssetLandmark lm = new AssetLandmark(a);

                            float rx = (uint)(lm.RegionHandle >> 32);
                            float ry = (uint)lm.RegionHandle;
                            region = lm.Position + new Vector3(rx, ry, 0) - region;

                            string reply = region.ToString();
                            dataserverPlugin.AddReply(i.ToString(),
                                                             reply, 1000);
                        });

                    ScriptSleep(1000);
                    return (LSL_Key)tid.ToString();                   
                }
            }
            ScriptSleep(1000);
            return (LSL_Key) String.Empty;
        }
コード例 #14
0
        public void SpawnCargoShipGroup(Vector3 startPosition, Vector3 stopPosition, ulong remoteUserId = 0)
        {
            try
            {
                //Load the spawn groups
                SpawnGroupsDefinitionsManager spawnGroupsDefinitionsManager = new SpawnGroupsDefinitionsManager();
                FileInfo contentDataFile = new FileInfo(Path.Combine(MyFileSystem.ContentPath, "Data", "SpawnGroups.sbc"));
                spawnGroupsDefinitionsManager.Load(contentDataFile);

                //Calculate lowest and highest frequencies
                float lowestFrequency = 999999;
                float highestFrequency = 0;
                foreach (SpawnGroupDefinition entry in spawnGroupsDefinitionsManager.Definitions)
                {
                    if (entry.Frequency < lowestFrequency)
                        lowestFrequency = entry.Frequency;
                    if (entry.Frequency > highestFrequency)
                        highestFrequency = entry.Frequency;
                }
                if (lowestFrequency <= 0)
                    lowestFrequency = 1;

                //Get a list of which groups *could* spawn
                Random random = new Random((int)DateTime.Now.ToBinary());
                double randomChance = random.NextDouble();
                randomChance = randomChance * (highestFrequency / lowestFrequency);
                List<SpawnGroupDefinition> possibleGroups = new List<SpawnGroupDefinition>();
                foreach (SpawnGroupDefinition entry in spawnGroupsDefinitionsManager.Definitions)
                {
                    if (entry.Frequency >= randomChance)
                    {
                        possibleGroups.Add(entry);
                    }
                }

                //Determine which group *will* spawn
                randomChance = random.NextDouble();
                int randomShipIndex = Math.Max(0, Math.Min((int)Math.Round(randomChance * possibleGroups.Count, 0), possibleGroups.Count-1));
                SpawnGroupDefinition randomSpawnGroup = possibleGroups[randomShipIndex];

                ChatManager.Instance.SendPrivateChatMessage(remoteUserId, "Spawning cargo group '" + randomSpawnGroup.Name + "' ...");

                //Spawn the ships in the group
                Matrix orientation = Matrix.CreateLookAt(startPosition, stopPosition, new Vector3(0, 1, 0));
                foreach (SpawnGroupPrefab entry in randomSpawnGroup.Prefabs)
                {
                    FileInfo prefabFile = new FileInfo(Path.Combine(MyFileSystem.ContentPath, "Data", "Prefabs", entry.SubtypeId + ".sbc"));
                    if (!prefabFile.Exists)
                        continue;

                    //Create the ship
                    CubeGridEntity cubeGrid = new CubeGridEntity(prefabFile);

                    //Set the ship position and orientation
                    Vector3 shipPosition = Vector3.Transform(entry.Position, orientation) + startPosition;
                    orientation.Translation = shipPosition;
                    MyPositionAndOrientation newPositionOrientation = new MyPositionAndOrientation(orientation);
                    cubeGrid.PositionAndOrientation = newPositionOrientation;

                    //Set the ship velocity
                    //Speed is clamped between 1.0f and the max cube grid speed
                    Vector3 travelVector = stopPosition - startPosition;
                    travelVector.Normalize();
                    Vector3 shipVelocity = travelVector * (float)Math.Min(cubeGrid.MaxLinearVelocity, Math.Max(1.0f, entry.Speed));
                    cubeGrid.LinearVelocity = shipVelocity;

                    cubeGrid.IsDampenersEnabled = false;

                    foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.BaseCubeBlocks)
                    {
                        //Set the beacon names
                        if (cubeBlock.TypeId == typeof(MyObjectBuilder_Beacon))
                        {
                            MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock;
                            beacon.CustomName = entry.BeaconText;
                        }

                        //Set the owner of every block
                        //TODO - Find out if setting to an arbitrary non-zero works for this
                        cubeBlock.Owner = PlayerMap.Instance.GetServerVirtualPlayerId();
                        cubeBlock.ShareMode = MyOwnershipShareModeEnum.Faction;
                    }

                    //And add the ship to the world
                    SectorObjectManager.Instance.AddEntity(cubeGrid);

                    //Force a refresh of the cube grid
                    List<CubeBlockEntity> cubeBlocks = cubeGrid.CubeBlocks;
                }

                ChatManager.Instance.SendPrivateChatMessage(remoteUserId, "Cargo group '" + randomSpawnGroup.DisplayName + "' spawned with " + randomSpawnGroup.Prefabs.Length.ToString() + " ships at " + startPosition.ToString());
            }
            catch (Exception ex)
            {
                LogManager.ErrorLog.WriteLine(ex);
            }
        }
コード例 #15
0
ファイル: PathfindingDemo.cs プロジェクト: amitprakash07/dx11
        protected override void OnMouseDown(object sender, MouseEventArgs e) {
            switch (e.Button) {
                case MouseButtons.Left:
                    _minimap.OnClick(e);
                    _lastMousePos = e.Location;
                    Window.Capture = true;
                    break;
                case MouseButtons.Right:
                    // move the unit around using the right clicks
                    var ray = _camera.GetPickingRay(new Vector2(e.X, e.Y), new Vector2(Viewport.Width, Viewport.Height));

                    var tile = new MapTile();
                    var worldPos = new Vector3();

                    // do intersection test
                    if (!_terrain.Intersect(ray, ref worldPos, ref tile)) {
                        return;
                    }
                    Console.WriteLine("Clicked at " + worldPos.ToString());
                    if (tile == null) {
                        return;
                    }
                    // move the unit towards the new goal
                    Console.WriteLine("Hit tile " + tile.MapPosition);
                    Console.WriteLine("Moving unit to " + tile.MapPosition);
                    _unit.Goto(tile);
                    break;
            }
        }
コード例 #16
0
        public void TestMemberFn_ToString_i ()
        {
            Vector3 a = new Vector3(42, -17, 13);

            String result = a.ToString();

            String expected = "{X:42 Y:-17 Z:13}";

            Assert.That(result, Is.EqualTo(expected));
        }
コード例 #17
0
ファイル: RobustPresence.cs プロジェクト: chazzmac/Aurora-Sim
        protected bool Set(Dictionary<string, object> sendData, string userID, UUID regionID, Vector3 position, Vector3 lookAt)
        {
            sendData["UserID"] = userID;
            sendData["RegionID"] = regionID.ToString();
            sendData["Position"] = position.ToString();
            sendData["LookAt"] = lookAt.ToString();

            string reqString = WebUtils.BuildQueryString(sendData);
            // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString);
            try
            {
                List<string> urls = m_registry.RequestModuleInterface<IConfigurationService>().FindValueOf("GridUserServerURI");
                foreach (string url in urls)
                {
                    string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                               url,
                               reqString);
                    if (reply != string.Empty)
                    {
                        Dictionary<string, object> replyData = WebUtils.ParseXmlResponse(reply);

                        if (replyData.ContainsKey("result"))
                        {
                            if (replyData["result"].ToString().ToLower() == "success")
                                return true;
                            else
                                return false;
                        }
                    }
                }
            }
            catch (Exception)
            { }

            return false;
        }
コード例 #18
0
        /// <summary>
        /// Updates the userpicks
        /// </summary>
        /// <param name='remoteClient'>
        /// Remote client.
        /// </param>
        /// <param name='pickID'>
        /// Pick I.
        /// </param>
        /// <param name='creatorID'>
        /// the creator of the pick
        /// </param>
        /// <param name='topPick'>
        /// Top pick.
        /// </param>
        /// <param name='name'>
        /// Name.
        /// </param>
        /// <param name='desc'>
        /// Desc.
        /// </param>
        /// <param name='snapshotID'>
        /// Snapshot I.
        /// </param>
        /// <param name='sortOrder'>
        /// Sort order.
        /// </param>
        /// <param name='enabled'>
        /// Enabled.
        /// </param>
        public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled)
        {            
            m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString());

            UserProfilePick pick = new UserProfilePick();
            string serverURI = string.Empty;
            GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
            ScenePresence p = FindPresence(remoteClient.AgentId);

            Vector3 avaPos = p.AbsolutePosition;
            // Getting the global position for the Avatar
            Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.WorldLocX + avaPos.X,
                                            remoteClient.Scene.RegionInfo.WorldLocY + avaPos.Y,
                                            avaPos.Z);

            string landOwnerName = string.Empty;
            ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y);

            if (land != null)
            {
                if (land.LandData.IsGroupOwned)
                {
                    IGroupsModule groupMod = p.Scene.RequestModuleInterface<IGroupsModule>();
                    UUID groupId = land.LandData.GroupID;
                    GroupRecord groupRecord = groupMod.GetGroupRecord(groupId);
                    landOwnerName = groupRecord.GroupName;
                }
                else
                {
                    IUserAccountService accounts = p.Scene.RequestModuleInterface<IUserAccountService>();
                    UserAccount user = accounts.GetUserAccount(p.Scene.RegionInfo.ScopeID, land.LandData.OwnerID);
                    landOwnerName = user.Name;
                }
            }
            else
            {
                m_log.WarnFormat(
                    "[PROFILES]: PickInfoUpdate found no parcel info at {0},{1} in {2}", 
                    avaPos.X, avaPos.Y, p.Scene.Name);
            }

            pick.PickId = pickID;
            pick.CreatorId = creatorID;
            pick.TopPick = topPick;
            pick.Name = name;
            pick.Desc = desc;
            pick.ParcelId = p.currentParcelUUID;
            pick.SnapshotId = snapshotID;
            pick.User = landOwnerName;
            pick.SimName = remoteClient.Scene.RegionInfo.RegionName;
            pick.GlobalPos = posGlobal.ToString();
            pick.SortOrder = sortOrder;
            pick.Enabled = enabled;

            object Pick = (object)pick;
            if(!rpc.JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAgentAlertMessage(
                        "Error updating pick", false);
                return;
            }

            m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString());
        }
コード例 #19
0
ファイル: KDTreeTest.cs プロジェクト: Jerdak/KDTree2
        public void FindClosestPointTest()
        {
            Console.WriteLine("Current Directory: " + System.IO.Directory.GetCurrentDirectory());
            List<Vector3> vertices;
            List<Face> faces;
            List<Color> colors;
            KDTree tree = new KDTree();
            {	//Build KDTree from a Wavefront .obj file
                if (!ObjIO.Read(@"D:\Libraries\KDTree2\KDTree_UnitTest\bin\Debug\test2.obj", out vertices, out colors, out faces))
                {
                    Assert.Fail("Failed to find test.obj");
                }
                tree.AddPoints(vertices);
                bool build_result = tree.Build();
                Assert.IsTrue(build_result);
            }

            {	// First test that loaded points can refind themselves.
                Stopwatch st = new Stopwatch();
                st.Start();

                bool match_result = true;
                for (int i = 0; i < vertices.Count; i++)
                {
                    int index = i;
                    int nearest_index = 0;
                    Vector3 tmp = tree.FindClosestPoint(vertices[index], 0.00f, ref nearest_index);
                    if (nearest_index != index)
                    {
                        Console.WriteLine("Vertex: " + vertices[index].ToString());
                        Console.WriteLine("Mis-Match: " + vertices[nearest_index].ToString());
                        Assert.Fail("Mismatched closest pair: " + index.ToString() + "," + nearest_index.ToString());
                    }
                }
                st.Stop();
                Console.WriteLine("Elapsed Exact Set = {0}", st.Elapsed.ToString());
                Assert.IsTrue(match_result);
            }

            {	// Next test that a completely random set of data can find a closest point, compare to brute force.
                Vector3 min,max,center,centroid,range;
                Vector3.Metrics(vertices,out min, out max, out center, out centroid, out range);
                Random random = new Random(42);
                Stopwatch st = new Stopwatch();
                st.Start();
                for (int i = 0; i < 1500; i++)
                {
                    float x = (float)random.Next((int)(min.X * 1000.0f), (int)(max.X * 1000.0f)); x /= 1000.0f;
                    float y = (float)random.Next((int)(min.Y * 1000.0f), (int)(max.Y * 1000.0f)); y /= 1000.0f;
                    float z = (float)random.Next((int)(min.Z * 1000.0f), (int)(max.Z * 1000.0f)); z /= 1000.0f;

                    int closest_index = 0;
                    int closest_index2 = 0;
                    Vector3 vertex = new Vector3(x, y, z);

                    Vector3 closest_vertex = tree.FindClosestPoint(vertex, 1.1f, ref closest_index);
                    Vector3 closest_vertex2 = tree.FindClosestPointBrute(vertex, ref closest_index2);

                    if (closest_vertex2.Distance(vertex) < closest_vertex.Distance(vertex))
                    {
                        st.Stop();
                        Console.WriteLine("Vertex: " + vertex.ToString());
                        Console.WriteLine("Match1: " + closest_vertex.ToString() + ": d=" + closest_vertex.Distance(vertex).ToString());
                        Console.WriteLine("Match2: " + closest_vertex2.ToString() + ": d=" + closest_vertex2.Distance(vertex).ToString());
                        //Assert.Fail("Incorrect matching vertex");
                        st.Start();
                    }
                }
                st.Stop();
                Console.WriteLine("Elapsed Random Set = {0}", st.Elapsed.ToString());
            }
        }
コード例 #20
0
        public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, string myversion, out string version, out string reason)
        {
            reason = "Failed to contact destination";
            version = "Unknown";

            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position);

            IPEndPoint ext = destination.ExternalEndPoint;
            if (ext == null) return false;

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + agentID + "/" + destination.RegionID.ToString() + "/";

            OSDMap request = new OSDMap();
            request.Add("viaTeleport", OSD.FromBoolean(viaTeleport));
            request.Add("position", OSD.FromString(position.ToString()));
            request.Add("my_version", OSD.FromString(myversion));
            if (agentHomeURI != null)
                request.Add("agent_home_uri", OSD.FromString(agentHomeURI));

            try
            {
                OSDMap result = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 30000, false, false);
                bool success = result["success"].AsBoolean();
                if (result.ContainsKey("_Result"))
                {
                    OSDMap data = (OSDMap)result["_Result"];

                    // FIXME: If there is a _Result map then it's the success key here that indicates the true success
                    // or failure, not the sibling result node.
                    success = data["success"];

                    reason = data["reason"].AsString();
                    if (data["version"] != null && data["version"].AsString() != string.Empty)
                        version = data["version"].AsString();

                    m_log.DebugFormat(
                        "[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3} ({4})",
                        uri, success, reason, version, data["version"].AsString());
                }

                if (!success)
                {
                    // If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the
                    // actual failure message
                    if (!result.ContainsKey("_Result"))
                    {
                        if (result.ContainsKey("Message"))
                        {
                            string message = result["Message"].AsString();
                            if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region
                            {
                                m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored");
                                return true;
                            }
    
                            reason = result["Message"];
                        }
                        else
                        {
                            reason = "Communications failure";
                        }
                    }

                    return false;
                }

                return success;
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}",e.ToString());
            }
            
            return false;
        }
コード例 #21
0
ファイル: LSL_Api.cs プロジェクト: OpenPlex-Sim/opensim
        public LSL_String llRequestInventoryData(string name)
        {
            m_host.AddScriptLPS(1);

            TaskInventoryDictionary itemDictionary = (TaskInventoryDictionary)m_host.TaskInventory.Clone();

            foreach (TaskInventoryItem item in itemDictionary.Values)
            {
                if (item.Type == 3 && item.Name == name)
                {
                    UUID tid = AsyncCommands.
                        DataserverPlugin.RegisterRequest(m_host.LocalId,
                                                     m_item.ItemID, item.AssetID.ToString());

                    Vector3 region = new Vector3(
                        World.RegionInfo.RegionLocX * Constants.RegionSize,
                        World.RegionInfo.RegionLocY * Constants.RegionSize,
                        0);

                    World.AssetService.Get(item.AssetID.ToString(), this,
                        delegate(string i, object sender, AssetBase a)
                        {
                            AssetLandmark lm = new AssetLandmark(a);

                            float rx = (uint)(lm.RegionHandle >> 32);
                            float ry = (uint)lm.RegionHandle;
                            region = lm.Position + new Vector3(rx, ry, 0) - region;

                            string reply = region.ToString();
                            AsyncCommands.
                                DataserverPlugin.DataserverReply(i.ToString(),
                                                             reply);
                        });

                    ScriptSleep(1000);
                    return tid.ToString();
                }
            }
            ScriptSleep(1000);
            return String.Empty;
        }
コード例 #22
0
        public bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt)
        {
            GridUserData d = m_Database.Get(userID);
            if (d == null)
            {
                d = new GridUserData();
                d.UserID = userID;
            }

            d.Data["HomeRegionID"] = homeID.ToString();
            d.Data["HomePosition"] = homePosition.ToString();
            d.Data["HomeLookAt"] = homeLookAt.ToString();

            return m_Database.Store(d);
        }
コード例 #23
0
ファイル: High.cs プロジェクト: zadark/par
        private void CmdTp(String[] words)
        {
            if (words.Length >= 4)
            {
                float x=0;
                float y=0;
                float z=0;
                try
                {
                    x = float.Parse(words[1].Trim());
                    y = float.Parse(words[2].Trim());
                    z = float.Parse(words[3].Trim());
                }
                catch
                {
                    plugin.SayToUser("Usage: \"/tp 100 100 25\" ");
                    return;
                }
                Vector3 go = new Vector3(x,y,z);
                plugin.SayToUser("Tping to " + go.ToString());
                doTp(go);

            }
            else
            {
                plugin.SayToUser("Usage: \"/tp 100 100 25\" ");
            }
        }
コード例 #24
0
        public bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
        {
            //m_log.DebugFormat("[Grid User Service]: SetLastPosition for {0}", userID);
            GridUserData d = m_Database.Get(userID);
            if (d == null)
            {
                d = new GridUserData();
                d.UserID = userID;
            }

            d.Data["LastRegionID"] = regionID.ToString();
            d.Data["LastPosition"] = lastPosition.ToString();
            d.Data["LastLookAt"] = lastLookAt.ToString();

            return m_Database.Store(d);
        }
コード例 #25
0
ファイル: PlayerMover.cs プロジェクト: FalseApple/d3db
        public void MoveTowards(Vector3 destination)
        {
            if (Trinity.Settings.Advanced.DisableAllMovement)
                return;

            Trinity.NavServerReport(true);

            if (!ZetaDia.IsInGame || !ZetaDia.Me.IsValid || ZetaDia.Me.IsDead || ZetaDia.IsLoadingWorld)
            {
                return;
            }

            if (UISafetyCheck())
            {
                return;
            }

            TimeLastUsedPlayerMover = DateTime.UtcNow;
            LastMoveToTarget = destination;

            // Set the public variable

            destination = WarnAndLogLongPath(destination);

            // Store player current position

            // Store distance to current moveto target
            float destinationDistance = MyPosition.Distance2D(destination);

            // Do unstuckery things
            if (Trinity.Settings.Advanced.UnstuckerEnabled)
            {
                // See if we can reset the 10-limit unstuck counter, if >120 seconds since we last generated an unstuck location
                // this is used if we're NOT stuck...
                if (TotalAntiStuckAttempts > 1 && DateTime.UtcNow.Subtract(LastGeneratedStuckPosition).TotalSeconds >= 120)
                {
                    TotalAntiStuckAttempts = 1;
                    TimesReachedStuckPoint = 0;
                    vSafeMovementLocation = Vector3.Zero;
                    NavHelper.UsedStuckSpots = new List<GridPoint>();
                    Logger.Log(TrinityLogLevel.Info, LogCategory.Movement, "Resetting unstuck timers", true);
                }

                // See if we need to, and can, generate unstuck actions
                // check if we're stuck
                //bool isStuck = UnstuckChecker();

                //if (isStuck)
                //{
                //    // Record the time we last apparently couldn't move for a brief period of time
                //    LastRecordedAnyStuck = DateTime.UtcNow;

                //    // See if there's any stuck position to try and navigate to generated by random mover
                //    //vSafeMovementLocation = UnstuckHandler(MyPosition, vMoveToTarget);

                //    if (vSafeMovementLocation == Vector3.Zero)
                //    {
                //        Logger.Log(TrinityLogLevel.Info, LogCategory.Movement, "Unable to find Unstuck point!", vSafeMovementLocation);
                //        return;
                //    }
                //    Logger.Log(TrinityLogLevel.Verbose, LogCategory.Movement, "SafeMovement Location set to {0}", vSafeMovementLocation);

                //}

                // See if we can clear the total unstuckattempts if we haven't been stuck in over 6 minutes.
                if (DateTime.UtcNow.Subtract(LastRecordedAnyStuck).TotalSeconds >= 360)
                {
                    TimesReachedMaxUnstucks = 0;
                }
                // Did we have a safe point already generated (eg from last loop through), if so use it as our current location instead
                if (vSafeMovementLocation != Vector3.Zero)
                {
                    // Set our current movement target to the safe point we generated last cycle
                    destination = vSafeMovementLocation;
                    destinationDistance = MyPosition.Distance2D(destination);
                }
                // Get distance to current destination
                // Remove the stuck position if it's been reached, this bit of code also creates multiple stuck-patterns in an ever increasing amount
                if (vSafeMovementLocation != Vector3.Zero && destinationDistance <= 3f)
                {
                    vSafeMovementLocation = Vector3.Zero;
                    TimesReachedStuckPoint++;

                    // Do we want to immediately generate a 2nd waypoint to "chain" anti-stucks in an ever-increasing path-length?
                    if (TimesReachedStuckPoint <= TotalAntiStuckAttempts)
                    {
                        vSafeMovementLocation = NavHelper.FindSafeZone(true, TotalAntiStuckAttempts, MyPosition);
                        destination = vSafeMovementLocation;
                    }
                    else
                    {
                        if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                            Logger.Log(TrinityLogLevel.Info, LogCategory.UserInformation, "Clearing old route and trying new path find to: " + LastMoveToTarget.ToString());
                        // Reset the path and allow a whole "New" unstuck generation next cycle
                        TimesReachedStuckPoint = 0;
                        // And cancel unstucking for 9 seconds so DB can try to navigate
                        CancelUnstuckerForSeconds = (9 * TotalAntiStuckAttempts);
                        if (CancelUnstuckerForSeconds < 20)
                            CancelUnstuckerForSeconds = 20;
                        LastCancelledUnstucker = DateTime.UtcNow;

                        Navigator.Clear();
                        PlayerMover.NavigateTo(LastMoveToTarget, "original destination");

                        return;
                    }
                }
            }

            if (TargetUtil.AnyMobsInRange(40f))
            {
                // Always move with WW
                if (TryBulKathosWWMovement(destination, destinationDistance))
                    return;
            }

            // don't use special movement within 3 seconds of being stuck
            bool cancelSpecialMovementAfterStuck = DateTime.UtcNow.Subtract(LastGeneratedStuckPosition).TotalMilliseconds > 3000;

            // See if we can use abilities like leap etc. for movement out of combat, but not in town
            if (Trinity.Settings.Combat.Misc.AllowOOCMovement && !Trinity.Player.IsInTown && cancelSpecialMovementAfterStuck && !CombatBase.IsInCombat)
            {
                // Whirlwind for a barb, special context only
                if (Trinity.Settings.Combat.Barbarian.SprintMode != BarbarianSprintMode.CombatOnly &&
                    CacheData.Hotbar.ActivePowers.Contains(SNOPower.Barbarian_Whirlwind) && Trinity.ObjectCache.Any(u => u.IsUnit &&
                    MathUtil.IntersectsPath(u.Position, u.Radius + 5f, Trinity.Player.Position, destination)) &&
                    Trinity.Player.PrimaryResource >= V.F("Barbarian.Whirlwind.MinFury") && !Trinity.IsWaitingForSpecial && V.B("Barbarian.Whirlwind.UseForMovement"))
                {
                    Skills.Barbarian.Whirlwind.Cast(destination);
                    if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                        Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Whirlwind for OOC movement, distance={0:0}", destinationDistance);
                    return;
                }

                if (TryBulKathosWWMovement(destination, destinationDistance))
                    return;

                // Whirlwind to keep Taguk's up
                if (CombatBase.CanCast(SNOPower.Barbarian_Whirlwind) && Trinity.Player.PrimaryResource > 10 && !Sets.BulKathossOath.IsFullyEquipped &&
                    !(CurrentTarget != null && CurrentTarget.Type == TrinityObjectType.Item && CurrentTarget.Distance < 10f) &&
                    Gems.Taeguk.IsEquipped && Skills.Barbarian.Whirlwind.TimeSinceUse > 2500 && Skills.Barbarian.Whirlwind.TimeSinceUse < 3000)
                {
                    Skills.Barbarian.Whirlwind.Cast(destination);
                    if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                        Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Whirlwind for OOC movement, distance={0:0}", destinationDistance);
                    return;
                }

                // Leap movement for a barb
                if (Trinity.Settings.Combat.Barbarian.UseLeapOOC && CacheData.Hotbar.ActivePowers.Contains(SNOPower.Barbarian_Leap) &&
                PowerManager.CanCast(SNOPower.Barbarian_Leap) && !ShrinesInArea(destination))
                {
                    Vector3 vThisTarget = destination;
                    if (destinationDistance > 35f)
                        vThisTarget = MathEx.CalculatePointFrom(destination, MyPosition, 35f);
                    ZetaDia.Me.UsePower(SNOPower.Barbarian_Leap, vThisTarget, Trinity.CurrentWorldDynamicId, -1);
                    SpellHistory.RecordSpell(SNOPower.Barbarian_Leap);
                    if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                        Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Leap for OOC movement, distance={0:0}", destinationDistance);
                    return;
                }
                // Furious Charge movement for a barb
                if (Trinity.Settings.Combat.Barbarian.UseChargeOOC && CacheData.Hotbar.ActivePowers.Contains(SNOPower.Barbarian_FuriousCharge) &&
                    destinationDistance >= 20f && Skills.Barbarian.FuriousCharge.Charges > 0 &&
                    PowerManager.CanCast(SNOPower.Barbarian_FuriousCharge) && !ShrinesInArea(destination))
                {
                    Vector3 vThisTarget = destination;
                    if (destinationDistance > 35f)
                        vThisTarget = MathEx.CalculatePointFrom(destination, MyPosition, 35f);
                    ZetaDia.Me.UsePower(SNOPower.Barbarian_FuriousCharge, vThisTarget, Trinity.CurrentWorldDynamicId, -1);
                    SpellHistory.RecordSpell(SNOPower.Barbarian_FuriousCharge);
                    if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                        Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Furious Charge for OOC movement, distance={0:0}", destinationDistance);
                    return;
                }

                int vaultDelay = Trinity.Settings.Combat.DemonHunter.VaultMovementDelay;
                // DemonHunter Vault
                var vaultBaseCost = Skills.DemonHunter.Vault.Cost*(1 - Trinity.Player.ResourceCostReductionPct);
                var vaultCost = Runes.DemonHunter.Acrobatics.IsActive ? 0 : Runes.DemonHunter.Tumble.IsActive && Skills.DemonHunter.Vault.TimeSinceUse < 6000 ? Math.Round(vaultBaseCost * 0.5) : vaultBaseCost;

                if (CacheData.Hotbar.ActivePowers.Contains(SNOPower.DemonHunter_Vault) && Trinity.Settings.Combat.DemonHunter.VaultMode != DemonHunterVaultMode.CombatOnly &&
                    CombatBase.TimeSincePowerUse(SNOPower.DemonHunter_Vault) > vaultDelay && Trinity.Player.SecondaryResource >= vaultCost && 
                    destinationDistance >= 18f &&
                    PowerManager.CanCast(SNOPower.DemonHunter_Vault) && !ShrinesInArea(destination) &&
                    // Don't Vault into avoidance/monsters if we're kiting
                    (CombatBase.KiteDistance <= 0 || (CombatBase.KiteDistance > 0 &&
                     (!CacheData.TimeBoundAvoidance.Any(a => a.Position.Distance(destination) <= CombatBase.KiteDistance) ||
                     (!CacheData.TimeBoundAvoidance.Any(a => MathEx.IntersectsPath(a.Position, a.Radius, Trinity.Player.Position, destination))) ||
                     !CacheData.MonsterObstacles.Any(a => a.Position.Distance(destination) <= CombatBase.KiteDistance))))
                    )
                {
                    Vector3 vThisTarget = destination;
                    if (destinationDistance > 35f)
                        vThisTarget = MathEx.CalculatePointFrom(destination, MyPosition, 35f);
                    ZetaDia.Me.UsePower(SNOPower.DemonHunter_Vault, vThisTarget, Trinity.CurrentWorldDynamicId, -1);
                    SpellHistory.RecordSpell(SNOPower.DemonHunter_Vault);
                    if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                        Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Vault for OOC movement, distance={0}", destinationDistance);
                    return;
                }

                // DemonHunter Strafe
                if (Skills.DemonHunter.Strafe.IsActive && Trinity.Player.PrimaryResource > 12 && TargetUtil.AnyMobsInRange(30f, false) &&
                    !(CurrentTarget != null && CurrentTarget.Type == TrinityObjectType.Item && CurrentTarget.Distance < 10f) &&
                    // Don't Strafe into avoidance/monsters if we're kiting
                    (CombatBase.KiteDistance <= 0 || (CombatBase.KiteDistance > 0 &&
                     (!CacheData.TimeBoundAvoidance.Any(a => a.Position.Distance(destination) <= CombatBase.KiteDistance) ||
                     (!CacheData.TimeBoundAvoidance.Any(a => MathEx.IntersectsPath(a.Position, a.Radius, Trinity.Player.Position, destination)))))))
                {
                    if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                        Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Strafe for OOC movement, distance={0}", destinationDistance);
                    Skills.DemonHunter.Strafe.Cast(destination);
                }

                // Strafe to keep Taguk's up
                if (CombatBase.CanCast(SNOPower.DemonHunter_Strafe) && Trinity.Player.PrimaryResource > 12 &&
                    Gems.Taeguk.IsEquipped && Skills.DemonHunter.Strafe.TimeSinceUse > 2250 && Skills.DemonHunter.Strafe.TimeSinceUse < 3000)
                {
                    Skills.DemonHunter.Strafe.Cast(destination);
                    return;
                }

                // Tempest rush for a monk
                if (CacheData.Hotbar.ActivePowers.Contains(SNOPower.Monk_TempestRush) &&
                    (Trinity.Settings.Combat.Monk.TROption == TempestRushOption.MovementOnly || Trinity.Settings.Combat.Monk.TROption == TempestRushOption.Always ||
                    (Trinity.Settings.Combat.Monk.TROption == TempestRushOption.TrashOnly && !TargetUtil.AnyElitesInRange(40f))))
                {
                    Vector3 vTargetAimPoint = destination;

                    bool canRayCastTarget = true;

                    vTargetAimPoint = TargetUtil.FindTempestRushTarget();

                    if (!CanChannelTempestRush &&
                        ((Trinity.Player.PrimaryResource >= Trinity.Settings.Combat.Monk.TR_MinSpirit &&
                        destinationDistance >= Trinity.Settings.Combat.Monk.TR_MinDist) ||
                         DateTime.UtcNow.Subtract(CacheData.AbilityLastUsed[SNOPower.Monk_TempestRush]).TotalMilliseconds <= 150) &&
                        canRayCastTarget && PowerManager.CanCast(SNOPower.Monk_TempestRush))
                    {
                        CanChannelTempestRush = true;
                    }
                    else if ((CanChannelTempestRush && (Trinity.Player.PrimaryResource < 10f)) || !canRayCastTarget)
                    {
                        CanChannelTempestRush = false;
                    }

                    double lastUse = DateTime.UtcNow.Subtract(CacheData.AbilityLastUsed[SNOPower.Monk_TempestRush]).TotalMilliseconds;

                    if (CanChannelTempestRush)
                    {
                        if (Trinity.SNOPowerUseTimer(SNOPower.Monk_TempestRush))
                        {
                            LastTempestRushPosition = vTargetAimPoint;

                            ZetaDia.Me.UsePower(SNOPower.Monk_TempestRush, vTargetAimPoint, Trinity.CurrentWorldDynamicId, -1);
                            SpellHistory.RecordSpell(SNOPower.Monk_TempestRush);

                            // simulate movement speed of 30
                            SpeedSensor lastSensor = SpeedSensors.OrderByDescending(s => s.Timestamp).FirstOrDefault();
                            SpeedSensors.Add(new SpeedSensor()
                            {
                                Location = MyPosition,
                                TimeSinceLastMove = new TimeSpan(0, 0, 0, 0, 1000),
                                Distance = 5f,
                                WorldID = Trinity.CurrentWorldDynamicId
                            });

                            if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                                Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Tempest Rush for OOC movement, distance={0:0} spirit={1:0} cd={2} lastUse={3:0} V3={4} vAim={5}",
                                    destinationDistance, Trinity.Player.PrimaryResource, PowerManager.CanCast(SNOPower.Monk_TempestRush), lastUse, destination, vTargetAimPoint);
                            return;
                        }
                        else
                            return;
                    }
                    else
                    {
                        if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                            Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement,
                            "Tempest rush failed!: {0:00.0} / {1} distance: {2:00.0} / {3} Raycast: {4} MS: {5:0.0} lastUse={6:0}",
                            Trinity.Player.PrimaryResource,
                            Trinity.Settings.Combat.Monk.TR_MinSpirit,
                            destinationDistance,
                            Trinity.Settings.Combat.Monk.TR_MinDist,
                            canRayCastTarget,
                            GetMovementSpeed(),
                            lastUse);

                        Trinity.MaintainTempestRush = false;
                    }

                    // Always set this from PlayerMover
                    MonkCombat.LastTempestRushLocation = vTargetAimPoint;

                }

                // Dashing Strike OOC
                if (Trinity.Player.ActorClass == ActorClass.Monk && CombatBase.CanCast(SNOPower.X1_Monk_DashingStrike) && Trinity.Settings.Combat.Monk.UseDashingStrikeOOC &&
                    (destinationDistance > 12f || !NavHelper.CanRayCast(destination) || TargetUtil.UnitsPlayerFacing(15, 90) >=3)
                    && (!(Legendary.Ingeom.IsEquipped && CurrentTarget != null && CurrentTarget.Type == TrinityObjectType.Item) && Skills.Monk.DashingStrike.TimeSinceUse > 200))
                {
                    var charges = Skills.Monk.DashingStrike.Charges;

                    //Logger.LogVerbose("OOC Dash Charges={0}", charges);
                    if (Sets.ThousandStorms.IsSecondBonusActive && !Trinity.ShouldWaitForLootDrop &&
                        (charges > 1 || CacheData.BuffsCache.Instance.HasCastingShrine))
                    {
                        if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                            Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Dashing Strike for OOC movement, distance={0} charges={1}", destinationDistance, Skills.Monk.DashingStrike.Charges);
                        Skills.Monk.DashingStrike.Cast(destination);
                        return;
                    }

                    if (!Sets.ThousandStorms.IsSecondBonusActive && charges > 0 && PowerManager.CanCast(Skills.Monk.DashingStrike.SNOPower) && !Trinity.ShouldWaitForLootDrop)
                    {
                        Skills.Monk.DashingStrike.Cast(destination);
                        if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                            Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Dashing Strike for OOC movement, distance={0}", destinationDistance);
                        return;  
                    }
                }

                // Teleport for a wizard 
                if (!Runes.Wizard.Calamity.IsActive && CombatBase.CanCast(SNOPower.Wizard_Teleport, CombatBase.CanCastFlags.NoTimer) &&
                    CombatBase.TimeSincePowerUse(SNOPower.Wizard_Teleport) > 250 &&
                    destinationDistance >= 10f && !ShrinesInArea(destination))
                {
                    const float maxTeleportRange = 75f;

                    Vector3 vThisTarget = destination;
                    if (destinationDistance > maxTeleportRange)
                        vThisTarget = MathEx.CalculatePointFrom(destination, MyPosition, maxTeleportRange);
                    ZetaDia.Me.UsePower(SNOPower.Wizard_Teleport, vThisTarget, Trinity.CurrentWorldDynamicId, -1);
                    SpellHistory.RecordSpell(SNOPower.Wizard_Teleport);
                    if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                        Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Teleport for OOC movement, distance={0}", destinationDistance);
                    return;
                }

                // Archon Teleport for a wizard 
                if (CacheData.Hotbar.ActivePowers.Contains(SNOPower.Wizard_Archon_Teleport) && destinationDistance >= 10f &&
                PowerManager.CanCast(SNOPower.Wizard_Archon_Teleport) && !ShrinesInArea(destination))
                {
                    Vector3 vThisTarget = destination;
                    if (destinationDistance > 35f)
                        vThisTarget = MathEx.CalculatePointFrom(destination, MyPosition, 35f);
                    ZetaDia.Me.UsePower(SNOPower.Wizard_Archon_Teleport, vThisTarget, Trinity.CurrentWorldDynamicId, -1);
                    SpellHistory.RecordSpell(SNOPower.Wizard_Archon_Teleport);
                    if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                        Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Using Archon Teleport for OOC movement, distance={0}", destinationDistance);
                    return;
                }


            }

            if (MyPosition.Distance2D(destination) > 3f)
            {
                // Default movement
                ZetaDia.Me.UsePower(SNOPower.Walk, destination, Trinity.CurrentWorldDynamicId, -1);

                if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                    Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "PlayerMover Moved to:{0} dir:{1} Speed:{2:0.00} Dist:{3:0} ZDiff:{4:0} CanStand:{5} Raycast:{6}",
                        NavHelper.PrettyPrintVector3(destination), MathUtil.GetHeadingToPoint(destination), MovementSpeed, MyPosition.Distance2D(destination),
                        Math.Abs(MyPosition.Z - destination.Z),
                        Trinity.MainGridProvider.CanStandAt(Trinity.MainGridProvider.WorldToGrid(destination.ToVector2())),
                        !Navigator.Raycast(MyPosition, destination)
                        );

            }
            else
            {
                if (Trinity.Settings.Advanced.LogCategories.HasFlag(LogCategory.Movement))
                    Logger.Log(TrinityLogLevel.Debug, LogCategory.Movement, "Reached MoveTowards Destination {0} Current Speed: {1:0.0}", destination, MovementSpeed);
            }

            //Trinity.IsMoveRequested = false;
        }
コード例 #26
0
        public bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
        {
            m_log.DebugFormat("[GRID USER SERVICE]: User {0} is offline", userID);
            GridUserData d = m_Database.Get(userID);

            if (d == null)
            {
                d = new GridUserData();
                d.UserID = userID;
            }

            d.Data["Online"] = false.ToString();
            d.Data["Logout"] = Util.UnixTimeSinceEpoch().ToString();
            d.Data["LastRegionID"] = regionID.ToString();
            d.Data["LastPosition"] = lastPosition.ToString();
            d.Data["LastLookAt"] = lastLookAt.ToString();

            return m_Database.Store(d);
        }
コード例 #27
0
        /// <summary>
        /// This deals with saving the report into the database.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="regionName"></param>
        /// <param name="abuserID"></param>
        /// <param name="catagory"></param>
        /// <param name="checkflags"></param>
        /// <param name="details"></param>
        /// <param name="objectID"></param>
        /// <param name="position"></param>
        /// <param name="reportType"></param>
        /// <param name="screenshotID"></param>
        /// <param name="summery"></param>
        /// <param name="reporter"></param>
        private void UserReport(IClientAPI client, string regionName,UUID abuserID, byte catagory, byte checkflags, string details, UUID objectID, Vector3 position, byte reportType ,UUID screenshotID, string summery, UUID reporter)
        {
            AbuseReport report = new AbuseReport();
            report.ObjectUUID = objectID;
            report.ObjectPosition = position.ToString();
            report.Active = true;
            report.Checked = false;
            report.Notes = "";
            report.AssignedTo = "No One";
            report.ScreenshotID = screenshotID;
            if (objectID != UUID.Zero)
            {
                SceneObjectPart Object = ((Scene)client.Scene).GetSceneObjectPart(objectID);
                report.ObjectName = Object.Name;
            }
        	else
                report.ObjectName = "";

        	string [] detailssplit = details.Split('\n');

            string AbuseDetails = detailssplit[detailssplit.Length - 1];

            report.AbuseDetails = AbuseDetails;

            report.ReporterName = client.Name;

            string[] findRegion = summery.Split('|');
            report.RegionName = findRegion[1];

            string[] findLocation = summery.Split('(');
            string[] findLocationend = findLocation[1].Split(')');
            report.AbuseLocation = findLocationend[0];

            string[] findCategory = summery.Split('[');
            string[] findCategoryend = findCategory[1].Split(']');
            report.Category = findCategoryend[0];

            string[] findAbuserName = summery.Split('{');
            string[] findAbuserNameend = findAbuserName[1].Split('}');
            report.AbuserName = findAbuserNameend[0];

            string[] findSummary = summery.Split('\"');

            string abuseSummary = findSummary[1];
            if (findSummary.Length != 0)
            {
                abuseSummary = findSummary[1];
            }

            report.AbuseSummary = abuseSummary;


            report.Number = (-1);

            EstateSettings ES = client.Scene.RegionInfo.EstateSettings;
            //If the abuse email is set up and the email module is available, send the email
            if (ES.AbuseEmailToEstateOwner && ES.AbuseEmail != "")
            {
                IEmailModule Email = m_SceneList[0].RequestModuleInterface<IEmailModule>();
                if(Email != null)
                    Email.SendEmail(UUID.Zero, ES.AbuseEmail, "Abuse Report", "This abuse report was submitted by " +
                        report.ReporterName + " against " + report.AbuserName + " at " + report.AbuseLocation + " in your region " + report.RegionName +
                        ". Summary: " + report.AbuseSummary + ". Details: " + report.AbuseDetails + ".");
            }
            //Tell the DB about it
            IAbuseReportsConnector conn = Aurora.DataManager.DataManager.RequestPlugin<IAbuseReportsConnector>();
            if(conn != null)
                conn.AddAbuseReport(report);
        }
コード例 #28
0
        protected bool Set(Dictionary<string, object> sendData, string userID, UUID regionID, Vector3 position, Vector3 lookAt)
        {
            sendData["UserID"] = userID;
            sendData["RegionID"] = regionID.ToString();
            sendData["Position"] = position.ToString();
            sendData["LookAt"] = lookAt.ToString();

            string reqString = ServerUtils.BuildQueryString(sendData);
            string uri = m_ServerURI + "/griduser";
            // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString);
            try
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        uri,
                        reqString,
                        m_Auth);
                if (reply != string.Empty)
                {
                    Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                    if (replyData.ContainsKey("result"))
                    {
                        if (replyData["result"].ToString().ToLower() == "success")
                            return true;
                        else
                            return false;
                    }
                    else
                        m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition reply data does not contain result field");

                }
                else
                    m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition received empty reply");
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server at {0}: {1}", uri, e.Message);
            }

            return false;
        }
コード例 #29
0
        /// <summary>
        ///
        /// </summary>
        public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall)
        {
            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateObject start");

            string uri = destination.ServerURI + ObjectPath() + sog.UUID + "/";

            try
            {
                OSDMap args = new OSDMap(2);

                args["sog"] = OSD.FromString(sog.ToXml2());
                args["extra"] = OSD.FromString(sog.ExtraToXmlString());
                args["modified"] = OSD.FromBoolean(sog.HasGroupChanged);
                args["new_position"] = newPosition.ToString();

                string state = sog.GetStateSnapshot();
                if (state.Length > 0)
                    args["state"] = OSD.FromString(state);

                // Add the input general arguments
                args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
                args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
                args["destination_name"] = OSD.FromString(destination.RegionName);
                args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());

                WebUtil.PostToService(uri, args, 40000);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] CreateObject failed with exception; {0}",e.ToString());
            }

            return true;
        }
コード例 #30
0
        public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache, out List<List<Vector3>> hulls, out List<Vector3> boundingHull)
        {
#if SPAM
            m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
#endif

            Mesh mesh = null;
            ulong key = 0;

            // If this mesh has been created already, return it instead of creating another copy
            // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
            m_uniqueMeshesRwLock.AcquireReaderLock(-1);
            try
            {
                if (shouldCache)
                {
                    key = primShape.GetMeshKey(size, lod);
                    if (m_uniqueMeshes.TryGetValue(key, out mesh))
                    {
                        m_uniqueMeshesBoundingHulls.TryGetValue(key, out boundingHull);
                        m_uniqueMeshesHulls.TryGetValue(key, out hulls);
                        return mesh;
                    }
                }

                LockCookie lc = m_uniqueMeshesRwLock.UpgradeToWriterLock(-1);
                try
                {
                    /* recheck since we allow a lot of threading here */
                    if (shouldCache)
                    {
                        if (m_uniqueMeshes.TryGetValue(key, out mesh))
                        {
                            m_uniqueMeshesBoundingHulls.TryGetValue(key, out boundingHull);
                            m_uniqueMeshesHulls.TryGetValue(key, out hulls);
                            return mesh;
                        }
                    }
                    if (size.X < 0.01f) size.X = 0.01f;
                    if (size.Y < 0.01f) size.Y = 0.01f;
                    if (size.Z < 0.01f) size.Z = 0.01f;

                    List<List<Vector3>> inhulls;
                    List<Vector3> inboundingHull;
                    mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod, out inhulls, out inboundingHull);

                    if (inhulls != null)
                    {
                        hulls = new List<List<Vector3>>();
                        foreach (var hull in inhulls)
                        {
                            List<Vector3> verts = new List<Vector3>();
                            foreach (var vert in hull)
                                verts.Add(vert * size);
                            hulls.Add(verts);
                        }
                    }
                    else
                    {
                        hulls = null;
                    }

                    if (inboundingHull != null)
                    {
                        boundingHull = new List<Vector3>();
                        foreach (var vert in inboundingHull)
                            boundingHull.Add(vert * size);
                    }
                    else
                    {
                        boundingHull = null;
                    }

                    if (mesh != null)
                    {
                        if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
                        {
#if SPAM
                            m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " + 
                                    minSizeForComplexMesh.ToString() + " - creating simple bounding box");
#endif
                            mesh = CreateBoundingBoxMesh(mesh);
                            mesh.DumpRaw(baseDir, primName, "Z extruded");
                        }

                        // trim the vertex and triangle lists to free up memory
                        mesh.TrimExcess();

                        if (shouldCache)
                        {
                            m_uniqueMeshes.Add(key, mesh);
                            m_uniqueMeshesHulls.Add(key, hulls);
                            m_uniqueMeshesBoundingHulls.Add(key, boundingHull);
                        }
                    }
                }
                finally
                {
                    m_uniqueMeshesRwLock.DowngradeFromWriterLock(ref lc);
                }
            }
            finally
            {
                m_uniqueMeshesRwLock.ReleaseReaderLock();
            }
            return mesh;
        }