Пример #1
0
        public override bool CanCombine(Point16 orig, Point16 dir)
        {
            NetworkCollection.HasFluidPipeAt(orig + dir, out FluidNetwork thisNet);
            NetworkCollection.HasFluidPipeAt(orig - dir, out FluidNetwork otherNet);
            var otherAxis = new Point16(dir.Y, dir.X);

            NetworkCollection.HasFluidPipeAt(orig + otherAxis, out FluidNetwork axisNet);
            NetworkCollection.HasFluidPipeAt(orig - otherAxis, out FluidNetwork otherAxisNet);

            Tile center = Framing.GetTileSafely(orig);

            if (ModContent.GetModTile(center.type) is TransportJunction)
            {
                //At this point, only one axis is being handled, so that's fine
                JunctionMerge merge = JunctionMergeable.mergeTypes[center.frameX / 18];

                if (((merge & JunctionMerge.Fluids_LeftRight) != 0 && dir.X != 0) || ((merge & JunctionMerge.Fluids_UpDown) != 0 && dir.Y != 0))
                {
                    return(otherNet is null || (otherNet.liquidType == thisNet.liquidType && otherNet.gasType == thisNet.gasType));
                }
                return(false);
            }

            //Not a junction at the center.  Need to check every direction
            //All directions just need to be checked against this one
            bool hasConnOther     = otherNet != null;
            bool hasConnAxis      = axisNet != null;
            bool hasConnAxisOther = otherAxisNet != null;

            return((!hasConnOther || (otherNet.liquidType == thisNet.liquidType && otherNet.gasType == thisNet.gasType)) &&
                   (!hasConnAxis || (axisNet.liquidType == thisNet.liquidType && axisNet.gasType == thisNet.gasType)) &&
                   (!hasConnAxisOther || (otherAxisNet.liquidType == thisNet.liquidType && otherAxisNet.gasType == thisNet.gasType)));
        }
Пример #2
0
 public override bool UseItem(Player player)
 {
     for (int i = 0; i < Main.maxTilesX; i++)
     {
         for (int j = 0; j < Main.maxTilesY; j++)
         {
             Tile    tile  = Framing.GetTileSafely(i, j);
             ModTile mTile = ModContent.GetModTile(tile.type);
             if (mTile != null)
             {
                 if (mTile.mod.Name == "Azercadmium")
                 {
                     if (mTile.Name == "Plants")
                     {
                         tile.type   = (ushort)ModContent.TileType <HellPlants>();
                         tile.frameY = 0;
                         tile.frameX = (short)MathHelper.Clamp(tile.frameX, 0, 198);
                     }
                     if (mTile.Name == "Stems")
                     {
                         tile.type = (ushort)ModContent.TileType <CinderCedarTree>();
                         if (tile.frameX > 264)
                         {
                             tile.frameX -= 264;
                         }
                     }
                 }
             }
         }
     }
     return(true);
 }
Пример #3
0
        private void Disengage(Point16 pos, int size)
        {
            if (!ByPosition.ContainsKey(pos))
            {
                return;
            }

            var entity = ByPosition[pos] as GearTileEntity;

            if (entity != null)
            {
                if (entity.size == size && entity.engaged)
                {
                    entity.rotationVelocity = 0;
                    entity.rotationOffset   = 0;

                    engaged = false;

                    Tile tile = Main.tile[Position.X, Position.Y];
                    (ModContent.GetModTile(tile.type) as GearTile)?.OnDisengage(this);

                    entity.RecurseOverGears(entity.Disengage);
                }
            }

            engaged = false;
        }
Пример #4
0
        public static void TryImportGases <T>(this T entity, Point16 pipePos, int indexToExtract) where T : MachineEntity, IGasMachine
        {
            if (indexToExtract < 0 || indexToExtract >= entity.GasEntries.Length)
            {
                return;
            }

            var entry = entity.GasEntries[indexToExtract];

            if (!NetworkCollection.HasFluidPipeAt(pipePos, out FluidNetwork net) ||
                net.liquidType != MachineLiquidID.None ||
                net.gasType == MachineGasID.None ||
                !entry.isInput ||
                (entry.id != MachineGasID.None && entry.id != net.gasType) ||
                (entry.validTypes?.Length > 0 && Array.FindIndex(entry.validTypes, id => id == net.gasType) == -1))
            {
                return;
            }

            Tile    tile    = Framing.GetTileSafely(pipePos);
            ModTile modTile = ModContent.GetModTile(tile.type);

            float rate = modTile is FluidTransportTile transport
                                ? transport.ExportRate
                                : (modTile is FluidPumpTile
                                        ? ModContent.GetInstance <FluidTransportTile>().ExportRate
                                        : -1);

            if (rate <= 0)
            {
                return;
            }

            float exported = Math.Min(rate, net.Capacity);

            if (exported + entry.current > entry.max)
            {
                exported = entry.max - entry.current;
            }

            if (exported <= 0)
            {
                return;
            }

            if (entry.id == MachineGasID.None)
            {
                entry.id = net.gasType;
            }

            entry.current   += exported;
            net.StoredFluid -= exported;

            if (net.StoredFluid <= 0)
            {
                net.gasType = MachineGasID.None;
            }
        }
Пример #5
0
        private void RefreshRates()
        {
            if (!needsRateRefresh)
            {
                return;
            }

            needsRateRefresh = false;

            TerraFlux import = new TerraFlux(0f);
            TerraFlux export = new TerraFlux(0f);

            int count = 0;

            var inst = ModContent.GetInstance <TFWireTile>();

            foreach (var wire in Hash)
            {
                ModTile tile = ModContent.GetModTile(Framing.GetTileSafely(wire.Position).type);

                if (tile is null)
                {
                    continue;
                }

                if (tile is TransportJunction)
                {
                    import += inst.ImportRate;
                    export += inst.ExportRate;
                }
                else if (tile is TFWireTile wireTile)
                {
                    import += wireTile.ImportRate;
                    export += wireTile.ExportRate;
                }
                else
                {
                    continue;
                }

                count++;
            }

            if (count == 0)
            {
                ImportRate = new TerraFlux(0f);
                ExportRate = new TerraFlux(0f);
            }
            else
            {
                ImportRate = import / count;
                ExportRate = export / count;
            }
        }
