public bool TrySpawnParticle(Vector3D worldPosition, MyTuple<int, ContactPropertyParticleProperties> particle)
		{
			if (!MyFakes.ENABLE_DRIVING_PARTICLES)
				return false;

			MyWheel wheel = Entity as MyWheel;
			if(wheel == null)
				return false;

            if (MyUtils.GetRandomInt(10) < 8)//spawn only about 20% of particles
                return false;
            var speedMultiplier = wheel.GetTopMostParent().Physics.LinearVelocity.Length() / MyGridPhysics.ShipMaxLinearVelocity();
			var currentTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;

            if (currentTime - m_lastEffectCreationTime < 50)
                return false;

			MyParticleEffect drivingEffect = null;
            if (!MyParticlesManager.TryCreateParticleEffect(particle.Item1, out drivingEffect))
				return false;

			m_lastEffectCreationTime = currentTime;
			m_lastGlobalEffectCreationTime = m_lastEffectCreationTime;

            drivingEffect.WorldMatrix = MatrixD.CreateTranslation(worldPosition);
            var speedScaleMultiplier = 1.0f + speedMultiplier * 6.0f;
            if (particle.Item2 != null)
            {
                drivingEffect.UserScale = particle.Item2.SizeMultiplier * speedScaleMultiplier;
                drivingEffect.UserColorMultiplier = particle.Item2.ColorMultiplier;
                drivingEffect.SetPreload(particle.Item2.Preload);
            }

			return true;
		}
            public MyPhysicalDistributionGroup(MyDefinitionId typeId, MyResourceSourceComponent tempConnectedSource)
            {
                SinksByPriority = null; SourcesByPriority = null; SinkSourcePairs = null; FirstEndpoint = null;
                SinkDataByPriority = null; SourceDataByPriority = null; StockpilingStorage = null; OtherStorage = null;
                InputOutputData = new MyTuple<MySinkGroupData, MySourceGroupData>();
                MaxAvailableResources = 0f; ResourceState = MyResourceStateEnum.NoPower;
                AllocateData();

                InitFromTempConnected(typeId, tempConnectedSource);
            }
Exemple #3
0
 public Order(PlaceMessage msg)
 {
     asset1 = msg.asset1;
     asset2 = msg.asset2;
     user = msg.user_id;
     price = msg.price;
     quantity = msg.quantity;
     buy = msg.buy;
     id = last_id++;
 }
			public MyPhysicalDistributionGroup(MyDefinitionId typeId, IMyConveyorEndpointBlock block)
			{
			    SinksByPriority = null; SourcesByPriority = null; SinkSourcePairs = null; FirstEndpoint = null;
				SinkDataByPriority = null; SourceDataByPriority = null; StockpilingStorage = null; OtherStorage = null;
				InputOutputData = new MyTuple<MySinkGroupData, MySourceGroupData>();
				MaxAvailableResources = 0f; ResourceState = MyResourceStateEnum.NoPower;
				AllocateData();

				Init(typeId, block);
			}
Exemple #5
0
 public PlaceMessage(byte[] msg)
 {
     int len = BitConverter.ToInt32(msg, 4);
     user_id = System.Text.Encoding.ASCII.GetString(msg, 8, len);
     price = new MyTuple<long, long>(BitConverter.ToInt64(msg, len + 8), BitConverter.ToInt64(msg, len + 16));
     quantity = BitConverter.ToInt64(msg, len + 24);
     buy = BitConverter.ToInt32(msg, len + 32) > 0;
     int len2 = BitConverter.ToInt32(msg, len + 36);
     asset1 = System.Text.Encoding.ASCII.GetString(msg, len + 40, len2);
     int len3 = BitConverter.ToInt32(msg, len + len2 + 40);
     asset2 = System.Text.Encoding.ASCII.GetString(msg, len + len2 + 44, len3); 
 }
Exemple #6
0
 void ComposePlaceMessage(string user_id, MyTuple<long, long> price, long quantity, bool buy, string asset1, string
     asset2)
 {
     msg.AddRange(BitConverter.GetBytes(2));//Place
     msg.AddRange(BitConverter.GetBytes(strlen(user_id)));
     msg.AddRange(System.Text.Encoding.ASCII.GetBytes(user_id));
     msg.AddRange(BitConverter.GetBytes(price.Item1));
     msg.AddRange(BitConverter.GetBytes(price.Item2));
     msg.AddRange(BitConverter.GetBytes(quantity));
     msg.AddRange(BitConverter.GetBytes(buy));
     msg.AddRange(BitConverter.GetBytes(strlen(asset1)));
     msg.AddRange(System.Text.Encoding.ASCII.GetBytes(asset1));
     msg.AddRange(BitConverter.GetBytes(strlen(asset2)));
     msg.AddRange(System.Text.Encoding.ASCII.GetBytes(asset2));
 }
