Esempio n. 1
0
 public AgentCutaway(AgentType agTy, Int32 ID, Coordinates pos_, AgentState state_)
 {
     type = agTy;
     agentID = ID;
     pos = pos_;
     state = state_;
 }
Esempio n. 2
0
 public Action Approach()
 {
     //!!
     current_agent_state = AgentState.Approach;
     debug.Log (showDebug, 4365623, "Approach");
     yield return NodeResult.Success;
 }
Esempio n. 3
0
        public void CanMove()
        {
            var state = new AgentState();
            var agent = Agent.Builder.Build(state).Build(new TestIdResolver());

            var structure = new Manufactory();
            agent.MoveInto(structure);
        }
Esempio n. 4
0
 // Use this for initialization
 void Start()
 {
     state = new AgentState(Random.Range(-1f, 1f));
     name += " (" + ((decimal)state.opinion).ToString("F") + ")";
     GetComponentInChildren<SpriteRenderer>().color = Color.Lerp(Color.black, Color.blue, (state.opinion + 1f) / 2f);
     AgentProximityDetector.inst.Add(this);
     StartCoroutine(BehaviourCycle());
 }
Esempio n. 5
0
    public Action Attack()
    {
        //!!
        current_agent_state = AgentState.Attack;
        core.Stop ();

        debug.Log (showDebug, 20, "Attack");

        yield return NodeResult.Success;
    }
Esempio n. 6
0
        public void CantHireAgentEmployedBySomeoneElse()
        {
            var state = new AgentState();
            var agent = Agent.Builder.Build(state).Build(new TestIdResolver());

            var c1 = new Corporation();
            c1.Hire(agent);

            var c2 = new Corporation();
            Should.Throw<ArgumentException>(() => c2.Hire(agent));
        }
Esempio n. 7
0
        public void CanBeHired()
        {
            var state = new AgentState();
            var agent = Agent.Builder.Build(state).Build(new TestIdResolver());

            var corporation = new Corporation();
            corporation.Hire(agent);

            agent.Corporation.ShouldBe(corporation);
            corporation.Employees.ShouldContain(agent);
        }
Esempio n. 8
0
        public void CreateAgent()
        {
            var state = new AgentState();

            var agent = Agent.Builder.Build(state).Build(new TestIdResolver());
            agent.ObjectType.ShouldBe(ObjectType.Agent);
            agent.Corporation.ShouldBe(null);
            agent.Location.ShouldBe(null);

            agent.Statistics.Intelligence.CurrentValue.ShouldBe(0);

            agent.Skills[SkillCode.SpaceshipCommand].Level.ShouldBe(0);
            agent.Implants[AgentStatistic.Intelligence].Value.ShouldBe(0);
        }
Esempio n. 9
0
 public AgentInfo(Color colour_, float radius_, AgentType agType_, 
                 Int32 ID_, AgentState state_, float communicateRad_,
                 Coordinates coord_, float speed_, float viewRadius_)
 {
     agentID = ID_;
     agentColor = colour_;
     agentRadius = radius_;
     agentType = agType_;
     agentState = state_;
     communicteRadius = communicateRad_;
     coord = coord_;
     speed = speed_;
     viewRadius = viewRadius_;
 }
Esempio n. 10
0
            public static ObjectBuilder<Agent> Build(AgentState state)
            {
                var agent = new Agent
                {
                    Id = state.ObjectId,
                    Name = state.Name,
                    Statistics = new AgentStatistics(state.Statistics.Select(Build)),
                    Implants = new ImplantCollection(state.Implants)
                };

                return new ObjectBuilder<Agent>(agent)
                    .Resolve((resolver, target) => target.Location = resolver.Get<ILocation>(state.Location))
                    .Resolve((resolver, target) => target.Skills = new SkillCollection(state.Skills.Select(skill => Build(resolver, skill))))
                    .Resolve(ApplyStatDeltas);
            }
Esempio n. 11
0
        public ItemEnhancement2Test()
        {
            var sheets = TableSheetsImporter.ImportSheets();

            _random      = new ItemEnhancementTest.TestRandom();
            _tableSheets = new TableSheets(sheets);
            var privateKey = new PrivateKey();

            _agentAddress = privateKey.PublicKey.ToAddress();
            var agentState = new AgentState(_agentAddress);

            _avatarAddress = _agentAddress.Derive("avatar");
            _avatarState   = new AvatarState(
                _avatarAddress,
                _agentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                default
                );

            agentState.avatarAddresses.Add(0, _avatarAddress);

            _currency = new Currency("NCG", 2, minter: null);
            var gold = new GoldCurrencyState(_currency);

            _slotAddress =
                _avatarAddress.Derive(string.Format(CultureInfo.InvariantCulture, CombinationSlotState.DeriveFormat, 0));

            _initialState = new State()
                            .SetState(_agentAddress, agentState.Serialize())
                            .SetState(_avatarAddress, _avatarState.Serialize())
                            .SetState(_slotAddress, new CombinationSlotState(_slotAddress, 0).Serialize())
                            .SetState(GoldCurrencyState.Address, gold.Serialize())
                            .MintAsset(GoldCurrencyState.Address, gold.Currency * 100000000000)
                            .TransferAsset(Addresses.GoldCurrency, _agentAddress, gold.Currency * 1000);

            Assert.Equal(gold.Currency * 99999999000, _initialState.GetBalance(Addresses.GoldCurrency, gold.Currency));
            Assert.Equal(gold.Currency * 1000, _initialState.GetBalance(_agentAddress, gold.Currency));

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState.SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Esempio n. 12
0
        public async Task ReportAsync(CancellationToken token, ModuleSet moduleSet, IRuntimeInfo runtimeInfo, long version, Option <DeploymentStatus> updatedStatus)
        {
            Option <AgentState> agentState = Option.None <AgentState>();

            using (await this.sync.LockAsync(token))
            {
                try
                {
                    agentState = await this.GetReportedStateAsync();

                    // if there is no reported JSON to compare against, then we don't do anything
                    // because this typically means that we never connected to IoT Hub before and
                    // we have no connection yet
                    await agentState.ForEachAsync(
                        async rs =>
                    {
                        AgentState currentState = this.BuildCurrentState(moduleSet, runtimeInfo, version > 0 ? version : rs.LastDesiredVersion, updatedStatus.GetOrElse(rs.LastDesiredStatus));
                        // diff, prepare patch and report
                        await this.DiffAndReportAsync(currentState, rs);
                    });
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    Events.BuildStateFailed(ex);

                    // something failed during the patch generation process; we do best effort
                    // error reporting by sending a minimal patch with just the error information
                    JObject patch = JObject.FromObject(
                        new
                    {
                        lastDesiredVersion = agentState.Map(rs => rs.LastDesiredVersion).GetOrElse(0),
                        lastDesiredStatus  = new DeploymentStatus(DeploymentStatusCode.Failed, ex.Message)
                    });

                    try
                    {
                        await this.edgeAgentConnection.UpdateReportedPropertiesAsync(new TwinCollection(patch.ToString()));
                    }
                    catch (Exception ex2) when(!ex2.IsFatal())
                    {
                        Events.UpdateErrorInfoFailed(ex2);
                    }
                }
            }
        }
        public void Should_NotUpdateAgentStateReportDate_When_AgentStateWasAggregatedButAggregatedStateWasNotProcessed()
        {
            // Arrange
            const int agentId = 1;

            var createDate = Now - TimeSpan.FromMilliseconds(MonitoringSettings.AgentActivePeriod - 1000);

            var agentStateCreateDates = new[]
            {
                new AgentStateCreateDate
                {
                    AgentId    = agentId,
                    CreateDate = createDate
                },
            };

            _unitOfWork.Setup(x => x.AgentStateRepository.GetLastAgentStateCreateDates(Now))
            .Returns(agentStateCreateDates);

            var errors1 = new[]
            {
                new Error {
                    Message = "error11"
                },
                new Error {
                    Message = "error12"
                },
            };

            var agentState1 = new AgentState
            {
                AgentId    = agentId,
                CreateDate = createDate,
                Errors     = errors1
            };

            _unitOfWork.Setup(x => x.AgentStateRepository.Get(It.IsAny <Expression <Func <AgentState, bool> > >(), null,
                                                              MonitoringContext.ErrorsProperty)).Returns(new[] { agentState1 });

            // Act
            var result = _aggregationService.Aggregate(Now);

            // Assert
            Assert.IsNull(agentState1.ReportDate);
        }
Esempio n. 14
0
    public void ResetValues()
    {
        // Reset AI values.
        m_health            = m_maxHealth;
        m_totalDamageTaken  = 0;
        m_totalDamageHealed = 0;
        m_bulletAmount      = m_bulletMax;
        m_navAgent.ResetPath();
        m_myState         = AgentState.patroling;
        m_healthPackFound = false;
        m_reloading       = false;
        m_tookDamage      = false;
        m_enemyLost       = true;
        // Also reset physics of rigidbody.
        Rigidbody body = GetComponent <Rigidbody>();

        body.velocity = body.angularVelocity = Vector3.zero;
    }
Esempio n. 15
0
    void UpdateHp(int inputDmg)
    {
        if (_curState == AgentState.dead)
        {
            return;
        }

        if (_hp > inputDmg)
        {
            _hp -= inputDmg;
        }

        else
        {
            _hp       = 0;
            _curState = AgentState.dead;
        }
    }
Esempio n. 16
0
 public static void Postfix(BattleAgentLogic __instance, Agent affectedAgent,
                            Agent affectorAgent,
                            AgentState agentState,
                            KillingBlow killingBlow)
 {
     if (affectedAgent != MissionSpawnAgentPatch.heroAgent)
     {
         AgentInitializeMissionEquipmentPatch.AgentOriginalWeaponSpeed.Remove(affectedAgent);
         MissionOnTickPatch.AgentRecoveryTimers.Remove(affectedAgent);
         MissionSpawnAgentPatch.CurrentStaminaPerAgent.Remove(affectedAgent);
         MissionSpawnAgentPatch.MaxStaminaPerAgent.Remove(affectedAgent);
     }
     else
     {
         // need to reset weapons' speeds on agent death
         MissionOnTickPatch.ChangeWeaponSpeedsHandler(affectedAgent, 1.0, false);
     }
 }
Esempio n. 17
0
        public AgentBase(Action <IAgent <TAction, TGoal>, IMaps <TAction, TGoal> > onInitGameData)
        {
            _onInitGameData       = onInitGameData;
            DebugMsgBase.Instance = InitDebugMsg();
            AgentState            = InitAgentState();
            Maps            = InitMaps();
            ActionManager   = InitActionManager();
            GoalManager     = InitGoalManager();
            _triggerManager = InitTriggerManager();
            Performer       = new Performer <TAction, TGoal>(this);

            AgentState.AddStateChangeListener(UpdateData);

            JudgeException(Maps, "Maps");
            JudgeException(ActionManager, "ActionManager");
            JudgeException(GoalManager, "GoalManager");
            JudgeException(_triggerManager, "_triggerManager");
        }
Esempio n. 18
0
    public void PositionSize(PendingOrder pendingorder, AgentState state)
    {
        //Check if this is for entry
        if (state != AgentState.EntryLong && state != AgentState.EntryShort)
        {
            return;
        }

        //Get current stop order
        var currentstop = Agent.PendingOrders
                          .Where(x => !x.IsCancelled)
                          .FirstOrDefault(x => x.Order.Symbol == pendingorder.Order.Symbol &&
                                          (x.Order.Type == OrderType.Stop || x.Order.Type == OrderType.StopLimit));

        //Check if we have a stop order, cannot determine the risk without it
        if (currentstop == null || !ATR.IsReady)
        {
            return;
        }

        //Get the current close
        var currentprice = CurrentBar[pendingorder.Order.Symbol].Close;

        //Get the current risk (delta price)/Leverage
        var risk = (Math.Abs(currentprice - currentstop.Order.StopPrice) / pendingorder.Order.Security.PipSize) * (pendingorder.Order.Security.PipValue / 100);

        //Calculate the amount of lots ((CE * %PE) / SV)
        int     microlots = Convert.ToInt32(((pendingorder.Account.Equity * (FixedPercentage * .0001M)) / (ATR.Result[0] / pendingorder.Order.Security.PipSize)));
        decimal quantity  = microlots * .01M;

        //Set the stop order on our size
        currentstop.Update(x => x.Quantity = quantity);

        //Set our pending order on our size (check if we need to reverse the current order)
        var currentpos = Agent.Positions[pendingorder.Order.Security];

        if (!currentpos.IsFlat)
        {
            quantity += Math.Abs(currentpos.Quantity);
        }

        //Update pending order
        pendingorder.Update(x => x.Quantity = quantity);
    }
Esempio n. 19
0
        public MimisbrunnrBattle6Test()
        {
            var sheets = TableSheetsImporter.ImportSheets();

            _tableSheets = new TableSheets(sheets);

            var privateKey = new PrivateKey();

            _agentAddress = privateKey.PublicKey.ToAddress();
            var agentState = new AgentState(_agentAddress);

            _avatarAddress = _agentAddress.Derive("avatar");
            var gameConfigState = new GameConfigState(sheets[nameof(GameConfigSheet)]);

            _rankingMapAddress = _avatarAddress.Derive("ranking_map");
            var avatarState = new AvatarState(
                _avatarAddress,
                _agentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                gameConfigState,
                _rankingMapAddress
                )
            {
                level = 400,
            };

            agentState.avatarAddresses.Add(0, _avatarAddress);

            _initialState = new State()
                            .SetState(_agentAddress, agentState.Serialize())
                            .SetState(_avatarAddress, avatarState.Serialize())
                            .SetState(_avatarAddress.Derive(LegacyInventoryKey), avatarState.inventory.Serialize())
                            .SetState(_avatarAddress.Derive(LegacyWorldInformationKey), avatarState.worldInformation.Serialize())
                            .SetState(_avatarAddress.Derive(LegacyQuestListKey), avatarState.questList.Serialize())
                            .SetState(_rankingMapAddress, new RankingMapState(_rankingMapAddress).Serialize())
                            .SetState(gameConfigState.address, gameConfigState.Serialize());

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState
                                .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Esempio n. 20
0
    void Start()
    {
        float diverseRate;

        diverseRate   = 1 + Random.Range(-Manager.AgentDiverseRate, Manager.AgentDiverseRate);
        WanderSpeed   = Manager.AgentWanderSpeed * diverseRate;
        diverseRate   = 1 + Random.Range(-Manager.AgentDiverseRate, Manager.AgentDiverseRate);
        ViewRange     = Manager.AgentViewRange * diverseRate;
        diverseRate   = 1 + Random.Range(-Manager.AgentDiverseRate, Manager.AgentDiverseRate);
        breedCooldown = Manager.AgentBreedCooldown * diverseRate;

        spawner       = GameObject.Find("AgentSpawner").transform;
        isAbleToBreed = false;
        breedTimer    = 0;
        MaxHealth     = (0.15f * WanderSpeed * WanderSpeed + 1.15f * ViewRange) * Manager.StartLifespan;
        health        = MaxHealth;
        state         = AgentState.Wander;
        homeland      = Manager.RandomWorldPosition();
    }
Esempio n. 21
0
        //TODO benchmark in reference parameters


        public static Vector3 CalculateNextVelocity(AgentState agent, AgentEnvironmentModel model)
        {
            Vector3 drivingForce             = DrivingForce(agent);
            Vector3 interactionForce         = InteractionForce(agent, model.Neighbours);
            Vector3 obstacleInteractionForce = ObstacleInteractionForce(agent, model.Walls);

            interactionForce.y         = 0; //Assumes all agents are vertically oriented
            obstacleInteractionForce.y = 0; //Assumes all walls are vertical oriented (perhaps a less fair assumption than the latter)

#if UnityEngine
            Debug.DrawLine(agent.position, agent.position + drivingForce, Color.red);
            Debug.DrawLine(agent.position, agent.position + interactionForce, Color.cyan);
            Debug.DrawLine(agent.position, agent.position + obstacleInteractionForce, Color.yellow);
#endif

            return(drivingForce +
                   interactionForce +
                   obstacleInteractionForce);
        }
Esempio n. 22
0
        public DailyReward5Test(ITestOutputHelper outputHelper)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.TestOutput(outputHelper)
                         .CreateLogger();

            _initialState = new State();
            var sheets = TableSheetsImporter.ImportSheets();

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState
                                .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }

            var tableSheets     = new TableSheets(sheets);
            var gameConfigState = new GameConfigState();

            gameConfigState.Set(tableSheets.GameConfigSheet);
            _agentAddress = new PrivateKey().ToAddress();
            var agentState = new AgentState(_agentAddress);

            _avatarAddress = new PrivateKey().ToAddress();
            var rankingMapAddress = new PrivateKey().ToAddress();
            var avatarState       = new AvatarState(
                _avatarAddress,
                _agentAddress,
                0,
                tableSheets.GetAvatarSheets(),
                gameConfigState,
                rankingMapAddress)
            {
                actionPoint = 0,
            };

            agentState.avatarAddresses[0] = _avatarAddress;

            _initialState = _initialState
                            .SetState(Addresses.GameConfig, gameConfigState.Serialize())
                            .SetState(_agentAddress, agentState.Serialize())
                            .SetState(_avatarAddress, avatarState.Serialize());
        }