Пример #6
0
        public static Vector2 TileEntityCenter(TileEntity entity, int tileType)
        {
            Machine tile = ModContent.GetModTile(tileType) as Machine;

            tile.GetDefaultParams(out _, out uint width, out uint height, out _);

            Point16 topLeft      = entity.Position;
            Point16 size         = new Point16((int)width, (int)height);
            Vector2 worldTopLeft = topLeft.ToVector2() * 16;

            return(worldTopLeft + size.ToVector2() * 8);            // * 16 / 2
        }
Пример #7
0
        public static void KillMachine(int i, int j, int type)
        {
            Tile    tile  = Main.tile[i, j];
            Machine mTile = ModContent.GetModTile(type) as Machine;

            mTile.GetDefaultParams(out _, out _, out _, out int itemType);

            int         itemIndex = Item.NewItem(i * 16, j * 16, 16, 16, itemType);
            MachineItem item      = Main.item[itemIndex].modItem as MachineItem;

            Point16 tePos = new Point16(i, j) - tile.TileCoord();

            if (TileEntity.ByPosition.ContainsKey(tePos))
            {
                MachineEntity tileEntity = TileEntity.ByPosition[tePos] as MachineEntity;
                //Drop any items the entity contains
                if (tileEntity.SlotsCount > 0)
                {
                    for (int slot = 0; slot < tileEntity.SlotsCount; slot++)
                    {
                        Item drop = tileEntity.RetrieveItem(slot);

                        //Drop the item and copy over any important data
                        if (drop.type > ItemID.None && drop.stack > 0)
                        {
                            int dropIndex = Item.NewItem(i * 16, j * 16, 16, 16, drop.type, drop.stack);
                            if (drop.modItem != null)
                            {
                                Main.item[dropIndex].modItem.Load(drop.modItem.Save());
                            }
                        }

                        tileEntity.ClearItem(slot);
                    }
                }

                item.entityData = tileEntity.Save();

                //Remove this machine from the wire networks if it's a powered machine
                if (tileEntity is PoweredMachineEntity pme)
                {
                    NetworkCollection.RemoveMachine(pme);
                }

                tileEntity.Kill(i, j);

                if (Main.netMode == NetmodeID.MultiplayerClient)
                {
                    NetMessage.SendData(MessageID.TileEntitySharing, remoteClient: -1, ignoreClient: Main.myPlayer, number: tileEntity.ID);
                }
            }
        }
Пример #8
0
        internal static float GetItemMovementProgressFactorAt(Point16 tilePos)
        {
            var mTile = ModContent.GetModTile(Framing.GetTileSafely(tilePos).type);

            return(mTile is null
                                ? -1
                                : (mTile is ItemTransportTile item
                                        ? item.TransferProgressPerTick
                                        : (mTile is TransportJunction
                                                ? ModContent.GetInstance <ItemTransportTile>().TransferProgressPerTick
                                                : (mTile is ItemPumpTile
                                                        ? ModContent.GetInstance <ItemTransportTile>().TransferProgressPerTick
                                                        : -1))));
        }
Пример #9
0
        public MachineEntity GetConnectedMachine(Point16 location)
        {
            var  actualLocation = GetBackwardsOffset(location);
            Tile tile           = Framing.GetTileSafely(actualLocation);

            if (!(ModContent.GetModTile(tile.type) is Machine))
            {
                return(null);
            }

            Point16 origin = actualLocation - tile.TileCoord();

            return(TileEntity.ByPosition.TryGetValue(origin, out TileEntity entity) && entity is MachineEntity machineEntity && (machineEntity is ILiquidMachine || machineEntity is IGasMachine) ? machineEntity : null);
        }
        public void TryExportLiquid(Point16 pumpPos)
        {
            (ModContent.GetModTile(MachineTile) as Machine).GetDefaultParams(out _, out uint width, out _, out _);

            float x = Position.X + width / 2f;

            if (pumpPos.X + 0.5f < x - 0.01f)
            {
                this.TryExportLiquids(pumpPos, 1);

                LiquidEntries[0].id      = LiquidEntries[1].id;
                LiquidEntries[0].current = LiquidEntries[1].current;
                LiquidEntries[0].max     = LiquidEntries[1].max;
            }
        }
        public void TryImportGas(Point16 pipePos)
        {
            (ModContent.GetModTile(MachineTile) as Machine).GetDefaultParams(out _, out uint width, out _, out _);

            float x = Position.X + width / 2f;

            if (pipePos.X + 0.5f > x + 0.01f)
            {
                this.TryImportGases(pipePos, 0);

                GasEntries[1].id      = GasEntries[0].id;
                GasEntries[1].current = GasEntries[0].current;
                GasEntries[1].max     = GasEntries[0].max;
            }
        }
        /// <summary>
        /// Called on Mod.Load
        /// </summary>
        public void Load()
        {
            if (!Main.dedServ)
            {
                interfaces = new Dictionary <string, UserInterface>();
                states     = new Dictionary <string, MachineUI>();

                var types = TechMod.types;
                foreach (var type in types)
                {
                    //Ignore abstract classes
                    if (type.IsAbstract)
                    {
                        continue;
                    }

                    if (typeof(MachineUI).IsAssignableFrom(type))
                    {
                        //Not abstract and doesn't have a parameterless ctor?  Throw an exception
                        if (type.GetConstructor(Type.EmptyTypes) is null)
                        {
                            throw new TypeLoadException($"Machine UI type \"{type.FullName}\" does not have a parameterless constructor.");
                        }

                        //Machine UI type.  Try to link the UI to the machine
                        MachineUI state   = Activator.CreateInstance(type) as MachineUI;
                        ModTile   machine = ModContent.GetModTile(state.TileType);

                        if (machine is null)
                        {
                            throw new TypeLoadException($"Machine UI type \"{type.FullName}\" had an invalid return value for its \"TileType\" getter property.");
                        }

                        //Register the UI
                        string name = machine.GetType().Name;
                        state.MachineName = name;
                        interfaces.Add(name, new UserInterface());
                        states.Add(name, state);
                    }
                }

                // Activate calls Initialize() on the UIState if not initialized, then calls OnActivate and then calls Activate on every child element
                foreach (var state in states.Values)
                {
                    state.Activate();
                }
            }
        }