Exemple #7
0
        private static void StartWriting(StreamWriter streamwriter)
        {
            //var text = MyTextHelper.Instance.EmploymentHistory;
            var textInLines = _text.Split('\n');
            var tuple = new MyTuple() { Writer = streamwriter, Text = textInLines} ;
            //Tuple <StreamWriter,string[],int> tuple = new Tuple <StreamWriter,string[],int>(streamwriter,textInLines,0)

            Timer t = new Timer(TimerCallback1, tuple, 0, _milliseconds);
            tuple.Time = t;
            //Timer time = new Timer(seconds * 1000);
            //foreach (var line in textInLines)
            //{

            //    streamwriter.WriteLine("data:" + line + "\n");
            //    streamwriter.Flush();
            //    Debug.WriteLine("Sent at: " + DateTime.Now.TimeOfDay + " " + line);
            //    Thread.Sleep(_milliseconds);

            //}
        }
	public static void HandleSomeEventA (string arg1, object arg2, double arg3, MyTuple mt)
	{
		Console.WriteLine ("SomeEvent handler A: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B);
	}
		private static void PrepareSinkSourceData(
			ref MyDefinitionId typeId,
			ref MyTuple<MySinkGroupData, MySourceGroupData> sinkSourceData,
			List<MyTuple<MyResourceSinkComponent, MyResourceSourceComponent>> sinkSourcePairs,
			List<int> stockpilingStorageList,
			List<int> otherStorageList)
		{
			stockpilingStorageList.Clear();
			otherStorageList.Clear();
			sinkSourceData.Item1.IsAdaptible = true;
			sinkSourceData.Item1.RequiredInput = 0f;
			sinkSourceData.Item1.RequiredInputCumulative = 0f;
			sinkSourceData.Item2.MaxAvailableResource = 0f;
			for (int pairIndex = 0; pairIndex < sinkSourcePairs.Count; ++pairIndex)
			{
				var sinkSourcePair = sinkSourcePairs[pairIndex];
				bool productionEnabled = sinkSourcePair.Item2.ProductionEnabledByType(typeId);
				bool isStockpiling = sinkSourcePair.Item2.Enabled && !productionEnabled && sinkSourcePair.Item1.RequiredInputByType(typeId) > 0;
				sinkSourceData.Item1.IsAdaptible = sinkSourceData.Item1.IsAdaptible && IsAdaptible(sinkSourcePair.Item1);
				sinkSourceData.Item1.RequiredInput += sinkSourcePair.Item1.RequiredInputByType(typeId);
				if (isStockpiling)
					sinkSourceData.Item1.RequiredInputCumulative += sinkSourcePair.Item1.RequiredInputByType(typeId);

				sinkSourceData.Item2.InfiniteCapacity = float.IsInfinity(sinkSourcePair.Item2.RemainingCapacityByType(typeId));
				if (isStockpiling)
					stockpilingStorageList.Add(pairIndex);
				else
				{
					otherStorageList.Add(pairIndex);
					if (sinkSourcePair.Item2.Enabled && productionEnabled)
						sinkSourceData.Item2.MaxAvailableResource += sinkSourcePair.Item2.MaxOutputByType(typeId);
				}
			}
		}
        public void Update(TimeSpan timestamp, UpdateFrequency updateFlags)
        {
            if (timestamp == TimeSpan.Zero)
            {
                return;
            }
            foreach (var bird in Hummingbirds)
            {
                if (bird.IsAlive())
                {
                    bird.Update();
                }
                else
                {
                    DeadBirds.Add(bird);
                }
            }

            foreach (var bird in DeadBirds)
            {
                DeregisterBird(bird);
            }

            runs++;
            if (runs % 20 == 0)
            {
                var intelItems = IntelProvider.GetFleetIntelligences(timestamp);

                // Get the top targets
                TopEnemies.Clear();
                EnemyToScore.Clear();

                foreach (var intelItem in intelItems)
                {
                    if (intelItem.Key.Item1 == IntelItemType.Enemy)
                    {
                        var esi  = (EnemyShipIntel)intelItem.Value;
                        var dist = (esi.GetPositionFromCanonicalTime(timestamp + IntelProvider.CanonicalTimeDiff) - Context.Reference.WorldMatrix.Translation).Length();
                        if (dist > MaxEngagementDist)
                        {
                            continue;
                        }

                        var priority = IntelProvider.GetPriority(esi.ID);
                        var size     = esi.Radius;

                        if (size < MinEngagementSize && priority < 3)
                        {
                            continue;
                        }

                        if (priority < 2)
                        {
                            continue;
                        }

                        int score = (int)(priority * 10000 + size);

                        EnemyToScore[esi] = score;

                        for (int i = 0; i <= TopEnemies.Count; i++)
                        {
                            if (i == TopEnemies.Count || score > EnemyToScore[TopEnemies[i]])
                            {
                                TopEnemies.Insert(i, esi);
                                break;
                            }
                        }
                    }
                }

                // Determine how many birds should be assigned to each enemy
                EnemyToNumBirds.Clear();

                int totalNeededBirds = 0;

                for (int i = 0; i < TopEnemies.Count && i < 4; i++)
                {
                    EnemyToNumBirds[TopEnemies[i]]      = EnemyCountToNumBirdsPerEnemy[TopEnemies.Count][i];
                    EnemyToAssignedBirds[TopEnemies[i]] = 0;
                    totalNeededBirds += EnemyToNumBirds[TopEnemies[i]];
                }

                // Remove excess birds from enemies
                foreach (var bird in Hummingbirds)
                {
                    var birdTargetID = BirdToEnemy[bird];
                    if (birdTargetID == 0)
                    {
                        continue;
                    }

                    if (!bird.IsCombatCapable())
                    {
                        BirdToEnemy[bird] = 0;
                        continue;
                    }

                    var birdTargetKey = MyTuple.Create(IntelItemType.Enemy, birdTargetID);
                    if (!intelItems.ContainsKey(birdTargetKey))
                    {
                        BirdToEnemy[bird] = 0;
                        continue;
                    }

                    var birdTarget = (EnemyShipIntel)intelItems[birdTargetKey];
                    if (!EnemyToNumBirds.ContainsKey(birdTarget) || EnemyToNumBirds[birdTarget] == 0)
                    {
                        BirdToEnemy[bird] = 0;
                        continue;
                    }

                    EnemyToNumBirds[birdTarget]--;
                    totalNeededBirds--;
                }

                // Assign birds to enemies
                foreach (var bird in Hummingbirds)
                {
                    if (totalNeededBirds == 0)
                    {
                        break;
                    }

                    // Bird can't fight, keep looking
                    if (!bird.IsCombatCapable())
                    {
                        continue;
                    }

                    // Bird already has target, keep looking
                    if (BirdToEnemy[bird] != 0)
                    {
                        continue;
                    }

                    EnemyShipIntel targetEnemy = null;
                    foreach (var enemy in EnemyToNumBirds.Keys)
                    {
                        if (EnemyToNumBirds[enemy] > 0)
                        {
                            targetEnemy = enemy;
                            break;
                        }
                    }

                    BirdToEnemy[bird] = targetEnemy.ID;
                    EnemyToNumBirds[targetEnemy]--;
                    totalNeededBirds--;
                }

                NeedsMoreBirds = totalNeededBirds > 0;
                int birdIndex;

                // ASSUME birds are not far enough from main controller that gravity direction matters too much
                var gravDir = Controller.GetTotalGravity();
                gravDir.Normalize();

                // For each enemy, assign bird target and destination
                foreach (var enemy in TopEnemies)
                {
                    birdIndex = 0;
                    foreach (var bird in Hummingbirds)
                    {
                        if (BirdToEnemy[bird] != enemy.ID)
                        {
                            continue;
                        }

                        if (bird.Gats.Count == 0)
                        {
                            continue;
                        }
                        var birdAltitudeTheta = Math.PI * ((runs / (BirdSineConstantSeconds * 30) % 2) - 1);
                        var birdSwayTheta     = Math.PI * ((runs / (BirdPendulumConstantSeconds * 30) % 2) - 1);
                        var targetPos         = enemy.GetPositionFromCanonicalTime(timestamp + IntelProvider.CanonicalTimeDiff);

                        bird.SetTarget(targetPos, enemy.GetVelocity() - gravDir * (float)TrigHelpers.FastCos(birdAltitudeTheta) * 2);

                        var targetToBase = bird.Base.WorldMatrix.Translation - targetPos;
                        targetToBase -= VectorHelpers.VectorProjection(targetToBase, gravDir);
                        var targetToBaseDist = targetToBase.Length();
                        targetToBase.Normalize();

                        var engageLocationLocus    = targetToBase * Math.Min(600, targetToBaseDist + 400) + targetPos;
                        var engageLocationSwayDir  = targetToBase.Cross(gravDir);
                        var engageLocationSwayDist = (TrigHelpers.FastCos(birdSwayTheta) - EnemyToAssignedBirds[enemy] * 0.5 + birdIndex + 0.5) * 100;

                        bird.SetDest(engageLocationLocus + engageLocationSwayDist * engageLocationSwayDir);

                        var birdDir = bird.Controller.WorldMatrix.Translation - Controller.WorldMatrix.Translation;
                        birdDir -= VectorHelpers.VectorProjection(birdDir, gravDir);;
                        var birdDist = birdDir.Length();

                        bird.Drive.DesiredAltitude = birdDist < 100 ? Hummingbird.RecommendedServiceCeiling :
                                                     (float)TrigHelpers.FastSin(birdAltitudeTheta + Math.PI * 0.5) *
                                                     (Hummingbird.RecommendedServiceCeiling - Hummingbird.RecommendedServiceFloor) + Hummingbird.RecommendedServiceFloor;

                        birdIndex++;
                    }
                }

                // Assign orbit task for unassigned birds
                int numReserveBirds = 0;
                foreach (var bird in Hummingbirds)
                {
                    if (BirdToEnemy[bird] == 0 && bird.IsCombatCapable())
                    {
                        numReserveBirds++;
                    }
                }
                birdIndex = 0;
                var randomPoint = new Vector3D(190, 2862, 809);
                randomPoint -= VectorHelpers.VectorProjection(randomPoint, gravDir);
                randomPoint.Normalize();

                var randomPointCross = randomPoint.Cross(gravDir);

                foreach (var bird in Hummingbirds)
                {
                    if (BirdToEnemy[bird] != 0)
                    {
                        continue;
                    }
                    bird.SetTarget(Vector3D.Zero, Vector3D.Zero);
                    bird.Drive.DesiredAltitude = 30;

                    if (bird.IsCombatCapable() && !bird.IsRetiring)
                    {
                        var birdOrbitTheta = Math.PI * (((2 * birdIndex / (float)numReserveBirds) + runs / (BirdOrbitSeconds * 30)) % 2 - 1);

                        var birdOrbitDest = Controller.WorldMatrix.Translation +
                                            TrigHelpers.FastCos(birdOrbitTheta) * randomPoint * BirdOrbitDist +
                                            TrigHelpers.FastSin(birdOrbitTheta) * randomPointCross * BirdOrbitDist;

                        bird.SetDest(birdOrbitDest);

                        birdIndex++;
                    }
                    else if (!bird.IsRetiring)
                    {
                        RetireBird(bird);
                    }
                    else if (bird.IsRetiring)
                    {
                        if (!bird.IsLanding)
                        {
                            var birdDir = bird.Controller.WorldMatrix.Translation - bird.Destination;
                            birdDir -= VectorHelpers.VectorProjection(birdDir, gravDir);
                            var birdDist = birdDir.Length();
                            birdDir.Normalize();

                            if (birdDist < 50)
                            {
                                bird.SetDest(Vector3D.Zero);
                                bird.Drive.Flush();
                                foreach (var engine in bird.Drive.HoverEngines)
                                {
                                    engine.AltitudeMin = 0;
                                }
                                bird.IsLanding = true;
                            }
                        }
                        else
                        {
                            double altitude;
                            bird.Controller.TryGetPlanetElevation(MyPlanetElevation.Surface, out altitude);
                            if (altitude < 6)
                            {
                                foreach (var engine in bird.Drive.HoverEngines)
                                {
                                    engine.Block.Enabled = false;
                                    DeadBirds.Add(bird);
                                }
                            }
                        }
                    }
                }
            }

            foreach (var cradle in Cradles)
            {
                if (cradle == null)
                {
                    continue;
                }
                cradle.Update();
            }

            if (runs % 60 == 0)
            {
                BirdReleaseTimeout--;
                for (int i = 0; i < Cradles.Count(); i++)
                {
                    if (Cradles[i] == null)
                    {
                        continue;
                    }
                    if (Cradles[i].Hummingbird == null)
                    {
                        Cradles[i].CheckHummingbird();
                    }
                    else if (NeedsMoreBirds && BirdReleaseTimeout <= 0)
                    {
                        Hummingbird bird = Cradles[i].Release();
                        bird.Base = Context.Reference;
                        RegisterBird(bird);
                        BirdReleaseTimeout = 5;
                    }
                }
            }

            DeadBirds.Clear();
        }
        public static void RemoveGPSFromEntity(string entityName, string GPSName, string GPSDescription, long playerId = -1)
        {
            MyEntity entity;
            if (MyEntities.TryGetEntityByName(entityName, out entity))
            {
                if (playerId == -1)
                    playerId = GetLocalPlayerId();
                MyTuple<string, string> gpsIdentifier = new MyTuple<string, string>(entityName, GPSName);

                var gps = MySession.Static.Gpss.GetGpsByName(playerId, GPSName);
                if (gps != null)
                    MySession.Static.Gpss.SendDelete(playerId, gps.Hash);
            }
        }
Exemple #12
0
 public void AddAsset(string asset, long quantity)
 {
     long i = eq[num[asset]].Item1;
     long r = eq[num[asset]].Item2;
     i += quantity / MAGIC;
     r += quantity % MAGIC;
     if (r >= MAGIC)
     {
         r -= MAGIC;
         ++i;
     }
     if (r < 0)
     {
         --i;
         r += MAGIC;
     }
     eq[num[asset]] = new MyTuple<long, long>(i, r);
 }
Exemple #13
0
 void GoHome(TimeSpan canonicalTime)
 {
     AgentSubsystem.AddTask(TaskType.Dock, MyTuple.Create(IntelItemType.NONE, (long)0), CommandType.Enqueue, 0, canonicalTime);
     Autopilot.Clear();
     Status = TaskStatus.Complete;
 }
Exemple #14
0
        void TryScan(TimeSpan localTime)
        {
            // Go through each target
            var intelItems    = IntelProvider.GetFleetIntelligences(localTime);
            var canonicalTime = localTime + IntelProvider.CanonicalTimeDiff;

            DetectedTargets.Clear();
            // WC only...
//            Context.Log.Debug("A");
            if (Context.WCAPI != null)
            {
                GetThreatsScratchpad.Clear();
                Context.WCAPI.GetSortedThreats(Context.Reference, GetThreatsScratchpad);

                foreach (var target in GetThreatsScratchpad.Keys)
                {
                    DetectedTargets[target.EntityId] = MyTuple.Create(target, true);
                }

                int priority = 0;
                while (true)
                {
                    var selectedTarget = Context.WCAPI.GetAiFocus(Context.Reference.CubeGrid.EntityId, priority);
                    if (selectedTarget == null)
                    {
                        break;
                    }
                    TryAddEnemyShipIntel(intelItems, localTime, canonicalTime, selectedTarget.Value, true, true);
                    break;
                }
            }
//            Context.Log.Debug("B");
            else
            {
                foreach (var turret in Turrets)
                {
                    if (!turret.HasTarget)
                    {
                        continue;
                    }

                    var target = turret.GetTargetedEntity();

                    if (!target.IsEmpty() && !DetectedTargets.ContainsKey(target.EntityId))
                    {
                        DetectedTargets[target.EntityId] = MyTuple.Create(target, false);
                    }
                }
            }
//            Context.Log.Debug("C");
            foreach (var target in DetectedTargets)
            {
                TryAddEnemyShipIntel(intelItems, localTime, canonicalTime, target.Value.Item1, target.Value.Item2);
            }
//            Context.Log.Debug("D");
            foreach (var kvp in intelItems)
            {
                if (kvp.Key.Item1 != IntelItemType.Enemy)
                {
                    continue;
                }
                EnemyShipIntel enemy = (EnemyShipIntel)kvp.Value;

                int priority = IntelProvider.GetPriority(kvp.Key.Item2);
                if (priority < 1)
                {
                    continue;
                }

                if (!EnemyShipIntel.PrioritizeTarget(enemy))
                {
                    continue;
                }
                if (enemy.LastValidatedCanonicalTime + TimeSpan.FromSeconds(0.2) > canonicalTime)
                {
                    continue;
                }
                if (enemy.LastValidatedCanonicalTime + TimeSpan.FromSeconds(0.4) > canonicalTime && priority < 4)
                {
                    continue;
                }

                Vector3D targetPosition = kvp.Value.GetPositionFromCanonicalTime(canonicalTime);

                TryScanTarget(targetPosition, localTime, enemy);
            }
        }
Exemple #15
0
            public override void HandleCallback(string callback)
            {
                switch (callback)
                {
                case "unicast":
                    MyIGCMessage message = Drone.NetworkService.GetUnicastListener().AcceptMessage();

                    if (message.Data == null)
                    {
                        Drone.LogToLcd($"\nNo Message");
                    }

                    if (message.Tag == DockingRequestChannel)
                    {
                        Drone.LogToLcd("\nReceived Docking Request");
                        IMyShipConnector dockingPort = GetFreeDockingPort();

                        if (dockingPort == null)
                        {
                            Drone.LogToLcd("\nNo Free Docking Port");
                        }
                        else
                        {
                            MyTuple <Vector3D, Vector3D, Vector3D> payload = new MyTuple <Vector3D, Vector3D, Vector3D>();
                            payload.Item1 = dockingPort.GetPosition() + dockingPort.WorldMatrix.Forward * 40;
                            payload.Item2 = dockingPort.GetPosition() + 1.5 * dockingPort.WorldMatrix.Forward;

                            Drone.LogToLcd($"\nClearance granted: {message.Source}");
                            Drone.LogToLcd($"\nApproach: {payload.Item1.ToString()}");
                            Drone.LogToLcd($"\nDocking Port: { payload.Item2.ToString()}");

                            Drone.Program.IGC.SendUnicastMessage(message.Source, DockingRequestChannel, payload);
                        }
                    }
                    else if (message.Tag == "Notifications")
                    {
                        Drone.LogToLcd($"Received notification:{message.Data.ToString()}");
                        DroneKlaxon.LoopPeriod = 2f;
                        DroneKlaxon.Play();
                    }
                    else if (message.Tag == "survey_reports")
                    {
                        MyTuple <long, string, double, Vector3D, Vector3D, Vector3D> report = (MyTuple <long, string, double, Vector3D, Vector3D, Vector3D>)message.Data;
                        Drone.LogToLcd($"Received survey_report: {report.ToString()}");

                        //TODO: This needs to be in a persistence layer, not the CustomData
                        MyIni            ini = new MyIni();
                        MyIniParseResult config;
                        if (!ini.TryParse(Drone.Program.Me.CustomData, out config))
                        {
                            throw new Exception($"Error parsing config: {config.ToString()}");
                        }

                        //TODO: what about multiple deposits?
                        ini.Set($"deposit {report.Item1.ToString()}", "deposit_type", report.Item2.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "deposit_depth", report.Item3.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "top_left_corner", report.Item4.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "top_right_corner", report.Item5.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "bottom_left_corner", report.Item6.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "index", 0);

                        Drone.Program.Me.CustomData = ini.ToString();
                    }
                    else if (message.Tag == "tunnel_complete")
                    {
                        MyIni ini = new MyIni();

                        MyIniParseResult config;
                        if (!ini.TryParse(Drone.Program.Me.CustomData, out config))
                        {
                            throw new Exception($"Error parsing config: {config.ToString()}");
                        }

                        int completedIndex = (int)message.Data;

                        List <string> sections = new List <string>();
                        ini.GetSections(sections);
                        IEnumerable <string> deposits = sections.Where(record => record.StartsWith("deposit"));
                        string deposit;

                        if (deposits != null && deposits.Count() != 0)
                        {
                            deposit = deposits.First();
                        }
                        else
                        {
                            throw new Exception("No deposit data found!");
                        }

                        ini.Set(deposit, "index", completedIndex + 1);
                        Drone.Program.Me.CustomData = ini.ToString();
                    }

                    break;

                case "docking_request_pending":
                    ProcessDockingRequest();
                    break;

                case "recall_miner":
                    Drone.LogToLcd("Recalling miner");
                    Drone.Program.IGC.SendUnicastMessage(MinerAddress, "recall", "recall");
                    break;

                case "recall_surveyor":
                    Drone.LogToLcd("Recalling surveyor");
                    Drone.Program.IGC.SendUnicastMessage(SurveyorAddress, "recall", "recall");
                    break;

                case "deploy_miner":
                    Drone.LogToLcd("Launching miner");

                    List <IMyProgrammableBlock> miners = new List <IMyProgrammableBlock>();
                    Drone.Grid().GetBlocksOfType(miners, pb => MyIni.HasSection(pb.CustomData, "miner"));

                    //We only support one miner for now
                    // Set the deposit details in the miners config
                    IMyProgrammableBlock miner   = miners.First();
                    MyIni            minerConfig = new MyIni();
                    MyIniParseResult result;
                    if (!minerConfig.TryParse(miner.CustomData, out result))
                    {
                        Drone.LogToLcd(miner.CustomData);
                        throw new Exception($"Error parsing config: {result.ToString()}");
                    }

                    //Vector3D MiningSite = DepositCentre + 10 * Vector3D.Normalize(DepositNormal);
                    //Vector3D TunnelEnd = DepositCentre - DepositDepth * Vector3D.Normalize(DepositNormal);

                    //get deposit data from catalogue
                    //calculate mining_site for next tunnel
                    //calculate tunnel_end from mining_site and depth
                    MyIni asteroidCatalogue = new MyIni();
                    asteroidCatalogue.TryParse(Drone.Program.Me.CustomData);
                    Tunnel tunnel = new Tunnel(asteroidCatalogue);

                    minerConfig.Set("miner", "mining_site", tunnel.StartingPoint.ToString());
                    minerConfig.Set("miner", "tunnel_end", tunnel.EndPoint.ToString());
                    minerConfig.Set("miner", "index", tunnel.TunnelIndex);
                    miner.CustomData = minerConfig.ToString();

                    miner.TryRun("launch");
                    break;

                case "deploy_surveyor":
                    Drone.LogToLcd("Launching surveyor");

                    List <IMyProgrammableBlock> surveyors = new List <IMyProgrammableBlock>();
                    Drone.Grid().GetBlocksOfType(surveyors, pb => MyIni.HasSection(pb.CustomData, "surveyor"));
                    IMyProgrammableBlock surveyor = surveyors.First();

                    surveyor.TryRun("launch");
                    break;

                case "echo":
                    Drone.LogToLcd("Echo");
                    DroneKlaxon.Play();
                    break;

                case "":
                    // Just Ignore empty arguments
                    break;

                default:
                    Drone.LogToLcd($"\nDrone received unrecognized callback: {callback}");
                    break;
                }
            }
Exemple #16
0
 public static void PrintTuple <T1, T2, T3>(MyTuple <T1, T2, T3> tuple)
 {
     Console.WriteLine(tuple.FirstItem + " -> " + tuple.SecondItem + " -> " + tuple.ThirdItem);
 }
Exemple #17
0
 internal void SetCascadeUpdateInterval(int cascadeNumber, int updateInterval, int updateIntervalFrame)
 {
     Debug.Assert(updateInterval > 0, "Update interval must be strictly positive!");
     Debug.Assert(updateInterval > updateIntervalFrame);
     m_shadowCascadeUpdateIntervals[cascadeNumber] = MyTuple.Create(updateInterval, updateIntervalFrame);
 }
        public override IMove GetNextMove(IBoard board)
        {
            //Im the max player
            var   maxResult = int.MinValue;
            IMove moveToDo  = null;
            var   rnd       = new Random();

            var possiblesMoves = board.GetPlausibleMoves(this);

            //to list to avoid multiples iteration
            var possiblesMoveList = possiblesMoves as List <IMove> ?? possiblesMoves.ToList();

            if (possiblesMoves == null || !possiblesMoveList.Any())
            {
                _nextMoveCancelled = false;
                return(new Move(true));
            }

            //sort to get better results
            //for improve, the first level will be sorted by board utility
            ComaprerByUtility.Board = board;
            possiblesMoveList.Sort(ComaprerByUtility);
            //possiblesMoveList.Sort(new ComparerByUtilityBoardDescending { Player = this, Board = board });



            //Increment the deep search if game is advanced
            var count = board.BlackPoints.Count + board.WhitePoints.Count - 4;

            //MaxLevel = count >= MiddleGameLevel ? OriginalMaxLevel + 3 : count >= EndGameLevel ? EndGameLevel : OriginalMaxLevel;

            MaxLevel = count >= EndGameLevel
                           ? EndGameLevel
                           : count >= MiddleGameLevel ? OriginalMaxLevel + 2 : OriginalMaxLevel;

            if (possiblesMoveList.Count > 1)

            {
                //Start the threads
                var board1            = board.Clone() as IBoard;
                var board2            = board.Clone() as IBoard;
                var thread1GiveResult = false;
                var thread2GiveResult = false;

                var moveList1  = new List <IMove>();
                var moveList2  = new List <IMove>();
                var middleList = possiblesMoveList.Count / 2;
                for (int i = 0; i < middleList; i++)
                {
                    moveList1.Add(possiblesMoveList[i]);
                }
                for (int i = middleList; i < possiblesMoveList.Count; i++)
                {
                    moveList2.Add(possiblesMoveList[i]);
                }

                var thread1 = new BackgroundWorker();

                var thread2 = new BackgroundWorker();


                MyTuple <int, IMove> thread1Result = null;
                MyTuple <int, IMove> thread2Result = null;

                thread1.DoWork += (_, __) =>
                {
                    thread1Result     = MaxInThread(board1, moveList1);
                    thread1GiveResult = true;
                };
                thread2.DoWork += (_, __) =>
                {
                    thread2Result     = MaxInThread(board2, moveList2);
                    thread2GiveResult = true;
                };
                thread1.RunWorkerAsync();
                thread2.RunWorkerAsync();
                while (!_nextMoveCancelled && (!thread1GiveResult || !thread2GiveResult)) //while any of both thread working
                {
                    Thread.Sleep(200);
                }
                if (_nextMoveCancelled)
                {
                    _nextMoveCancelled = false;
                    return(null);
                }

                return(thread2Result.Item1 > thread1Result.Item1 ? thread2Result.Item2 : thread1Result.Item2);
            }
            else
            {
                var result = MaxInThread(board, possiblesMoveList);
                _nextMoveCancelled = false;
                return(result.Item2);
            }
        }
        void RecallCrafts(TimeSpan localTime)
        {
            FriendlyShipScratchpad.Clear();

            var intelItems = IntelProvider.GetFleetIntelligences(localTime);

            foreach (var kvp in intelItems)
            {
                if (kvp.Key.Item1 == IntelItemType.Friendly)
                {
                    var friendly = (FriendlyShipIntel)kvp.Value;
                    if (!string.IsNullOrEmpty(friendly.CommandChannelTag))
                    {
                        FriendlyShipScratchpad.Add(friendly);
                    }
                }
            }

            if (FriendlyShipScratchpad.Count == 0)
            {
                return;
            }

            for (int i = 0; i < FriendlyShipScratchpad.Count; i++)
            {
                IntelProvider.ReportCommand(FriendlyShipScratchpad[i], TaskType.Dock, MyTuple.Create(IntelItemType.NONE, (long)0), localTime);
            }
        }
        void Attack(TimeSpan localTime)
        {
            FriendlyShipScratchpad.Clear();

            var intelItems = IntelProvider.GetFleetIntelligences(localTime);

            foreach (var kvp in intelItems)
            {
                if (kvp.Key.Item1 == IntelItemType.Friendly)
                {
                    var friendly = (FriendlyShipIntel)kvp.Value;
                    if (friendly.AgentClass == AgentClass.Fighter && (friendly.AgentStatus & AgentStatus.Docked) != 0 && (friendly.GetPositionFromCanonicalTime(localTime + IntelProvider.CanonicalTimeDiff) - Controller.GetPosition()).Length() < 100)
                    {
                        FriendlyShipScratchpad.Add(friendly);
                    }
                }
            }

            if (FriendlyShipScratchpad.Count == 0)
            {
                return;
            }

            for (int i = 0; i < FriendlyShipScratchpad.Count; i++)
            {
                var targetWaypoint = new Waypoint();

                var gravDir = Controller.GetNaturalGravity();
                targetWaypoint.Position = Controller.GetPosition();
                var angle = 2 * i * Math.PI / FriendlyShipScratchpad.Count;

                if (gravDir != Vector3D.Zero)
                {
                    gravDir.Normalize();
                    var flatForward = Controller.WorldMatrix.Forward - VectorHelpers.VectorProjection(Controller.WorldMatrix.Forward, gravDir);
                    flatForward.Normalize();
                    var flatLeftDir = Vector3D.Cross(flatForward, gravDir);
                    targetWaypoint.Position += (flatForward * TrigHelpers.FastCos(angle) + flatLeftDir * TrigHelpers.FastSin(angle)) * 500;
                    targetWaypoint.Position -= gravDir * 200;
                }
                else
                {
                    targetWaypoint.Position += (Controller.WorldMatrix.Forward * TrigHelpers.FastCos(angle) + Controller.WorldMatrix.Left * TrigHelpers.FastSin(angle)) * 500;
                }

                targetWaypoint.Position += Controller.GetShipVelocities().LinearVelocity * 3;
                IntelProvider.ReportFleetIntelligence(targetWaypoint, localTime);
                IntelProvider.ReportCommand(FriendlyShipScratchpad[i], TaskType.Attack, MyTuple.Create(IntelItemType.Waypoint, targetWaypoint.ID), localTime);
            }
        }
Exemple #21
0
        public void Do(Dictionary <MyTuple <IntelItemType, long>, IFleetIntelligence> IntelItems, TimeSpan canonicalTime, Profiler profiler)
        {
            IMyShipController controller = Autopilot.Controller;
            var      currentPosition     = controller.WorldMatrix.Translation;
            Vector3D linearVelocity      = controller.GetShipVelocities().LinearVelocity;

            if (!TargetPositionSet)
            {
                if (IntelKey.Item1 == IntelItemType.Waypoint && IntelItems.ContainsKey(IntelKey))
                {
                    TargetPosition = IntelItems[IntelKey].GetPositionFromCanonicalTime(canonicalTime);
                }
                TargetPositionSet = true;
            }

            Vector3D worldAttackPoint;

            if (TargetPositionSet && TargetPosition != Vector3D.Zero)
            {
                worldAttackPoint = TargetPosition;
            }
            else
            {
                if (IntelKey.Item1 != IntelItemType.Enemy || !IntelItems.ContainsKey(IntelKey))
                {
                    AgentSubsystem.AddTask(TaskType.Dock, MyTuple.Create(IntelItemType.NONE, (long)0), CommandType.Enqueue, 0, canonicalTime);
                    Status = TaskStatus.Aborted;
                    return;
                }

                var target = (EnemyShipIntel)IntelItems[IntelKey];
                worldAttackPoint = currentPosition + AttackHelpers.GetAttackPoint(target.GetVelocity(), target.GetPositionFromCanonicalTime(canonicalTime) + target.GetVelocity() * 0.08 - currentPosition, 98);
            }

            Vector3D dirToTarget = worldAttackPoint - currentPosition;

            if (dirToTarget.Length() < LocustCombatSystem.kEngageRange && deployTime == TimeSpan.Zero)
            {
                CombatSystem.Deploy();
                deployTime = canonicalTime;
            }

            dirToTarget.Normalize();
            LeadTask.Destination.Direction = dirToTarget;
            LeadTask.Destination.Position  = worldAttackPoint + dirToTarget * 400;

            if (deployTime != TimeSpan.Zero)
            {
                if (deployTime + TimeSpan.FromSeconds(2) < canonicalTime)
                {
                    AgentSubsystem.AddTask(TaskType.Dock, MyTuple.Create(IntelItemType.NONE, (long)0), CommandType.Enqueue, 0, canonicalTime);
                    Status = TaskStatus.Aborted;
                    return;
                }
                else
                {
                    LeadTask.Destination.DirectionUp = Math.Sin(kRotateTheta) * controller.WorldMatrix.Right + Math.Cos(kRotateTheta) * controller.WorldMatrix.Up;
                }
            }

            LeadTask.Do(IntelItems, canonicalTime, profiler);
        }
 public ITask GenerateTask(TaskType type, MyTuple <IntelItemType, long> intelKey, Dictionary <MyTuple <IntelItemType, long>, IFleetIntelligence> IntelItems, TimeSpan canonicalTime, long myID)
 {
     return(MyTask);
 }
Exemple #23
0
        public LocustAttackTask(MyGridProgram program, LocustCombatSystem combatSystem, IAutopilot autopilot, IAgentSubsystem agentSubsystem, MyTuple <IntelItemType, long> intelKey)
        {
            Program        = program;
            CombatSystem   = combatSystem;
            Autopilot      = autopilot;
            AgentSubsystem = agentSubsystem;
            IntelKey       = intelKey;

            Status = TaskStatus.Incomplete;

            LeadTask = new WaypointTask(Program, Autopilot, new Waypoint(), WaypointTask.AvoidObstacleMode.Avoid);
        }
Exemple #24
0
        internal void RecordCommandLists(MyCullQuery processedCullQuery, Queue <CommandList> outCommandLists)
        {
            ProfilerShort.Begin("PrepareWork");

            ProfilerShort.Begin("Init");
            Debug.Assert(m_workList.Count == 0, "Work list not cleared after use!");

            foreach (List <MyRenderCullResultFlat> cullResults in m_passElements)
            {
                cullResults.Clear();
                m_sortListPool.Deallocate(cullResults);
            }
            m_passElements.Clear();
            m_passElements2.Clear();

            for (int renderPassIndex = 0; renderPassIndex < processedCullQuery.Size; ++renderPassIndex)
            {
                if (!MyRender11.DeferredContextsEnabled)
                {
                    processedCullQuery.RenderingPasses[renderPassIndex].SetImmediate(true);
                }

                m_passElements.Add(m_sortListPool.Allocate());
                m_passElements2.Add(null);
            }

            ProfilerShort.BeginNextBlock("Flatten");
            for (int i = 0; i < processedCullQuery.Size; ++i)
            {
                m_affectedQueueIds.SetSize(0);
                var frustumQuery = processedCullQuery.FrustumCullQueries[i];

                for (int renderPassIndex = 0; renderPassIndex < processedCullQuery.Size; renderPassIndex++)
                {
                    if ((processedCullQuery.RenderingPasses[renderPassIndex].ProcessingMask & frustumQuery.Bitmask) > 0)
                    {
                        m_affectedQueueIds.Add(renderPassIndex);
                    }
                }

                var cullProxies = frustumQuery.List;
                var queryType   = frustumQuery.Type;

                foreach (MyCullProxy cullProxy in cullProxies)
                {
                    var renderableProxies = cullProxy.RenderableProxies;
                    if (renderableProxies == null)
                    {
                        continue;
                    }

                    for (int proxyIndex = 0; proxyIndex < renderableProxies.Length; ++proxyIndex)
                    {
                        var flag = renderableProxies[proxyIndex].DrawSubmesh.Flags;
                        if (queryType == MyFrustumEnum.MainFrustum)
                        {
                            if ((flag & MyDrawSubmesh.MySubmeshFlags.Gbuffer) != MyDrawSubmesh.MySubmeshFlags.Gbuffer)
                            {
                                continue;
                            }
                        }
                        else if (queryType == MyFrustumEnum.ShadowCascade || queryType == MyFrustumEnum.ShadowProjection)
                        {
                            if ((flag & MyDrawSubmesh.MySubmeshFlags.Depth) != MyDrawSubmesh.MySubmeshFlags.Depth)
                            {
                                continue;
                            }
                        }

                        MyRenderableProxy renderableProxy = renderableProxies[proxyIndex];
                        ulong             sortKey         = cullProxy.SortingKeys[proxyIndex];

                        for (int queueIndex = 0; queueIndex < m_affectedQueueIds.Count; ++queueIndex)
                        {
                            var queueId = m_affectedQueueIds[queueIndex];
                            var item    = new MyRenderCullResultFlat
                            {
                                SortKey     = sortKey,
                                RenderProxy = renderableProxy,
                            };

                            m_passElements[queueId].Add(item);
                        }
                    }
                }

                // proxy 2
                var list2 = frustumQuery.List2;

                // flatten and sort
                m_flattenedKeys.SetSize(0);
                m_indirectionList.SetSize(0);
                m_location.SetSize(0);

                int indirectionCounter = 0;
                for (int list2Index = 0; list2Index < list2.Count; ++list2Index)
                {
                    for (int sortKeyIndex = 0; sortKeyIndex < list2[list2Index].SortingKeys.Length; sortKeyIndex++)
                    {
                        m_flattenedKeys.Add(list2[list2Index].SortingKeys[sortKeyIndex]);
                        m_indirectionList.Add(indirectionCounter++);
                        m_location.Add(MyTuple.Create(list2Index, sortKeyIndex));
                    }
                }

                MyRenderableProxy_2[] flattenedProxies = null;

                if (indirectionCounter > 0)
                {
                    flattenedProxies = new MyRenderableProxy_2[indirectionCounter];
                }

                m_sortingKeysComparer.Values = m_flattenedKeys;
                m_indirectionList.Sort(0, m_indirectionList.Count, m_sortingKeysComparer);

                if (flattenedProxies != null)
                {
                    for (int e = 0; e < indirectionCounter; e++)
                    {
                        var l = m_location[m_indirectionList[e]];
                        flattenedProxies[e] = list2[l.Item1].Proxies[l.Item2];
                    }
                }

                for (int l = 0; l < m_affectedQueueIds.Count; l++)
                {
                    m_passElements2[m_affectedQueueIds[l]] = flattenedProxies;
                }
            }
            ProfilerShort.BeginNextBlock("Sort");
            foreach (var flatCullResults in m_passElements)
            {
                foreach (MyRenderCullResultFlat element in flatCullResults)
                {
                    List <MyRenderCullResultFlat> sortList;
                    if (m_tmpSortListDictionary.TryGetValue(element.SortKey, out sortList))
                    {
                        sortList.Add(element);
                    }
                    else
                    {
                        sortList = m_sortListPool.Allocate();
                        sortList.Add(element);
                        m_tmpSortListDictionary.Add(element.SortKey, sortList);
                    }
                }
                flatCullResults.Clear();
                foreach (var sortList in m_tmpSortListDictionary.Values)
                {
                    flatCullResults.AddList(sortList);
                    sortList.SetSize(0);
                    m_sortListPool.Deallocate(sortList);
                }
                m_tmpSortListDictionary.Clear();
            }

            int jobsNum = GetRenderingThreadsNum();

            // always amortize this path
            ProfilerShort.BeginNextBlock("WorkAmortization");

            //passElements.RemoveAll(x => x.Count == 0);

            int workSum = 0;

            foreach (var list in m_passElements)
            {
                workSum += list.Count;
            }

            int batchWork = (workSum + jobsNum - 1) / jobsNum;

            Debug.Assert(m_subworks.Count == 0);

            int work = 0;

            for (int passElementIndex = 0; passElementIndex < m_passElements.Count; ++passElementIndex)
            {
                var flatCullResults = m_passElements[passElementIndex];
                if (flatCullResults.Count == 0)
                {
                    MyObjectPoolManager.Deallocate(processedCullQuery.RenderingPasses[passElementIndex]);
                    processedCullQuery.RenderingPasses[passElementIndex] = null;
                    if (m_passElements2[passElementIndex] == null || m_passElements2[passElementIndex].Length == 0)
                    {
                        continue;
                    }
                }

                if (processedCullQuery.RenderingPasses[passElementIndex] == null)
                {
                    continue;
                }

                int passBegin = 0;

                if (m_passElements2[passElementIndex] != null && m_passElements2[passElementIndex].Length > 0)
                {
                    m_subworks.Add(new MyRenderingWorkItem
                    {
                        Pass  = processedCullQuery.RenderingPasses[passElementIndex].Fork(),
                        List2 = m_passElements2[passElementIndex]
                    });
                }

                while (passBegin < flatCullResults.Count)
                {
                    int toTake = Math.Min(flatCullResults.Count - passBegin, batchWork - work);

                    var workItem = new MyRenderingWorkItem
                    {
                        Renderables = flatCullResults,
                        Begin       = passBegin,
                        End         = passBegin + toTake
                    };

                    if (toTake < flatCullResults.Count && workItem.End != workItem.Renderables.Count)
                    {
                        workItem.Pass = processedCullQuery.RenderingPasses[passElementIndex].Fork();
                    }
                    else
                    {
                        workItem.Pass = processedCullQuery.RenderingPasses[passElementIndex];
                        processedCullQuery.RenderingPasses[passElementIndex] = null;    // Consume the pass so it doesn't get cleaned up later with the cull query, but instead with the work item
                    }

                    m_subworks.Add(workItem);

                    passBegin += toTake;
                    work      += toTake;

                    Debug.Assert(work <= batchWork);
                    if (work != batchWork)
                    {
                        continue;
                    }

                    if (MyRender11.DeferredContextsEnabled)
                    {
                        var renderWork = MyObjectPoolManager.Allocate <MyRenderingWorkRecordCommands>();
                        renderWork.Init(MyRenderContextPool.AcquireRC(), m_subworks);
                        m_workList.Add(renderWork);
                    }
                    else
                    {
                        var renderWork = MyObjectPoolManager.Allocate <MyRenderingWorkRecordCommands>();
                        renderWork.Init(m_subworks);
                        m_workList.Add(renderWork);
                    }

                    work = 0;

                    m_subworks.Clear();
                }
            }
            if (m_subworks.Count > 0)
            {
                if (MyRender11.DeferredContextsEnabled)
                {
                    var renderWork = MyObjectPoolManager.Allocate <MyRenderingWorkRecordCommands>();
                    renderWork.Init(MyRenderContextPool.AcquireRC(), m_subworks);
                    m_workList.Add(renderWork);
                }
                else
                {
                    var renderWork = MyObjectPoolManager.Allocate <MyRenderingWorkRecordCommands>();
                    renderWork.Init(m_subworks);
                    m_workList.Add(renderWork);
                }
                m_subworks.Clear();
            }

            ProfilerShort.End();

            ProfilerShort.End();

            DoRecordingWork(outCommandLists);

            foreach (var renderWork in m_workList)
            {
                MyObjectPoolManager.Deallocate(renderWork);
            }
            m_workList.Clear();
        }
Exemple #25
0
 public static void MUL(MyTuple<long, long> price, long quantity, out long q1, out long q2)
 {
     q1 = price.Item1 * quantity + price.Item2 * (quantity / MAGIC) + price.Item2 * (quantity % MAGIC) / MAGIC;
     q2 = price.Item2 * (quantity % MAGIC) % MAGIC;
 }
		public bool CanDoAction(string actionId, bool continuous, out MyTuple<ushort, MyStringHash> message)
		{
			MyStatAction action;
			if(!m_statActions.TryGetValue(actionId, out action)) 
            {
                message = new MyTuple<ushort, MyStringHash>(0, action.StatId);
				return true;
            }

            if (action.CanPerformWithout)
            {
                message = new MyTuple<ushort, MyStringHash>(0, action.StatId);
                return true;
            }

			MyEntityStat stat;
			if(!m_stats.TryGetValue(action.StatId, out stat))
            {
                message = new MyTuple<ushort, MyStringHash>(0, action.StatId);
				return true;
            }

            if (continuous)
            {
                if (stat.Value < action.Cost)
                {
                    message = new MyTuple<ushort, MyStringHash>(STAT_VALUE_TOO_LOW, action.StatId);
                    return false;
                }
            }
            else
            {
                if (stat.Value < action.Cost || stat.Value < action.AmountToActivate)
                {
                    message = new MyTuple<ushort, MyStringHash>(STAT_VALUE_TOO_LOW, action.StatId);
                    Debug.Write(String.Format("value: {0}, cost: {1}, activation: {2}", stat.Value, action.Cost, action.AmountToActivate));
                    return false;
                }
            }

            message = new MyTuple<ushort, MyStringHash>(0, action.StatId);
			return true;
		}
Exemple #27
0
 public void AddCurrency(string asset, long quantity, MyTuple<long, long> price)
 {
     long q1, q2;
     MUL(price, quantity, out q1, out q2);
     long i = eq[num[asset]].Item1;
     long r = eq[num[asset]].Item2;
     i += q1;
     r += q2;
     if (r >= MAGIC)
     {
         r -= MAGIC;
         ++i;
     }
     if (r < 0)
     {
         --i;
         r += MAGIC;
     }
     eq[num[asset]] = new MyTuple<long, long>(i, r);
 }
        public static void SetGPSHighlight(string entityName, string GPSName, string GPSDescription, bool enabled = true, int thickness = 1, int pulseTimeInFrames = 120, Color color = default(Color), long playerId = -1)
        {
            MyEntity entity;
            if (MyEntities.TryGetEntityByName(entityName, out entity))
            {
                if (playerId == -1)
                    playerId = GetLocalPlayerId();
                MyTuple<string, string> gpsIdentifier = new MyTuple<string, string>(entityName, GPSName);

                if (enabled)
                {
                    MyGps newGPS = new MyGps { ShowOnHud = true, Name = GPSName, Description = GPSDescription, AlwaysVisible = true };
                    MySession.Static.Gpss.SendAddGps(playerId, ref newGPS, entity.EntityId);
                }
                else
                {
                    var gps = MySession.Static.Gpss.GetGpsByName(playerId, GPSName);
                    if (gps != null)
                        MySession.Static.Gpss.SendDelete(playerId, gps.Hash);
                }
                SetHighlight(entityName, enabled: enabled, thickness: thickness, pulseTimeInFrames: pulseTimeInFrames, color: color, playerId: playerId);
            }
        }
Exemple #29
0
        internal bool GetTargetState(Session s)
        {
            var ai         = s.TrackingAi;
            var validFocus = false;
            var size0      = s.Settings.Enforcement.ShipSizes[0];
            var size1      = s.Settings.Enforcement.ShipSizes[1];
            var size2      = s.Settings.Enforcement.ShipSizes[2];
            var size3      = s.Settings.Enforcement.ShipSizes[3];
            var size4      = s.Settings.Enforcement.ShipSizes[4];
            var size5      = s.Settings.Enforcement.ShipSizes[5];
            var size6      = s.Settings.Enforcement.ShipSizes[6];

            if (s.Tick - MasterUpdateTick > 600 || MasterUpdateTick < 600 && _masterTargets.Count == 0)
            {
                BuildMasterCollections(ai);
            }

            for (int i = 0; i < ai.Construct.Data.Repo.FocusData.Target.Length; i++)
            {
                var      targetId = ai.Construct.Data.Repo.FocusData.Target[i];
                float    offenseRating;
                MyEntity target;
                if (targetId <= 0 || !MyEntities.TryGetEntityById(targetId, out target) || !_masterTargets.TryGetValue(target, out offenseRating))
                {
                    continue;
                }
                validFocus = true;
                if (!s.Tick20)
                {
                    continue;
                }
                var grid      = target as MyCubeGrid;
                var partCount = 1;
                var largeGrid = false;
                var smallGrid = false;
                if (grid != null)
                {
                    largeGrid = grid.GridSizeEnum == MyCubeSize.Large;
                    smallGrid = !largeGrid;
                    GridAi  targetAi;
                    GridMap gridMap;
                    if (s.GridToMasterAi.TryGetValue(grid, out targetAi))
                    {
                        partCount = targetAi.Construct.BlockCount;
                    }
                    else if (s.GridToInfoMap.TryGetValue(grid, out gridMap))
                    {
                        partCount = gridMap.MostBlocks;
                    }
                }

                var targetVel = target.Physics?.LinearVelocity ?? Vector3.Zero;
                if (MyUtils.IsZero(targetVel, 1E-01F))
                {
                    targetVel = Vector3.Zero;
                }
                var targetDir    = Vector3D.Normalize(targetVel);
                var targetRevDir = -targetDir;
                var targetPos    = target.PositionComp.WorldAABB.Center;
                var myPos        = ai.MyGrid.PositionComp.WorldAABB.Center;
                var myHeading    = Vector3D.Normalize(myPos - targetPos);

                if ((size6.LargeGrid && largeGrid || !size6.LargeGrid && smallGrid) && partCount > size6.BlockCount)
                {
                    ai.TargetState[i].Size = 6;
                }
                else if ((size5.LargeGrid && largeGrid || !size5.LargeGrid && smallGrid) && partCount > size5.BlockCount)
                {
                    ai.TargetState[i].Size = 5;
                }
                else if ((size4.LargeGrid && largeGrid || !size4.LargeGrid && smallGrid) && partCount > size4.BlockCount)
                {
                    ai.TargetState[i].Size = 4;
                }
                else if ((size3.LargeGrid && largeGrid || !size3.LargeGrid && smallGrid) && partCount > size3.BlockCount)
                {
                    ai.TargetState[i].Size = 3;
                }
                else if ((size2.LargeGrid && largeGrid || !size2.LargeGrid && smallGrid) && partCount > size2.BlockCount)
                {
                    ai.TargetState[i].Size = 2;
                }
                else if ((size1.LargeGrid && largeGrid || !size1.LargeGrid && smallGrid) && partCount > size1.BlockCount)
                {
                    ai.TargetState[i].Size = 1;
                }
                else
                {
                    ai.TargetState[i].Size = 0;
                }

                ai.TargetState[i].SizeExtended = partCount / (largeGrid ? 100f : 500f);

                var intercept = MathFuncs.IsDotProductWithinTolerance(ref targetDir, ref myHeading, s.ApproachDegrees);
                var retreat   = MathFuncs.IsDotProductWithinTolerance(ref targetRevDir, ref myHeading, s.ApproachDegrees);
                if (intercept)
                {
                    ai.TargetState[i].Engagement = 0;
                }
                else if (retreat)
                {
                    ai.TargetState[i].Engagement = 1;
                }
                else
                {
                    ai.TargetState[i].Engagement = 2;
                }

                var distanceFromCenters = Vector3D.Distance(ai.MyGrid.PositionComp.WorldAABB.Center, target.PositionComp.WorldAABB.Center);
                distanceFromCenters -= ai.MyGrid.PositionComp.LocalVolume.Radius;
                distanceFromCenters -= target.PositionComp.LocalVolume.Radius;
                distanceFromCenters  = distanceFromCenters <= 0 ? 0 : distanceFromCenters;

                var distPercent = (distanceFromCenters / ai.MaxTargetingRange) * 100;
                if (distPercent > 95)
                {
                    ai.TargetState[i].Distance = 9;
                }
                else if (distPercent > 90)
                {
                    ai.TargetState[i].Distance = 8;
                }
                else if (distPercent > 80)
                {
                    ai.TargetState[i].Distance = 7;
                }
                else if (distPercent > 70)
                {
                    ai.TargetState[i].Distance = 6;
                }
                else if (distPercent > 60)
                {
                    ai.TargetState[i].Distance = 5;
                }
                else if (distPercent > 50)
                {
                    ai.TargetState[i].Distance = 4;
                }
                else if (distPercent > 40)
                {
                    ai.TargetState[i].Distance = 3;
                }
                else if (distPercent > 30)
                {
                    ai.TargetState[i].Distance = 2;
                }
                else if (distPercent > 20)
                {
                    ai.TargetState[i].Distance = 1;
                }
                else if (distPercent > 0)
                {
                    ai.TargetState[i].Distance = 0;
                }
                else
                {
                    ai.TargetState[i].Distance = -1;
                }

                var speed = Math.Round(target.Physics?.Speed ?? 0, 1);
                if (speed <= 0)
                {
                    ai.TargetState[i].Speed = -1;
                }
                else
                {
                    var speedPercent = (speed / s.MaxEntitySpeed) * 100;
                    if (speedPercent > 95)
                    {
                        ai.TargetState[i].Speed = 9;
                    }
                    else if (speedPercent > 90)
                    {
                        ai.TargetState[i].Speed = 8;
                    }
                    else if (speedPercent > 80)
                    {
                        ai.TargetState[i].Speed = 7;
                    }
                    else if (speedPercent > 70)
                    {
                        ai.TargetState[i].Speed = 6;
                    }
                    else if (speedPercent > 60)
                    {
                        ai.TargetState[i].Speed = 5;
                    }
                    else if (speedPercent > 50)
                    {
                        ai.TargetState[i].Speed = 4;
                    }
                    else if (speedPercent > 40)
                    {
                        ai.TargetState[i].Speed = 3;
                    }
                    else if (speedPercent > 30)
                    {
                        ai.TargetState[i].Speed = 2;
                    }
                    else if (speedPercent > 20)
                    {
                        ai.TargetState[i].Speed = 1;
                    }
                    else if (speedPercent > 0.3)
                    {
                        ai.TargetState[i].Speed = 0;
                    }
                    else
                    {
                        ai.TargetState[i].Speed = -1;
                    }
                }

                MyTuple <bool, bool, float, float, float, int> shieldInfo = new MyTuple <bool, bool, float, float, float, int>();
                if (s.ShieldApiLoaded)
                {
                    shieldInfo = s.SApi.GetShieldInfo(target);
                }
                if (shieldInfo.Item1)
                {
                    var shieldPercent = shieldInfo.Item5;
                    if (shieldPercent > 95)
                    {
                        ai.TargetState[i].ShieldHealth = 9;
                    }
                    else if (shieldPercent > 90)
                    {
                        ai.TargetState[i].ShieldHealth = 8;
                    }
                    else if (shieldPercent > 80)
                    {
                        ai.TargetState[i].ShieldHealth = 7;
                    }
                    else if (shieldPercent > 70)
                    {
                        ai.TargetState[i].ShieldHealth = 6;
                    }
                    else if (shieldPercent > 60)
                    {
                        ai.TargetState[i].ShieldHealth = 5;
                    }
                    else if (shieldPercent > 50)
                    {
                        ai.TargetState[i].ShieldHealth = 4;
                    }
                    else if (shieldPercent > 40)
                    {
                        ai.TargetState[i].ShieldHealth = 3;
                    }
                    else if (shieldPercent > 30)
                    {
                        ai.TargetState[i].ShieldHealth = 2;
                    }
                    else if (shieldPercent > 20)
                    {
                        ai.TargetState[i].ShieldHealth = 1;
                    }
                    else if (shieldPercent > 0)
                    {
                        ai.TargetState[i].ShieldHealth = 0;
                    }
                    else
                    {
                        ai.TargetState[i].ShieldHealth = -1;
                    }
                }
                else
                {
                    ai.TargetState[i].ShieldHealth = -1;
                }

                var friend = false;
                if (grid != null && grid.BigOwners.Count != 0)
                {
                    var relation = MyIDModule.GetRelationPlayerBlock(ai.AiOwner, grid.BigOwners[0], MyOwnershipShareModeEnum.Faction);
                    if (relation == MyRelationsBetweenPlayerAndBlock.FactionShare || relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.Friends)
                    {
                        friend = true;
                    }
                }

                if (friend)
                {
                    ai.TargetState[i].ThreatLvl = -1;
                }
                else
                {
                    int shieldBonus = 0;
                    if (s.ShieldApiLoaded)
                    {
                        var myShieldInfo = s.SApi.GetShieldInfo(ai.MyGrid);
                        if (shieldInfo.Item1 && myShieldInfo.Item1)
                        {
                            shieldBonus = shieldInfo.Item5 > myShieldInfo.Item5 ? 1 : -1;
                        }
                        else if (shieldInfo.Item1)
                        {
                            shieldBonus = 1;
                        }
                        else if (myShieldInfo.Item1)
                        {
                            shieldBonus = -1;
                        }
                    }

                    if (offenseRating > 5)
                    {
                        ai.TargetState[i].ThreatLvl = shieldBonus < 0 ? 8 : 9;
                    }
                    else if (offenseRating > 4)
                    {
                        ai.TargetState[i].ThreatLvl = 8 + shieldBonus;
                    }
                    else if (offenseRating > 3)
                    {
                        ai.TargetState[i].ThreatLvl = 7 + shieldBonus;
                    }
                    else if (offenseRating > 2)
                    {
                        ai.TargetState[i].ThreatLvl = 6 + shieldBonus;
                    }
                    else if (offenseRating > 1)
                    {
                        ai.TargetState[i].ThreatLvl = 5 + shieldBonus;
                    }
                    else if (offenseRating > 0.5)
                    {
                        ai.TargetState[i].ThreatLvl = 4 + shieldBonus;
                    }
                    else if (offenseRating > 0.25)
                    {
                        ai.TargetState[i].ThreatLvl = 3 + shieldBonus;
                    }

                    else if (offenseRating > 0.125)
                    {
                        ai.TargetState[i].ThreatLvl = 2 + shieldBonus;
                    }
                    else if (offenseRating > 0.0625)
                    {
                        ai.TargetState[i].ThreatLvl = 1 + shieldBonus;
                    }
                    else if (offenseRating > 0)
                    {
                        ai.TargetState[i].ThreatLvl = shieldBonus > 0 ? 1 : 0;
                    }
                    else
                    {
                        ai.TargetState[i].ThreatLvl = -1;
                    }
                }
            }
            return(validFocus);
        }
Exemple #30
0
        internal void Init()
        {
            if (Inited)
            {
                return;
            }
            Inited = true;
            Log.Init("debug", this);
            Log.Init("perf", this, false);
            Log.Init("stats", this, false);
            Log.Init("net", this, false);
            Log.Init("report", this, false);
            Log.Init("combat", this, false);

            MpActive        = MyAPIGateway.Multiplayer.MultiplayerActive;
            IsServer        = MyAPIGateway.Multiplayer.IsServer;
            DedicatedServer = MyAPIGateway.Utilities.IsDedicated;
            IsCreative      = MyAPIGateway.Session.CreativeMode;
            IsClient        = !IsServer && !DedicatedServer && MpActive;
            HandlesInput    = !IsServer || IsServer && !DedicatedServer;
            IsHost          = IsServer && !DedicatedServer && MpActive;
            MpServer        = IsHost || DedicatedServer;

            foreach (var x in WeaponDefinitions)
            {
                foreach (var ammo in x.Ammos)
                {
                    var ae             = ammo.AreaEffect;
                    var areaRadius     = ae.Base.Radius > 0 ? ae.Base.Radius : ae.AreaEffectRadius;
                    var detonateRadius = ae.Detonation.DetonationRadius;
                    var fragments      = ammo.Shrapnel.Fragments > 0 ? ammo.Shrapnel.Fragments : 1;
                    if (areaRadius > 0)
                    {
                        if (!LargeBlockSphereDb.ContainsKey(ModRadius(areaRadius, true)))
                        {
                            GenerateBlockSphere(MyCubeSize.Large, ModRadius(areaRadius, true));
                        }
                        if (!LargeBlockSphereDb.ContainsKey(ModRadius(areaRadius / fragments, true)))
                        {
                            GenerateBlockSphere(MyCubeSize.Large, ModRadius(areaRadius / fragments, true));
                        }

                        if (!SmallBlockSphereDb.ContainsKey(ModRadius(areaRadius, false)))
                        {
                            GenerateBlockSphere(MyCubeSize.Small, ModRadius(areaRadius, false));
                        }
                        if (!SmallBlockSphereDb.ContainsKey(ModRadius(areaRadius / fragments, false)))
                        {
                            GenerateBlockSphere(MyCubeSize.Small, ModRadius(areaRadius / fragments, false));
                        }
                    }
                    if (detonateRadius > 0)
                    {
                        if (!LargeBlockSphereDb.ContainsKey(ModRadius(detonateRadius, true)))
                        {
                            GenerateBlockSphere(MyCubeSize.Large, ModRadius(detonateRadius, true));
                        }
                        if (!LargeBlockSphereDb.ContainsKey(ModRadius(detonateRadius / fragments, true)))
                        {
                            GenerateBlockSphere(MyCubeSize.Large, ModRadius(detonateRadius / fragments, true));
                        }

                        if (!SmallBlockSphereDb.ContainsKey(ModRadius(detonateRadius, false)))
                        {
                            GenerateBlockSphere(MyCubeSize.Small, ModRadius(detonateRadius, false));
                        }
                        if (!SmallBlockSphereDb.ContainsKey(ModRadius(detonateRadius / fragments, false)))
                        {
                            GenerateBlockSphere(MyCubeSize.Small, ModRadius(detonateRadius / fragments, false));
                        }
                    }
                }
            }
            foreach (var weaponDef in WeaponDefinitions)
            {
                foreach (var mount in weaponDef.Assignments.MountPoints)
                {
                    var subTypeId       = mount.SubtypeId;
                    var muzzlePartId    = mount.MuzzlePartId;
                    var azimuthPartId   = mount.AzimuthPartId;
                    var elevationPartId = mount.ElevationPartId;

                    var extraInfo = new MyTuple <string, string, string> {
                        Item1 = weaponDef.HardPoint.WeaponName, Item2 = azimuthPartId, Item3 = elevationPartId
                    };

                    if (!_turretDefinitions.ContainsKey(subTypeId))
                    {
                        _turretDefinitions[subTypeId] = new Dictionary <string, MyTuple <string, string, string> >
                        {
                            [muzzlePartId] = extraInfo
                        };
                        _subTypeIdToWeaponDefs[subTypeId] = new List <WeaponDefinition> {
                            weaponDef
                        };
                    }
                    else
                    {
                        _turretDefinitions[subTypeId][muzzlePartId] = extraInfo;
                        _subTypeIdToWeaponDefs[subTypeId].Add(weaponDef);
                    }
                }
            }

            foreach (var tDef in _turretDefinitions)
            {
                var subTypeIdHash = MyStringHash.GetOrCompute(tDef.Key);
                SubTypeIdHashMap[tDef.Key] = subTypeIdHash;

                WeaponAreaRestriction areaRestriction;
                if (this.WeaponAreaRestrictions.ContainsKey(subTypeIdHash))
                {
                    areaRestriction = this.WeaponAreaRestrictions[subTypeIdHash];
                }
                else
                {
                    areaRestriction = new WeaponAreaRestriction();
                    WeaponAreaRestrictions[subTypeIdHash] = areaRestriction;
                }

                var    weapons     = _subTypeIdToWeaponDefs[tDef.Key];
                var    hasTurret   = false;
                var    firstWeapon = true;
                string modPath     = null;
                foreach (var wepDef in weapons)
                {
                    try {
                        modPath = wepDef.ModPath;
                        if (wepDef.HardPoint.Ai.TurretAttached)
                        {
                            hasTurret = true;
                        }

                        if (wepDef.HardPoint.HardWare.Armor != WeaponDefinition.HardPointDef.HardwareDef.ArmorState.IsWeapon)
                        {
                            DamageHandler = true;
                        }

                        foreach (var def in AllDefinitions)
                        {
                            MyDefinitionId defid;
                            var            matchingDef = def.Id.SubtypeName == tDef.Key || (ReplaceVanilla && VanillaCoreIds.TryGetValue(MyStringHash.GetOrCompute(tDef.Key), out defid) && defid == def.Id);
                            if (matchingDef)
                            {
                                if (wepDef.HardPoint.Other.RestrictionRadius > 0)
                                {
                                    if (wepDef.HardPoint.Other.CheckForAnyWeapon && !areaRestriction.CheckForAnyWeapon)
                                    {
                                        areaRestriction.CheckForAnyWeapon = true;
                                    }
                                    if (wepDef.HardPoint.Other.CheckInflatedBox)
                                    {
                                        if (areaRestriction.RestrictionBoxInflation < wepDef.HardPoint.Other.RestrictionRadius)
                                        {
                                            areaRestriction.RestrictionBoxInflation = wepDef.HardPoint.Other.RestrictionRadius;
                                        }
                                    }
                                    else
                                    {
                                        if (areaRestriction.RestrictionRadius < wepDef.HardPoint.Other.RestrictionRadius)
                                        {
                                            areaRestriction.RestrictionRadius = wepDef.HardPoint.Other.RestrictionRadius;
                                        }
                                    }
                                }

                                WeaponCoreBlockDefs[tDef.Key] = def.Id;
                                var designator = false;

                                for (int i = 0; i < wepDef.Assignments.MountPoints.Length; i++)
                                {
                                    if (wepDef.Assignments.MountPoints[i].MuzzlePartId == "Designator")
                                    {
                                        designator = true;
                                        break;
                                    }
                                }

                                if (!designator)
                                {
                                    var wepBlockDef = def as MyWeaponBlockDefinition;
                                    if (wepBlockDef != null)
                                    {
                                        if (firstWeapon)
                                        {
                                            wepBlockDef.InventoryMaxVolume = 0;
                                        }

                                        wepBlockDef.InventoryMaxVolume += wepDef.HardPoint.HardWare.InventorySize;

                                        var weaponCsDef = MyDefinitionManager.Static.GetWeaponDefinition(wepBlockDef.WeaponDefinitionId);

                                        if (weaponCsDef.WeaponAmmoDatas[0] == null)
                                        {
                                            Log.Line($"WeaponAmmoData is null, check the Ammo definition for {tDef.Key}");
                                        }
                                        weaponCsDef.WeaponAmmoDatas[0].RateOfFire = wepDef.HardPoint.Loading.RateOfFire;

                                        weaponCsDef.WeaponAmmoDatas[0].ShotsInBurst = wepDef.HardPoint.Loading.ShotsInBurst;
                                    }
                                    else if (def is MyConveyorSorterDefinition)
                                    {
                                        if (firstWeapon)
                                        {
                                            ((MyConveyorSorterDefinition)def).InventorySize = Vector3.Zero;
                                        }

                                        var size = Math.Pow(wepDef.HardPoint.HardWare.InventorySize, 1d / 3d);

                                        ((MyConveyorSorterDefinition)def).InventorySize += new Vector3(size, size, size);
                                    }

                                    firstWeapon = false;

                                    for (int i = 0; i < wepDef.Assignments.MountPoints.Length; i++)
                                    {
                                        var az = !string.IsNullOrEmpty(wepDef.Assignments.MountPoints[i].AzimuthPartId) ? wepDef.Assignments.MountPoints[i].AzimuthPartId : "MissileTurretBase1";
                                        var el = !string.IsNullOrEmpty(wepDef.Assignments.MountPoints[i].ElevationPartId) ? wepDef.Assignments.MountPoints[i].ElevationPartId : "MissileTurretBarrels";

                                        if (def is MyLargeTurretBaseDefinition && (VanillaSubpartNames.Contains(az) || VanillaSubpartNames.Contains(el)))
                                        {
                                            var gunDef    = (MyLargeTurretBaseDefinition)def;
                                            var blockDefs = wepDef.HardPoint.HardWare;
                                            gunDef.MinAzimuthDegrees   = blockDefs.MinAzimuth;
                                            gunDef.MaxAzimuthDegrees   = blockDefs.MaxAzimuth;
                                            gunDef.MinElevationDegrees = blockDefs.MinElevation;
                                            gunDef.MaxElevationDegrees = blockDefs.MaxElevation;
                                            gunDef.RotationSpeed       = blockDefs.RotateRate / 60;
                                            gunDef.ElevationSpeed      = blockDefs.ElevateRate / 60;
                                            gunDef.AiEnabled           = false;
                                            gunDef.IdleRotation        = false;
                                        }

                                        var cubeDef = def as MyCubeBlockDefinition;
                                        if (cubeDef != null)
                                        {
                                            for (int x = 0; x < wepDef.Assignments.MountPoints.Length; x++)
                                            {
                                                var mp = wepDef.Assignments.MountPoints[x];
                                                if (mp.SubtypeId == def.Id.SubtypeName)
                                                {
                                                    cubeDef.GeneralDamageMultiplier = mp.DurabilityMod > 0 ? mp.DurabilityMod : cubeDef.CubeSize == MyCubeSize.Large ? 0.25f : 0.05f;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Line($"Failed to load {wepDef.HardPoint.WeaponName}");
                    }
                }

                MyDefinitionId defId;
                if (WeaponCoreBlockDefs.TryGetValue(tDef.Key, out defId))
                {
                    if (hasTurret)
                    {
                        WeaponCoreTurretBlockDefs.Add(defId);
                    }
                    else
                    {
                        WeaponCoreFixedBlockDefs.Add(defId);
                    }
                }
                WeaponPlatforms[defId] = new WeaponStructure(this, tDef, weapons, modPath);
            }

            MyAPIGateway.TerminalControls.CustomControlGetter += CustomControlHandler;
        }
        private void VoiceMessageReceived(byte[] data, int dataSize, ulong sender, TimeSpan timestamp)
        {
            if (!m_enabled)
                return;

            if (!IsCharacterValid(MySession.LocalCharacter))
                return;

            ProcessBuffer(data, dataSize, sender);
            if (MyFakes.ENABLE_VOICE_CHAT_DEBUGGING)
                m_debugReceivedVoice[sender] = new MyTuple<int, TimeSpan>(dataSize, timestamp);
        }
        public override void RecreateControls(bool contructor)
        {
            base.RecreateControls(contructor);
            Vector2 value  = JumpSelectorGui.listpos;
            float   num    = JumpSelectorGui.listoffset;
            Vector2 vector = JumpSelectorGui.listsize;

            vector.X -= (float)(this.JumpDrives.Count - 1) * num;
            vector.X /= (float)this.JumpDrives.Count;
            for (int i = 0; i < this.JumpDrives.Count; i++)
            {
                MyTuple <string, Color> tooltip       = this.GetTooltip(this.JumpDrives[i]);
                string             item               = tooltip.Item1;
                Color              item2              = tooltip.Item2;
                MyGuiControlButton myGuiControlButton = new MyGuiControlButton(new Vector2?(value), MyGuiControlButtonStyleEnum.Rectangular, new Vector2?(vector), null, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER, item, null, 0.8f, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, MyGuiControlHighlightType.WHEN_CURSOR_OVER, null, GuiSounds.MouseClick, 1f, new int?(i), false, false, false, null);
                myGuiControlButton.DrawCrossTextureWhenDisabled = true;
                myGuiControlButton.Enabled = this.JumpDrives[i].IsBuilt;
                myGuiControlButton.ShowTooltipWhenDisabled = true;
                myGuiControlButton.BorderColor             = item2;
                myGuiControlButton.BorderEnabled           = true;
                myGuiControlButton.BorderSize   = 2;
                myGuiControlButton.TooltipDelay = 0;
                this.Controls.Add(myGuiControlButton);
                myGuiControlButton.ButtonClicked += this.ToggleJDPower;
                this.buttonlist.Add(myGuiControlButton);
                value.X += vector.X + num;
            }
            this.listlabel = new MyGuiControlLabel(new Vector2?(JumpSelectorGui.labelpos), new Vector2?(JumpSelectorGui.labelsize), "Power Toggles", null, 0.7f, "Blue", MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER, false, float.PositiveInfinity, false);
            this.Controls.Add(this.listlabel);
            this.rangelabel = new MyGuiControlLabel(new Vector2?(JumpSelectorGui.rangepos), new Vector2?(JumpSelectorGui.rangesize), string.Format("Max Range: {0:N0}km", this.JumpSystem.GetMaxJumpDistance(this.ControlledBy.OwnerId) / 1000.0), null, 0.7f, "Blue", MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER, false, float.PositiveInfinity, false);
            this.Controls.Add(this.rangelabel);
            this.radioButtonGPS = new MyGuiControlRadioButton
            {
                Position     = JumpSelectorGui.gpspos,
                Size         = JumpSelectorGui.radiosize,
                Name         = "radioGPS",
                OriginAlign  = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER,
                Key          = 0,
                VisualStyle  = MyGuiControlRadioButtonStyleEnum.Rectangular,
                CanHaveFocus = false,
                Text         = new StringBuilder("Jump to GPS")
            };
            this.radioButtonBlind = new MyGuiControlRadioButton
            {
                Position     = JumpSelectorGui.blindpos,
                Size         = JumpSelectorGui.radiosize,
                Name         = "radioBlind",
                OriginAlign  = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER,
                Key          = 1,
                VisualStyle  = MyGuiControlRadioButtonStyleEnum.Rectangular,
                CanHaveFocus = false,
                Text         = new StringBuilder("Blind Jump")
            };
            this.radioButtonGroup = new MyGuiControlRadioButtonGroup();
            this.radioButtonGroup.Add(this.radioButtonGPS);
            this.radioButtonGroup.Add(this.radioButtonBlind);
            this.distanceTextbox      = new MyGuiControlTextbox(new Vector2?(JumpSelectorGui.textpos), JumpSelectorGui.lastDistance, 10, null, 0.8f, MyGuiControlTextboxType.DigitsOnly, MyGuiControlTextboxStyleEnum.Default, false);
            this.distanceTextbox.Size = JumpSelectorGui.textsize;
            Vector2 value2 = new Vector2(JumpSelectorGui.combopos.X, JumpSelectorGui.combopos.Y - JumpSelectorGui.textsize.Y - 0.01f);

            this.searchTextbox      = new MyGuiControlTextbox(new Vector2?(value2), null, 20, null, 0.8f, MyGuiControlTextboxType.Normal, MyGuiControlTextboxStyleEnum.Default, false);
            this.searchTextbox.Size = JumpSelectorGui.textsize;
            this.searchTextbox.SetToolTip("Search GPS Entries");
            this.gpsCombobox   = new MyGuiControlCombobox(new Vector2?(JumpSelectorGui.combopos), new Vector2?(JumpSelectorGui.combosize), null, null, 10, null, false, null, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, null, false, false);
            this.confirmButton = new MyGuiControlButton(new Vector2?(JumpSelectorGui.confirmpos), MyGuiControlButtonStyleEnum.Default, new Vector2?(JumpSelectorGui.confirmsize), null, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, null, new StringBuilder("Confirm"), 0.8f, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, MyGuiControlHighlightType.WHEN_CURSOR_OVER, null, GuiSounds.MouseClick, 1f, null, false, false, false, null);
            this.cancelButton  = new MyGuiControlButton(new Vector2?(JumpSelectorGui.cancelpos), MyGuiControlButtonStyleEnum.Default, new Vector2?(JumpSelectorGui.cancelsize), null, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, null, new StringBuilder("Cancel"), 0.8f, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, MyGuiControlHighlightType.WHEN_CURSOR_OVER, null, GuiSounds.MouseClick, 1f, null, false, false, false, null);
            this.GetGPSList();
            this.Controls.Add(this.radioButtonGPS);
            this.Controls.Add(this.radioButtonBlind);
            this.Controls.Add(this.distanceTextbox);
            this.Controls.Add(this.searchTextbox);
            this.Controls.Add(this.gpsCombobox);
            this.Controls.Add(this.confirmButton);
            this.Controls.Add(this.cancelButton);
            base.FocusedControl = this.distanceTextbox;
            this.gpsCombobox.SelectItemByIndex(JumpSelectorGui.lastSelectedGps);
            this.radioButtonGroup.SelectByKey(1);
            this.distanceTextbox.SelectAll();
            this.confirmButton.ButtonClicked  += this.confirmButton_OnButtonClick;
            this.cancelButton.ButtonClicked   += this.cancelButton_OnButtonClick;
            this.distanceTextbox.FocusChanged += this.SelectBlindOption;
            this.distanceTextbox.TextChanged  += this.DistanceTextChanged;
            this.distanceTextbox.EnterPressed += this.BlindJump;
            this.gpsCombobox.FocusChanged     += this.SelectGPSOption;
            this.searchTextbox.TextChanged    += this.FilterGpsList;
            this.searchTextbox.FocusChanged   += this.SearchFocusChanged;
        }
Exemple #33
0
        public void Main(string argument, UpdateType updateSource)
        {
            Context.UpdateTime();
            if (argument == "combatautopilottoggle")
            {
                CombatAutopilot = !CombatAutopilot;

//                 foreach (var welder in Welders)
//                 {
//                     welder.Enabled = true;
//                 }

                if (!CombatAutopilot)
                {
                    AgentSubsystem.AddTask(TaskType.None, MyTuple.Create(IntelItemType.NONE, (long)0), CommandType.Override, 0, TimeSpan.Zero);
                    AutopilotSubsystem.Clear();
                }

                UpdateName();
            }
            else if (commandLine.TryParse(argument))
            {
                subsystemManager.CommandV2(commandLine);
            }
            else
            {
                runs++;

                /*
                 * if (Connector != null && runs % 5 == 0)
                 * {
                 *  if (lastDocked)
                 *  {
                 *      if (Connector.Status == MyShipConnectorStatus.Connectable)
                 *      {
                 *          if (scriptDocked)
                 *          {
                 *              scriptDocked = false;
                 *          }
                 *          else
                 *          {
                 *              scriptDocked = true;
                 *              DockingSubsystem.Dock();
                 *          }
                 *      }
                 *  }
                 *  else
                 *  {
                 *      if (Connector.Status == MyShipConnectorStatus.Connected)
                 *      {
                 *          DockingSubsystem.Dock();
                 *      }
                 *  }
                 *
                 *  if (scriptDocked && !CombatLoaderSubsystem.LoadingInventory && CombatLoaderSubsystem.QueueReload == 0)
                 *  {
                 *      DockingSubsystem.Undock();
                 *  }
                 *
                 *  lastDocked = Connector.Status == MyShipConnectorStatus.Connected;
                 *  scriptDocked = scriptDocked && lastDocked;
                 * }
                 */
                if (runs % 30 == 0)
                {
                    if (CombatAutopilot)
                    {
                        var hadTarget  = PriorityTarget != null;
                        var intelItems = IntelSubsystem.GetFleetIntelligences(Context.LocalTime);

                        PriorityTarget = null;
                        float HighestEnemyPriority = 0;

                        foreach (var kvp in intelItems)
                        {
                            if (kvp.Key.Item1 == IntelItemType.Enemy)
                            {
                                var enemy = kvp.Value as EnemyShipIntel;
                                var dist  = (int)(enemy.GetPositionFromCanonicalTime(Context.CanonicalTime) - Me.GetPosition()).Length();
                                var size  = enemy.Radius;
                                if (dist > 2000 || size < 30)
                                {
                                    continue;
                                }

                                var priority = 2000 - dist;

                                if (priority > HighestEnemyPriority)
                                {
                                    PriorityTarget       = enemy;
                                    HighestEnemyPriority = priority;
                                    LargestTargetDist    = dist;
                                }
                            }
                        }

                        if (PriorityTarget == null)
                        {
                            if (hadTarget)
                            {
                                AgentSubsystem.AddTask(TaskType.None, MyTuple.Create(IntelItemType.NONE, (long)0), CommandType.Override, 0, TimeSpan.Zero);
                                AutopilotSubsystem.Clear();
                            }
                        }
                        else
                        {
                            AgentSubsystem.AddTask(TaskType.Attack, MyTuple.Create(IntelItemType.Enemy, PriorityTarget.ID), CommandType.Override, 0,
                                                   Context.CanonicalTime);
                        }
                    }
                    else
                    {
                        PriorityTarget = null;
                    }

                    UpdateName();
                }

                subsystemManager.Update(updateSource);

                var status = subsystemManager.GetStatus();
                if (status != string.Empty)
                {
                    Echo(status);
                }
            }
        }
Exemple #34
0
        internal Tuple<byte[], List<byte[]>> Place(PlaceMessage pm)
        {
            Order o = new Order(pm);
            Tuple<byte[], List<byte[]>> ans = new Tuple<byte[], List<byte[]>>(BitConverter.GetBytes(o.id), new List<byte[]>());
            ans.Item2.Add(o.AddedString());
            orders[o.id] = o;

            if (!users.ContainsKey(pm.user_id))
            {
                //ошибка, юзера нет
            }

            if (pm.buy) //покупаем asset2 за asset1
            {
                long q1, q2;
                User.MUL(pm.price, pm.quantity, out q1, out q2);

                //проверить хватит ли денег
                if (users[pm.user_id].eq[User.num[pm.asset1]].CompareTo(new MyTuple<long, long>(q1, q2)) < 0)
                { //денег не хватило
                }

                if (!buy.ContainsKey(pm.asset1))
                {
                    buy[pm.asset1] = new Dictionary<string, SortedDictionary<MyTuple<long, long>, List<Order>>>();
                }
                if (!buy[pm.asset1].ContainsKey(pm.asset2))
                {
                    buy[pm.asset1][pm.asset2] = new SortedDictionary<MyTuple<long, long>, List<Order>>();
                }
                if (!buy[pm.asset1][pm.asset2].ContainsKey(pm.price))
                {
                    buy[pm.asset1][pm.asset2][pm.price] = new List<Order>();
                }
                buy[pm.asset1][pm.asset2][pm.price].Add(o);
            }
            else //продаем asset2 за asset1
            {
               //проверить хватит ли денег
                MyTuple<long, long> T = new MyTuple<long, long>(pm.quantity/User.MAGIC, pm.quantity%User.MAGIC);
                if (users[pm.user_id].eq[User.num[pm.asset2]].CompareTo(T)<0) ;
                { //денег не хватило
                }
                if (pm.quantity<=0 || pm.price.Item1<0 || pm.price.Item2<0 || (pm.price.Item1)==0 && (pm.price.Item2)==0)
                {
                    //проверка на отрицательную смму и количество
                }
                if (!buy.ContainsKey(pm.asset1))
                {
                    buy[pm.asset1] = new Dictionary<string, SortedDictionary<MyTuple<long, long>, List<Order>>>();
                }
                if (!buy[pm.asset1].ContainsKey(pm.asset2))
                {
                    buy[pm.asset1][pm.asset2] = new SortedDictionary<MyTuple<long, long>, List<Order>>();
                }
                if (!buy[pm.asset1][pm.asset2].ContainsKey(pm.price))
                {
                    buy[pm.asset1][pm.asset2][pm.price] = new List<Order>();
                }
                buy[pm.asset1][pm.asset2][pm.price].Add(o);
            }
            while (sell[pm.asset1][pm.asset2].First().Key.CompareTo(buy[pm.asset1][pm.asset2].Last().Key) <= 0)
            {
                MyTuple<long, long> price = pm.buy ? sell[pm.asset1][pm.asset2].First().Key : buy[pm.asset1][pm.asset2].First().Key;
                List<Order> l1 = sell[pm.asset1][pm.asset2].First().Value;
                List<Order> l2 = buy[pm.asset1][pm.asset2].Last().Value;
                while (l1.Count > 0 && l2.Count > 0)
                {
                    long q = Math.Min(l1[0].quantity, l2[0].quantity);
                    users[l1[0].user].AddAsset(pm.asset1, -q);
                    users[l2[0].user].AddAsset(pm.asset1, q);
                    users[l1[0].user].AddCurrency(pm.asset2, q, price);
                    users[l2[0].user].AddCurrency(pm.asset2, -q, price);
                    l1[0].quantity -= q;
                    l2[0].quantity -= q;
                    List<byte> tick = new List<byte>();
                    tick.AddRange(System.Text.Encoding.ASCII.GetBytes(pm.asset1 + "/" + pm.asset2));
                    tick.Add(2);
                    tick.AddRange(BitConverter.GetBytes(l1[0].id));
                    tick.AddRange(BitConverter.GetBytes(l2[0].id));
                    tick.AddRange(BitConverter.GetBytes(price.Item1));
                    tick.AddRange(BitConverter.GetBytes(price.Item2));
                    tick.AddRange(BitConverter.GetBytes(q));
                    ans.Item2.Add(tick.ToArray());
                    if (l1[0].quantity == 0)
                    {
                        l1.RemoveAt(0);
                    }
                    if (l2[0].quantity == 0)
                    {
                        l2.RemoveAt(0);
                    }
                }
                if (l1.Count == 0)
                {
                    sell[pm.asset1][pm.asset2].Remove(sell[pm.asset1][pm.asset2].First().Key);
                }
                if (l2.Count == 0)
                {
                    buy[pm.asset1][pm.asset2].Remove(buy[pm.asset1][pm.asset2].Last().Key);
                }
            }
            return ans;
        }
        public static void AddGPSToEntity(string entityName, string GPSName, string GPSDescription, long playerId = -1)
        {
            MyEntity entity;
            if (MyEntities.TryGetEntityByName(entityName, out entity))
            {
                if (playerId == -1)
                    playerId = GetLocalPlayerId();
                MyTuple<string, string> gpsIdentifier = new MyTuple<string, string>(entityName, GPSName);

                MyGps newGPS = new MyGps { ShowOnHud = true, Name = GPSName, Description = GPSDescription, AlwaysVisible = true };
                MySession.Static.Gpss.SendAddGps(playerId, ref newGPS, entity.EntityId);
            }
        }
Exemple #36
0
        internal void Init()
        {
            if (Inited)
            {
                return;
            }
            Inited = true;
            Log.Init("debugdevelop.log");
            Log.Line($"Logging Started");

            foreach (var x in WeaponDefinitions)
            {
                foreach (var ammo in x.Ammos)
                {
                    var ae             = ammo.AreaEffect;
                    var areaRadius     = ae.AreaEffectRadius;
                    var detonateRadius = ae.Detonation.DetonationRadius;
                    var fragments      = ammo.Shrapnel.Fragments > 0 ? ammo.Shrapnel.Fragments : 1;
                    if (areaRadius > 0)
                    {
                        if (!LargeBlockSphereDb.ContainsKey(ModRadius(areaRadius, true)))
                        {
                            GenerateBlockSphere(MyCubeSize.Large, ModRadius(areaRadius, true));
                        }
                        if (!LargeBlockSphereDb.ContainsKey(ModRadius(areaRadius / fragments, true)))
                        {
                            GenerateBlockSphere(MyCubeSize.Large, ModRadius(areaRadius / fragments, true));
                        }

                        if (!SmallBlockSphereDb.ContainsKey(ModRadius(areaRadius, false)))
                        {
                            GenerateBlockSphere(MyCubeSize.Small, ModRadius(areaRadius, false));
                        }
                        if (!SmallBlockSphereDb.ContainsKey(ModRadius(areaRadius / fragments, false)))
                        {
                            GenerateBlockSphere(MyCubeSize.Small, ModRadius(areaRadius / fragments, false));
                        }
                    }
                    if (detonateRadius > 0)
                    {
                        if (!LargeBlockSphereDb.ContainsKey(ModRadius(detonateRadius, true)))
                        {
                            GenerateBlockSphere(MyCubeSize.Large, ModRadius(detonateRadius, true));
                        }
                        if (!LargeBlockSphereDb.ContainsKey(ModRadius(detonateRadius / fragments, true)))
                        {
                            GenerateBlockSphere(MyCubeSize.Large, ModRadius(detonateRadius / fragments, true));
                        }

                        if (!SmallBlockSphereDb.ContainsKey(ModRadius(detonateRadius, false)))
                        {
                            GenerateBlockSphere(MyCubeSize.Small, ModRadius(detonateRadius, false));
                        }
                        if (!SmallBlockSphereDb.ContainsKey(ModRadius(detonateRadius / fragments, false)))
                        {
                            GenerateBlockSphere(MyCubeSize.Small, ModRadius(detonateRadius / fragments, false));
                        }
                    }
                }
            }
            foreach (var weaponDef in WeaponDefinitions)
            {
                foreach (var mount in weaponDef.Assignments.MountPoints)
                {
                    var subTypeId       = mount.SubtypeId;
                    var muzzlePartId    = mount.MuzzlePartId;
                    var azimuthPartId   = mount.AzimuthPartId;
                    var elevationPartId = mount.ElevationPartId;

                    var extraInfo = new MyTuple <string, string, string> {
                        Item1 = weaponDef.HardPoint.WeaponName, Item2 = azimuthPartId, Item3 = elevationPartId
                    };

                    if (!_turretDefinitions.ContainsKey(subTypeId))
                    {
                        foreach (var def in AllDefinitions)
                        {
                            MyDefinitionId defid;
                            if (def.Id.SubtypeName == subTypeId || (ReplaceVanilla && VanillaCoreIds.TryGetValue(MyStringHash.GetOrCompute(subTypeId), out defid) && defid == def.Id))
                            {
                                var gunDef = def as MyLargeTurretBaseDefinition;
                                if (gunDef != null)
                                {
                                    var blockDefs = weaponDef.HardPoint.HardWare;

                                    gunDef.MinAzimuthDegrees   = blockDefs.MinAzimuth;
                                    gunDef.MaxAzimuthDegrees   = blockDefs.MaxAzimuth;
                                    gunDef.MinElevationDegrees = blockDefs.MinElevation;
                                    gunDef.MaxElevationDegrees = blockDefs.MaxElevation;
                                    gunDef.RotationSpeed       = blockDefs.RotateRate;
                                    gunDef.ElevationSpeed      = blockDefs.ElevateRate;
                                    gunDef.AiEnabled           = false;
                                }

                                WeaponCoreBlockDefs[subTypeId] = def.Id;
                            }
                        }
                        _turretDefinitions[subTypeId] = new Dictionary <string, MyTuple <string, string, string> >
                        {
                            [muzzlePartId] = extraInfo
                        };
                        _subTypeIdToWeaponDefs[subTypeId] = new List <WeaponDefinition> {
                            weaponDef
                        };
                    }
                    else
                    {
                        _turretDefinitions[subTypeId][muzzlePartId] = extraInfo;
                        _subTypeIdToWeaponDefs[subTypeId].Add(weaponDef);
                    }
                }
            }

            foreach (var tDef in _turretDefinitions)
            {
                var subTypeIdHash = MyStringHash.GetOrCompute(tDef.Key);
                SubTypeIdHashMap[tDef.Key] = subTypeIdHash;

                var weapons = _subTypeIdToWeaponDefs[tDef.Key];

                var hasTurret = false;
                foreach (var wepDef in weapons)
                {
                    if (wepDef.HardPoint.Ai.TurretAttached)
                    {
                        hasTurret = true;
                    }
                }

                MyDefinitionId defId;
                if (WeaponCoreBlockDefs.TryGetValue(tDef.Key, out defId))
                {
                    if (hasTurret)
                    {
                        WeaponCoreTurretBlockDefs.Add(defId);
                    }
                    else
                    {
                        WeaponCoreFixedBlockDefs.Add(defId);
                    }
                }

                WeaponPlatforms[subTypeIdHash] = new WeaponStructure(this, tDef, weapons);
            }

            MyAPIGateway.TerminalControls.CustomControlGetter += CustomControlHandler;
        }
        public bool CanDoAction(string actionId, out MyTuple<ushort, MyStringHash> message, bool continuous = false)
        {
            message = new MyTuple<ushort, MyStringHash>(0, MyStringHash.NullOrEmpty);

            if (m_scripts == null || m_scripts.Count == 0)
                return true;

			bool cannotPerformAction = true;
			foreach (var script in m_scripts)
			{
                MyTuple<ushort, MyStringHash> msg;
                cannotPerformAction &= !script.CanDoAction(actionId, continuous, out msg);
                if (msg.Item1 != 0)
                    message = msg;
			}
            
			return !cannotPerformAction;
		}
Exemple #38
0
    public static void Main()
    {
        Bus bus = Bus.Session;

        string     bus_name = "org.ndesk.test";
        ObjectPath path     = new ObjectPath("/org/ndesk/test");

        DemoObject demo;

        if (bus.RequestName(bus_name) == RequestNameReply.PrimaryOwner)
        {
            //create a new instance of the object to be exported
            demo = new DemoObject();
            bus.Register(path, demo);

            //run the main loop
            while (true)
            {
                bus.Iterate();
            }
        }
        else
        {
            //import a remote to a local proxy
            demo = bus.GetObject <DemoObject> (bus_name, path);
        }

        demo.Say("Hello world!");
        demo.Say("Sibérie");
        demo.Say(21);
        demo.SayByteArray(new byte[] { 0, 2, 1 }, "test string");
        demo.SayByteEnumArray(new BEnum[] { BEnum.Zero, BEnum.Two, BEnum.One }, "test string two");
        Console.WriteLine(demo.EchoCaps("foo bar"));
        Console.WriteLine(demo.GetEnum());
        demo.CheckEnum(DemoEnum.Bar);
        demo.CheckEnum(demo.GetEnum());

        Console.WriteLine();
        long someLong = demo.GetSomeLong();

        Console.WriteLine("someLong: " + someLong);

        Console.WriteLine();
        ulong someULong = demo.GetSomeULong();

        Console.WriteLine("someULong: " + someULong);

        /*
         * Console.WriteLine ();
         * string outVal;
         * demo.ReturnOut (out outVal);
         * Console.WriteLine ("outVal: " + outVal);
         */

        Console.WriteLine();
        string[] texts = { "one", "two", "three" };
        texts = demo.EchoCapsArr(texts);
        foreach (string text in texts)
        {
            Console.WriteLine(text);
        }

        Console.WriteLine();
        string[][] arrarr = demo.ArrArr();
        Console.WriteLine(arrarr[1][0]);

        Console.WriteLine();
        int[] vals = demo.TextToInts("1 2 3");
        foreach (int val in vals)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine();
        MyTuple fooTuple = demo.GetTuple();

        Console.WriteLine("A: " + fooTuple.A);
        Console.WriteLine("B: " + fooTuple.B);

        Console.WriteLine();
        //KeyValuePair<string,string>[] kvps = demo.GetDict ();
        IDictionary <string, string> dict = demo.GetDict();

        foreach (KeyValuePair <string, string> kvp in dict)
        {
            Console.WriteLine(kvp.Key + ": " + kvp.Value);
        }

        Console.WriteLine();
        demo.SomeEvent += delegate(string arg1, object arg2, double arg3, MyTuple mt) { Console.WriteLine("SomeEvent handler: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B); };
        demo.SomeEvent += delegate(string arg1, object arg2, double arg3, MyTuple mt) { Console.WriteLine("SomeEvent handler two: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B); };
        demo.FireOffSomeEvent();
        //handle the raised signal
        //bus.Iterate ();

        Console.WriteLine();
        demo.SomeEvent += HandleSomeEventA;
        demo.FireOffSomeEvent();
        //handle the raised signal
        //bus.Iterate ();

        Console.WriteLine();
        demo.SomeEvent -= HandleSomeEventA;
        demo.FireOffSomeEvent();
        //handle the raised signal
        //bus.Iterate ();

        Console.WriteLine();
        {
            object tmp = demo.GetArrayOfInts();
            int[]  arr = (int[])tmp;
            Console.WriteLine("Array of ints as variant: " + arr[0] + " " + arr[1]);
        }

        Console.WriteLine();
        {
            demo.UseSomeVariant("hello");
            demo.UseSomeVariant(21);
        }

        Console.WriteLine();
        {
            Console.WriteLine("get SomeProp: " + demo.SomeProp);
            demo.SomeProp = 4;
        }
    }
		private static void ComputeInitialDistributionData(
			ref MyDefinitionId typeId,
			MySinkGroupData[] sinkDataByPriority,
			MySourceGroupData[] sourceDataByPriority,
            ref MyTuple<MySinkGroupData, MySourceGroupData> sinkSourceData,
            HashSet<MyResourceSinkComponent>[] sinksByPriority,
			HashSet<MyResourceSourceComponent>[] sourcesByPriority,
            List<MyTuple<MyResourceSinkComponent, MyResourceSourceComponent>> sinkSourcePairs,
			List<int> stockpilingStorageList,
			List<int> otherStorageList,
			out float maxAvailableResource)
		{
			// Clear state of all sources and sinks. Also find out how 
			// much of resource is available for distribution.
			maxAvailableResource = 0.0f;

			Debug.Assert(sourceDataByPriority.Length == sourcesByPriority.Length);
			for (int i = 0; i < sourceDataByPriority.Length; ++i)
			{
				var resourceSources = sourcesByPriority[i];
				MySourceGroupData sourceGroupData = sourceDataByPriority[i];
				sourceGroupData.MaxAvailableResource = 0f;
				foreach (MyResourceSourceComponent source in resourceSources)
				{
					if (!source.Enabled || !source.HasCapacityRemainingByType(typeId))
						continue;

					sourceGroupData.MaxAvailableResource += source.MaxOutputByType(typeId);
					sourceGroupData.InfiniteCapacity = source.IsInfiniteCapacity;
				}
				maxAvailableResource += sourceGroupData.MaxAvailableResource;
				sourceDataByPriority[i] = sourceGroupData;
			}

			float requiredInputCumulative = 0.0f;
			for (int i = 0; i < sinksByPriority.Length; ++i)
			{
				float requiredInput = 0.0f;
				bool isAdaptible = true;
				foreach (MyResourceSinkComponent sink in sinksByPriority[i])
				{
					requiredInput += sink.RequiredInputByType(typeId);
					isAdaptible = isAdaptible && IsAdaptible(sink);
				}
				sinkDataByPriority[i].RequiredInput = requiredInput;
				sinkDataByPriority[i].IsAdaptible = isAdaptible;

				requiredInputCumulative += requiredInput;
				sinkDataByPriority[i].RequiredInputCumulative = requiredInputCumulative;
			}

            PrepareSinkSourceData(ref typeId, ref sinkSourceData, sinkSourcePairs, stockpilingStorageList, otherStorageList);
            maxAvailableResource += sinkSourceData.Item2.MaxAvailableResource;
		}
 public ReadOnlyApiCollection(MyTuple <Func <int, TValue>, Func <int> > tuple)
     : this(tuple.Item1, tuple.Item2)
 {
 }
	    /// <summary>
	    /// Recomputes power distribution in subset of all priority groups (in range
	    /// from startPriorityIdx until the end). Passing index 0 recomputes all priority groups.
	    /// </summary>
	    private static MyResourceStateEnum RecomputeResourceDistributionPartial(
			ref MyDefinitionId typeId,
			int startPriorityIdx, 
			MySinkGroupData[] sinkDataByPriority,
			MySourceGroupData[] sourceDataByPriority,
            ref MyTuple<MySinkGroupData, MySourceGroupData> sinkSourceData,
            HashSet<MyResourceSinkComponent>[] sinksByPriority,
			HashSet<MyResourceSourceComponent>[] sourcesByPriority,
            List<MyTuple<MyResourceSinkComponent, MyResourceSourceComponent>> sinkSourcePairs,
			List<int> stockpilingStorageList,
			List<int> otherStorageList,
			float availableResource)
	    {
            ProfilerShort.Begin("MyResourceDistributor.RecomputeResourceDistributionPartial");
		    ProfilerShort.Begin("Non-zero inputs");
		    float totalAvailableResource = availableResource;
		    int sinkPriorityIndex = startPriorityIdx;

            // Distribute power over the sinks by priority
			for (; sinkPriorityIndex < sinksByPriority.Length; ++sinkPriorityIndex)
		    {
				sinkDataByPriority[sinkPriorityIndex].RemainingAvailableResource = availableResource;

				if (sinkDataByPriority[sinkPriorityIndex].RequiredInput <= availableResource)
			    {
				    // Run everything in the group at max.
					availableResource -= sinkDataByPriority[sinkPriorityIndex].RequiredInput;
				    foreach (MyResourceSinkComponent sink in sinksByPriority[sinkPriorityIndex])
						sink.SetInputFromDistributor(typeId, sink.RequiredInputByType(typeId), sinkDataByPriority[sinkPriorityIndex].IsAdaptible);
			    }
				else if (sinkDataByPriority[sinkPriorityIndex].IsAdaptible && availableResource > 0.0f)
			    {
				    // Distribute power in this group based on ratio of its requirement vs. group requirement.
				    foreach (MyResourceSinkComponent sink in sinksByPriority[sinkPriorityIndex])
				    {
						float ratio = sink.RequiredInputByType(typeId) / sinkDataByPriority[sinkPriorityIndex].RequiredInput;
						sink.SetInputFromDistributor(typeId, ratio * availableResource, true);
				    }
				    availableResource = 0.0f;
			    }
			    else
			    {
				    // Not enough power for this group and members can't adapt.
				    // None of the lower priority groups will get any power either.
                    foreach (MyResourceSinkComponent sink in sinksByPriority[sinkPriorityIndex])
						sink.SetInputFromDistributor(typeId, 0.0f, sinkDataByPriority[sinkPriorityIndex].IsAdaptible);
					sinkDataByPriority[sinkPriorityIndex].RemainingAvailableResource = availableResource;
				    ++sinkPriorityIndex; // move on to next group
				    break;
			    }
		    }
            ProfilerShort.End();
            ProfilerShort.Begin("Zero inputs");
		    // Set remaining data.
			for (; sinkPriorityIndex < sinkDataByPriority.Length; ++sinkPriorityIndex)
		    {
				sinkDataByPriority[sinkPriorityIndex].RemainingAvailableResource = 0.0f;
				foreach (MyResourceSinkComponent sink in sinksByPriority[sinkPriorityIndex])
					sink.SetInputFromDistributor(typeId, 0.0f, sinkDataByPriority[sinkPriorityIndex].IsAdaptible);
		    }
            ProfilerShort.End();
            float consumptionForNonStorage = totalAvailableResource - availableResource + (startPriorityIdx != 0 ? sinkDataByPriority[0].RemainingAvailableResource - sinkDataByPriority[startPriorityIdx].RemainingAvailableResource : 0f);

            // Distribute remaining energy over stockpiling storage
	        float totalAvailableResourcesForStockpiles = Math.Max(totalAvailableResource - consumptionForNonStorage, 0);
	        float availableResourcesForStockpiles = totalAvailableResourcesForStockpiles;
            if (stockpilingStorageList.Count > 0)
            {
                ProfilerShort.Begin("Stockpiles");
				float stockpilesRequiredInput = sinkSourceData.Item1.RequiredInputCumulative;
				if (stockpilesRequiredInput <= availableResourcesForStockpiles)
                {
					availableResourcesForStockpiles -= stockpilesRequiredInput;
                    //ToArray = Hotfix for collection modified exception
                    foreach (int pairIndex in stockpilingStorageList.ToArray())
                    {
                        var sink = sinkSourcePairs[pairIndex].Item1;
                        sink.SetInputFromDistributor(typeId, sink.RequiredInputByType(typeId), true);
                    }
                    sinkSourceData.Item1.RemainingAvailableResource = availableResourcesForStockpiles;
                }
                else
                {
                    //ToArray = Hotfix for collection modified exception
                    foreach (int pairIndex in stockpilingStorageList.ToArray())
                    {
                        var sink = sinkSourcePairs[pairIndex].Item1;
						float ratio = sink.RequiredInputByType(typeId) / stockpilesRequiredInput;
                        sink.SetInputFromDistributor(typeId, ratio * totalAvailableResourcesForStockpiles, true);
                    }
                    availableResourcesForStockpiles = 0f;
                    sinkSourceData.Item1.RemainingAvailableResource = availableResourcesForStockpiles;
                }
                ProfilerShort.End();
            }

            // Distribute remaining power over non-stockpiling storage
	        float consumptionForStockpiles = totalAvailableResourcesForStockpiles - availableResourcesForStockpiles;
            float totalAvailableResourcesForStorage = Math.Max(totalAvailableResource - (sinkSourceData.Item2.MaxAvailableResource - sinkSourceData.Item2.MaxAvailableResource * sinkSourceData.Item2.UsageRatio) - consumptionForNonStorage - consumptionForStockpiles, 0);
            float availableResourcesForStorage = totalAvailableResourcesForStorage;
            if (otherStorageList.Count > 0)
            {
                ProfilerShort.Begin("Non-stockpiling storage");
				float ordinaryStorageRequiredInput = sinkSourceData.Item1.RequiredInput - sinkSourceData.Item1.RequiredInputCumulative;
				if (ordinaryStorageRequiredInput <= availableResourcesForStorage)
                {
					availableResourcesForStorage -= ordinaryStorageRequiredInput;
                    foreach (int pairIndex in otherStorageList)
                    {
                        var sink = sinkSourcePairs[pairIndex].Item1;
                        sink.SetInputFromDistributor(typeId, sink.RequiredInputByType(typeId), true);
                    }
                    sinkSourceData.Item1.RemainingAvailableResource = availableResourcesForStorage;
                }
                else
                {
                    foreach (int pairIndex in otherStorageList)
                    {
                        var sink = sinkSourcePairs[pairIndex].Item1;
                        float ratio = sink.RequiredInputByType(typeId) / ordinaryStorageRequiredInput;
                        sink.SetInputFromDistributor(typeId, ratio * availableResourcesForStorage, true);
                    }
                    availableResourcesForStorage = 0f;
                    sinkSourceData.Item1.RemainingAvailableResource = availableResourcesForStorage;
                }
                ProfilerShort.End();
            }
            
            ProfilerShort.Begin("Sources");
            float consumptionForStorage = totalAvailableResourcesForStorage - availableResourcesForStorage;
	        float consumptionForNonStorageAndStockpiles = consumptionForStockpiles + consumptionForNonStorage;
	        if (sinkSourceData.Item2.MaxAvailableResource > 0)
	        {
                float amountToSupply = consumptionForNonStorageAndStockpiles;
	            sinkSourceData.Item2.UsageRatio = Math.Min(1f, amountToSupply/sinkSourceData.Item2.MaxAvailableResource);
                consumptionForNonStorageAndStockpiles -= Math.Min(amountToSupply, sinkSourceData.Item2.MaxAvailableResource);
	        }
	        else
	            sinkSourceData.Item2.UsageRatio = 0f;

            sinkSourceData.Item2.ActiveCount = 0;
            foreach (int pairIndex in otherStorageList)
            {
                var source = sinkSourcePairs[pairIndex].Item2;
                if (!source.Enabled || !source.ProductionEnabledByType(typeId) || !source.HasCapacityRemainingByType(typeId))
                    continue;

                ++sinkSourceData.Item2.ActiveCount;
                ProfilerShort.Begin("Set CurrentOutput");
                source.SetOutputByType(typeId, sinkSourceData.Item2.UsageRatio * source.MaxOutputByType(typeId));
                ProfilerShort.End();
            }

	        int sourcePriorityIndex = 0;
            float totalRemainingConsumption = consumptionForNonStorageAndStockpiles + consumptionForStorage;
			for (; sourcePriorityIndex < sourcesByPriority.Length; ++sourcePriorityIndex)
		    {
			    if (sourceDataByPriority[sourcePriorityIndex].MaxAvailableResource > 0f)
			    {
                    float amountToSupply = Math.Max(totalRemainingConsumption, 0f);
				    sourceDataByPriority[sourcePriorityIndex].UsageRatio = Math.Min(1f, amountToSupply/sourceDataByPriority[sourcePriorityIndex].MaxAvailableResource);
                    totalRemainingConsumption -= Math.Min(amountToSupply, sourceDataByPriority[sourcePriorityIndex].MaxAvailableResource);
			    }
			    else
				    sourceDataByPriority[sourcePriorityIndex].UsageRatio = 0f;

			    sourceDataByPriority[sourcePriorityIndex].ActiveCount = 0;
			    foreach (MyResourceSourceComponent source in sourcesByPriority[sourcePriorityIndex])
			    {
				    if (!source.Enabled || !source.HasCapacityRemainingByType(typeId))
					    continue;

				    ++sourceDataByPriority[sourcePriorityIndex].ActiveCount;
				    ProfilerShort.Begin("Set CurrentOutput");
                    source.SetOutputByType(typeId, sourceDataByPriority[sourcePriorityIndex].UsageRatio * source.MaxOutputByType(typeId));
				    ProfilerShort.End();
			    }
		    }

		    MyResourceStateEnum resultState;
			if (totalAvailableResource == 0.0f)
				resultState = MyResourceStateEnum.NoPower;
			else if (sinkDataByPriority[m_sinkGroupPrioritiesTotal - 1].RequiredInputCumulative > totalAvailableResource)
		    {
				MySinkGroupData lastGroup = sinkDataByPriority.Last();
			    if (lastGroup.IsAdaptible && lastGroup.RemainingAvailableResource != 0.0f)
					resultState = MyResourceStateEnum.OverloadAdaptible;
			    else
					resultState = MyResourceStateEnum.OverloadBlackout;
		    }
		    else
				resultState = MyResourceStateEnum.Ok;
		    ProfilerShort.End();

            ProfilerShort.End();

		    return resultState;
	    }
Exemple #42
0
        internal void UpdateCache()
        {
            TotalPowerNetConsumption = PowerConsumptionByGroup.Values.Sum();
            TotalPowerStorage        = BlockCountByType
                                       .Select(x => MyTuple.Create(MyDefinitionManager.Static.GetCubeBlockDefinition(x.Key), x.Value))
                                       .Where(x => x.Item1 is MyBatteryBlockDefinition)
                                       .Sum(x => ((MyBatteryBlockDefinition)x.Item1).MaxStoredPower * x.Item2);
            TotalInventoryCapacity = BlockCountByType
                                     .Select(x => x.Value * InventoryUtility.GetInventoryVolume(x.Key))
                                     .Sum();

            m_productionCache.Clear();
            m_gasStorageCache.Clear();
            foreach (var kv in BlockCountByType)
            {
                var def        = MyDefinitionManager.Static.GetCubeBlockDefinition(kv.Key);
                var gasTankDef = def as MyGasTankDefinition;
                if (gasTankDef != null)
                {
                    m_gasStorageCache.AddValue(gasTankDef.StoredGasId, gasTankDef.Capacity * kv.Value);
                    continue;
                }
                var oxyDef = def as MyOxygenGeneratorDefinition;
                if (oxyDef != null)
                {
                    if (oxyDef.ProducedGases == null)
                    {
                        continue;
                    }
                    foreach (var recipe in oxyDef.ProducedGases)
                    {
                        m_productionCache.AddValue(recipe.Id, recipe.IceToGasRatio * oxyDef.IceConsumptionPerSecond * kv.Value);
                    }
                    continue;
                }

                var oxyFarmDef = def as MyOxygenFarmDefinition;
                if (oxyFarmDef != null)
                {
                    m_productionCache.AddValue(oxyFarmDef.ProducedGas, oxyFarmDef.MaxGasOutput * Utilities.SunMovementMultiplier * (oxyFarmDef.IsTwoSided ? 1 : 0.5f) * kv.Value);
                    continue;
                }

                var prodDef = def as MyProductionBlockDefinition;
                if (prodDef == null)
                {
                    continue;
                }
                var speedMult = 1.0;
                var asmDef    = def as MyAssemblerDefinition;
                if (asmDef != null)
                {
                    speedMult = asmDef.AssemblySpeed;
                }
                var refineDef = def as MyRefineryDefinition;
                if (refineDef != null)
                {
                    speedMult = refineDef.RefineSpeed;
                }
                foreach (var bpc in prodDef.BlueprintClasses)
                {
                    foreach (var bp in bpc)
                    {
                        foreach (var result in bp.Results)
                        {
                            m_productionCache.AddValue(result.Id, speedMult * (1 / bp.BaseProductionTimeInSeconds) * (double)result.Amount * kv.Value);
                        }
                        foreach (var preq in bp.Prerequisites)
                        {
                            if (preq.Id.TypeId != typeof(MyObjectBuilder_Ore))
                            {
                                continue;
                            }
                            m_productionCache.AddValue(preq.Id, speedMult * (1 / bp.BaseProductionTimeInSeconds) * (double)preq.Amount * kv.Value);
                        }
                    }
                }
            }

            var reqResources = 0D;

            foreach (var kv in BlockCountByType)
            {
                reqResources += BlueprintIndex.Instance.GetRawResourcesFor(kv.Key) * kv.Value;
            }
            TotalRawResources = reqResources;
        }
Exemple #43
0
 public static void HandleSomeEventB(string arg1, object arg2, double arg3, MyTuple mt)
 {
     Console.WriteLine("SomeEvent handler B: " + arg1 + ", " + arg2 + ", " + arg3 + ", " + mt.A + ", " + mt.B);
 }
 public void SetTarget(long targetID)
 {
     TargetKey = MyTuple.Create(IntelItemType.Enemy, targetID);
 }