public VoxelPlacementDefinition(MyObjectBuilder_VoxelMiningDefinition.MiningDef ob, NamedLogger log)
            {
                Material = MyDefinitionManager.Get <MyVoxelMaterialDefinition>(ob.VoxelMaterial);
                if (Material == null)
                {
                    log.Warning($"Could not find voxel material definition {ob.VoxelMaterial}");
                    Material = MyVoxelMaterialDefinition.Default;
                }

                Volume = ob.VolumeAttribute;
                var replacementItems = new Dictionary <MyDefinitionId, int>();

                foreach (var item in ob.MinedItems)
                {
                    MyObjectBuilderType type;
                    try
                    {
                        type = MyObjectBuilderType.Parse(item.Type);
                    }
                    catch
                    {
                        log.Warning($"Can not parse defined builder type {item.Type}");
                        continue;
                    }

                    var key = new MyDefinitionId(type, MyStringHash.GetOrCompute(item.Subtype));
                    replacementItems[key] = item.Amount;
                }

                Items = replacementItems;
            }
Exemplo n.º 2
0
        private static void DoOperationClient(PaintOperation data)
        {
            MyVoxelBase target;

            if (!MyEntities.TryGetEntityById(data.VoxelId, out target))
            {
                return;
            }

            var miningDef = MyDefinitionManager.Get <MyVoxelMiningDefinition>(data.MiningId);

            if (miningDef == null)
            {
                return;
            }

            var filter = new bool[256];

            for (var i = 0; i < filter.Length; i++)
            {
                filter[i] = miningDef.MiningEntries.ContainsKey(i);
            }

            PaintVoxels(target, data.Position, data.Radius, data.Plane, data.Material, filter, null);
        }
Exemplo n.º 3
0
        public override bool Check(MyDefinitionId itemId)
        {
            var def = MyDefinitionManager.Get <MyInventoryItemDefinition>(itemId);

            if (def == null)
            {
                return(false);
            }

            switch (_equality)
            {
            case MrzEqualityResult.Equal:
                return(Math.Abs(def.Mass - _mass) < MrzUtils.Epsilon);

            case MrzEqualityResult.NotEqual:
                return(Math.Abs(def.Mass - _mass) > MrzUtils.Epsilon);

            case MrzEqualityResult.Less:
                return(def.Mass < _mass);

            case MrzEqualityResult.Greater:
                return(def.Mass > _mass);

            case MrzEqualityResult.LessOrEqual:
                return(def.Mass <= _mass);

            case MrzEqualityResult.GreateOrEqual:
                return(def.Mass >= _mass);

            default:
                return(false);
            }
        }
Exemplo n.º 4
0
        public void Unblit(out IGradeShape fillShape, out IGradeShape excavateShape)
        {
            fillShape = excavateShape = null;

            var def = MyDefinitionManager.Get <RailGradeComponentDefinition>(Definition);

            if (def == null)
            {
                return;
            }

            if (def.Support.HasValue)
            {
                var s = def.Support.Value;
                fillShape = CompositeGradeShape.Composite(Edges
                                                          .Select(e => def.Support.Value.CreateShape(e, false)).ToArray());
            }

            if (def.Excavate.HasValue)
            {
                var s = def.Excavate.Value;
                excavateShape = CompositeGradeShape.Composite(Edges
                                                              .Select(e => def.Excavate.Value.CreateShape(e, true)).ToArray());
            }
        }
Exemplo n.º 5
0
            public MiningEntry(MyObjectBuilder_VoxelMiningDefinition_MiningDef item)
            {
                var dictionary = new Dictionary <MyDefinitionId, int>();

                if (item.MinedItems != null)
                {
                    foreach (MyObjectBuilder_VoxelMiningDefinition_MinedItem minedItem in item.MinedItems)
                    {
                        var sid = new SerializableDefinitionId
                        {
                            TypeIdString = minedItem.Type,
                            SubtypeName  = minedItem.Subtype
                        };
                        dictionary[sid] = minedItem.Amount;
                    }
                }

                MinedItems = dictionary;

                var num = item.Volume.HasValue ? Math.Max(item.Volume.Value, 1) : 64;
                var materialDefinition = MyDefinitionManager.Get <MyVoxelMaterialDefinition>(item.VoxelMaterial);

                if (materialDefinition == null || materialDefinition.Index == byte.MaxValue)
                {
                    MySession.Static.Log.Warning($"Cannot find voxel material {item.VoxelMaterial}");
                    Material = MyVoxelMaterialDefinition.Default;
                    Volume   = 64;
                }
                else
                {
                    Material = materialDefinition;
                    Volume   = num;
                }
            }
Exemplo n.º 6
0
        public static T Definition <T>(MyDefinitionId definition, string msg) where T : MyDefinitionBase
        {
            var res = MyDefinitionManager.Get <T>(definition);

            if (res == null)
            {
                Warn($"ASSERT: Failed to find {definition}.  {msg}");
            }
            return(res);
        }
        private void NotifyInventoryInteractionSuccess(long entityId, SerializableDefinitionId id, int amount)
        {
            if (MySession.Static.PlayerEntity == null || MySession.Static.PlayerEntity.EntityId != entityId)
            {
                return;
            }

            var text           = MyTexts.GetString(_definition.SuccessNotification);
            var itemDefinition = MyDefinitionManager.Get <MyInventoryItemDefinition>(id);

            _successNotification.Text = string.Format(text, itemDefinition?.DisplayNameText ?? id.ToString(), amount);
            _successNotification?.Show();
        }
        /// <summary>
        /// Returns a random item id associated with this tag. If no items belong to this tag, or the tag is null, null is returned.
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public static MyDefinitionId?GetRandomItemFromTag(MyStringHash tag)
        {
            var tagDef = MyDefinitionManager.Get <MyItemTagDefinition>(tag);

            if (tagDef?.Items == null || tagDef.Items.Count == 0)
            {
                return(null);
            }

            var index = MyRandom.Instance.Next(tagDef.Items.Count);

            return(tagDef.Items[index].Id);
        }