Пример #13
0
        public static void TryExportLiquids <T>(this T entity, Point16 pumpPos, int indexToExtract) where T : MachineEntity, ILiquidMachine
        {
            if (indexToExtract < 0 || indexToExtract >= entity.LiquidEntries.Length)
            {
                return;
            }

            var entry = entity.LiquidEntries[indexToExtract];

            if (!NetworkCollection.HasFluidPipeAt(pumpPos, out FluidNetwork net) ||
                net.gasType != MachineGasID.None ||
                entry.isInput ||
                (entry.id != MachineLiquidID.None && net.liquidType != MachineLiquidID.None && entry.id != net.liquidType))
            {
                return;
            }

            Tile    tile    = Framing.GetTileSafely(pumpPos);
            ModTile modTile = ModContent.GetModTile(tile.type);

            if (!(modTile is FluidPumpTile pump) || pump.GetConnectedMachine(pumpPos) != entity)
            {
                return;
            }

            float rate = pump.CapacityExtractedPerPump;

            float extracted = Math.Min(rate, entry.current);

            if (net.liquidType == MachineLiquidID.None)
            {
                net.liquidType = entry.id;
            }

            if (net.StoredFluid + extracted > net.Capacity)
            {
                extracted = net.Capacity - net.StoredFluid;
            }

            net.StoredFluid += extracted;
            entry.current   -= extracted;

            if (entry.current <= 0)
            {
                entry.id = MachineLiquidID.None;
            }
        }
Пример #14
0
        public override void Action(CommandCaller caller, string input, string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }
            if (args[0].ToLower() == "channel")
            {
                string result = "";
                for (int i = 0; i < 16; ++i)
                {
                    result = result + ModContainer.device.channels[i].activeCount + " ";
                }
                Main.NewText(result);
                return;
            }
            if (selection == new Point16(-1, -1))
            {
                Main.NewText("You should make a selection first.");
                return;
            }
            int  x = selection.X, y = selection.Y;
            byte value;

            switch (args[0].ToLower()[0])
            {
            case 'p':
                value = (byte)Math.Max(0, Math.Min(127, int.Parse(args[0].Substring(1))));
                DataCore.extField[x, y].pitch = value;
                Main.NewText("pitch changed to " + value);
                break;

            case 'v':
                value = (byte)Math.Max(0, Math.Min(127, int.Parse(args[0].Substring(1))));
                DataCore.extField[x, y].velocity = value;
                Main.NewText("velocity changed to " + value);
                break;

            default:
                return;
            }
            var action = () => ModContent.GetModTile(Main.tile[x, y].type).HitWire(x, y);

            action();
            Scheduler.Schedule(60, action);
        }