Esempio n. 23
0
    public void handleActions()
    {
        Action                       currentAction;
        MailBox <Action>             raq    = simulationState.readyActionQueue;
        Dictionary <int, AgentState> agents = simulationState.agents;

        while (raq.NotEmpty())
        {
            // get action from the ready action queue
            // if the action is executable,
            //     put it in unity's action queue
            //     let the agent know that its action was executable
            // else
            //     let the agent know that its action was not executable
            //simulationState.stdout.Send(String.Format("AH: there are actions to process...\n"));
            if (raq.NBRecv(out currentAction))
            {
                int agentID = currentAction.agentID;
                try {
                    AgentState agentState = agents[agentID];
                    agentState.lastAction     = currentAction;
                    agentState.lastActionTime = SimulationState.getInstance().getTime();
                    if (simulationState.executableAction(currentAction))
                    {
                        //simulationState.stdout.Send(String.Format("AH: the action is executable.\n"));
                        //agents[agentID].results.Send(ActionResult.success);
                        agents[agentID].lastActionResult = ActionResult.success;
                        simulationState.applyActionEffects(currentAction);
                    }
                    else
                    {
                        //simulationState.stdout.Send(String.Format("AH: the action is not executable.\n"));
                        agents[agentID].results.Send(ActionResult.failure);
                        agents[agentID].lastActionResult = ActionResult.failure;
                    }
                }
                catch (System.Collections.Generic.KeyNotFoundException e) {
                    simulationState.stdout.Send(String.Format("AH: Error: agent id {0} not present in agent database.\n", agentID));
                    Debug.LogError(e.ToString());
                }
            }
        }
    }
Esempio n. 24
0
        public static void AddAndUnlockOption(
            AgentState agentState,
            Equipment equipment,
            IRandom random,
            EquipmentItemSubRecipeSheetV2.Row subRecipe,
            EquipmentItemOptionSheet optionSheet,
            SkillSheet skillSheet
            )
        {
            foreach (var optionInfo in subRecipe.Options.OrderByDescending(e => e.Ratio))
            {
                if (!optionSheet.TryGetValue(optionInfo.Id, out var optionRow))
                {
                    continue;
                }

                var value = random.Next(1, GameConfig.MaximumProbability + 1);
                if (value > optionInfo.Ratio)
                {
                    continue;
                }

                if (optionRow.StatType != StatType.NONE)
                {
                    var statMap = CombinationEquipment5.GetStat(optionRow, random);
                    equipment.StatsMap.AddStatAdditionalValue(statMap.StatType, statMap.Value);
                    equipment.Update(equipment.RequiredBlockIndex + optionInfo.RequiredBlockIndex);
                    equipment.optionCountFromCombination++;
                    agentState.unlockedOptions.Add(optionRow.Id);
                }
                else
                {
                    var skill = CombinationEquipment5.GetSkill(optionRow, skillSheet, random);
                    if (!(skill is null))
                    {
                        equipment.Skills.Add(skill);
                        equipment.Update(equipment.RequiredBlockIndex + optionInfo.RequiredBlockIndex);
                        equipment.optionCountFromCombination++;
                        agentState.unlockedOptions.Add(optionRow.Id);
                    }
                }
            }
        }