Exemplo n.º 9
0
 private void EnsureMemorized()
 {
     if (_hasMemorized)
     {
         return;
     }
     _memorizedModifier = MyDefinitionManager.Get <EquiModifierBaseDefinition>(_modifierId);
     if (_memorizedModifier == null)
     {
         MyDefinitionErrors.Add(_owner.Package, $"Failed to find modifier {_modifierId} for {_owner.Id}", LogSeverity.Critical);
     }
     _memorizedData = _memorizedModifier?.CreateData(_modifierData);
     _hasMemorized  = true;
 }
        private void TrySpawnEquipment(long deltaFrames)
        {
            _spawned = true;

            MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::{Entity.EntityId}");

            var inventory = this.Get <MyInventoryBase>(_definition.Inventory) ?? this.Get <MyInventoryBase>();

            if (inventory == null)
            {
                return;
            }

            MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Inventory {_definition.Inventory}");

            var loot = MyDefinitionManager.Get <MyLootTableDefinition>(_definition.LootTable);

            if (loot == null)
            {
                return;
            }

            MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Loot table {_definition.LootTable}");
            var oldItems = inventory.Items.ToList <MyInventoryItem>();

            MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Old count:{oldItems.Count}");
            inventory.GenerateContent(loot);
            var newItems = inventory.Items;

            MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::New count:{newItems.Count}");

            for (var i = 0; i < newItems.Count; i++)
            {
                var newItem = newItems.ItemAt(i);
                if (i >= oldItems.Count)
                {
                    MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Activating {newItem.DefinitionId}");
                    MyItemActivateHelper.ActivateItem(Entity, inventory, newItem);
                    continue;
                }

                var oldItem = oldItems[i];
                if (newItem.Amount > oldItem.Amount)
                {
                    MrzUtils.ShowNotificationDebug($"TrySpawnEquipment::Activating {newItem.DefinitionId}");
                    MyItemActivateHelper.ActivateItem(Entity, inventory, newItem);
                }
            }
        }
Exemplo n.º 11
0
        public override void Activate(MyEntityStatComponent owner)
        {
            base.Activate(owner);
            if (owner.Entity == null || _activatedComponentDefinition == null)
            {
                return; // can't do anything about this
            }
            // Component exists?
            {
                MyEntityComponent existingComponent;
                MyMultiComponent  existingMulti;
                if (owner.Entity.Components.TryGet(_definition.AddedComponent.TypeId, _definition.AddedComponent.SubtypeId, out existingComponent))
                {
                    return;
                }
                if (owner.Entity.Components.TryGet(_definition.AddedComponent.TypeId, out existingComponent))
                {
                    existingMulti = existingComponent as MyMultiComponent;
                    if (existingMulti == null || existingMulti.SubtypeId == _definition.AddedComponent.SubtypeId)
                    {
                        return;
                    }
                }
            }

            if (_activatedComponent == null)
            {
//                _activatedComponent = MyEntityComponent.Factory.CreateInstance(_definition.AddedComponent.TypeId);
                if (_definition.AddedComponent.TypeId == typeof(MyObjectBuilder_PhantomEffectComponent))
                {
                    _activatedComponent = new MyPhantomEffectComponent();
                }
                else
                {
                    throw new Exception("Invalid component type " + _definition.AddedComponent.TypeId);
                }
                var def = MyDefinitionManager.Get <MyEntityComponentDefinition>(_definition.AddedComponent);
                if (def != null)
                {
                    _activatedComponent.Init(def);
                }
            }

            if (_activatedComponent.Entity == null)
            {
                owner.Entity.Components.Add(_activatedComponent);
            }
        }
Exemplo n.º 12
0
        private static void spawnBarbarian(Vector3D position)
        {
            var newPos = MyEntities.FindFreePlace(position, 1f, 200, 5, 5f);

            if (!newPos.HasValue)
            {
                return;
            }
            var botPosition   = newPos.Value;
            var botDefinition = (MyAgentDefinition)MyDefinitionManager.Get <MyBotDefinition>(barbarianId);
            var createdEntity = MySession.Static.Scene.CreateEntity(botDefinition.BotEntity);

            createdEntity.PositionComp.SetWorldMatrix(MatrixD.CreateWorld(botPosition));
            botDefinition.RaiseBeforeBotSpawned(createdEntity);
            MySession.Static.Scene.ActivateEntity(createdEntity);
            botDefinition.AfterBotSpawned(createdEntity);
        }
Exemplo n.º 13
0
        public override void Init(MyEntity holder, MyHandItem item, MyHandItemBehaviorDefinition definition)
        {
            base.Init(holder, item, definition);

            var def = (MrzVoxelPainterBehaviorDefinition)definition;

            _mining = MyDefinitionManager.Get <MyVoxelMiningDefinition>(def.Mining);
            for (var i = 0; i < _filter.Length; i++)
            {
                _filter[i] = _mining.MiningEntries.ContainsKey(i);
            }

            var material = MyDefinitionManager.Get <MyVoxelMaterialDefinition>(def.PaintMaterial);

            _fillMaterial = material?.Index ?? (byte)0;

            _inventory        = holder.Get <MyInventoryBase>(MyCharacterConstants.MainInventory);
            _wrongToolMessage = MrzUtils.CreateNotification(string.Format(def.WrongToolMessage, Item.GetDefinition().DisplayNameText), MrzUtils.NotificationType.Error);
        }
        public override bool Check(MyDefinitionId itemId)
        {
            var def = MyDefinitionManager.Get <MyInventoryItemDefinition>(itemId);

            if (def == null)
            {
                return(false);
            }

            var itemSize = def.Size;

            if (def is MyBlockItemDefinition)
            {
                MrzUtils.ShowNotificationDebug($"Original mass: {itemSize}");
                itemSize *= _blockSize;
                MrzUtils.ShowNotificationDebug($"Corrected mass: {itemSize}");
            }

            switch (_equality)
            {
            case MrzEqualityResult.Equal:
                return(itemSize == _size);

            case MrzEqualityResult.NotEqual:
                return(itemSize != _size);

            case MrzEqualityResult.Less:
                return(itemSize.IsLessThan(_size));

            case MrzEqualityResult.Greater:
                return(itemSize.IsGreaterThan(_size));

            case MrzEqualityResult.LessOrEqual:
                return(itemSize.IsLessOrEqual(_size));

            case MrzEqualityResult.GreateOrEqual:
                return(itemSize.IsGreaterOrEqual(_size));

            default:
                return(false);
            }
        }
        /// <summary>
        /// Bendy component definition for the given entity container ID
        /// </summary>
        /// <param name="entityDef">container ID</param>
        /// <returns>Definition, or null if none exists</returns>
        public static BendyComponentDefinition DefinitionFor(MyDefinitionId entityDef)
        {
            var containerDef = MyDefinitionManager.Get <MyContainerDefinition>(entityDef);

            if (containerDef?.Components == null)
            {
                return(null);
            }

            foreach (var k in containerDef.Components)
            {
                var def = k.Definition as BendyComponentDefinition;
                if (def != null)
                {
                    return(def);
                }
            }

            return(null);
        }