Пример #15
0
        public static bool TryFindMachineEntity(Point16 pos, out MachineEntity entity)
        {
            entity = null;

            Tile    tile  = Framing.GetTileSafely(pos);
            ModTile mTile = ModContent.GetModTile(tile.type);

            if (mTile is Machine)
            {
                Point16 origin = pos - tile.TileCoord();

                if (TileEntity.ByPosition.TryGetValue(origin, out TileEntity te) && (entity = te as MachineEntity) != null)
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #16
0
        private void Engage(Point16 pos, int size)
        {
            if (!ByPosition.ContainsKey(pos))
            {
                return;
            }

            var entity = ByPosition[pos] as GearTileEntity;

            if (entity != null)
            {
                if (entity.size == size && !entity.engaged)
                {
                    int   thisSize = Teeth;
                    int   nextSize = entity.Teeth;
                    float ratio    = (thisSize / (float)nextSize);

                    entity.rotationVelocity = rotationVelocity * -1 * ratio;

                    if (entity == this)                     //This is here to prevent the first gear which engages from reversing itself
                    {
                        entity.rotationVelocity *= -1;
                    }

                    float trueAngle = ((Position.ToVector2() * 16 + Vector2.One * 8) - (entity.Position.ToVector2() * 16 + Vector2.One * 8)).ToRotation();

                    entity.rotationOffset = -(ratio * rotationOffset) + ((1 + ratio) * trueAngle) + (float)Math.PI / entity.Teeth;

                    engaged = true;

                    Tile tile = Main.tile[Position.X, Position.Y];
                    (ModContent.GetModTile(tile.type) as GearTile)?.OnEngage(this);

                    entity.RecurseOverGears(entity.Engage);
                }
            }

            engaged = true;
        }
Пример #17
0
        public sealed override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (UIDelay > 0)
            {
                UIDelay--;
            }

            Main.playerInventory = true;

            if (UIEntity != null)
            {
                //Get the machine's center position
                Vector2 middle = TileUtils.TileEntityCenter(UIEntity, TileType);

                (ModContent.GetModTile(TileType) as Machine).GetDefaultParams(out _, out uint width, out uint height, out _);

                //Check if the inventory key was pressed or if the player is too far away from the tile.  If so, close the UI
                bool tooFar = Math.Abs(Main.LocalPlayer.Center.X - middle.X) > width * 8 + Main.LocalPlayer.lastTileRangeX * 16;
                tooFar |= Math.Abs(Main.LocalPlayer.Center.Y - middle.Y) > height * 8 + Main.LocalPlayer.lastTileRangeY * 16;
                if (Main.LocalPlayer.GetModPlayer <TerraSciencePlayer>().InventoryKeyPressed || tooFar)
                {
                    TechMod.Instance.machineLoader.HideUI(MachineName);
                    Main.playerInventory = false;
                    return;
                }

                PreUpdateEntity();

                UpdateEntity();

                UpdateMisc();

                UpdateText(Text);
            }
        }
Пример #18
0
        public unsafe static TagCompound SaveStructure(Rectangle target)
        {
            TagCompound tag = new TagCompound();

            tag.Add("Version", StructureHelper.Instance.Version.ToString());
            tag.Add("Width", target.Width);
            tag.Add("Height", target.Height);

            List <TileSaveData> data = new List <TileSaveData>();

            for (int x = target.X; x <= target.X + target.Width; x++)
            {
                for (int y = target.Y; y <= target.Y + target.Height; y++)
                {
                    Tile   tile = Framing.GetTileSafely(x, y);
                    string tileName;
                    string wallName;
                    string teName;
                    if (tile.TileType >= TileID.Count)
                    {
                        tileName = ModContent.GetModTile(tile.TileType).Mod.Name + " " + ModContent.GetModTile(tile.TileType).Name;
                    }
                    else
                    {
                        tileName = tile.TileType.ToString();
                    }
                    if (tile.WallType >= WallID.Count)
                    {
                        wallName = ModContent.GetModWall(tile.WallType).Mod.Name + " " + ModContent.GetModWall(tile.WallType).Name;
                    }
                    else
                    {
                        wallName = tile.WallType.ToString();
                    }

                    TileEntity  teTarget  = null; //grabbing TE data
                    TagCompound entityTag = new TagCompound();

                    if (TileEntity.ByPosition.ContainsKey(new Point16(x, y)))
                    {
                        teTarget = TileEntity.ByPosition[new Point16(x, y)];
                    }

                    if (teTarget != null)
                    {
                        if (teTarget.type < 2)
                        {
                            teName = teTarget.type.ToString();
                        }
                        else
                        {
                            ModTileEntity entityTarget = teTarget as ModTileEntity;

                            if (entityTarget != null)
                            {
                                teName = entityTarget.Mod.Name + " " + entityTarget.Name;
                                (teTarget as ModTileEntity).SaveData(entityTag);
                            }
                            else
                            {
                                teName = "";
                            }
                        }
                    }
                    else
                    {
                        teName = "";
                    }

                    int   wallWireData;
                    short packedLiquidData;

                    fixed(void *ptr = &tile.Get <TileWallWireStateData>())
                    {
                        var intPtr = (int *)(ptr);

                        intPtr++;

                        wallWireData = *intPtr;
                    }

                    fixed(void *ptr = &tile.Get <LiquidData>())
                    {
                        var shortPtr = (short *)ptr;

                        packedLiquidData = *shortPtr;
                    }

                    data.Add(
                        new TileSaveData(
                            tileName,
                            wallName,
                            tile.TileFrameX,
                            tile.TileFrameY,
                            wallWireData,
                            packedLiquidData,
                            teName,
                            entityTag
                            ));
                }
            }

            tag.Add("TileData", data);
            return(tag);
        }
Пример #19
0
        public override bool ValidTile(int i, int j)
        {
            Tile tile = Main.tile[i, j];

            return(ModContent.GetModTile(tile.type) is GearTile && tile.active());
        }
Пример #20
0
        private bool CheckTileMerge(int i, int j, int dirX, int dirY)
        {
            if (MergeType == JunctionType.None)
            {
                return(false);
            }

            if ((dirX == 0 && dirY == 0) || (dirX != 0 && dirY != 0))
            {
                return(false);
            }

            if (dirX < -1 || dirX > 1 || dirY < -1 || dirY > 1)
            {
                return(false);
            }

            int targetX = i + dirX;
            int targetY = j + dirY;

            if (targetX < 0 || targetX >= Main.maxTilesX || targetY < 0 || targetY >= Main.maxTilesY)
            {
                return(false);
            }

            Tile    target        = Framing.GetTileSafely(targetX, targetY);
            ModTile targetModTile = ModContent.GetModTile(target.type);

            if (!target.active())
            {
                return(false);
            }

            //If this merge type is "Items" and the tile is a chest, merge
            if (MergeType == JunctionType.Items && (TileID.Sets.BasicChest[target.type] || (targetModTile != null && (targetModTile.adjTiles.Contains(TileID.Containers) || targetModTile.adjTiles.Contains(TileID.Containers2)))))
            {
                return(true);
            }

            if (target.type < TileID.Count)
            {
                return(false);
            }

            if (targetModTile is JunctionMergeable merge)
            {
                bool hasSameMerge = merge.MergeType == MergeType;

                //Need to check if the target is a pump and the pump is pointing in the right direction
                if (merge is ItemPumpTile || merge is FluidPumpTile)
                {
                    int frame = target.frameX / 18;
                    return(hasSameMerge && ((dirY == 1 && frame == 0) || (dirX == 1 && frame == 1) || (dirY == -1 && frame == 2) || (dirX == -1 && frame == 3)));
                }
                else
                {
                    return(hasSameMerge);
                }
            }
            else if (targetModTile is TransportJunction)
            {
                int frameX = target.frameX / 18;

                //Junction has the default frame?  Don't let them merge...
                if (frameX == 0)
                {
                    return(false);
                }

                //Invalid frame?  Don't merge
                if (frameX < 0 || frameX > junctionColumns)
                {
                    return(false);
                }

                //dirX == -1 means the junction must have a frame showing this mergetype on its right edge
                //dirX == 1 means the junction must have a frame showing this mergetype on its left edge
                //dirY == -1 means the junction must have a frame showing this mergetype on its bottom edge
                //dirY == 1 means the junction must have a frame showing this mergetype on its top edge

                //See Content/Tiles/TransportJunction.png for reference

                JunctionMerge otherMerge = mergeTypes[frameX];

                int shift = ((int)MergeType - 1) * 4;

                int mask = 0;
                if (dirX == -1)
                {
                    mask |= 0x4;
                }
                else if (dirX == 1)
                {
                    mask |= 0x2;
                }

                if (dirY == -1)
                {
                    mask |= 0x08;
                }
                else if (dirY == 1)
                {
                    mask |= 0x01;
                }

                mask <<= shift;

                return(((int)otherMerge & mask) != 0);
            }
            else if (targetModTile is Machine && TileUtils.tileToEntity.TryGetValue(targetModTile.Type, out MachineEntity entity))
            {
                return((MergeType == JunctionType.Wires && entity is PoweredMachineEntity) ||
                       (MergeType == JunctionType.Items && (entity.GetInputSlots().Length > 0 || entity.GetOutputSlots().Length > 0)) ||
                       (MergeType == JunctionType.Fluids && (entity is ILiquidMachine || entity is IGasMachine)));
            }
            else if (((MergeType == JunctionType.Items && targetModTile is ItemPumpTile) || (MergeType == JunctionType.Fluids && targetModTile is FluidPumpTile)) && ((dirX == -1 && target.frameX / 18 == 3) || (dirX == 1 && target.frameX / 18 == 1) || (dirY == -1 && target.frameX / 18 == 2) || (dirY == 1 && target.frameX / 18 == 0)))
            {
                return(true);
            }


            //Tile wasn't a junction-mergeable tile
            return(false);
        }
Пример #21
0
        public List <(Point16, short)> SavePumpDirs()
        {
            var pumps = GetEntries().Where(e => ModContent.GetModTile(Framing.GetTileSafely(e.Position).type) is FluidPumpTile).ToList();

            return(pumps.Count == 0 ? null : pumps.Select(e => (e.Position, (short)(Framing.GetTileSafely(e.Position).frameX / 18))).ToList());
        }
Пример #22
0
        public FluidNetwork() : base()
        {
            pipesConnectedToMachines = new List <Point16>();
            pumpTimers = new Dictionary <Point16, Timer>();

            OnEntryPlace += pos => {
                Tile tile = Framing.GetTileSafely(pos);

                if (ModContent.GetModTile(tile.type) is FluidPumpTile)
                {
                    Capacity += ModContent.GetInstance <FluidTransportTile>().Capacity;

                    if (!pumpTimers.ContainsKey(pos))
                    {
                        pumpTimers.Add(pos, new Timer()
                        {
                            value = 34
                        });
                    }
                }
                else if (ModContent.GetModTile(tile.type) is FluidTransportTile transport)
                {
                    Capacity += transport.Capacity;
                }

                if (TileEntityUtils.TryFindMachineEntity(pos + new Point16(0, -1), out MachineEntity entity) && (entity is ILiquidMachine || entity is IGasMachine))
                {
                    pipesConnectedToMachines.Add(pos);
                }

                if (TileEntityUtils.TryFindMachineEntity(pos + new Point16(-1, 0), out entity) && (entity is ILiquidMachine || entity is IGasMachine))
                {
                    if (!pipesConnectedToMachines.Contains(pos))
                    {
                        pipesConnectedToMachines.Add(pos);
                    }
                }

                if (TileEntityUtils.TryFindMachineEntity(pos + new Point16(1, 0), out entity) && (entity is ILiquidMachine || entity is IGasMachine))
                {
                    if (!pipesConnectedToMachines.Contains(pos))
                    {
                        pipesConnectedToMachines.Add(pos);
                    }
                }

                if (TileEntityUtils.TryFindMachineEntity(pos + new Point16(0, 1), out entity) && (entity is ILiquidMachine || entity is IGasMachine))
                {
                    if (!pipesConnectedToMachines.Contains(pos))
                    {
                        pipesConnectedToMachines.Add(pos);
                    }
                }
            };

            OnEntryKill += pos => {
                Tile  tile = Framing.GetTileSafely(pos);
                float cap  = 0;
                if (ModContent.GetModTile(tile.type) is FluidPumpTile)
                {
                    cap = ModContent.GetInstance <FluidTransportTile>().Capacity;

                    pumpTimers.Remove(pos);
                }
                else if (ModContent.GetModTile(tile.type) is FluidTransportTile transport)
                {
                    cap += transport.Capacity;
                }

                Capacity    -= cap;
                StoredFluid -= cap;

                pipesConnectedToMachines.Remove(pos);
            };

            PostRefreshConnections += () => {
                if (StoredFluid > Capacity)
                {
                    StoredFluid = Capacity;
                }
            };
        }
Пример #23
0
        public void SaveStructure(Rectangle target)
        {
            TagCompound tag = new TagCompound();

            tag.Add("Width", Width);
            tag.Add("Height", Height);

            List <TileSaveData> data = new List <TileSaveData>();

            for (int x = target.X; x <= target.X + target.Width; x++)
            {
                for (int y = target.Y; y <= target.Y + target.Height; y++)
                {
                    Tile   tile = Framing.GetTileSafely(x, y);
                    string tileName;
                    string wallName;
                    string teName;
                    if (tile.type >= TileID.Count)
                    {
                        tileName = ModContent.GetModTile(tile.type).mod.Name + " " + ModContent.GetModTile(tile.type).Name;
                    }
                    else
                    {
                        tileName = tile.type.ToString();
                    }
                    if (tile.wall >= WallID.Count)
                    {
                        wallName = ModContent.GetModWall(tile.wall).mod.Name + " " + ModContent.GetModWall(tile.wall).Name;
                    }
                    else
                    {
                        wallName = tile.wall.ToString();
                    }

                    TileEntity  teTarget  = null; //grabbing TE data
                    TagCompound entityTag = null;

                    if (TileEntity.ByPosition.ContainsKey(new Point16(x, y)))
                    {
                        teTarget = TileEntity.ByPosition[new Point16(x, y)];
                    }

                    if (teTarget != null)
                    {
                        if (teTarget.type < 2)
                        {
                            teName = teTarget.type.ToString();
                        }
                        else
                        {
                            ModTileEntity entityTarget = ModTileEntity.GetTileEntity(teTarget.type);
                            if (entityTarget != null)
                            {
                                teName    = entityTarget.mod.Name + " " + entityTarget.Name;
                                entityTag = (teTarget as ModTileEntity).Save();
                            }
                            else
                            {
                                teName = "";
                            }
                        }
                    }
                    else
                    {
                        teName = "";
                    }

                    byte[] wireArray = new byte[]
                    {
                        (byte)tile.wire().ToInt(),
                        (byte)tile.wire2().ToInt(),
                        (byte)tile.wire3().ToInt(),
                        (byte)tile.wire4().ToInt()
                    };
                    data.Add(new TileSaveData(tile.active(), tileName, wallName, tile.frameX, tile.frameY, (short)tile.wallFrameX(), (short)tile.wallFrameY(),
                                              tile.slope(), tile.halfBrick(), tile.actuator(), !tile.nactive(), tile.liquid, tile.liquidType(), tile.color(), tile.wallColor(), wireArray,
                                              teName, entityTag));
                }
            }
            tag.Add("TileData", data);

            StructureCache.Add(tag);
            Main.NewText("Structure added. Total structure count: " + StructureCache.Count, Color.Cyan);

            TopLeft     = default;
            SecondPoint = false;
            Width       = 0;
            Height      = 0;
        }
        ////////////////

        private void InitializeComponents()
        {
            var mymod = ModHelpersMod.Instance;
            UIModControlPanelTab self  = this;
            ModControlPanelLogic logic = this.Logic;
            float top = 0;

            this.Theme.ApplyPanel(this);


            ////////

            var tip = new UIText("To enable issue reports for your mod, ");

            this.Append((UIElement)tip);

            this.TipUrl = new UIWebUrl(this.Theme, "read this.",
                                       "https://forums.terraria.org/index.php?threads/mod-helpers.63670/#modders",
                                       false, 1f);
            this.TipUrl.Left.Set(tip.GetInnerDimensions().Width, 0f);
            this.TipUrl.Top.Set(-2f, 0f);
            this.Append((UIElement)this.TipUrl);

            this.OpenConfigList = new UITextPanelButton(this.Theme, "Edit Configs");
            this.OpenConfigList.Top.Set(top - 8f, 0f);
            this.OpenConfigList.Left.Set(-188f, 1f);
            this.OpenConfigList.Width.Set(160f, 0f);
            this.OpenConfigList.OnClick += (_, __) => {
                MainMenuHelpers.OpenModConfigListUI();
            };
            this.Append(this.OpenConfigList);

            top += 24f;

            ////

            var modListPanel = new UIPanel();

            {
                modListPanel.Top.Set(top, 0f);
                modListPanel.Width.Set(0f, 1f);
                modListPanel.Height.Set(UIModControlPanelTab.ModListHeight, 0f);
                modListPanel.HAlign = 0f;
                modListPanel.SetPadding(4f);
                modListPanel.PaddingTop      = 0.0f;
                modListPanel.BackgroundColor = this.Theme.ListBgColor;
                modListPanel.BorderColor     = this.Theme.ListEdgeColor;
                this.Append((UIElement)modListPanel);

                this.ModListElem = new UIList();
                {
                    this.ModListElem.Width.Set(-25, 1f);
                    this.ModListElem.Height.Set(0f, 1f);
                    this.ModListElem.HAlign      = 0f;
                    this.ModListElem.ListPadding = 4f;
                    this.ModListElem.SetPadding(0f);
                    modListPanel.Append((UIElement)this.ModListElem);

                    top += UIModControlPanelTab.ModListHeight + this.PaddingTop - 8;

                    UIScrollbar scrollbar = new UIScrollbar();
                    {
                        scrollbar.Top.Set(8f, 0f);
                        scrollbar.Height.Set(-16f, 1f);
                        scrollbar.SetView(100f, 1000f);
                        scrollbar.HAlign = 1f;
                        modListPanel.Append((UIElement)scrollbar);
                        this.ModListElem.SetScrollbar(scrollbar);
                    }
                }
            }

            ////

            this.IssueTitleInput = new UITextInputAreaPanel(this.Theme, "Enter title of mod issue", 128);
            this.IssueTitleInput.Top.Set(top, 0f);
            this.IssueTitleInput.Width.Set(0f, 1f);
            this.IssueTitleInput.Height.Pixels = 36f;
            this.IssueTitleInput.HAlign        = 0f;
            this.IssueTitleInput.SetPadding(8f);
            this.IssueTitleInput.Disable();
            this.IssueTitleInput.OnPreTextChange += (_) => {
                self.RefreshIssueSubmitButton();
                return(true);
            };
            this.Append((UIElement)this.IssueTitleInput);

            top += 36f;

            this.IssueBodyInput = new UITextInputAreaPanel(this.Theme, "Describe mod issue");
            this.IssueBodyInput.Top.Set(top, 0f);
            this.IssueBodyInput.Width.Set(0f, 1f);
            this.IssueBodyInput.Height.Pixels = 36f;
            this.IssueBodyInput.HAlign        = 0f;
            this.IssueBodyInput.SetPadding(8f);
            this.IssueBodyInput.Disable();
            this.IssueBodyInput.OnPreTextChange += (_) => {
                self.RefreshIssueSubmitButton();
                return(true);
            };
            this.Append((UIElement)this.IssueBodyInput);

            top += 36f;

            ////

            this.IssueSubmitButton = new UITextPanelButton(this.Theme, "Submit Issue");
            this.IssueSubmitButton.Top.Set(top, 0f);
            this.IssueSubmitButton.Left.Set(0f, 0f);
            this.IssueSubmitButton.Width.Set(200f, 0f);
            this.IssueSubmitButton.Disable();
            this.IssueSubmitButton.OnClick += (_, __) => {
                if (self.AwaitingReport || !self.IssueSubmitButton.IsEnabled)
                {
                    return;
                }
                self.SubmitIssue();
            };
            this.Append(this.IssueSubmitButton);

            top += 26f;

            this.ModLockButton = new UITextPanelButton(this.Theme, UIModControlPanelTab.ModLockTitle);
            this.ModLockButton.Top.Set(top, 0f);
            this.ModLockButton.Left.Set(0f, 0f);
            this.ModLockButton.Width.Set(0f, 1f);
            if (Main.netMode != 0 || !ModHelpersMod.Config.WorldModLockEnable)
            {
                this.ModLockButton.Disable();
            }
            this.ModLockButton.OnClick += (_, __) => {
                if (!self.ModLockButton.IsEnabled)
                {
                    return;
                }
                self.ToggleModLock();
                Main.PlaySound(SoundID.Unlock);
            };
            this.Append(this.ModLockButton);

            this.RefreshModLockButton();

            top += 26f;

            this.CleanupModTiles = new UITextPanelButton(this.Theme, "Cleanup unused mod tiles");
            this.CleanupModTiles.Top.Set(top, 0f);
            this.CleanupModTiles.Left.Set(0f, 0f);
            this.CleanupModTiles.Width.Set(0f, 1f);
            if (Main.netMode != 0)
            {
                this.CleanupModTiles.Disable();
            }
            this.CleanupModTiles.OnClick += (_, __) => {
                if (!self.CleanupModTiles.IsEnabled)
                {
                    return;
                }

                int cleaned = 0;

                for (int i = 0; i < Main.maxTilesX; i++)
                {
                    for (int j = 0; j < Main.maxTilesY; j++)
                    {
                        Tile tile = Framing.GetTileSafely(i, j);
                        if (TileHelpers.IsAir(tile))
                        {
                            continue;
                        }
                        ModTile modTile = ModContent.GetModTile(tile.type);
                        if (modTile == null)
                        {
                            continue;
                        }

                        if (modTile.mod == null || modTile is MysteryTile)
                        {
                            TileHelpers.KillTile(i, j, false, false);
                            cleaned++;
                        }
                    }
                }

                Main.NewText(cleaned + " modded tiles cleaned up.", Color.Lime);
            };
            this.Append(this.CleanupModTiles);

            top += 32f;

            ////

            /*var modrec_url = new UIWebUrl( this.Theme, "Need mods?", "https://sites.google.com/site/terrariamodsuggestions/" );
             * modrecUrl.Top.Set( top, 0f );
             * modrecUrl.Left.Set( 0f, 0f );
             * this.InnerContainer.Append( modrecUrl );
             *
             * var serverbrowser_url = new UIWebUrl( this.Theme, "Lonely?", "https://forums.terraria.org/index.php?threads/server-browser-early-beta.68346/" );
             * serverbrowser_url.Top.Set( top, 0f );
             * this.InnerContainer.Append( serverbrowser_url );
             * serverbrowser_url.Left.Set( -serverbrowser_url.GetDimensions().Width * 0.5f, 0.5f );*/

            string supportMsg = UIModControlPanelTab.SupportMessages[this.RandomSupportTextIdx];

            this.SupportUrl = new UIWebUrl(this.Theme, supportMsg, "https://www.patreon.com/hamstar0", false);
            this.SupportUrl.Top.Set(top, 0f);
            this.Append(this.SupportUrl);
            //this.SupportUrl.Left.Set( -this.SupportUrl.GetDimensions().Width, 1f );
            this.SupportUrl.Left.Set(-this.SupportUrl.GetDimensions().Width * 0.5f, 0.5f);
        }
Пример #25
0
        public void SaveStructure(Rectangle target, string targetPath = null)
        {
            string path = ModLoader.ModPath.Replace("Mods", "SavedStructures");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string thisPath = targetPath ?? Path.Combine(path, "SavedStructure_" + DateTime.Now.ToString("d-M-y----H-m-s-f"));

            Main.NewText("Structure saved as " + thisPath, Color.Yellow);
            FileStream stream = File.Create(thisPath);

            stream.Close();

            TagCompound tag = new TagCompound();

            tag.Add("Width", Width);
            tag.Add("Height", Height);

            List <TileSaveData> data = new List <TileSaveData>();

            for (int x = target.X; x <= target.X + target.Width; x++)
            {
                for (int y = target.Y; y <= target.Y + target.Height; y++)
                {
                    Tile   tile = Framing.GetTileSafely(x, y);
                    string tileName;
                    string wallName;
                    string teName;
                    if (tile.type >= TileID.Count)
                    {
                        tileName = ModContent.GetModTile(tile.type).mod.Name + " " + ModContent.GetModTile(tile.type).Name;
                    }
                    else
                    {
                        tileName = tile.type.ToString();
                    }
                    if (tile.wall >= WallID.Count)
                    {
                        wallName = ModContent.GetModWall(tile.wall).mod.Name + " " + ModContent.GetModWall(tile.wall).Name;
                    }
                    else
                    {
                        wallName = tile.wall.ToString();
                    }

                    TileEntity  teTarget  = null; //grabbing TE data
                    TagCompound entityTag = null;

                    if (TileEntity.ByPosition.ContainsKey(new Point16(x, y)))
                    {
                        teTarget = TileEntity.ByPosition[new Point16(x, y)];
                    }

                    if (teTarget != null)
                    {
                        if (teTarget.type < 2)
                        {
                            teName = teTarget.type.ToString();
                        }
                        else
                        {
                            ModTileEntity entityTarget = ModTileEntity.GetTileEntity(teTarget.type);
                            if (entityTarget != null)
                            {
                                teName    = entityTarget.mod.Name + " " + entityTarget.Name;
                                entityTag = (teTarget as ModTileEntity).Save();
                            }
                            else
                            {
                                teName = "";
                            }
                        }
                    }
                    else
                    {
                        teName = "";
                    }

                    byte[] wireArray = new byte[]
                    {
                        (byte)tile.wire().ToInt(),
                        (byte)tile.wire2().ToInt(),
                        (byte)tile.wire3().ToInt(),
                        (byte)tile.wire4().ToInt()
                    };
                    data.Add(new TileSaveData(tile.active(), tileName, wallName, tile.frameX, tile.frameY, (short)tile.wallFrameX(), (short)tile.wallFrameY(),
                                              tile.slope(), tile.halfBrick(), tile.actuator(), !tile.nactive(), tile.liquid, tile.liquidType(), tile.color(), tile.wallColor(), wireArray,
                                              teName, entityTag));
                }
            }
            tag.Add("TileData", data);

            TagIO.ToFile(tag, thisPath);
        }
Пример #26
0
        public WireNetwork() : base()
        {
            OnClear += () => {
                Capacity          = new TerraFlux(0f);
                totalExportedFlux = new TerraFlux(0f);
                needsRateRefresh  = true;
            };
            OnEntryPlace += pos => {
                Tile tile  = Framing.GetTileSafely(pos.X, pos.Y);
                var  mTile = ModContent.GetModTile(tile.type);

                TerraFlux cap = new TerraFlux(0f);

                if (mTile is TFWireTile wire)
                {
                    cap = wire.Capacity;
                }
                else if (mTile is TransportJunction junction)
                {
                    cap = ModContent.GetInstance <TFWireTile>().Capacity;
                }
                else
                {
                    return;
                }

                Capacity += cap;

                needsRateRefresh = true;
            };
            OnEntryKill += pos => {
                Tile      tile  = Framing.GetTileSafely(pos.X, pos.Y);
                var       mTile = ModContent.GetModTile(tile.type);
                TerraFlux cap   = new TerraFlux(0f);
                if (mTile is TFWireTile wire)
                {
                    cap = wire.Capacity;
                }
                else if (mTile is TransportJunction junction)
                {
                    cap = ModContent.GetInstance <TFWireTile>().Capacity;
                }
                else
                {
                    return;
                }

                Capacity   -= cap;
                StoredFlux -= cap;

                if ((float)StoredFlux < 0)
                {
                    StoredFlux = new TerraFlux(0f);
                }

                needsRateRefresh = true;
            };
            PostRefreshConnections += () => {
                if (StoredFlux > Capacity)
                {
                    StoredFlux = Capacity;
                }
            };
        }
Пример #27
0
        private static List <Entry> GetItemWalkableEntires(ItemNetwork net, List <Entry> existing, Entry parent, Point16 target)
        {
            List <Entry> possible = new List <Entry>()
            {
                new Entry()
                {
                    location = parent.location + new Point16(0, -1), parent = parent
                },
                new Entry()
                {
                    location = parent.location + new Point16(-1, 0), parent = parent
                },
                new Entry()
                {
                    location = parent.location + new Point16(1, 0), parent = parent
                },
                new Entry()
                {
                    location = parent.location + new Point16(0, 1), parent = parent
                }
            };

            Tile parentTile = Framing.GetTileSafely(parent.location);

            if (ModContent.GetModTile(parentTile.type) is ItemPumpTile)
            {
                int frameX = parentTile.frameX / 18;
                switch (frameX)
                {
                case 0:
                    possible.RemoveAt(3);
                    break;

                case 1:
                    possible.RemoveAt(2);
                    break;

                case 2:
                    possible.RemoveAt(0);
                    break;

                case 3:
                    possible.RemoveAt(1);
                    break;

                default:
                    throw new Exception($"Inner TerraScience error -- Unexpected pump tile frame (ID: {frameX})");
                }
            }

            for (int i = 0; i < possible.Count; i++)
            {
                var possibleLoc = possible[i].location;
                if ((!net.HasEntryAt(possibleLoc) && !net.HasMachineAt(possibleLoc) && !net.HasChestAt(possibleLoc)) || ModContent.GetModTile(Framing.GetTileSafely(possibleLoc).type) is ItemPumpTile || existing.Any(e => e.location == possibleLoc))
                {
                    possible.RemoveAt(i);
                    i--;
                }
                else
                {
                    possible[i].travelTime = parent.travelTime + GetItemTravelTime(possibleLoc);
                    possible[i].SetDistance(target);
                }
            }

            return(possible);
        }
Пример #28
0
        /// <summary>
        /// Attempts to move the item in this object along the <seealso cref="itemNetwork"/>
        /// </summary>
        public void Update()
        {
            oldCenter = worldCenter;

            var newTilePos = worldCenter.ToTileCoordinates16();

            if (delayPathCalc && itemNetwork.HasEntryAt(newTilePos))
            {
                delayPathCalc = false;
            }

            CalculatePath();

            MoveAlongNetwork();

            newTilePos = worldCenter.ToTileCoordinates16();
            Tile sourceTile = Framing.GetTileSafely(newTilePos);

            if (ModContent.GetModTile(sourceTile.type) is ItemPumpTile pump)
            {
                //Force the move direction to be away from the pump
                moveDir = -(pump.GetBackwardsOffset(newTilePos) - newTilePos).ToVector2();
            }

            if (!delayPathCalc && (!sourceTile.active() || !itemNetwork.HasEntryAt(newTilePos)))
            {
                Item data = ItemIO.Load(itemData);

                //If the tile is a machine or chest, try to put this item in there
                Chest         chest    = null;
                MachineEntity entity   = null;
                bool          sendBack = true;

                if ((entity = FindConnectedMachine(itemNetwork, newTilePos, data)) != null || (chest = FindConnectedChest(itemNetwork, newTilePos, data, out _)) != null)
                {
                    if (chest is Chest)
                    {
                        sendBack = !chest.TryInsertItems(data);

                        if (sendBack)
                        {
                            itemData = ItemIO.Save(data);
                        }
                    }
                    else
                    {
                        entity.InputItemFromNetwork(this, out sendBack);
                    }

                    if (!sendBack)
                    {
                        itemNetwork.RemovePath(this.id);
                    }
                    else
                    {
                        //Send the item back into the network and force it to create a new path
                        needsPathRefresh = true;
                        moveDir         *= -1;
                        delayPathCalc    = true;
                    }
                }
                else
                {
                    if (FindConnectedChest(itemNetwork, newTilePos, data, out _) is null && !(TileEntityUtils.TryFindMachineEntity(newTilePos + new Point16(0, -1), out _) || TileEntityUtils.TryFindMachineEntity(newTilePos + new Point16(-1, 0), out _) || TileEntityUtils.TryFindMachineEntity(newTilePos + new Point16(0, 1), out _) || TileEntityUtils.TryFindMachineEntity(newTilePos + new Point16(1, 0), out _)))
                    {
                        SpawnInWorld();
                    }
                    else
                    {
                        wander           = true;
                        moveDir         *= -1;
                        delayPathCalc    = true;
                        needsPathRefresh = true;

                        worldCenter = itemNetwork.GetEntries().Select(pipe => pipe.Position).OrderBy(p => Vector2.DistanceSquared(p.ToWorldCoordinates(), worldCenter)).First().ToWorldCoordinates();
                    }
                }