Esempio n. 25
0
        public ClaimMonsterCollectionReward2Test(ITestOutputHelper outputHelper)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.TestOutput(outputHelper)
                         .CreateLogger();

            _signer        = default;
            _avatarAddress = _signer.Derive("avatar");
            _state         = new State();
            Dictionary <string, string> sheets = TableSheetsImporter.ImportSheets();

            _tableSheets = new TableSheets(sheets);
            var rankingMapAddress = new PrivateKey().ToAddress();
            var agentState        = new AgentState(_signer);
            var avatarState       = new AvatarState(
                _avatarAddress,
                _signer,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                rankingMapAddress);

            agentState.avatarAddresses[0] = _avatarAddress;

            var currency          = new Currency("NCG", 2, minters: null);
            var goldCurrencyState = new GoldCurrencyState(currency);

            _state = _state
                     .SetState(_signer, agentState.Serialize())
                     .SetState(_avatarAddress.Derive(LegacyInventoryKey), avatarState.inventory.Serialize())
                     .SetState(_avatarAddress.Derive(LegacyWorldInformationKey), avatarState.worldInformation.Serialize())
                     .SetState(_avatarAddress.Derive(LegacyQuestListKey), avatarState.questList.Serialize())
                     .SetState(_avatarAddress, avatarState.SerializeV2())
                     .SetState(Addresses.GoldCurrency, goldCurrencyState.Serialize());

            foreach ((string key, string value) in sheets)
            {
                _state = _state
                         .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Esempio n. 26
0
        public bool SetAgentLineControl(string extension, string agentid, AgentState state, CallCenterCall ccc)
        {
            bool success = false;

            try
            {
                if (Global.cacheMgr != null)
                {
                    log.Debug("Adding or update agentlinecontrol: " + extension + state.ToString());
                    if (Global.cacheMgr.Contains(extension) && Global.cacheMgr.GetData(extension) is AgentLineControl)
                    {
                        AgentLineControl currentAgentLineControl = ((AgentLineControl)Global.cacheMgr.GetData(extension));
                        currentAgentLineControl.agentstate     = state;
                        currentAgentLineControl.callcentercall = ccc;
                        Global.cacheMgr.Add(extension, currentAgentLineControl);
                    }
                    else
                    {
                        AgentLineControl alc = new AgentLineControl();
                        LineControl      lc  = ((LineControl)Global.cacheMgr.GetData(extension));
                        alc.agentid               = agentid;
                        alc.agentstate            = state;
                        alc.callcentercall        = ccc;
                        alc.directoryNumber       = lc.directoryNumber;
                        alc.doNotDisturb          = lc.doNotDisturb;
                        alc.forward               = lc.forward;
                        alc.lineControlConnection = lc.lineControlConnection;
                        alc.mwiOn     = lc.mwiOn;
                        alc.status    = lc.status;
                        alc.monitored = lc.monitored;
                        Global.cacheMgr.Add(extension, alc);
                    }
                    success = true;
                }
                return(success);
            }
            catch (Exception e)
            {
                log.Error("Error while setting agentlinecontrol : " + e.Message);
                return(success);
            }
        }
Esempio n. 27
0
        public void Execute()
        {
            var privateKey   = new PrivateKey();
            var agentAddress = privateKey.PublicKey.ToAddress();
            var agentState   = new AgentState(agentAddress);

            var tableSheets   = TableSheets.FromTableSheetsState(_tableSheetsState);
            var avatarAddress = agentAddress.Derive("avatar");
            var avatarState   = new AvatarState(
                avatarAddress,
                agentAddress,
                0,
                tableSheets,
                new GameConfigState()
                );

            agentState.avatarAddresses.Add(0, avatarAddress);

            var row        = tableSheets.EquipmentItemSheet.Values.First();
            var equipment  = (Equipment)ItemFactory.CreateItemUsable(row, default, 0, 0);
    private void OnCollisionEnter(Collision collision)
    {
        State = AgentState.Landed;

        EventHandler <AgentLocation> handler = AgentLanded;

        AgentLocation locn = new AgentLocation();

        locn.Location = transform.position;


        //If we hit water, we landed.
        if (collision.gameObject.tag == "Water")
        {
            if (handler != null)
            {
                handler(this, locn);
            }
        }
    }
Esempio n. 29
0
 // Avoid bullets by moving from side to side.
 public bool Kite()
 {
     if (!m_navAgent.hasPath || m_myState == AgentState.patroling)
     {
         CancelPath();
         m_myState = AgentState.kiting;
         // Randomize which direction to kite.
         float randomSign  = Mathf.Sign(Random.Range(-1.0f, 1.0f));
         float randomAngle = Random.Range(45.0f, 180.0f);
         // Calculate kiting position
         Vector3    kiteVec = transform.position - (Quaternion.AngleAxis(randomSign * randomAngle, Vector3.up) * transform.forward) * 3.0f;
         NavMeshHit hit;
         // Find suitable navmesh point
         NavMesh.SamplePosition(kiteVec, out hit, Mathf.Infinity, NavMesh.AllAreas);
         // Move towards that point.
         WalkTowards(hit.position);
         return(true);
     }
     return(false);
 }
Esempio n. 30
0
        private void UpdateAction()
        {
            const int attackScalar = 4;

            _agentStatus = AgentStateUtility.RandomFrom(ValidAgentStates);
            _agentClock  = ActionDelay;

            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (_agentStatus)
            {
            case AgentState.Moving:
                _currentDirection = DirectionUtility.RandomVerticalDirection();
                break;

            case AgentState.Attacking:
                _agentClock *= attackScalar;
                _sprite      = EnemySpriteFactory.Instance.CreateAquamentusFiring();
                break;
            }
        }
Esempio n. 31
0
        public void TestUpdateShort()
        {
            var linearPath = new LinearPath(Vector3.zero, Vector3.forward);
            var paths      = new List <PathDescription>()
            {
                new PathDescription(new DummyAIPath(linearPath), 0, 1)
            };

            var state = new AgentState(0, 0, null);

            var agent = new DummyStateAgent(state);

            GetSpeedDelegate getSpeed = s => 1.0f;

            AgentState newState;

            state.Update(agent, 1 / 60.0f, getSpeed, paths, out newState);

            Assert.AreEqual(1 / 60.0f, newState.Progress, 0.000001f);
        }
Esempio n. 32
0
        public void Execute()
        {
            var privateKey   = new PrivateKey();
            var agentAddress = privateKey.PublicKey.ToAddress();
            var agent        = new AgentState(agentAddress);

            var avatarAddress = agentAddress.Derive("avatar");
            var avatar        = new AvatarState(avatarAddress, agentAddress, 0, _tableSheets, new GameConfigState());

            agent.avatarAddresses.Add(0, avatarAddress);

            var weekly = new WeeklyArenaState(default(Address));

            weekly.Set(avatar, _tableSheets.CharacterSheet);
            weekly.End();

            var gold = new GoldCurrencyState(new Currency("NCG", minter: null));

            var state = new State(ImmutableDictionary <Address, IValue> .Empty
                                  .Add(default, weekly.Serialize())
Esempio n. 33
0
        /// 设置状态条
        /// <summary>
        /// 设置状态条
        /// </summary>
        /// <param name="cur"></param>
        private void ShowStatusTool(PhoneStatus cur, AgentState agentState)
        {
            //主叫被叫还原
            SetZhujiaoDn("");
            SetBeijiaoDn("");
            //计时通话时长
            if (agentState == AgentState.AS9_通话中 && GetTimeForCall() == false)
            {
                StartTimeForCall();
            }
            //结束计时
            if (agentState == AgentState.AS5_话后 && GetTimeForCall())
            {
                EndTimeForCall();
            }

            if (agentState == AgentState.AS9_通话中 || agentState == AgentState.AS8_振铃 || agentState == AgentState.AS5_话后)
            {
                //拨号时,其实是在呼叫分机,所以实际的主被叫不对
                if (cur == PhoneStatus.PS14_呼出拨号中)
                {
                    SetZhujiaoDn(LoginUser.ExtensionNum);
                    //处理号码
                    SetBeijiaoDn(HollyContactHelper.Instance.HaoMaProcess(OutCallNumber));
                }
                else
                {
                    //通话中,设置主叫和被叫
                    SetZhujiaoDn(HollyContactHelper.Instance.GetZhujiaoPhone());
                    SetBeijiaoDn(HollyContactHelper.Instance.GetBeijiaoPhone());
                }
            }
            else
            {
                RestTimeForCall();
            }

            //设置其他文字
            SetCTIStatus(cur.ToString().Substring(5));
            SetLuodiNum(HollyContactHelper.Instance.GetLuodiNum(), HollyContactHelper.Instance.GetSkillGroupName());
        }
Esempio n. 34
0
        public MimisbrunnrBattle2Test()
        {
            var sheets = TableSheetsImporter.ImportSheets();

            _tableSheets = new TableSheets(sheets);

            var privateKey = new PrivateKey();

            _agentAddress = privateKey.PublicKey.ToAddress();
            var agentState = new AgentState(_agentAddress);

            _avatarAddress     = _agentAddress.Derive("avatar");
            _rankingMapAddress = _avatarAddress.Derive("ranking_map");
            var avatarState = new AvatarState(
                _avatarAddress,
                _agentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(sheets[nameof(GameConfigSheet)]),
                _rankingMapAddress
                )
            {
                level = 400,
            };

            agentState.avatarAddresses.Add(0, _avatarAddress);

            _weeklyArenaState = new WeeklyArenaState(0);

            _initialState = new State()
                            .SetState(_weeklyArenaState.address, _weeklyArenaState.Serialize())
                            .SetState(_agentAddress, agentState.Serialize())
                            .SetState(_avatarAddress, avatarState.Serialize())
                            .SetState(_rankingMapAddress, new RankingMapState(_rankingMapAddress).Serialize());

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState
                                .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Esempio n. 35
0
        /// <summary>
        /// 인자로 받은 에이전트 상태를 바탕으로 로컬 세팅을 초기화 한다.
        /// 에이전트 상태가 포함하는 모든 아바타 상태 또한 포함된다.
        /// 이미 초기화되어 있는 에이전트와 같을 경우에는 아바타의 주소에 대해서만
        /// </summary>
        /// <param name="agentState"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public void InitializeAgentAndAvatars(AgentState agentState)
        {
            if (agentState is null)
            {
                throw new ArgumentNullException(nameof(agentState));
            }

            var address = agentState.address;

            // 이미 초기화되어 있는 에이전트와 같을 경우.
            if (!(_agentModifierInfo is null) &&
                _agentModifierInfo.Address.Equals(address))
            {
                return;
            }

            // _agentModifierInfo 초기화하기.
            _agentModifierInfo =
                new ModifierInfo <AgentStateModifier>(address);
            _agentGoldModifierInfo = new ModifierInfo <AgentGoldModifier>(address);
        }
    //Connector info?



    // Constructor
    public Agent(GameObject prefab, Material material, PhysicMaterial physicsMaterial, Vector3 center, int _Id)
    {
        Id = _Id;

        Obj = UnityEngine.Object.Instantiate(prefab, center, Quaternion.identity);
        Obj.GetComponent <MeshRenderer>().sharedMaterial = material;

        BoxColl = Obj.AddComponent <BoxCollider>();
        BoxColl.sharedMaterial = physicsMaterial;

        Rb = Obj.GetComponent <Rigidbody>();


        State = AgentState.Inactive;

        ScentValue = 0;
        ScentMax   = 20;
        StepCount  = 0;

        activeConnectors = new List <Connections>();
    }
Esempio n. 37
0
        public override void OnAgentRemoved(
            Agent affectedAgent,
            Agent affectorAgent,
            AgentState agentState,
            KillingBlow blow)
        {
            if (!this.IsRoundInProgress || affectedAgent.IsMount)
            {
                return;
            }
            Team team = affectedAgent.Team;

            if (this.IsGameModeUsingGold)
            {
                this.UpdateTeamPowerBasedOnGold(team);
            }
            else
            {
                this.UpdateTeamPowerBasedOnTroopCount(team);
            }
        }
Esempio n. 38
0
        public void TestUpdateLong()
        {
            var linearPath = new LinearPath(Vector3.zero, Vector3.forward);
            var paths      = new List <PathDescription>()
            {
                new PathDescription(new DummyAIPath(linearPath), 0, 1)
            };

            var state = new AgentState(0, 0, null);

            var agent = new DummyStateAgent(state);

            GetSpeedDelegate getSpeed = s => 1.0f;

            AgentState newState;
            var        result = state.Update(agent, 1 + 1 / 60.0f, getSpeed, paths, out newState);

            Assert.IsTrue(result.HasFlag(AgentStateResult.Moved));
            Assert.IsTrue(result.HasFlag(AgentStateResult.ChangedPath));
            Assert.AreEqual(1 / 60.0f, newState.Progress, 0.000001f);
        }
Esempio n. 39
0
 public MakeInitialStateResult(
     IAccountStateDelta state,
     CreateTestbed testbed,
     AgentState agentState,
     AvatarState avatarState,
     GoldCurrencyState goldCurrencyState,
     Address rankingMapAddress,
     TableSheets tableSheets,
     FungibleAssetValue currencyGold,
     FungibleAssetValue agentCurrencyGold)
 {
     _state             = state;
     _testbed           = testbed;
     _agentState        = agentState;
     _avatarState       = avatarState;
     _goldCurrencyState = goldCurrencyState;
     _rankingMapAddress = rankingMapAddress;
     _tableSheets       = tableSheets;
     _currencyGold      = currencyGold;
     _agentCurrencyGold = agentCurrencyGold;
 }
Esempio n. 40
0
 private void ActivateWaypointMovement(bool setPreviousState = false)
 {
     if (waypoints.Length > 1)
     {
         FindPointerToClosestWaypoint();
     }
     else
     {
         currentWaypoint = 0;
     }
     agent.SetDestination(waypoints[currentWaypoint]);
     agent.isStopped = false;
     if (setPreviousState)
     {
         controller.State = currentMovingState;
     }
     else
     {
         currentMovingState = controller.State;
     }
 }
Esempio n. 41
0
 public void setState(AgentState s) { m_state = s; }
Esempio n. 42
0
        /// <summary>
        /// This is the event handler for client movement.   If a client is moving, this event is triggering.
        /// </summary>
        public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
        {
            bool recoverPhysActor = false;
            if (m_isChildAgent)
            {
                //m_log.Warn("[CROSSING]: HandleAgentUpdate from child agent ignored "+agentData.AgentID.ToString());
                return;
            }
            if (IsInTransit)
            {
                // m_log.Error("[CROSSING]: AgentUpdate called during transit! Ignored.");
                return;
            }

            SceneObjectPart part = m_posInfo.Parent;
            EntityBase.PositionInfo posInfo = GetPosInfo();
            if (part != null)
            {   // sitting on a prim
                if (part.ParentGroup.InTransit)
                {
                    // m_log.Warn("[CROSSING]: AgentUpdate called during prim transit! Ignored.");
                    return;
                }
            }

            if (!posInfo.Position.IsFinite())
            {
                RemoveFromPhysicalScene();
                m_log.Error("[SCENE PRESENCE]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error# 9999902");

                if (m_LastFinitePos.IsFinite())
                {
                    SetAgentPositionInfo(false, m_LastFinitePos, posInfo.Parent, Vector3.Zero, Vector3.Zero);
                }
                else
                {
                    Vector3 emergencyPos = new Vector3(127.0f, 127.0f, 127.0f);
                    SetAgentPositionInfo(false, emergencyPos, posInfo.Parent, Vector3.Zero, Vector3.Zero);
                    m_log.Error("[SCENE PRESENCE]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error# 9999903");
                }

                AddToPhysicalScene(false);
            }
            else
            {
                m_LastFinitePos = m_posInfo.Position;
            }

            m_perfMonMS = Environment.TickCount;

            uint flags = agentData.ControlFlags;
            Quaternion bodyRotation = agentData.BodyRotation;

            // Camera location in world.  We'll need to raytrace
            // from this location from time to time.

            bool doCullingCheck = false;
            bool update_rotation = false;
            if (m_sceneView != null && m_sceneView.UseCulling)
            {
                if (!m_sceneView.NeedsFullSceneUpdate && (Environment.TickCount - m_lastCullCheckMS) > 0 &&
                    Vector3.DistanceSquared(agentData.CameraCenter, m_lastCameraCenter) > m_sceneView.DistanceBeforeCullingRequired * m_sceneView.DistanceBeforeCullingRequired)
                {
                    //Check for new entities that we may now be able to see with this camera movement
                    m_lastCameraCenter = agentData.CameraCenter;
                    doCullingCheck = true;
                }
                else if (!m_sceneView.NeedsFullSceneUpdate && agentData.Far > m_DrawDistance)
                {
                    //Check to see if the draw distance has gone up
                    doCullingCheck = true;
                }
                //Do a culling check, if required
                if (doCullingCheck)
                {
                    m_sceneView.CheckForDistantEntitiesToShow();
                    //Also tell all child regions about the change
                    SendChildAgentUpdate();
                    m_lastCullCheckMS = Environment.TickCount + 1000;//Only do the camera check at the most once a sec
                }
            }



            m_CameraCenter = agentData.CameraCenter;

            // Use these three vectors to figure out what the agent is looking at
            // Convert it to a Matrix and/or Quaternion
            m_CameraAtAxis = agentData.CameraAtAxis;
            m_CameraLeftAxis = agentData.CameraLeftAxis;
            m_CameraUpAxis = agentData.CameraUpAxis;


            // check if the Agent's Draw distance setting has changed
            if (m_DrawDistance != agentData.Far)
            {
                m_DrawDistance = agentData.Far;
                m_remotePresences.HandleDrawDistanceChanged((uint)agentData.Far);
            }

            if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
            {
                StandUp(false, true);
                bodyRotation = m_bodyRot;   // if standing, preserve the current rotation
                update_rotation = true;
            }

            m_mouseLook = (flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;

            m_leftButtonDown = (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;

            lock (m_scriptedcontrols)
            {
                if (m_scriptedcontrols.Count > 0)
                {
                    SendControlToScripts(flags);
                    flags = RemoveIgnoredControls(flags, IgnoredControls);
                }
            }

            PhysicsActor physActor = PhysicsActor;

            m_AgentControlFlags = flags;
            m_headrotation = agentData.HeadRotation;
            m_state = (AgentState)agentData.State;

            if (physActor == null)
            {
                Velocity = Vector3.Zero;
                return;
            }

            if (m_autopilotMoving)
                CheckAtSitTarget();

            if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
            {
                m_animPersistUntil = 0;    // abort any timed animation
                TrySetMovementAnimation("SIT_GROUND_CONSTRAINED");
                m_sittingGround = true;
            }
            // In the future, these values might need to go global.
            // Here's where you get them.

            if (m_allowMovement)
            {
                bool update_movementflag = false;
                bool DCFlagKeyPressed = false;
                Vector3 agent_control_v3 = Vector3.Zero;

                // Update the physactor's rotation. This communicates the rotation to the character controller.
                physActor.Rotation = bodyRotation;

                bool oldflying = physActor.Flying;

                if (m_forceFly)
                    physActor.Flying = true;
                else if (m_flyDisabled)
                    physActor.Flying = false;
                else
                    physActor.Flying = ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);

                if (physActor.Flying != oldflying)
                {
                    update_movementflag = true;

                    if (physActor.Flying && physActor.CollidingGround)
                    {
                        physActor.AddForce(new Vector3(0f, 0f, FLY_LAUNCH_FORCE) * physActor.Mass, ForceType.GlobalLinearImpulse);
                    }
                }

                if (bodyRotation != m_bodyRot)
                {
                    m_bodyRot = bodyRotation;
                    update_rotation = true;
                }

                if (m_posInfo.Parent != null)
                {
                    // abort any automated movement
                    m_moveToPositionTarget = Vector3.Zero;
                    m_moveToPositionInProgress = false;
                    update_movementflag = true;
                }
                else
                {
                
                    bool bAllowUpdateMoveToPosition = false;
                    bool bResetMoveToPosition = false;

                    Vector3[] dirVectors;

                    // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
                    // this prevents 'jumping' in inappropriate situations.
                    if ((m_mouseLook || m_leftButtonDown) && !physActor.Flying)
                        dirVectors = GetWalkDirectionVectors();
                    else
                        dirVectors = Dir_Vectors;

                    bool nudgeStarted = false;
                    for (int i=0; i<Dir_Flags.Length; ++i)
                    {
                        Dir_ControlFlags DCF = Dir_Flags[i];

                        if ((flags & (uint) DCF) != 0)
                        {
                            bResetMoveToPosition = true;
                            DCFlagKeyPressed = true;
                            agent_control_v3 += dirVectors[i];
                            
                            if ((m_movementflag & (uint) DCF) == 0)
                            {
                                m_movementflag += (uint)DCF & PrimaryMovements;   // This is an abomination.
                                update_movementflag = true;

                                // The viewers do not send up or down nudges.
                                if ((DCF & Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE) != 0 ||
                                    (DCF & Dir_ControlFlags.DIR_CONTROL_FLAG_REVERSE_NUDGE) != 0 ||
                                    (DCF & Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN_NUDGE) != 0 ||
                                    (DCF & Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT_NUDGE) != 0 ||
                                    (DCF & Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT_NUDGE) != 0
                                   )
                                {
                                    //when we start a nudge, we let it run for a period of time and then cancel the force
                                    _nudgeStart = (uint)Environment.TickCount;
                                    if ((DCF & Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT_NUDGE) != 0 ||
                                        (DCF & Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT_NUDGE) != 0)
                                        _nudgeDuration = NUDGE_DURATION_LR;
                                    else
                                        _nudgeDuration = NUDGE_DURATION_AT;

                                    nudgeStarted = true;
                                }
                                else
                                {
                                    if (!nudgeStarted) _nudgeStart = 0;
                                }

                                if (((DCF & Dir_ControlFlags.DIR_CONTROL_FLAG_UP) != 0) && physActor.CollidingGround && !physActor.Flying)
                                {
                                    //begin a jump
                                    physActor.AddForce(new Vector3(0.0f, 0.0f, JUMP_FORCE) * physActor.Mass, ForceType.LocalLinearImpulse);
                                }
                            }
                        }
                        else
                        {
                            if ((m_movementflag & (uint) DCF) != 0)
                            {
                                m_movementflag -= (uint) DCF & PrimaryMovements;  // This is an abomination.
                                update_movementflag = true;
                                if (!nudgeStarted) _nudgeStart = 0;
                            }
                            else
                            {
                                bAllowUpdateMoveToPosition = true;
                            }
                        }
                    }

                    //Paupaw:Do Proper PID for Autopilot here
                    if (bResetMoveToPosition)
                    {
                        m_moveToPositionTarget = Vector3.Zero;
                        m_moveToPositionInProgress = false;
                        update_movementflag = true;
                        bAllowUpdateMoveToPosition = false;
                    }

                    if (bAllowUpdateMoveToPosition && (m_moveToPositionInProgress && !m_autopilotMoving))
                    {
                        //Check the error term of the current position in relation to the target position
                        if (IsAtTarget(m_moveToPositionTarget))
                        {
                            // we are close enough to the target
                            m_moveToPositionTarget = Vector3.Zero;
                            m_moveToPositionInProgress = false;
                            update_movementflag = true;
                        }
                        else
                        {
                            try
                            {
                                // move avatar in 3D at one meter/second towards target, in avatar coordinate frame.
                                // This movement vector gets added to the velocity through AddNewMovement().
                                // Theoretically we might need a more complex PID approach here if other 
                                // unknown forces are acting on the avatar and we need to adaptively respond
                                // to such forces, but the following simple approach seems to works fine.
                                Vector3 LocalVectorToTarget =
                                    (m_moveToPositionTarget - AbsolutePosition) // vector from cur. pos to target in global coords
                                    * Matrix4.CreateFromQuaternion(Quaternion.Inverse(bodyRotation)); // change to avatar coords
                                LocalVectorToTarget.Normalize();
                                agent_control_v3 += LocalVectorToTarget;

                                Vector3 movementPush = (m_moveToPositionTarget - AbsolutePosition);
                                movementPush.Normalize();
                                movementPush.Z *= physActor.Mass;
                                if (physActor.IsColliding)
                                    movementPush.Z *= FLY_LAUNCH_FORCE;
                                physActor.AddForce(movementPush, ForceType.GlobalLinearImpulse);

                                // update avatar movement flags. the avatar coordinate system is as follows:
                                //
                                //                        +X (forward)
                                //
                                //                        ^
                                //                        |
                                //                        |
                                //                        |
                                //                        |
                                //     (left) +Y <--------o--------> -Y
                                //                       avatar
                                //                        |
                                //                        |
                                //                        |
                                //                        |
                                //                        v
                                //                        -X
                                //

                                // based on the above avatar coordinate system, classify the movement into 
                                // one of left/right/back/forward.
                                if (LocalVectorToTarget.Y > 0)//MoveLeft
                                {
                                    m_movementflag += (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
                                    update_movementflag = true;
                                }
                                else if (LocalVectorToTarget.Y < 0) //MoveRight
                                {
                                    m_movementflag += (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
                                    update_movementflag = true;
                                }
                                if (LocalVectorToTarget.X < 0) //MoveBack
                                {
                                    m_movementflag += (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
                                    update_movementflag = true;
                                }
                                else if (LocalVectorToTarget.X > 0) //Move Forward
                                {
                                    m_movementflag += (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
                                    update_movementflag = true;
                                }
                                if (LocalVectorToTarget.Z > 0) //Up
                                {
                                    // Don't set these flags for up - doing so will make the avatar
                                    // keep trying to jump even if walking along level ground.
                                    // m_movementflag += (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_UP;
                                    update_movementflag = true;
                                }
                                else if (LocalVectorToTarget.Z < 0) //Down
                                {
                                    // Don't set these flags for down - doing so will make the avatar crouch.
                                    // m_movementflag += (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN;
                                    update_movementflag = true;
                                }
                            }
                            catch (Exception)
                            {

                                //Avoid system crash, can be slower but...
                            }

                        }
                    }

                    // Determine whether the user has said to stop and the agent is not sitting.
                    physActor.SetAirBrakes = (m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_STOP) != 0 && !IsInTransitOnPrim && !m_moveToPositionInProgress;

                }
                
                // Cause the avatar to stop flying if it's colliding
                // with something with the down arrow pressed.

                // Only do this if we're flying
                if (physActor != null && physActor.Flying && !m_forceFly)
                {
                    // Are the landing controls requirements filled?
                    bool controlland = (((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
                                        ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));

                    // Are the collision requirements fulfilled?
                    bool colliding = (physActor.CollidingGround == true);

                    if (physActor.Flying && colliding && controlland)
                    {
                        StopFlying();
                    }
                }

                if (m_newPhysActorNeedsUpdate && physActor != null)
                    update_movementflag = true;

                if (!m_sittingGround && (update_movementflag || (update_rotation && DCFlagKeyPressed)))
                {
                    AddNewMovement(agent_control_v3, bodyRotation);

                    if (update_movementflag)
                        UpdateMovementAnimations();

                    if (physActor != null)
                        m_newPhysActorNeedsUpdate = false;
                }
                else if (update_rotation)
                {
                    //avatar is spinning with no other changes
//                    m_log.WarnFormat("[SP]: HandleAgentUpdate: Sending terse update vel={0}",this.Velocity);
                    SendTerseUpdateToAllClients();
                }
            }

            m_scene.EventManager.TriggerOnClientMovement(this);

            m_scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS);
        }
Esempio n. 43
0
 public WrappedObjectState(AgentState value)
 {
     Value = value;
 }
Esempio n. 44
0
        /**
         * Used by local processes to open a connection to Swarm
         */
        private Int32 OpenConnection_1_0( Hashtable InParameters, ref Hashtable OutParameters )
        {
            // Always wait until the agent is fully initialized
            Initialized.WaitOne();

            // Unpack the input parameters
            Int32 LocalProcessID = ( Int32 )InParameters["ProcessID"];
            ELogFlags LoggingFlags = ( ELogFlags )InParameters["LoggingFlags"];

            // Check for optional parameters
            if( InParameters.Contains( "ProcessIsOwner" ) )
            {
                bool LocalProcessIsOwner = ( bool )InParameters["ProcessIsOwner"];
                if( LocalProcessIsOwner )
                {
                    OwnerProcessID = LocalProcessID;
                }
            }

            // If a restart or an exit has been requested, stop accepting new connections
            if( AgentIsShuttingDown )
            {
                return Constants.INVALID;
            }

            // If this is a "first" new local connection, clear the log window
            LocalConnectionRequestWaiting.Set();
            lock( Connections )
            {
                LocalConnectionRequestWaiting.Reset();

                Int32 LocalConnectionCount = 0;
                foreach( Connection NextConnection in Connections.Values )
                {
                    if( NextConnection is LocalConnection )
                    {
                        LocalConnectionCount++;
                    }
                }
                if( LocalConnectionCount == 0 )
                {
                    AgentApplication.ClearLogWindow();
                }
            }

            CreateTimings( LoggingFlags );

            // Get a new unique handle that this potential connection will be known by
            Int32 NewConnectionHandle = GetUniqueHandle();

            // Local connection request, the connection ID is the process ID of the caller
            LocalConnection NewLocalConnection = new LocalConnection( NewConnectionHandle, LocalProcessID );

            // Determine if this connection is a replacement of another, existing connection
            foreach( Connection ExistingConnection in Connections.Values )
            {
                if( ExistingConnection is LocalConnection )
                {
                    LocalConnection ExistingLocalConnection = ExistingConnection as LocalConnection;
                    if( ExistingLocalConnection.ProcessID == LocalProcessID )
                    {
                        // If this process already has a connection, close the older one
                        // since generally the only way this happens is when a connection
                        // dies and is re-established later
                        Log( EVerbosityLevel.Informative, ELogColour.Orange, "[Connection] Detected new local connection from same process ID as an existing one, closing the old one" );
                        Hashtable OldInParameters = null;
                        Hashtable OldOutParameters = null;
                        CloseConnection( ExistingConnection.Handle, OldInParameters, ref OldOutParameters );
                    }
                }
            }

            // Determine if this connection is a child of another, existing connection
            Connection ParentConnection = null;
            AgentJob ParentJob = null;
            foreach( AgentJob Job in ActiveJobs.Values )
            {
                if( Job.CurrentState == AgentJob.JobState.AGENT_JOB_RUNNING )
                {
                    // If the incoming connection is from a process spawned by a Job
                    // associated with an existing connection, note the parent-child
                    // relationship
                    lock( Job.ProcessObjectLock )
                    {
                        if( ( Job.ProcessObject != null ) &&
                            ( Job.ProcessObject.Id == LocalProcessID ) )
                        {
                            // Grab the parent and its Job
                            ParentConnection = Job.Owner;
                            ParentJob = Job;

                            // Found what we want, break out
                            break;
                        }
                    }

                    // If the Job was marked as manually started, then try to match
                    // based on the full path name of the executable
                    EJobTaskFlags JobFlags = Job.Specification.JobFlags;
                    if( ( JobFlags & EJobTaskFlags.FLAG_MANUAL_START ) != 0 )
                    {
                        Process ProcessObject = Process.GetProcessById( LocalProcessID );
                        string ProcessFilename = Path.GetFileName( ProcessObject.MainModule.FileName );
                        string OriginalExecutableName;
                        if( Job.Specification.DependenciesOriginalNames.TryGetValue( Job.Specification.ExecutableName, out OriginalExecutableName ) )
                        {
                            // Compare in a way that allows matching with the debug executable, which contains the release executable name
                            //@todo - detect debug executable in a robust method, possibly through optional dependencies
                            string OriginalExecutableWithoutExtention = System.IO.Path.GetFileNameWithoutExtension(OriginalExecutableName);
                            if (OriginalExecutableWithoutExtention.Contains(ProcessFilename) || ProcessFilename.Contains(OriginalExecutableWithoutExtention))
                            {
                                Log( EVerbosityLevel.Informative, ELogColour.Green, "[Job] Attaching new process handle to existing Job" );
                                ProcessObject.EnableRaisingEvents = true;
                                ProcessObject.Exited += new EventHandler( Job.ExitedProcessEventHandler );
                                Job.ProcessObject = ProcessObject;

                                // Grab the parent and its Job
                                ParentConnection = Job.Owner;
                                ParentJob = Job;

                                // Found what we want, break out
                                break;
                            }
                        }
                    }
                }
            }

            // If we found a parent connection, establish the parent-child relationship
            if( ParentConnection != null )
            {
                Log( EVerbosityLevel.Informative, ELogColour.Green, "[Job] Found a parent connection for PID " + LocalProcessID );
                Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[Job]     {0:X8} -> {1:X8}", ParentConnection.Handle, NewConnectionHandle ) );

                NewLocalConnection.Parent = ParentConnection;
                NewLocalConnection.Job = ParentJob;
                ParentConnection.LocalChildren.Add( NewConnectionHandle, NewLocalConnection );
                ParentConnection.LocalChildrenSeen++;
                ParentConnection.ChildrenSeen++;
            }

            // There are times we want to ensure no new connections are coming online
            // where we'll lock the Connections dictionary (see MaintainCache)
            LocalConnectionRequestWaiting.Set();
            lock( Connections )
            {
                LocalConnectionRequestWaiting.Reset();

                // Add the new local connection to the list of tracked connections
                Connections.Add( NewConnectionHandle, NewLocalConnection );
                NewLocalConnection.CurrentState = ConnectionState.CONNECTED;
            }

            // If this is an Instigator's connection, update some state
            if( ParentConnection == null )
            {
                // Update our state and ping the coordinator, if this is an instigating connection
                CurrentState = AgentState.Working;
                WorkingFor = Environment.MachineName;
                PingCoordinator( true );
            }

            // Fill in the connection configuration output parameter
            OutParameters = new Hashtable();
            OutParameters["Version"] = ESwarmVersionValue.VER_1_0;
            OutParameters["AgentProcessID"] = AgentProcessID;
            OutParameters["AgentCachePath"] = GetCacheLocation();

            // There are two requirements to be a pure local connection: be local and
            // have no remote parents. The main benefit of a pure local connection is
            // that they get to avoid calling into the Agent for the Channel API.
            bool IsPureLocalConnection = true;
            if( NewLocalConnection.Job != null )
            {
                OutParameters["AgentJobGuid"] = NewLocalConnection.Job.JobGuid;
                if( NewLocalConnection.Job.Owner is RemoteConnection )
                {
                    IsPureLocalConnection = false;
                }
            }
            OutParameters["IsPureLocalConnection"] = IsPureLocalConnection;

            // Return the handle for the new local connection
            return NewConnectionHandle;
        }
Esempio n. 45
0
 public bool HasAgent(AgentWrapper agent, AgentState agentState)
 {
     return Retry.UntilTrue(
         () =>
         {
             var found = agents.GetAgent(a => a.Name.Equals(agent.TestRunner.Name) && a.Status.Equals(agentState));
             return found != null;
         }, 500);
 }
Esempio n. 46
0
            /// <summary>
            /// Builds an AgentUpdate packet entirely from parameters. This
            /// will not touch the state of Self.Movement or
            /// Self.Movement.Camera in any way
            /// </summary>
            /// <param name="controlFlags"></param>
            /// <param name="position"></param>
            /// <param name="forwardAxis"></param>
            /// <param name="leftAxis"></param>
            /// <param name="upAxis"></param>
            /// <param name="bodyRotation"></param>
            /// <param name="headRotation"></param>
            /// <param name="farClip"></param>
            /// <param name="reliable"></param>
            /// <param name="flags"></param>
            /// <param name="state"></param>
            public void SendManualUpdate(AgentManager.ControlFlags controlFlags, Vector3 position, Vector3 forwardAxis,
                Vector3 leftAxis, Vector3 upAxis, Quaternion bodyRotation, Quaternion headRotation, float farClip,
                AgentFlags flags, AgentState state, bool reliable)
            {
                AgentUpdatePacket update = new AgentUpdatePacket();

                update.AgentData.AgentID = Client.Self.AgentID;
                update.AgentData.SessionID = Client.Self.SessionID;
                update.AgentData.BodyRotation = bodyRotation;
                update.AgentData.HeadRotation = headRotation;
                update.AgentData.CameraCenter = position;
                update.AgentData.CameraAtAxis = forwardAxis;
                update.AgentData.CameraLeftAxis = leftAxis;
                update.AgentData.CameraUpAxis = upAxis;
                update.AgentData.Far = farClip;
                update.AgentData.ControlFlags = (uint)controlFlags;
                update.AgentData.Flags = (byte)flags;
                update.AgentData.State = (byte)state;

                update.Header.Reliable = reliable;

                Client.Network.SendPacket(update);
            }
Esempio n. 47
0
        public MockUniverse(IIdGenerator idGenerator = null)
        {
            _idGenerator = idGenerator ?? new IdGenerator();
            var universeId = Id();

            SpaceshipCommand = TestSkills.For(SkillCode.SpaceshipCommand);
            BluePrint = TestItems.BluePrint(ItemCode.MissileLauncher);
            ShipBluePrint = TestItems.BluePrint(ItemCode.LightFrigate);
            Weapon = TestItems.Weapon(ItemCode.MissileLauncher);
            Item = TestItems.Item(ItemCode.Veldnium);

            John = new AgentState
            {
                ObjectId = Id(),
                Name = "John",
                Statistics = Enum.GetValues(typeof(AgentStatistic)).Cast<AgentStatistic>().Select(x => new AgentStatisticState { Statistic = x, CurrentValue = 50, Value = 50 }),
                Implants = new[] { AgentStatistic.Intelligence, AgentStatistic.Willpower, }.Select(x => new Implant { Stat = x, Rank = 3, Value = 15 }),
                Skills = new[] { new SkillLevel(SkillCode.SpaceshipCommand, level: 5) }
            };

            MSCorp = new CorporationState
            {
                ObjectId = Id(),
                Name = "MS",
                Employees = new[] { John }
            };

            AppleCorp = new CorporationState
            {
                ObjectId = Id(),
                Name = "Apple",
            };

            BuyOrder = new AuctionState
            {
                ObjectId = Id(),
                PricePerUnit = 5,
                Trader = John.ToObjectReference(),
                Item = new ItemState { Code = ItemCode.Veldnium, Quantity = 50 },
                Owner = MSCorp.ToObjectReference(),
            };

            SellOrder = new AuctionState
            {
                ObjectId = Id(),
                PricePerUnit = 10,
                Trader = John.ToObjectReference(),
                Item = new ItemState { Code = ItemCode.Veldnium, Quantity = 100 },
                Owner = MSCorp.ToObjectReference(),
            };

            Earth = new CelestialObjectState
            {
                ObjectId = Id(),
                CelestialObjectType = CelestialObjectType.Planet,
                Name = "Earth",
                LocalCoordinates = new Vector(Units.FromAU(1), 0),
                Mass = Units.SolarMass*1E-6,
                Size = 5d,
            };
            AsteroidBelt = new CelestialObjectState
            {
                ObjectId = Id(),
                CelestialObjectType = CelestialObjectType.AsteriodBelt,
                Name = "Asteroid Belt",
                Orbits = Earth.ToObjectReference(),
                LocalCoordinates = new Vector(-5.5, 0, 0),
                AsteroidBelt = new AsteroidBeltState
                {
                    Richness = 500000,
                    AmountRemaining = 250000,
                },
            };
            Moon = new CelestialObjectState
            {
                ObjectId = Id(),
                CelestialObjectType = CelestialObjectType.Moon,
                Name = "Moon",
                Orbits = Earth.ToObjectReference(),
                Mass = 0.5d,
                Size = 0.5d,
                LocalCoordinates = new Vector(7.5, 0, 0)
            };
            Manufactory = new StructureState()
            {
                ObjectId = Id(),
                Name = "MFC",
                Orbits = Moon.ToObjectReference(),
                LocalCoordinates = new Vector(0.5001, 0, 0),
                Owner = MSCorp.ToObjectReference(),
                Manufactory = new ManufactoryState() { Efficiency = 0.5d },
            };
            TradingStation = new StructureState()
            {
                ObjectId = Id(),
                Name = "TS",
                Orbits = Moon.ToObjectReference(),
                LocalCoordinates = new Vector(-0.5001, 0, 0),
                Owner = MSCorp.ToObjectReference(),
                HangerItems = new[] { new HangarItemState { Owner = MSCorp.ToObjectReference(), Items = new[] { ItemCode.MissileLauncher.ToItemState(quantity:10) }  }, },
                BuyOrders = new[] { BuyOrder },
                SellOrders = new[] { SellOrder },
                TradingStation = new TradingStationState()
            };

            Ship = new ShipState()
            {
                ObjectId = Id(),
                Name = "Ship",
                LocalCoordinates = new Vector(8.5, 0, 0),
                Code = ItemCode.LightFrigate,
                HardPoints = new[]
                {
                    new HardPointState
                    {
                        Position = HardPointPosition.Front,
                        Orientation = HardPoint.CalculateOrientation(HardPointPosition.Front),
                        Speed = 0.5d,
                        Weapon = new WeaponState
                        {
                            ObjectId = Id(),
                            Name = "Blaster",
                            Code = Weapon.Code,
                        }
                    },
                },
                Pilot = John,
                Statistics = Enum.GetValues(typeof(ShipStatistic)).Cast<ShipStatistic>().Select(x => new ShipStatisticState { Statistic = x, CurrentValue = 50, Value = 50 }),
            };
            SolarSystem = new SolarSystemState
            {
                ObjectId = Id(),
                Name = "Sol",
                Satellites = new[] { Earth, Moon, AsteroidBelt, },
                Structures = new[] { Manufactory, TradingStation },
                Ships = new[] { Ship }
            };
            StarCluster = new StarClusterState
            {
                ObjectId = Id(),
                Name = "Revvon",
                SolarSystems = new[] { SolarSystem },
                MarketPlace = new MarketPlaceState
                {
                    AuctionLength = 10,
                    SettlementDelay = 5,
                    Settlements = new[]
                    {
                        new SettlementState
                        {
                            ObjectId = Id(),
                            Item = new ItemState { Code = ItemCode.Veldnium, Quantity = 50 },
                            Owner = MSCorp.ToObjectReference(),
                            Location = TradingStation.ToObjectReference(),
                            TimeToSettlement = 100,
                            SpendByOwner = new Dictionary<ObjectReference, long> { { AppleCorp.ToObjectReference(), 1000 } },
                        }
                    },
                    Auctions = new[] { BuyOrder.ToObjectReference(), SellOrder.ToObjectReference() },
                }
            };

            Universe = new UniverseState
            {
                ObjectId = universeId,
                StarClusters = new[] {StarCluster},
                Weapons = new[] { Weapon },
                Skills = TestSkills.Skills,
                Corporations = new[] { MSCorp, AppleCorp },
                Items = TestItems.Items,
                BluePrints = TestItems.BluePrints,
                Ships = new[]
                {
                    new ShipInfo
                    {
                        Code = ItemCode.LightFrigate,
                        ShipClass = ShipClass.LightFrigate,
                        PilotRequirements = new[]
                        {
                            new State.SkillLevel(SkillCode.SpaceshipCommand, level:1),
                        }
                    }
                }
            };
        }
Esempio n. 48
0
            /// <summary>
            /// Send new AgentUpdate packet to update our current camera 
            /// position and rotation
            /// </summary>
            /// <param name="reliable">Whether to require server acknowledgement
            /// of this packet</param>
            /// <param name="simulator">Simulator to send the update to</param>
            public void SendUpdate(bool reliable, Simulator simulator)
            {
                // Since version 1.40.4 of the Linden simulator, sending this update
                // causes corruption of the agent position in the simulator
                if (simulator != null && (!simulator.HandshakeComplete))
                    return;

                Vector3 origin = Camera.Position;
                Vector3 xAxis = Camera.LeftAxis;
                Vector3 yAxis = Camera.AtAxis;
                Vector3 zAxis = Camera.UpAxis;

                // Attempted to sort these in a rough order of how often they might change
                if (agentControls == 0 &&
                    yAxis == LastCameraYAxis &&
                    origin == LastCameraCenter &&
                    State == lastState &&
                    HeadRotation == LastHeadRotation &&
                    BodyRotation == LastBodyRotation &&
                    xAxis == LastCameraXAxis &&
                    Camera.Far == LastFar &&
                    zAxis == LastCameraZAxis)
                {
                    ++duplicateCount;
                }
                else
                {
                    duplicateCount = 0;
                }

                if (Client.Settings.DISABLE_AGENT_UPDATE_DUPLICATE_CHECK || duplicateCount < 10)
                {
                    // Store the current state to do duplicate checking
                    LastHeadRotation = HeadRotation;
                    LastBodyRotation = BodyRotation;
                    LastCameraYAxis = yAxis;
                    LastCameraCenter = origin;
                    LastCameraXAxis = xAxis;
                    LastCameraZAxis = zAxis;
                    LastFar = Camera.Far;
                    lastState = State;

                    // Build the AgentUpdate packet and send it
                    AgentUpdatePacket update = new AgentUpdatePacket();
                    update.Header.Reliable = reliable;

                    update.AgentData.AgentID = Client.Self.AgentID;
                    update.AgentData.SessionID = Client.Self.SessionID;
                    update.AgentData.HeadRotation = HeadRotation;
                    update.AgentData.BodyRotation = BodyRotation;
                    update.AgentData.CameraAtAxis = yAxis;
                    update.AgentData.CameraCenter = origin;
                    update.AgentData.CameraLeftAxis = xAxis;
                    update.AgentData.CameraUpAxis = zAxis;
                    update.AgentData.Far = Camera.Far;
                    update.AgentData.State = (byte)State;
                    update.AgentData.ControlFlags = agentControls;
                    update.AgentData.Flags = (byte)Flags;

                    Client.Network.SendPacket(update, simulator);

                    if (autoResetControls) {
                        ResetControlFlags();
                    }
                }
            }
Esempio n. 49
0
 public AgentEntry(PhoneBookItemInfo agentInfo, AgentState state)
     : this()
 {
     AgentInfo = agentInfo;
     State = state;
 }
Esempio n. 50
0
        /**
         * Used by an agent to open a remote connection to another agent. Remote
         * connections are bi-directional and this routine, along with its pair,
         * ConfirmRemoteConnection, are used to resolve all handshaking. Remote
         * connections are used by Agents to work on Tasks for Jobs they're
         * managing on behalf of a LocalConnection.
         */
        public Int32 OpenRemoteConnection( string RequestingAgentName, Int32 ConnectionHandle, ELogFlags LoggingFlags, bool IsAssigned, DateTime AssignedTimestamp )
        {
            // Always wait until the agent is fully initialized
            Initialized.WaitOne();

            Int32 RemoteConnectionHandle = Constants.INVALID;

            CreateTimings( LoggingFlags );
            StartTiming( "OpenRemoteConn-Internal", true );

            // Make sure we only have one thread in here at a time
            lock( Connections )
            {
                // Reject any incoming remote connection if:
                // we're in standalone mode
                // of if the CPU is already busy
                // or if a restart/exit has been requested
                if( ( AgentApplication.Options.EnableStandaloneMode ) ||
                    ( CurrentState == AgentState.Busy ) ||
                    ( AgentIsShuttingDown ) )
                {
                    return Constants.INVALID;
                }
                else
                {
                    // Determine if this is a request for a connection or an assignment
                    if( IsAssigned )
                    {
                        // Make sure the assignment isn't stale
                        if( AssignedTimestamp <= LastAssignedTime )
                        {
                            return Constants.INVALID;
                        }
                        if( Connections.Count != 0 )
                        {
                            // If there are any active jobs running in which the owner is the instigator,
                            // meaning that this agent is connected directly to the instigator, reject
                            foreach( AgentJob Job in ActiveJobs.Values )
                            {
                                if( Job.OwnerIsInstigator )
                                {
                                    return Constants.INVALID;
                                }
                            }

                            // Close any existing remote connections in favor of this incoming one
                            foreach( Connection ExistingConnection in Connections.Values )
                            {
                                if( ExistingConnection is RemoteConnection )
                                {
                                    Log( EVerbosityLevel.Informative, ELogColour.Orange, "[Connection] Detected incoming assigned remote connection, closing existing remote connection" );
                                    Hashtable OldInParameters = null;
                                    Hashtable OldOutParameters = null;
                                    CloseConnection( ExistingConnection.Handle, OldInParameters, ref OldOutParameters );
                                }
                            }
                        }
                    }
                    else
                    {
                        // For connection requests, any other connection at all will cause a rejection
                        if( Connections.Count != 0 )
                        {
                            return Constants.INVALID;
                        }
                    }
                }

                // First, ping the remote host to make sure we can talk to it,
                // starting with verifying the Agent with the Coordinator
                try
                {
                    if( ( Coordinator != null ) &&
                        ( CoordinatorResponding ) &&
                        ( AgentApplication.Options.EnableStandaloneMode == false ) )
                    {
                        AgentInfo RequestingAgentInfo = null;

                        Hashtable RequestedConfiguration = new Hashtable();
                        RequestedConfiguration["Version"] = new Version( 0, 0, 0, 0 );
                        RequestedConfiguration["RequestingAgentName"] = Environment.MachineName;
                        List<AgentInfo> PotentialRemoteAgents = Coordinator.GetAvailableAgents( RequestedConfiguration );
                        foreach( AgentInfo NextAgentInfo in PotentialRemoteAgents )
                        {
                            if( NextAgentInfo.Name == RequestingAgentName )
                            {
                                RequestingAgentInfo = NextAgentInfo;
                                break;
                            }
                        }

                        if( RequestingAgentInfo != null )
                        {
                            Debug.Assert( RequestingAgentInfo.Configuration.ContainsKey( "IPAddress" ) );
                            string RequestingAgentIPAddress = RequestingAgentInfo.Configuration["IPAddress"].ToString();

                            ValidateHostName(RequestingAgentIPAddress);

                            // Now, ping the Agent
                            if( PingRemoteHost( RequestingAgentName, RequestingAgentIPAddress ) )
                            {
                                // Get the remote agent's interface object and wrap it
                                string RemoteAgentURL = String.Format( "tcp://{0}:{1}/SwarmAgent",
                                    RequestingAgentIPAddress,
                                    Properties.Settings.Default.AgentRemotingPort.ToString() );

                                Agent RequestingAgentInterface = ( Agent )Activator.GetObject( typeof( Agent ), RemoteAgentURL );
                                RemoteConnectionInterfaceWrapper WrappedRequestingAgentInterface = new RemoteConnectionInterfaceWrapper( ConnectionHandle, RequestingAgentName, RequestingAgentIPAddress, RequestingAgentInterface );
                                Log( EVerbosityLevel.Informative, ELogColour.Green, "[Connect] Remote agent connection object obtained: " + RequestingAgentName );

                                // Confirm the connection
                                try
                                {
                                    // Send the connection GUID back to the requesting agent as
                                    // confirmation that we've received the request and plan to
                                    // accept it after the handshaking is complete
                                    RemoteConnectionHandle = WrappedRequestingAgentInterface.ConfirmRemoteConnection( ConnectionHandle );
                                    if( RemoteConnectionHandle >= 0 )
                                    {
                                        // Create the new remote connection object
                                        RemoteConnection NewRemoteConnection = new RemoteConnection( ConnectionHandle,
                                                                                                     RequestingAgentInfo,
                                                                                                     WrappedRequestingAgentInterface );

                                        // There are times we want to ensure no new connections are coming online
                                        // where we'll lock the Connections dictionary (see MaintainCache). Note
                                        // that we're already in the lock above...
                                        Connections.Add( ConnectionHandle, NewRemoteConnection );
                                        NewRemoteConnection.CurrentState = ConnectionState.CONNECTED;

                                        // Update our state and ping the coordinator
                                        CurrentState = AgentState.Working;
                                        WorkingFor = RequestingAgentName;
                                        if( IsAssigned )
                                        {
                                            // Successful assignment
                                            LastAssignedTime = AssignedTimestamp;
                                        }
                                        PingCoordinator( true );

                                        Log( EVerbosityLevel.Informative, ELogColour.Green, "[Connect] Remote agent connection confirmed: " + RequestingAgentName );
                                    }
                                }
                                catch( Exception Ex )
                                {
                                    Log( EVerbosityLevel.Informative, ELogColour.Red, "[Connect] OpenRemoteConnection: " + Ex.ToString() );
                                    RemoteConnectionHandle = Constants.ERROR_EXCEPTION;
                                }
                            }
                            else
                            {
                                // Failed to ping, simply return with an appropriate error code
                                Log( EVerbosityLevel.Informative, ELogColour.Red, "[Connect] Failed to ping " + RequestingAgentName + " at " + RequestingAgentIPAddress + " to confirm the remote connection" );
                                RemoteConnectionHandle = Constants.ERROR_CONNECTION_NOT_FOUND;
                            }
                        }
                        else
                        {
                            // Failed to find the Agent info for the requesting Agent, simply return with an appropriate error code
                            Log( EVerbosityLevel.Informative, ELogColour.Red, "[Connect] Failed to lookup " + RequestingAgentName + " in the Coordinator" );
                            RemoteConnectionHandle = Constants.ERROR_CONNECTION_NOT_FOUND;
                        }
                    }
                    else
                    {
                        // Could not contact the Coordinator, simply return with an appropriate error code
                        Log( EVerbosityLevel.Informative, ELogColour.Red, "[Connect] Failed to contact the Coordinator" );
                        RemoteConnectionHandle = Constants.ERROR_CONNECTION_NOT_FOUND;
                    }
                }
                catch( Exception Ex )
                {
                    Log( EVerbosityLevel.Verbose, ELogColour.Red, "[Connect] Remote agent connection failed: " + RequestingAgentName );
                    Log( EVerbosityLevel.Verbose, ELogColour.Red, "[Connect] Exception details: " + Ex.ToString() );
                }

                if( RemoteConnectionHandle < 0 )
                {
                    // If we get here, we have failed to create the connection
                    Log( EVerbosityLevel.Informative, ELogColour.Red, "[Connect] Remote agent connection failed: " + RequestingAgentName );
                }

                StopTiming();
            }
            return RemoteConnectionHandle;
        }
Esempio n. 51
0
            /// <summary>
            /// Send new AgentUpdate packet to update our current camera 
            /// position and rotation
            /// </summary>
            /// <param name="reliable">Whether to require server acknowledgement
            /// of this packet</param>
            /// <param name="simulator">Simulator to send the update to</param>
            public void SendUpdate(bool reliable, Simulator simulator)
            {
                Vector3 origin = Camera.Position;
                Vector3 xAxis = Camera.LeftAxis;
                Vector3 yAxis = Camera.AtAxis;
                Vector3 zAxis = Camera.UpAxis;

                // Attempted to sort these in a rough order of how often they might change
                if (agentControls == 0 &&
                    yAxis == LastCameraYAxis &&
                    origin == LastCameraCenter &&
                    State == lastState &&
                    HeadRotation == LastHeadRotation &&
                    BodyRotation == LastBodyRotation &&
                    xAxis == LastCameraXAxis &&
                    Camera.Far == LastFar &&
                    zAxis == LastCameraZAxis)
                {
                    ++duplicateCount;
                }
                else
                {
                    duplicateCount = 0;
                }

                if (Self.DisableAgentUpdateDuplicateCheck || duplicateCount < 10)
                {
                    // Store the current state to do duplicate checking
                    LastHeadRotation = HeadRotation;
                    LastBodyRotation = BodyRotation;
                    LastCameraYAxis = yAxis;
                    LastCameraCenter = origin;
                    LastCameraXAxis = xAxis;
                    LastCameraZAxis = zAxis;
                    LastFar = Camera.Far;
                    lastState = State;

                    // Build the AgentUpdate packet and send it
                    AgentUpdatePacket update = new AgentUpdatePacket();
                    update.Header.Reliable = reliable;

                    update.AgentData.AgentID = Network.AgentID;
                    update.AgentData.SessionID = Network.SessionID;
                    update.AgentData.HeadRotation = HeadRotation;
                    update.AgentData.BodyRotation = BodyRotation;
                    update.AgentData.CameraAtAxis = yAxis;
                    update.AgentData.CameraCenter = origin;
                    update.AgentData.CameraLeftAxis = xAxis;
                    update.AgentData.CameraUpAxis = zAxis;
                    update.AgentData.Far = Camera.Far;
                    update.AgentData.State = (byte)State;
                    update.AgentData.ControlFlags = agentControls;
                    update.AgentData.Flags = (byte)Flags;

                    Network.SendPacket(update, simulator);

                    if (autoResetControls) {
                        ResetControlFlags();
                    }
                }
            }
Esempio n. 52
0
        /// <summary>
        /// Invoke upon enter each state. It sets initial behaviour of the CharacterScript for that state.
        /// </summary>
        /// <param name="agentState"></param>
        private void OnEnter(AgentState agentState)
        {
            activeBoundingBox = (agentState == AgentState.Slide) 
                ? boundingBoxes[BoundingBoxKeys.Slide] :
                  boundingBoxes[BoundingBoxKeys.Normal];

            switch (agentState)
            {
                case AgentState.Run:
                    PlayAnimation(AgentAnimationKeys.Active);
                    break;
                case AgentState.ChangeLaneLeft:
                    OnEnterChangeLane(true);
                    break;
                case AgentState.ChangeLaneRight:
                    OnEnterChangeLane(false);
                    break;
                case AgentState.Slide:
                    PlayAnimation(AgentAnimationKeys.Slide);
                    break;
                case AgentState.Die:
                    PlayAnimation(AgentAnimationKeys.Crash);
                    break;
                default:
                    throw new ArgumentOutOfRangeException("agentState");
            }
        }
Esempio n. 53
0
	private AgentState FetchAgentState()
	{
		// read from property
		InfoDataCenter infoDataCenter = GlobalSingleton.GetInfoDataCenter() ;
		string stateStr = infoDataCenter.ReadProperty( "CHARACTER_" + AgentName , "STATE" ) ;
		m_AgentState = AgentStateFromStr( stateStr ) ;
		return m_AgentState ;
	}
Esempio n. 54
0
        public void MaintainConnections()
        {
            // If we're not initialied yet, do nothing
            if( !Initialized.WaitOne( 0 ) )
            {
                return;
            }

            // Ping the coordinator periodically
            PingCoordinator( false );

            // For each active connection
            List<Connection> DroppedConnections = new List<Connection>();
            List<Connection> ClosedAndInactiveConnections = new List<Connection>();

            foreach( KeyValuePair<Int32, Connection> NextHandleAndConnection in Connections.Copy() )
            {
                Int32 NextHandle = NextHandleAndConnection.Key;
                Connection NextConnection = NextHandleAndConnection.Value;

                Log( EVerbosityLevel.SuperVerbose, ELogColour.Green, String.Format( "[MaintainConnections] Maintaining Connection ({0:X8})", NextHandle ) );

                // For connections that are still connected, we mostly just look
                // for dropped connections to clean up if necessary
                if( NextConnection.CurrentState == ConnectionState.CONNECTED )
                {
                    if( NextConnection is LocalConnection )
                    {
                        LocalConnection Local = NextConnection as LocalConnection;

                        // For each local connection, verify the process is still running
                        bool bProcessIsStillRunning = false;
                        Process ProcessObject = null;
                        try
                        {
                            ProcessObject = Process.GetProcessById( Local.ProcessID );
                            if( ProcessObject.HasExited == false )
                            {
                                // Connection is still alive
                                bProcessIsStillRunning = true;
                            }
                        }
                        catch( Exception )
                        {
                            // Process no longer exists, fall through
                        }

                        // Process is gone, but connection is still around -> dropped
                        if( bProcessIsStillRunning == false )
                        {
                            Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[MaintainConnections] Detected dropped local connection, cleaning up ({0:X8})", Local.Handle ) );
                            DroppedConnections.Add( Local );
                        }
                        else
                        {
                            Log( EVerbosityLevel.SuperVerbose, ELogColour.Green, String.Format( "[MaintainConnections] Local connection alive ({0:X8})", Local.Handle ) );
                        }
                    }
                    else
                    {
                        RemoteConnection Remote = NextConnection as RemoteConnection;

                        // Interface is no longer alive -> dropped
                        if( !Remote.Interface.IsAlive() )
                        {
                            Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[MaintainConnections] Detected dropped remote connection, cleaning up ({0:X8})", Remote.Handle ) );
                            DroppedConnections.Add( Remote );
                        }
                        else
                        {
                            // If all children of a remote connection have been closed, then
                            // we can ask this connection to close down as well, since its
                            // services are no longer needed on this machine
                            if( ( Remote.ChildrenSeen > 0 ) &&
                                ( Remote.LocalChildren.Count == 0 ) &&
                                ( Remote.RemoteChildren.Count == 0 ) )
                            {
                                Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[MaintainConnections] Detected finished connection, closing ({0:X8})", Remote.Handle ) );
                                Hashtable RemoteInParameters = null;
                                Hashtable RemoteOutParameters = null;
                                CloseConnection( Remote.Handle, RemoteInParameters, ref RemoteOutParameters );
                            }
                            else
                            {
                                Log( EVerbosityLevel.SuperVerbose, ELogColour.Green, String.Format( "[MaintainConnections] Remote connection alive ({0:X8})", Remote.Handle ) );
                            }
                        }
                    }
                }
                // For connections that are no longer active, clean up when we can
                else if( NextConnection.CurrentState == ConnectionState.DISCONNECTED )
                {
                    if( NextConnection is LocalConnection )
                    {
                        LocalConnection Local = NextConnection as LocalConnection;

                        // Connection is no longer active. If the local message queue has emptied,
                        // add it to the list of connections to clean up. We only need to wait for
                        // the local queue to empty here, since we know all messages have been
                        // delived before we allowed the connection to be closed
                        if( Local.MessageQueue.Count == 0 )
                        {
                            Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[MaintainConnections] Local connection has closed ({0:X8})", Local.Handle ) );
                            ClosedAndInactiveConnections.Add( Local );
                        }
                        else
                        {
                            // Wait for a couple seconds...
                            TimeSpan TimeSinceConnectionClosed = DateTime.UtcNow - Local.DisconnectedTime;
                            TimeSpan TimeToWait = TimeSpan.FromSeconds(2);

                            // If this one isn't going quietly and it's got a Job, wait until
                            // the Job is gone at least (closed when the owner is closed, and
                            // possibly killed in MaintainJobs). If it doesn't have a Job,
                            // just add it to the list of connections to clean up.
                            if( ( TimeSinceConnectionClosed > TimeToWait ) &&
                                ( Local.Job == null ) )
                            {
                                Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[MaintainConnections] Local connection has timed-out and is being forceably closed ({0:X8})", Local.Handle ) );
                                ClosedAndInactiveConnections.Add( Local );
                            }
                            else
                            {
                                Log( EVerbosityLevel.ExtraVerbose, ELogColour.Green, String.Format( "[MaintainConnections] Waiting for closed local conection to drain its message queue... ({0:X8})", Local.Handle ) );
                            }
                        }
                    }
                    else
                    {
                        Debug.Assert( NextConnection is RemoteConnection );

                        // For any inactive remote connections, just remove them
                        Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[MaintainConnections] Remote connection has closed ({0:X8})", NextHandle ) );
                        ClosedAndInactiveConnections.Add( NextConnection );
                    }
                }
                else
                {
                    Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[MaintainConnections] Connection {0:X8} is {1}", NextHandle, NextConnection.CurrentState ) );
                }
            }

            // Close all dropped connections
            foreach( Connection Dropped in DroppedConnections )
            {
                // Only try to close the connection if it remains active.
                // Most common case of inactive here is an alias for a remote
                // connection that been closed in a previous iteration of this
                // same loop.
                if( Dropped.CurrentState == ConnectionState.CONNECTED )
                {
                    Hashtable DroppedInParameters = null;
                    Hashtable DroppedOutParameters = null;
                    CloseConnection( Dropped.Handle, DroppedInParameters, ref DroppedOutParameters );

                    // Different clean-up items depending on whether this is a remote or local connection
                    if( Dropped is LocalConnection )
                    {
                        LocalConnection LocalClosed = Dropped as LocalConnection;

                        // If a local connection was dropped, empty its message queue and signal
                        // since we know all messages sent to this connection have been delivered
                        // but will never be received
                        lock( LocalClosed.MessageQueue )
                        {
                            LocalClosed.MessageQueue.Clear();
                            LocalClosed.MessageAvailableSignal();
                        }
                    }
                }
            }

            // Remove all fully closed and inactive connections
            foreach( Connection Closed in ClosedAndInactiveConnections )
            {
                // For any closed connection, make sure all channels have been properly cleaned up
                foreach( Channel OpenChannel in Closed.OpenChannels.Values )
                {
                    // If the file was opened for writing, discard the file completely
                    // If the file was opened for reading, leave it alone
                    if( ( OpenChannel.Flags & EChannelFlags.ACCESS_WRITE ) != 0 )
                    {
                        Log( EVerbosityLevel.Informative, ELogColour.Orange, "[MaintainConnections] Closing orphaned channel: \"" + OpenChannel.Name + "\"" );

                        // Delete the file if it exists
                        if( File.Exists( OpenChannel.FullName ) )
                        {
                            try
                            {
                                File.Delete( OpenChannel.FullName );
                            }
                            catch( Exception )
                            {
                                if( OpenChannel is JobChannel )
                                {
                                    Log( EVerbosityLevel.Informative, ELogColour.Orange, "[MaintainConnections] Failed to delete orphaned, writable Job channel (generally benign): \"" + OpenChannel.Name + "\"" );
                                }
                                else
                                {
                                    Log( EVerbosityLevel.Informative, ELogColour.Orange, "[MaintainConnections] Failed to delete orphaned, writable persistent cache channel (possible cache corruption): \"" + OpenChannel.Name + "\"" );
                                }
                            }
                        }
                    }
                }

                // Finally, remove the connection from the set
                if( Connections.Remove( Closed.Handle ) )
                {
                    // If this is a remote connection, remove all known aliases first
                    if( Closed is RemoteConnection )
                    {
                        RemoteConnection RemoteClosed = Closed as RemoteConnection;
                        foreach( Int32 Alias in RemoteClosed.Aliases )
                        {
                            Connections.Remove( Alias );
                            string LogMessage = String.Format( "[MaintainConnections] Removed alias for remote connection: {0:X8} was an alias for {1:X8}",
                                Alias,
                                RemoteClosed.Handle );
                            Log( EVerbosityLevel.Informative, ELogColour.Green, LogMessage );
                        }
                    }

                    Log( EVerbosityLevel.Informative, ELogColour.Green, String.Format( "[MaintainConnections] Removed connection {0:X8}", Closed.Handle ) );
                }

                // If this is the last connection open, log it out and reset the NextCleanUpCacheTime
                if( Connections.Count == 0 )
                {
                    Log( EVerbosityLevel.Informative, ELogColour.Green, "[MaintainConnections] All connections have closed" );

                    // Restart the agent's log on simple boundary conditions like this,
                    // even though we may end up with more connections and jobs per file,
                    // we won't end up spreading single connections across multiple logs
                    AgentApplication.StartNewLogFile();

                    // Update our state and ping the coordinator
                    CurrentState = AgentState.Available;
                    WorkingFor = "";
                    PingCoordinator( true );

                    // Wait a brief time before starting it
                    NextCleanUpCacheTime = DateTime.UtcNow + TimeSpan.FromSeconds(10);
                }
            }

            // If there are no more open connections, do any idle time adjustments
            if( Connections.Count == 0 )
            {
                // After all connections are closed, reset the coordinator condition
                CoordinatorResponding = true;
            }
        }
Esempio n. 55
0
        private void ChangeStatus(AgentMetadata agent, AgentState agentState)
        {
            if (agent == null)
                return;

            var oldStatus = agent.Status;
            ((IAgentStateSetter)agent).Status = agentState;

            if (oldStatus != agentState)
            {
                log.Debug(string.Format("Agent '{0}' state was changed from {1} to {2}", agent.Address, oldStatus, agentState));
            }

            if (oldStatus != AgentState.Ready && agentState == AgentState.Ready)
                ReadyAgentAppeared.SafeInvoke(this, EventArgs.Empty);
            else if (!oldStatus.IsOneOf(new[]{AgentState.Disconnected, AgentState.Error})
                && agentState.IsOneOf(new[]{AgentState.Disconnected, AgentState.Error}))
            {
                ClientDisconnectedOrFailed.SafeInvoke(this, EventArgs.Empty);
            }
        }
Esempio n. 56
0
 public HerdAgent(CancellationTokenSource cancelTokenSource)
 {
     m_cancelTokenSource= cancelTokenSource;
     m_state = AgentState.AVAILABLE;
 }
Esempio n. 57
0
            /// <summary>
            /// Builds an AgentUpdate packet entirely from parameters. This
            /// will not touch the state of Self.Movement or
            /// Self.Movement.Camera in any way
            /// </summary>
            /// <param name="controlFlags"></param>
            /// <param name="position"></param>
            /// <param name="forwardAxis"></param>
            /// <param name="leftAxis"></param>
            /// <param name="upAxis"></param>
            /// <param name="bodyRotation"></param>
            /// <param name="headRotation"></param>
            /// <param name="farClip"></param>
            /// <param name="reliable"></param>
            /// <param name="flags"></param>
            /// <param name="state"></param>
            public void SendManualUpdate(AgentManager.ControlFlags controlFlags, Vector3 position, Vector3 forwardAxis,
                Vector3 leftAxis, Vector3 upAxis, Quaternion bodyRotation, Quaternion headRotation, float farClip,
                AgentFlags flags, AgentState state, bool reliable)
            {
                // Since version 1.40.4 of the Linden simulator, sending this update
                // causes corruption of the agent position in the simulator
                if (Client.Network.CurrentSim != null && (!Client.Network.CurrentSim.HandshakeComplete))
                    return;

                AgentUpdatePacket update = new AgentUpdatePacket();

                update.AgentData.AgentID = Client.Self.AgentID;
                update.AgentData.SessionID = Client.Self.SessionID;
                update.AgentData.BodyRotation = bodyRotation;
                update.AgentData.HeadRotation = headRotation;
                update.AgentData.CameraCenter = position;
                update.AgentData.CameraAtAxis = forwardAxis;
                update.AgentData.CameraLeftAxis = leftAxis;
                update.AgentData.CameraUpAxis = upAxis;
                update.AgentData.Far = farClip;
                update.AgentData.ControlFlags = (uint)controlFlags;
                update.AgentData.Flags = (byte)flags;
                update.AgentData.State = (byte)state;

                update.Header.Reliable = reliable;

                Client.Network.SendPacket(update);
            }
Esempio n. 58
0
	protected void WriteAgentState( AgentState _Set )
	{
		// Set to property
		InfoDataCenter infoDataCenter = GlobalSingleton.GetInfoDataCenter() ;
		infoDataCenter.WriteProperty( "CHARACTER_" + AgentName , "STATE" , _Set.ToString() ) ;
		m_AgentState = _Set ;
	}
Esempio n. 59
0
 public void setState(AgentState state)
 {
     info.agentState = state;
 }
Esempio n. 60
0
            /// <summary>
            /// Send new AgentUpdate packet to update our current camera 
            /// position and rotation
            /// </summary>
            /// <param name="reliable">Whether to require server acknowledgement
            /// of this packet</param>
            /// <param name="simulator">Simulator to send the update to</param>
            public void SendUpdate(bool reliable, Simulator simulator)
            {
                // Attempted to sort these in a rough order of how often they might change
                if (agentControls == 0 &&
                    Camera.CameraAtAxis == Camera.LastCameraAtAxis &&
                    Camera.CameraCenter == Camera.LastCameraCenter &&
                    State != lastState &&
                    Camera.HeadRotation == Camera.LastHeadRotation &&
                    Camera.BodyRotation == Camera.LastBodyRotation &&
                    Camera.CameraLeftAxis == Camera.LastCameraLeftAxis &&
                    Camera.Far == Camera.LastFar &&
                    Camera.CameraUpAxis == Camera.LastCameraUpAxis)
                {
                    ++duplicateCount;
                }
                else
                {
                    duplicateCount = 0;
                }

                if (duplicateCount < 2)
                {
                    // Store the current state to do duplicate checking in the future
                    Camera.LastHeadRotation = Camera.HeadRotation;
                    Camera.LastBodyRotation = Camera.BodyRotation;
                    Camera.LastCameraAtAxis = Camera.CameraAtAxis;
                    Camera.LastCameraCenter = Camera.CameraCenter;
                    Camera.LastCameraLeftAxis = Camera.CameraLeftAxis;
                    Camera.LastCameraUpAxis = Camera.CameraUpAxis;
                    Camera.LastFar = Camera.Far;
                    lastState = State;

                    // Build the AgentUpdate packet and send it
                    AgentUpdatePacket update = new AgentUpdatePacket();
                    update.Header.Reliable = reliable;

                    update.AgentData.AgentID = Client.Network.AgentID;
                    update.AgentData.SessionID = Client.Network.SessionID;
                    update.AgentData.HeadRotation = Camera.HeadRotation;
                    update.AgentData.BodyRotation = Camera.BodyRotation;
                    update.AgentData.CameraAtAxis = Camera.CameraAtAxis;
                    update.AgentData.CameraCenter = Camera.CameraCenter;
                    update.AgentData.CameraLeftAxis = Camera.CameraLeftAxis;
                    update.AgentData.CameraUpAxis = Camera.CameraUpAxis;
                    update.AgentData.Far = Camera.Far;
                    update.AgentData.State = (byte)State;
                    update.AgentData.ControlFlags = agentControls;
                    update.AgentData.Flags = (byte)Flags;

                    Client.Network.SendPacket(update, simulator);
                }
            }