Exemplo n.º 16
0
        public int RemoveItemFuzzy(MyDefinitionId id, int amount)
        {
            if (id.TypeId != typeof(MyObjectBuilder_ItemTagDefinition))
            {
                return(RemoveItem(id, amount));
            }
            var def     = MyDefinitionManager.Get <MyItemTagDefinition>(id);
            var removed = 0;

            foreach (var k in def.Items)
            {
                var removedPart = RemoveItem(k.Id, amount);
                amount  -= removedPart;
                removed += removedPart;
                if (amount <= 0)
                {
                    break;
                }
            }
            return(removed);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Add items of the definition id specified.
        ///
        /// If Id is an item, simply add the items.
        /// If Id is a tag, add a random item with that tag.
        /// If Id is loot table, add results of that loot table.
        /// </summary>
        /// <param name="inventory"></param>
        /// <param name="id"></param>
        /// <param name="amount"></param>
        /// <returns>True if item added, false if item didn't fit</returns>
        public static bool AddItemsFuzzyOrLoot(this MyInventoryBase inventory, MyDefinitionId id, int amount = 1)
        {
            var result = true;

            if (id.TypeId == typeof(MyObjectBuilder_LootTableDefinition))
            {
                var lootTableDefinition = MyDefinitionManager.Get <MyLootTableDefinition>(id);
                for (var i = 0; i < amount; i++)
                {
                    inventory.GenerateContent(lootTableDefinition);
                }
            }
            else if (id.TypeId == typeof(MyObjectBuilder_ItemTagDefinition))
            {
                result = inventory.AddItemsWithTag(id.SubtypeId, amount, true);
            }
            else
            {
                result = inventory.AddItems(id, amount);
            }

            return(result);
        }
        private void OnPhysicsChanged(MyPhysicsComponentBase obj)
        {
            if (!obj.Enabled)
            {
                return;
            }
            var objectMass = obj.Mass;
            var myMass     = objectMass;

            if (objectMass <= 0)
            {
                objectMass = 1f;
            }
            var block = Container.Get <MyBlockComponent>();

            if (block != null)
            {
                var blockDef = MyDefinitionManager.Get <MyBlockDefinition>(block.DefinitionId);
                if (blockDef != null)
                {
                    myMass = blockDef.Mass;
                }
            }

            var ratio = MathHelper.Clamp((Definition.MassInfluence ?? myMass) / objectMass, 0, 1);

            if (Definition.LinearDamping.HasValue)
            {
                obj.LinearDamping = MathHelper.Lerp(DefaultLinearDamping, Definition.LinearDamping.Value, ratio);
            }

            if (Definition.AngularDamping.HasValue)
            {
                obj.AngularDamping = MathHelper.Lerp(DefaultAngularDamping, Definition.AngularDamping.Value, ratio);
            }
        }
Exemplo n.º 19
0
        public static void GenerateLuckyContent(this MyInventoryBase inventory, MyLootTableDefinition lootTableDefinition,
                                                LootContext context, HashSet <MyStringHash> blacklistedLootTables = null)
        {
            var cachingHashSet = new CachingHashSet <MyLootTableDefinition.Row>();

            foreach (var item in lootTableDefinition.LootTable)
            {
                cachingHashSet.Add(item);
            }
            cachingHashSet.ApplyChanges();
            var num = 0f;

            if (blacklistedLootTables == null)
            {
                blacklistedLootTables = new HashSet <MyStringHash>();
            }
            blacklistedLootTables.Add(lootTableDefinition.Id.SubtypeId);
            foreach (var row in cachingHashSet)
            {
                if (row.AlwaysDrops && row.ItemDefinition != null)
                {
                    if (row.ItemDefinition.Value.TypeId == typeof(MyObjectBuilder_LootTableDefinition))
                    {
                        var nestedTable = MyDefinitionManager.Get <MyLootTableDefinition>(row.ItemDefinition.Value);
                        if (nestedTable != null && !blacklistedLootTables.Contains(nestedTable.Id.SubtypeId))
                        {
                            inventory.GenerateLuckyContent(nestedTable, context, blacklistedLootTables);
                        }
                    }
                    else
                    {
                        AddItemsFuzzy(inventory, row.ItemDefinition.Value, row.Amount);
                    }

                    if (row.IsUnique)
                    {
                        cachingHashSet.Remove(row, false);
                        continue;
                    }
                }

                num += row.Weight;
            }

            var rollLucky = Math.Round(lootTableDefinition.Rolls * context.RollMultiplier + context.RollAdditive);

            for (var j = 0; j < rollLucky; j++)
            {
                var num2 = MyRandom.Instance.NextFloat(0f, num);
                cachingHashSet.ApplyChanges();
                foreach (var row2 in cachingHashSet)
                {
                    num2 -= row2.Weight;
                    if (num2 > 0f || row2.ItemDefinition == null)
                    {
                        continue;
                    }
                    if (row2.ItemDefinition.Value.TypeId == typeof(MyObjectBuilder_LootTableDefinition))
                    {
                        var nestedTable = MyDefinitionManager.Get <MyLootTableDefinition>(row2.ItemDefinition.Value);
                        if (nestedTable != null)
                        {
                            inventory.GenerateLuckyContent(nestedTable, context);
                        }
                    }
                    else
                    {
                        AddItemsFuzzy(inventory, row2.ItemDefinition.Value, row2.Amount);
                    }

                    if (row2.IsUnique)
                    {
                        cachingHashSet.Remove(row2, false);
                        num -= row2.Weight;
                    }

                    break;
                }
            }

            blacklistedLootTables.Remove(lootTableDefinition.Id.SubtypeId);
        }
Exemplo n.º 20
0
 public override void Init(MyEntityEffectDefinition definition, long applicantEntityId)
 {
     base.Init(definition, applicantEntityId);
     _definition = (EquiComponentEffectDefinition)definition;
     _activatedComponentDefinition = MyDefinitionManager.Get <MyEntityComponentDefinition>(_definition.AddedComponent);
 }
        private static void PlaceEdge(EdgePlacerConfig cfg, Vector3D[] segments)
        {
            MyEntity holderEntity;

            MyEntities.TryGetEntityById(cfg.EntityPlacing, out holderEntity);
            var holderPlayer = holderEntity != null?MyAPIGateway.Players.GetPlayerControllingEntity(holderEntity) : null;

            var def = DefinitionFor(cfg.Placed);

            if (def == null)
            {
                MyEventContext.ValidationFailed();
                return;
            }

            #region Validation

            if (!MyEventContext.Current.IsLocallyInvoked)
            {
                if (holderEntity == null || holderPlayer == null ||
                    MyEventContext.Current.Sender.Value != holderPlayer.SteamUserId)
                {
                    MyEventContext.ValidationFailed();
                    return;
                }

                if (MyAreaPermissionSystem.Static != null)
                {
                    foreach (var pos in segments)
                    {
                        if (MyAreaPermissionSystem.Static.HasPermission(holderPlayer.IdentityId, pos,
                                                                        MyPermissionsConstants.Build))
                        {
                            continue;
                        }
                        holderPlayer.ShowNotification("You cannot build here", 2000, null, new Vector4(1, 0, 0, 1));
                        MyEventContext.ValidationFailed();
                        return;
                    }
                }

                var validPlacedType = false;
                foreach (var item in holderEntity.GetInventory(MyCharacterConstants.MainInventory).Items)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    var itemDef =
                        MyDefinitionManager.Get <MyInventoryItemDefinition>(item.DefinitionId) as MyHandItemDefinition;
                    if (itemDef == null)
                    {
                        continue;
                    }
                    foreach (var behaviorDef in itemDef.Behaviors)
                    {
                        var placeDef = behaviorDef as EdgePlacerBehaviorDefinition;
                        if (placeDef == null || placeDef.Placed != cfg.Placed)
                        {
                            continue;
                        }
                        validPlacedType = true;
                        break;
                    }

                    if (validPlacedType)
                    {
                        break;
                    }
                }

                if (!validPlacedType)
                {
                    MyEventContext.ValidationFailed();
                    MySession.Static.Log.Warning(
                        $"{holderPlayer} tried to place {cfg.Placed}, but has no item that can place it");
                    return;
                }

                var layer     = MySession.Static.Components.Get <BendyController>().GetOrCreateLayer(def.Layer);
                var annotated = AnnotateNodes(layer, segments);
                var tmp       = new List <string>();
                if (!ValidatePath(def, layer, annotated, tmp))
                {
                    holderPlayer.ShowNotification(string.Join("\n", tmp));
                    MyEventContext.ValidationFailed();
                    return;
                }
            }

            #endregion


            var graph = MySession.Static.Components.Get <BendyController>().GetOrCreateLayer(def.Layer);

            for (var i = 1; i < segments.Length; i++)
            {
                var nextNode = graph.GetOrCreateNode(segments[i - 1]);
                var prevNode = graph.GetOrCreateNode(segments[i]);

                if (graph.GetEdge(prevNode, nextNode) != null)
                {
                    continue;
                }

                var obContainer = new MyObjectBuilder_ComponentContainer();
                var worldMatrix = MatrixD.CreateWorld((prevNode.Position + nextNode.Position) / 2,
                                                      Vector3D.Normalize(nextNode.Position - prevNode.Position),
                                                      Vector3D.Normalize(nextNode.Up + prevNode.Up));
                var worldMatrixInv = MatrixD.Invert(worldMatrix);
                ((ICollection <MyObjectBuilder_EntityComponent>)obContainer.Components).Add(
                    new MyObjectBuilder_BendyComponent()
                {
                    Overrides = new[]
                    {
                        new MyObjectBuilder_BendyComponent.NodePose
                        {
                            Index    = 0,
                            Position = (Vector3)Vector3D.Transform(prevNode.Position, worldMatrixInv),
                            Up       = (Vector3)Vector3D.Transform(prevNode.Up, worldMatrixInv)
                        },
                        new MyObjectBuilder_BendyComponent.NodePose
                        {
                            Index    = 1,
                            Position = (Vector3)Vector3D.Transform(nextNode.Position, worldMatrixInv),
                            Up       = (Vector3)Vector3D.Transform(nextNode.Up, worldMatrixInv)
                        }
                    }
                });
                var entOb = new MyObjectBuilder_EntityBase()
                {
                    EntityDefinitionId     = (MyDefinitionId)cfg.Placed,
                    PersistentFlags        = MyPersistentEntityFlags2.InScene,
                    PositionAndOrientation = new MyPositionAndOrientation(worldMatrix),
                    SubtypeName            = cfg.Placed.SubtypeId,
                    ComponentContainer     = obContainer
                };
                var entity = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(entOb);
                if (holderPlayer != null && holderPlayer.IsCreative())
                {
                    entity.Components.Get <ConstructableComponent>()?.InstallFromCreative();
                    ConstructableComponentDefinition.CcComponent test;
                    int test2;
                    entity.Components.Get <ConstructableComponent>()
                    ?.IncreaseIntegrity(1e9f, out test, out test2);
                }

                entity.Components.Get <BendyPhysicsComponent>()?.DestroyEnvItems();

                EntityAdded?.Invoke(holderEntity, holderPlayer, entity);
            }
        }
Exemplo n.º 22
0
        public void Install <TU>(SupplyForInstall <TU> supplier, TU userData)
        {
            using (new StockpileChangeWatcher(this))
            {
                _tmpStockpile.Items.Clear();
                if (_stockpile != null)
                {
                    foreach (var k in _stockpile.Items)
                    {
                        _tmpStockpile.AddItem(k.Key, k.Value);
                    }
                }

                foreach (var c in Definition.Components)
                {
                    var req      = (MyDefinitionId)c.Required;
                    var existing = _tmpStockpile.RemoveItemFuzzy(req, c.Count);
                    var remain   = c.Count - existing;
                    if (remain <= 0)
                    {
                        continue;
                    }

                    if (req.TypeId == typeof(MyObjectBuilder_ItemTagDefinition))
                    {
                        var tag = MyDefinitionManager.Get <MyItemTagDefinition>(req);
                        foreach (var subReq in tag.Items)
                        {
                            var removed = remain;
                            supplier.Invoke(userData, subReq.Id, ref removed);
                            if (removed == 0)
                            {
                                continue;
                            }
                            if (_stockpile == null)
                            {
                                _stockpile = new ConstructionStockpile();
                            }
                            _stockpile.AddItem(subReq.Id, removed);
                            remain -= removed;
                            if (remain <= 0)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        var removed = remain;
                        supplier.Invoke(userData, req, ref removed);
                        if (removed > 0)
                        {
                            if (_stockpile == null)
                            {
                                _stockpile = new ConstructionStockpile();
                            }
                            _stockpile.AddItem(req, removed);
                            remain -= removed;
                        }
                    }

                    if (remain > 0)
                    {
                        break;
                    }
                }

                _tmpStockpile.Clear();
            }
        }
Exemplo n.º 23
0
            internal ImmutableLightFeature(DelReportError reporter, MyObjectBuilder_EquiLightComponentDefinition.LightFeature feature)
            {
                Id   = feature.Id ?? throw new NullReferenceException("Light features must have a ID");
                Bone = feature.Bone;
                if (feature.Point != null && feature.Point.IsEnabled)
                {
                    PointLight = feature.Point.LightLayout;
                }
                else
                {
                    PointLight = null;
                }

                if (feature.Spot != null && feature.Spot.IsEnabled)
                {
                    SpotLight             = feature.Spot.SpotLightLayout;
                    SpotLightCastsShadows = feature.Spot.CastShadowsOrDefault;
                    SpotLightMask         = feature.Spot.MaskOrDefault;
                }
                else
                {
                    SpotLight             = null;
                    SpotLightCastsShadows = false;
                    SpotLightMask         = null;
                }

                if (!string.IsNullOrEmpty(feature.Flare?.Definition))
                {
                    var flareDef = MyDefinitionManager.Get <EquiFlareDefinition>(feature.Flare.Definition);
                    if (flareDef == null)
                    {
                        reporter($"Light {Id} references unknown flare {feature.Flare.Definition}", LogSeverity.Error);
                        Flare.Enabled = false;
                    }
                    else
                    {
                        var intensityMultiplier = feature.Flare.IntensityMultiplier ?? 1;
                        var sizeMultiplier      = feature.Flare.SizeMultiplier ?? 1;
                        Flare.Enabled        = true;
                        Flare.Type           = MyGlareTypeEnum.Distant;
                        Flare.MaxDistance    = feature.Flare.MaxDistanceOverride ?? flareDef.MaxDistance;
                        Flare.Intensity      = intensityMultiplier * flareDef.Intensity;
                        Flare.SizeMultiplier = sizeMultiplier * flareDef.Size;

                        Flare.QueryFreqMinMs = 150;
                        Flare.QueryFreqRndMs = 100;

                        Flare.QueryShift = 0;
                        Flare.QuerySize  = feature.Flare.OcclusionQuerySize ?? .1f;

                        // ReSharper disable CompareOfFloatsByEqualityOperator
                        if (flareDef.Glares.Length > 0 && (intensityMultiplier != 1 || sizeMultiplier != 1))
                        {
                            Flare.Glares = new MySubGlare[flareDef.Glares.Length];
                            for (var i = 0; i < Flare.Glares.Length; i++)
                            {
                                ref var src = ref flareDef.Glares[i];
                                ref var dst = ref Flare.Glares[i];
                                dst       = src;
                                dst.Size *= sizeMultiplier;
                                if (intensityMultiplier == 1)
                                {
                                    continue;
                                }
                                dst.OcclusionToIntensityCurve = new MySubGlare.KeyPoint[src.OcclusionToIntensityCurve.Length];
                                for (var j = 0; j < src.OcclusionToIntensityCurve.Length; j++)
                                {
                                    ref var srcStop = ref src.OcclusionToIntensityCurve[j];
                                    ref var dstStop = ref dst.OcclusionToIntensityCurve[j];
                                    dstStop            = srcStop;
                                    dstStop.Intensity *= intensityMultiplier;
                                }
                            }
        protected override void Hit()
        {
            if (!MyAPIGateway.Session.IsServerDecider())
            {
                return;
            }

            var player = MyAPIGateway.Players.GetPlayerControllingEntity(Holder);

            if (player == null)
            {
                return;
            }

            var constructable = GetConstructableComponent();

            if (constructable == null)
            {
                return;
            }

            int messageTime;

            switch (ActiveAction)
            {
            case MyHandItemActionEnum.Primary:
            {
                messageTime = (int)((Definition.Effects[0]?.AnimationEndMilliseconds ?? 1000) * 1.5);

                if (!HasPermission(MyPermissionsConstants.Repair))
                {
                    player.ShowNotification($"You cannot repair here!", messageTime, null, new Vector4(1, 0, 0, 1));
                    return;
                }

                var before = constructable.BuildIntegrity;
                var dt     = Definition.Efficiency;// to match vanilla * (Definition.Effects[0]?.AnimationEndMilliseconds ?? 1000f) / 1000f;
                if (player.IsCreative())
                {
                    constructable.InstallFromCreative();
                }
                else
                {
                    constructable.InstallFrom(_sourceInventories);
                }
                ConstructableComponentDefinition.CcComponent required;
                int requiredCount;
                UpdateDurability(-1);
                constructable.IncreaseIntegrity(dt, out required, out requiredCount);
                if (requiredCount > 0)
                {
                    string name = null;
                    // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                    if (required.Required.Type == typeof(MyObjectBuilder_ItemTagDefinition).Name)
                    {
                        name = MyDefinitionManager.Get <MyItemTagDefinition>(required.Required)?.DisplayNameOf();
                    }
                    else
                    {
                        name = MyDefinitionManager.Get <MyInventoryItemDefinition>(required.Required)?.DisplayNameOf();
                    }
                    name = name ?? required.Required.Subtype;
                    player.ShowNotification($"Requires {requiredCount} {name}", 2000, null, new Vector4(1, 0, 0, 1));
                }
                OnConstructed?.Invoke(this, constructable, before, constructable.BuildIntegrity);
                break;
            }

            case MyHandItemActionEnum.Secondary:
            {
                messageTime = (int)((Definition.Effects[1]?.AnimationEndMilliseconds ?? 1000) * 1.5);

                if (!HasPermission(MyPermissionsConstants.Deconstruct))
                {
                    player.ShowNotification($"You cannot deconstruct here!", messageTime, null, new Vector4(1, 0, 0, 1));
                    return;
                }

                var before = constructable.BuildIntegrity;
                var dt     = Definition.Efficiency;// to match vanilla * (Definition.Effects[1]?.AnimationEndMilliseconds ?? 1000f) / 1000f;
                if (!HasPermission(MyPermissionsConstants.QuickDeconstruct))
                {
                    dt *= 0.3333333f;
                }
                UpdateDurability(-1);
                constructable.DecreaseIntegrity(dt);
                constructable.UninstallTo(_destinationInventory);

                if (constructable.BuildIntegrity <= 0)
                {
                    constructable.UninstallAndDrop();
                    constructable.Entity.Close();
                }

                OnConstructed?.Invoke(this, constructable, before, constructable.BuildIntegrity);
                break;
            }

            case MyHandItemActionEnum.None:
            case MyHandItemActionEnum.Tertiary:
            default:
                messageTime = 2000;
                break;
            }

            player.ShowNotification($"{constructable.BuildPercent * 100:F0} %", messageTime);
        }
Exemplo n.º 25
0
        public void QueryFinishedGameThread(long dt)
        {
            _queriesInFlight--;
            if (_queriesInFlight != 0)
            {
                return;
            }

            for (var i = 0; i < _totalVoxelData.Length; i++)
            {
                _totalVoxelData[i] = 0;
            }
            float multiplier;

            if (Definition.Mode == VoxelPowerCountMode.Volume)
            {
                multiplier = (1L << (3 * Definition.LevelOfDetail)) / (float)byte.MaxValue;
            }
            else
            {
                multiplier = (1L << (2 * Definition.LevelOfDetail));
            }
            // consume data from workers.
            foreach (var worker in _trackedVoxels.Values)
            {
                for (var i = 0; i < Math.Min(_totalVoxelData.Length, worker.Counts.Length); i++)
                {
                    _totalVoxelData[i] += worker.Counts[i] * multiplier;
                }
            }

            // check materials
            var result = Definition.Operator == QuestConditionCompositeOperator.AND;

            foreach (var mtl in Definition.Materials)
            {
                var voxEntry = MyDefinitionManager.Get <MyVoxelMaterialDefinition>(mtl.Material);
                if (voxEntry == null)
                {
                    continue;
                }
                if (Definition.DebugMode)
                {
                    MyAPIGateway.Utilities?.ShowNotification(
                        $"VoxelPowerDbg: Entry {voxEntry.Id.SubtypeName}={_totalVoxelData[voxEntry.Index]} Condition: {(mtl.LessThan ? "<" : ">=")} {mtl.Amount}");
                }
                var eval = mtl.LessThan ? _totalVoxelData[voxEntry.Index] < mtl.Amount : _totalVoxelData[voxEntry.Index] >= mtl.Amount;
                if (Definition.Operator == QuestConditionCompositeOperator.AND)
                {
                    result &= eval;
                    if (!result)
                    {
                        break;
                    }
                }
                else if (Definition.Operator == QuestConditionCompositeOperator.OR)
                {
                    result |= eval;
                    if (result)
                    {
                        break;
                    }
                }
            }

            if (Definition.DebugMode)
            {
                MyAPIGateway.Utilities?.ShowNotification("VoxelPowerDbg: Refreshed");
            }
            Disturbed = false;
            IsPowered = result;
        }
Exemplo n.º 26
0
        public static string DescContainer(MyDefinitionId id)
        {
            var cc = MyDefinitionManager.Get <MyContainerDefinition>(id);

            return(cc?.DisplayNameOf() ?? id.SubtypeName);
        }
Exemplo n.º 27
0
        protected override void Hit()
        {
            if (!MyAPIGateway.Session.IsServerDecider())
            {
                return;
            }
            var player = MyAPIGateway.Players.GetPlayerControllingEntity(Holder);

            if (player == null)
            {
                return;
            }

            if (!HasPermission(MyPermissionsConstants.Mining))
            {
                player.ShowNotification("You don't have permission to terraform here.", 2000, null, new Vector4(1, 0, 0, 1));
                return;
            }

            bool isExcavating = ActiveAction == MyHandItemActionEnum.Primary;

            var           radius = isExcavating ? Definition.ExcavateRadius : Definition.FillRadius;
            uint          availableForDeposit;
            StringBuilder requiredMaterials = null;

            if (isExcavating)
            {
                availableForDeposit = 0;
            }
            else
            {
                availableForDeposit = Definition.FillVolume;
                var andHead = -1;
                var missing = 0;
                if (!player.IsCreative())
                {
                    foreach (var item in Definition.FillMaterial.MinedItems)
                    {
                        var amount = 0;
                        foreach (var inv in Holder.Components.GetComponents <MyInventoryBase>())
                        {
                            amount += inv.GetItemAmountFuzzy(item.Key);
                        }
                        amount = amount * Definition.FillMaterial.Volume / item.Value;
                        if (amount == 0)
                        {
                            if (requiredMaterials == null)
                            {
                                requiredMaterials = new StringBuilder("You require ");
                            }
                            var itemDef = MyDefinitionManager.Get <MyInventoryItemDefinition>(item.Key);
                            andHead = requiredMaterials.Length;
                            missing++;
                            requiredMaterials.Append(itemDef?.DisplayNameOf() ?? item.Key.ToString()).Append(", ");
                        }

                        availableForDeposit = (uint)Math.Min(availableForDeposit, amount);
                    }
                }

                if (missing > 0 && requiredMaterials != null)
                {
                    if (andHead != -1 && missing >= 2)
                    {
                        requiredMaterials.Insert(andHead, "and ");
                    }
                    requiredMaterials.Remove(requiredMaterials.Length - 2, 2);
                }
            }

            var availableForExcavate = isExcavating ? Definition.ExcavateVolume : 0;

            uint totalDeposited;
            uint totalExcavated;
            bool triedToChange;
            bool intersectedDynamic;
            var  result = RailGraderSystem.DoGrading(_gradeComponents, Target.Position, radius, availableForDeposit,
                                                     availableForExcavate, _excavated, Definition.FillMaterial.Material.Index,
                                                     out totalDeposited, out totalExcavated, testDynamic: true,
                                                     triedToChange: out triedToChange, intersectedDynamic: out intersectedDynamic);

            #region Give Items

            var ranOutOfInventorySpace = false;
            if (triedToChange && isExcavating && !player.IsCreative())
            {
                for (var i = 0; i < _excavated.Length; i++)
                {
                    if (_excavated[i] == 0)
                    {
                        continue;
                    }
                    MyVoxelMiningDefinition.MiningEntry einfo;
                    if (Definition.ExcavateDefinition == null || !Definition.ExcavateDefinition.MiningEntries.TryGetValue(i, out einfo))
                    {
                        continue;
                    }
                    var outputInventory = Holder.GetInventory(MyCharacterConstants.MainInventory);
                    var count           = (int)Math.Floor(_excavated[i] / (float)einfo.Volume);
                    if (count == 0)
                    {
                        continue;
                    }
                    _excavated[i] -= (uint)Math.Max(0, count * einfo.Volume);
                    foreach (var k in einfo.MinedItems)
                    {
                        var amount = k.Value * count;
                        if (outputInventory != null && outputInventory.AddItems(k.Key, amount))
                        {
                            continue;
                        }
                        ranOutOfInventorySpace = true;
                        var pos = MyAPIGateway.Entities.FindFreePlace(Target.Position, radius) ?? Target.Position;
                        MySession.Static.Components.Get <MyFloatingObjects>()
                        ?.Spawn(MyInventoryItem.Create(k.Key, amount), MatrixD.CreateTranslation(pos), null);
                    }
                }
            }

            if (ranOutOfInventorySpace)
            {
                player.ShowNotification("Inventory is full", color: new Vector4(1, 0, 0, 1));
            }

            #endregion

            #region Take Items

            _depositAccumulation += (int)totalDeposited;
            if (!player.IsCreative())
            {
                if (_depositAccumulation > 0 && !isExcavating && Definition.FillMaterial.MinedItems != null)
                {
                    int amnt = (int)Math.Floor(_depositAccumulation / (float)Definition.FillMaterial.Volume);
                    _depositAccumulation -= amnt * Definition.FillMaterial.Volume;
                    if (amnt > 0)
                    {
                        foreach (var k in Definition.FillMaterial.MinedItems)
                        {
                            var required = amnt * k.Value;
                            if (required == 0)
                            {
                                return;
                            }
                            foreach (var inv in Holder.Components.GetComponents <MyInventoryBase>())
                            {
                                var count = Math.Min(required, inv.GetItemAmountFuzzy(k.Key));
                                if (count > 0 && inv.RemoveItemsFuzzy(k.Key, count))
                                {
                                    required -= count;
                                }
                            }
                        }
                    }
                }
            }

            #endregion

            if (totalDeposited > 0 || totalExcavated > 0)
            {
                var duraCost = (int)Math.Round(totalDeposited * Definition.FillDurabilityPerVol + totalExcavated * Definition.ExcavateDurabilityPerVol);
                if (duraCost > 0)
                {
                    UpdateDurability(-duraCost);
                }
                GraderUsed?.Invoke(this, _gradeComponents, totalDeposited, totalExcavated);
                RailGraderSystem.RaiseDoGrade(_gradeComponents, Target.Position, radius, availableForDeposit, availableForExcavate,
                                              Definition.FillMaterial.Material.Index, totalExcavated, totalDeposited);
                return;
            }

            if (!isExcavating && intersectedDynamic && triedToChange)
            {
                player.ShowNotification("Cannot fill where there are players or dynamic grids", color: new Vector4(1, 0, 0, 1));
            }
            if (!isExcavating && requiredMaterials != null && triedToChange)
            {
                player.ShowNotification(requiredMaterials?.ToString(), color: new Vector4(1, 0, 0, 1));
            }
        }
Exemplo n.º 28
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_EquiHarvestableComponentDefinition)def;

            _lootTableByTag.Clear();
            _lootTableByItem.Clear();
            if (ob.Entries == null)
            {
                return;
            }
            foreach (var k in ob.Entries)
            {
                if (string.IsNullOrWhiteSpace(k.From))
                {
                    MyDefinitionErrors.Add(Package, $"{Id} has an entry with no from state", LogSeverity.Warning);
                    continue;
                }

                if (k.Harvesters == null || k.Harvesters.Length == 0)
                {
                    MyDefinitionErrors.Add(Package, $"{Id} has an entry with no harvesters", LogSeverity.Warning);
                    continue;
                }

                MyLootTableDefinition lootTable = null;
                if (k.LootTable.HasValue)
                {
                    lootTable = MyDefinitionManager.Get <MyLootTableDefinition>(k.LootTable.Value);
                    if (lootTable == null)
                    {
                        MyDefinitionErrors.Add(Package, $"{Id} has an entry from {k.From} referring to missing loot table {k.LootTable}",
                                               LogSeverity.Warning);
                        continue;
                    }
                }

                foreach (var item in k.Harvesters)
                {
                    if (!item.IsValid())
                    {
                        MyDefinitionErrors.Add(Package, $"{Id} has an entry with an invalid harvester", LogSeverity.Warning);
                    }
                }


                var sourceState = MyStringHash.GetOrCompute(k.From);
                var destState   = MyStringHash.GetOrCompute(k.To);
                var data        = new Data(lootTable, destState, k.RequiresPermission, k.ActionHint ?? "Harvest",
                                           MyStringHash.GetOrCompute(k.ActionIcon ?? "Pickup_Item"));

                foreach (var item in k.Harvesters)
                {
                    if (!item.IsValid())
                    {
                        continue;
                    }

                    if (!string.IsNullOrWhiteSpace(item.Tag))
                    {
                        _lootTableByTag[new TagKey(sourceState, MyStringHash.GetOrCompute(item.Tag))] = data;
                    }
                    else
                    {
                        _lootTableByItem[new DefinitionKey(sourceState, item)] = data;
                    }
                }
            }
        }
Exemplo n.º 29
0
        public static bool Apply <TInstance>(MyInventoryBase items, ListReader <ImmutableInventoryAction> actions,
                                             LuckyLoot.LootContext?luckContext = null, ActionWithArg <TInstance, ImmutableInventoryAction>?errorReporter = null)
        {
            var luck    = luckContext ?? LuckyLoot.DefaultLoot;
            var success = true;

            foreach (var action in actions)
            {
                switch (action.Mode)
                {
                case ImmutableInventoryAction.InventoryActionMode.GiveTakeItem:
                {
                    if (action.Amount > 0)
                    {
                        success = action.TargetId.TypeId == typeof(MyObjectBuilder_ItemTagDefinition)
                                ? items.AddItemsWithTag(action.TargetId.SubtypeId, action.Amount)
                                : items.AddItems(action.TargetId, action.Amount);
                    }
                    else
                    {
                        success = action.TargetId.TypeId == typeof(MyObjectBuilder_ItemTagDefinition)
                                ? items.RemoveItemsWithTag(action.TargetId.SubtypeId, -action.Amount)
                                : items.RemoveItems(action.TargetId, -action.Amount);
                    }
                    break;
                }

                case ImmutableInventoryAction.InventoryActionMode.RepairDamageItem:
                {
                    var remaining = action.Amount;
                    if (action.TargetId.TypeId == typeof(MyObjectBuilder_ItemTagDefinition))
                    {
                        foreach (var item in items.Items)
                        {
                            if (item is MyDurableItem durable && item.HasTag(action.TargetId.SubtypeId))
                            {
                                ApplyDurability(durable, ref remaining);
                                if (durable.Durability == 0)
                                {
                                    var broken = durable.GetDefinition().BrokenItem;
                                    var amount = item.Amount;
                                    if (!items.Remove(item))
                                    {
                                        break;
                                    }

                                    if (broken.HasValue && !items.AddItems(broken.Value, amount))
                                    {
                                        break;
                                    }
                                }

                                if (remaining == 0)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (var item in items.Items)
                        {
                            if (item is MyDurableItem durable && item.DefinitionId == action.TargetId)
                            {
                                ApplyDurability(durable, ref remaining);
                                if (durable.Durability == 0)
                                {
                                    var broken = durable.GetDefinition().BrokenItem;
                                    var amount = item.Amount;
                                    if (!items.Remove(item))
                                    {
                                        break;
                                    }
                                    if (broken.HasValue && !items.AddItems(broken.Value, amount))
                                    {
                                        break;
                                    }
                                }

                                if (remaining == 0)
                                {
                                    break;
                                }
                            }
                        }
                    }

                    success = remaining == 0;
                    break;
                }

                case ImmutableInventoryAction.InventoryActionMode.GiveTakeLootTable:
                {
                    using (ItemCollection.Borrow(out var tmp))
                    {
                        using (PoolManager.Get(out HashSet <MyStringHash> tmpSet))
                        {
                            var table = MyDefinitionManager.Get <MyLootTableDefinition>(action.TargetId);
                            for (var pass = 0; pass < Math.Abs(action.Amount); pass++)
                            {
                                tmpSet.Clear();
                                tmp.GenerateLuckyContent(table, luck, tmpSet);
                            }
                        }

                        if (action.Amount > 0)
                        {
                            foreach (var item in tmp.Items)
                            {
                                success &= items.Add(item);
                            }
                        }
                        else
                        {
                            foreach (var item in tmp.Items)
                            {
                                success &= items.RemoveItems(item.DefinitionId, item.Amount);
                            }
                        }
                    }

                    break;
                }

                default:
                    throw new Exception("Bad mode");
                }

                if (!success)
                {
                    errorReporter?.Invoke(action);
                    return(false);
                }
            }

            return(success);
        }