Beispiel #1
0
        protected override IMetadataFile InitMetadata()
        {
            WorldMetadata metadata = new WorldMetadata();

            this.PluginTrace.WriteLineInfo("Starting one time metadata initialization...");
            for (int x = 0; x < Main.maxTilesX - 1; x++)
            {
                for (int y = 0; y < Main.maxTilesY - 1; y++)
                {
                    if (!TerrariaUtils.Tiles[x, y].active())
                    {
                        continue;
                    }

                    DPoint tileLocation = new DPoint(x, y);
                    switch (TerrariaUtils.Tiles[x, y].type)
                    {
                    case TileID.Timers: {
                        // Is active timer?
                        if (TerrariaUtils.Tiles[x, y].frameY > 0)
                        {
                            if (!metadata.ActiveTimers.ContainsKey(tileLocation))
                            {
                                metadata.ActiveTimers.Add(tileLocation, new ActiveTimerMetadata());
                            }
                        }

                        break;
                    }

                    case TileID.GrandfatherClocks: {
                        ObjectMeasureData measureData = TerrariaUtils.Tiles.MeasureObject(tileLocation);

                        if (!metadata.Clocks.ContainsKey(measureData.OriginTileLocation))
                        {
                            metadata.Clocks.Add(measureData.OriginTileLocation, new GrandfatherClockMetadata(null));
                        }

                        break;
                    }

                    case AdvancedCircuits.BlockType_WirelessTransmitter: {
                        foreach (DPoint portLocation in AdvancedCircuits.EnumerateComponentPortLocations(tileLocation, new DPoint(1, 1)))
                        {
                            if (TerrariaUtils.Tiles[portLocation].HasWire() && !metadata.WirelessTransmitters.ContainsKey(tileLocation))
                            {
                                metadata.WirelessTransmitters.Add(tileLocation, "{Server}");
                            }
                        }

                        break;
                    }
                    }
                }
            }
            this.PluginTrace.WriteLineInfo("Metadata initialization complete.");

            return(metadata);
        }
 public BranchProcessData(DPoint branchingTileLocation, DPoint firstWireLocation, SignalType signal) : this()
 {
     this.BranchingTileLocation = branchingTileLocation;
     this.FirstWireLocation     = firstWireLocation;
     this.LastWireLocation      = DPoint.Empty;
     this.Signal    = signal;
     this.Direction = AdvancedCircuits.DirectionFromTileLocations(branchingTileLocation, firstWireLocation);
 }
Beispiel #3
0
        public void ResetTimer(ObjectMeasureData measureData)
        {
            ActiveTimerMetadata activeTimer;

            if (this.WorldMetadata.ActiveTimers.TryGetValue(measureData.OriginTileLocation, out activeTimer))
            {
                activeTimer.FramesLeft = AdvancedCircuits.MeasureTimerFrameTime(measureData.OriginTileLocation);
            }
        }
Beispiel #4
0
        public static SignalType BoolToSignal(bool?signal)
        {
            if (signal == null)
            {
                return(SignalType.Swap);
            }

            return(AdvancedCircuits.BoolToSignal(signal.Value));
        }
Beispiel #5
0
        public static bool IsComponentWiredByPort(DPoint componentOriginLocation, DPoint componentSize)
        {
            foreach (DPoint portLocation in AdvancedCircuits.EnumerateComponentPortLocations(componentOriginLocation, componentSize))
            {
                if (TerrariaUtils.Tiles[portLocation].HasWire())
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #6
0
        public static IEnumerable <DPoint> EnumerateComponentPortLocations(ObjectMeasureData measureData)
        {
            DPoint componentOriginLocation = measureData.OriginTileLocation;
            DPoint componentSize           = measureData.Size;

            if (measureData.BlockType == TileID.OpenDoor)
            {
                componentSize = new DPoint(1, 3);
            }

            return(AdvancedCircuits.EnumerateComponentPortLocations(componentOriginLocation, componentSize));
        }
Beispiel #7
0
 public RootBranchProcessData(DPoint senderLocation, DPoint firstWireLocation, SignalType signal, WireColor wireColor)
 {
     this.SenderLocation                        = senderLocation;
     this.FirstWireLocation                     = firstWireLocation;
     this.LastWireLocation                      = firstWireLocation;
     this.WireColor                             = wireColor;
     this.Direction                             = AdvancedCircuits.DirectionFromTileLocations(senderLocation, firstWireLocation);
     this.Signal                                = signal;
     this.SignaledComponentLocations            = new List <DPoint>();
     this.BlockActivator                        = null;
     this.BlockActivatorLocation                = DPoint.Empty;
     this.BlockActivatorDeactivatedBlockCounter = 0;
     this.BlockActivatorMode                    = BlockActivatorMode.Default;
 }
        public bool HandleDoorUse(
            TSPlayer player, DPoint tileLocation, bool isOpening, NPC npc = null, Direction direction = Direction.Unknown
            )
        {
            try {
                this.ProcessCircuit(player, tileLocation, AdvancedCircuits.BoolToSignal(isOpening), false);
            } catch (Exception ex) {
                this.PluginTrace.WriteLineError(
                    "DoorUse for \"{0}\" at {1} failed. See inner exception for details.\n{2}",
                    TerrariaUtils.Tiles.GetBlockTypeName((BlockType)TerrariaUtils.Tiles[tileLocation].type), tileLocation, ex.ToString()
                    );
            }

            return(false);
        }
Beispiel #9
0
        public void RegisterUnregisterTimer(TSPlayer triggeringPlayer, ObjectMeasureData measureData, bool register)
        {
            bool alreadyRegistered = this.WorldMetadata.ActiveTimers.ContainsKey(measureData.OriginTileLocation);

            if (register)
            {
                if (!alreadyRegistered)
                {
                    this.WorldMetadata.ActiveTimers.Add(
                        measureData.OriginTileLocation, new ActiveTimerMetadata(AdvancedCircuits.MeasureTimerFrameTime(measureData.OriginTileLocation), triggeringPlayer.Name)
                        );
                }
            }
            else if (alreadyRegistered)
            {
                this.WorldMetadata.ActiveTimers.Remove(measureData.OriginTileLocation);
            }
        }
        private bool TryExecuteSubCommand(string commandNameLC, CommandArgs args)
        {
            switch (commandNameLC)
            {
            case "commands":
            case "cmds":
                args.Player.SendMessage("Available Sub-Commands:", Color.White);
                args.Player.SendMessage("/ac blocks", Color.Yellow);
                args.Player.SendMessage("/ac toggle|switch", Color.Yellow);

                if (args.Player.Group.HasPermission(AdvancedCircuitsPlugin.ReloadCfg_Permission))
                {
                    args.Player.SendMessage("/ac reloadcfg", Color.Yellow);
                }

                return(true);

            case "reloadcfg":
                if (args.Player.Group.HasPermission(AdvancedCircuitsPlugin.ReloadCfg_Permission))
                {
                    this.PluginTrace.WriteLineInfo("Reloading configuration file.");
                    try {
                        this.ReloadConfigurationCallback();
                        this.PluginTrace.WriteLineInfo("Configuration file successfully reloaded.");

                        if (args.Player != TSPlayer.Server)
                        {
                            args.Player.SendMessage("Configuration file successfully reloaded.", Color.Yellow);
                        }
                    } catch (Exception ex) {
                        this.PluginTrace.WriteLineError(
                            "Reloading the configuration file failed. Keeping old configuration. Exception details:\n{0}", ex
                            );
                    }
                }
                else
                {
                    args.Player.SendErrorMessage("You do not have the necessary permission to do that.");
                }

                return(true);

            case "blocks":
            case "ores":
            case "tiles":
                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return(true);
                }

                PaginationTools.SendPage(
                    args.Player, pageNumber,
                    new List <string>()
                {
                    "Copper Ore - OR-Gate",
                    "Silver Ore - AND-Gate",
                    "Gold Ore - XOR-Gate / XOR-Port",
                    "Obsidian - NOT-Gate / NOT-Port",
                    "Iron Ore - Swapper",
                    "Spike - Crossover Bridge",
                    "Glass - Input Port",
                    "Active Stone - Active Stone and Block Activator",
                    "Adamantite Ore - Wireless Transmitter"
                },
                    new PaginationTools.Settings {
                    HeaderFormat    = "Advanced Circuits Special Blocks (Page {0} of {1})",
                    HeaderTextColor = Color.Lime,
                    LineTextColor   = Color.LightGray,
                    MaxLinesPerPage = 4,
                }
                    );

                return(true);

            case "toggle":
            case "switch":
                args.Player.SendInfoMessage("Place or destroy a wire on the component you want to toggle.");

                if (args.Parameters.Count > 3)
                {
                    args.Player.SendErrorMessage("Proper syntax: /ac switch [state] [+p]");
                    args.Player.SendInfoMessage("Type /ac switch help to get more help to this command.");
                    return(true);
                }

                bool persistentMode = false;
                bool?newState       = null;
                if (args.Parameters.Count > 1)
                {
                    int newStateRaw;
                    if (int.TryParse(args.Parameters[1], out newStateRaw))
                    {
                        newState = (newStateRaw == 1);
                    }

                    persistentMode = args.ContainsParameter("+p", StringComparison.InvariantCultureIgnoreCase);
                }

                CommandInteraction interaction = this.StartOrResetCommandInteraction(args.Player);
                interaction.DoesNeverComplete = persistentMode;
                interaction.TileEditCallback  = (player, editType, blockType, location, blockStyle) => {
                    if (
                        editType != TileEditType.PlaceTile ||
                        editType != TileEditType.PlaceWall ||
                        editType != TileEditType.DestroyWall ||
                        editType != TileEditType.PlaceActuator
                        )
                    {
                        CommandInteractionResult result = new CommandInteractionResult {
                            IsHandled = true, IsInteractionCompleted = true
                        };
                        ITile tile = TerrariaUtils.Tiles[location];

                        if (
                            !args.Player.HasBuildPermission(location.X, location.Y) || (
                                this.PluginCooperationHandler.IsProtectorAvailable &&
                                this.PluginCooperationHandler.Protector_CheckProtected(args.Player, location, false)
                                ))
                        {
                            player.SendErrorMessage("This object is protected.");
                            player.SendTileSquare(location, 1);
                            return(result);
                        }

                        int hitBlockType = tile.type;
                        if (tile.active() && hitBlockType == TileID.ActiveStoneBlock)
                        {
                            if (newState == null || newState == false)
                            {
                                TerrariaUtils.Tiles.SetBlock(location, TileID.InactiveStoneBlock);
                            }
                            else
                            {
                                args.Player.SendTileSquare(location);
                            }
                        }
                        else if (hitBlockType == TileID.InactiveStoneBlock)
                        {
                            if (tile.active() && newState == null || newState == true)
                            {
                                TerrariaUtils.Tiles.SetBlock(location, TileID.ActiveStoneBlock);
                            }
                            else
                            {
                                args.Player.SendTileSquare(location);
                            }
                        }
                        else if (tile.active() && TerrariaUtils.Tiles.IsMultistateObject(hitBlockType))
                        {
                            ObjectMeasureData measureData = TerrariaUtils.Tiles.MeasureObject(location);
                            bool currentState             = TerrariaUtils.Tiles.ObjectHasActiveState(measureData);
                            if (newState == null)
                            {
                                newState = !TerrariaUtils.Tiles.ObjectHasActiveState(measureData);
                            }

                            if (currentState != newState.Value)
                            {
                                TerrariaUtils.Tiles.SetObjectState(measureData, newState.Value);
                            }
                            else
                            {
                                args.Player.SendTileSquare(location);
                            }
                        }
                        else if (
                            hitBlockType == AdvancedCircuits.BlockType_ORGate ||
                            hitBlockType == AdvancedCircuits.BlockType_ANDGate ||
                            hitBlockType == AdvancedCircuits.BlockType_XORGate
                            )
                        {
                            if (
                                !args.Player.HasBuildPermission(location.X, location.Y) || (
                                    this.PluginCooperationHandler.IsProtectorAvailable &&
                                    this.PluginCooperationHandler.Protector_CheckProtected(args.Player, location, false)
                                    ))
                            {
                                player.SendErrorMessage("This gate is protected.");
                                player.SendTileSquare(location);
                                return(result);
                            }

                            PaintColor paint = (PaintColor)TerrariaUtils.Tiles[location].color();
                            if (paint == AdvancedCircuits.Paint_Gate_TemporaryState)
                            {
                                player.SendErrorMessage("The gate is painted {0}, there's no point in initializing it.", AdvancedCircuits.Paint_Gate_TemporaryState);
                                args.Player.SendTileSquare(location);
                                return(result);
                            }

                            GateStateMetadata gateState;
                            if (!this.WorldMetadata.GateStates.TryGetValue(location, out gateState))
                            {
                                gateState = new GateStateMetadata();
                                this.WorldMetadata.GateStates.Add(location, gateState);
                            }

                            List <DPoint> gatePortLocations = new List <DPoint>(AdvancedCircuits.EnumerateComponentPortLocations(location, new DPoint(1, 1)));
                            for (int i = 0; i < 4; i++)
                            {
                                ITile gatePort = TerrariaUtils.Tiles[gatePortLocations[i]];
                                if (!gatePort.active() || gatePort.type != (int)AdvancedCircuits.BlockType_InputPort)
                                {
                                    continue;
                                }

                                if (newState == null)
                                {
                                    if (gateState.PortStates[i] == null)
                                    {
                                        gateState.PortStates[i] = true;
                                    }
                                    else
                                    {
                                        gateState.PortStates[i] = !gateState.PortStates[i];
                                    }
                                }
                                else
                                {
                                    gateState.PortStates[i] = newState.Value;
                                }
                            }

                            player.SendSuccessMessage("The states of this gate's ports are now:");
                            this.SendGatePortStatesInfo(args.Player, gateState);
                            args.Player.SendTileSquare(location);
                        }
                        else if (tile.active() && tile.type == (int)AdvancedCircuits.BlockType_InputPort)
                        {
                            foreach (DPoint adjacentTileLocation in AdvancedCircuits.EnumerateComponentPortLocations(location, new DPoint(1, 1)))
                            {
                                ITile adjacentTile = TerrariaUtils.Tiles[adjacentTileLocation];
                                if (!adjacentTile.active() || !AdvancedCircuits.IsLogicalGate(adjacentTile.type))
                                {
                                    continue;
                                }

                                if (
                                    !args.Player.HasBuildPermission(adjacentTileLocation.X, adjacentTileLocation.Y) || (
                                        this.PluginCooperationHandler.IsProtectorAvailable &&
                                        this.PluginCooperationHandler.Protector_CheckProtected(args.Player, adjacentTileLocation, false)
                                        ))
                                {
                                    player.SendErrorMessage("This gate is protected.");
                                    player.SendTileSquare(location);
                                    return(result);
                                }

                                PaintColor paint = (PaintColor)TerrariaUtils.Tiles[location].color();
                                if (paint == AdvancedCircuits.Paint_Gate_TemporaryState)
                                {
                                    player.SendErrorMessage("The gate is painted {0}, there's no point in initializing it.", AdvancedCircuits.Paint_Gate_TemporaryState);
                                    args.Player.SendTileSquare(location);
                                    return(result);
                                }

                                GateStateMetadata gateState;
                                if (!this.WorldMetadata.GateStates.TryGetValue(adjacentTileLocation, out gateState))
                                {
                                    gateState = new GateStateMetadata();
                                    this.WorldMetadata.GateStates.Add(adjacentTileLocation, gateState);
                                }

                                int portIndex;
                                switch (AdvancedCircuits.DirectionFromTileLocations(adjacentTileLocation, location))
                                {
                                case Direction.Up:
                                    portIndex = 0;
                                    break;

                                case Direction.Down:
                                    portIndex = 1;
                                    break;

                                case Direction.Left:
                                    portIndex = 2;
                                    break;

                                case Direction.Right:
                                    portIndex = 3;
                                    break;

                                default:
                                    return(result);
                                }

                                if (newState == null)
                                {
                                    if (gateState.PortStates[portIndex] == null)
                                    {
                                        gateState.PortStates[portIndex] = true;
                                    }
                                    else
                                    {
                                        gateState.PortStates[portIndex] = !gateState.PortStates[portIndex];
                                    }
                                }
                                else
                                {
                                    gateState.PortStates[portIndex] = newState.Value;
                                }

                                player.SendSuccessMessage("The states of this gate's ports are now:");
                                this.SendGatePortStatesInfo(args.Player, gateState);
                                args.Player.SendTileSquare(location);
                                return(result);
                            }

                            player.SendErrorMessage($"The state of \"{TerrariaUtils.Tiles.GetBlockTypeName(hitBlockType, 0)}\" can not be changed.");
                            player.SendTileSquare(location);
                        }

                        return(result);
                    }

                    return(new CommandInteractionResult {
                        IsHandled = false, IsInteractionCompleted = false
                    });
                };
                interaction.TimeExpiredCallback = (player) => {
                    player.SendErrorMessage("Waited too long, no component will be toggled.");
                };

                args.Player.SendSuccessMessage("Hit an object to change its state.");
                return(true);
            }

            return(false);
        }
        private bool CheckTilePermission(TSPlayer player, DPoint location, int blockType, int objectStyle, PaintColor paint, bool dropItem = false)
        {
            switch (blockType)
            {
            case TileID.Statues: {
                DPoint originTileLocation = new DPoint(location.X - 1, location.Y - 2);
                if (!TerrariaUtils.Tiles.IsObjectWired(originTileLocation, new DPoint(2, 3)))
                {
                    break;
                }
                StatueStyle  statueStyle = TerrariaUtils.Tiles.GetStatueStyle(objectStyle);
                StatueConfig statueConfig;
                if (!this.Config.StatueConfigs.TryGetValue(statueStyle, out statueConfig) || statueConfig == null)
                {
                    break;
                }

                if (!player.Group.HasPermission(statueConfig.WirePermission))
                {
                    player.SendTileSquareEx(location, 10);

                    if (dropItem)
                    {
                        int itemTypeToDrop;
                        itemTypeToDrop = TerrariaUtils.Tiles.GetItemTypeFromStatueStyle(statueStyle);

                        Item.NewItem(location.X * TerrariaUtils.TileSize, location.Y * TerrariaUtils.TileSize, 0, 0, itemTypeToDrop);
                    }

                    this.TellNoStatueWiringPermission(player, statueStyle);
                    return(false);
                }

                break;
            }

            case TileID.Traps: {
                ITile destTile = TerrariaUtils.Tiles[location];
                if (!destTile.HasWire())
                {
                    break;
                }
                TrapConfig trapConfig;
                TrapStyle  trapStyle = TerrariaUtils.Tiles.GetTrapStyle(destTile.frameY / 18);

                TrapConfigKey configKey = new TrapConfigKey(trapStyle, paint);
                if (!this.Config.TrapConfigs.TryGetValue(configKey, out trapConfig))
                {
                    break;
                }

                if (!player.Group.HasPermission(trapConfig.WirePermission))
                {
                    player.SendTileSquareEx(location, 10);

                    if (dropItem)
                    {
                        int itemTypeToDrop = TerrariaUtils.Tiles.GetItemTypeFromTrapStyle(trapStyle);
                        Item.NewItem(location.X * TerrariaUtils.TileSize, location.Y * TerrariaUtils.TileSize, 0, 0, itemTypeToDrop);
                    }

                    this.TellMissingComponentWiringPermission(player, blockType);
                    return(false);
                }

                break;
            }

            case TileID.Boulder: {
                DPoint originTileLocation = new DPoint(location.X - 1, location.Y - 1);
                if (!TerrariaUtils.Tiles.IsObjectWired(originTileLocation, new DPoint(2, 2)))
                {
                    break;
                }

                if (!player.Group.HasPermission(AdvancedCircuitsPlugin.WireBoulder_Permission))
                {
                    player.SendTileSquareEx(location, 10);

                    if (dropItem)
                    {
                        Item.NewItem(location.X * TerrariaUtils.TileSize, location.Y * TerrariaUtils.TileSize, 0, 0, ItemID.Boulder);
                    }

                    this.TellMissingComponentWiringPermission(player, blockType);
                    return(false);
                }

                break;
            }

            case TileID.Signs: {
                if (!TerrariaUtils.Tiles.IsObjectWired(location, new DPoint(2, 2)))
                {
                    break;
                }

                if (!player.Group.HasPermission(AdvancedCircuitsPlugin.WireSign_Permission))
                {
                    player.SendTileSquareEx(location, 10);

                    if (dropItem)
                    {
                        Item.NewItem(location.X * TerrariaUtils.TileSize, location.Y * TerrariaUtils.TileSize, 0, 0, ItemID.Sign);
                    }

                    this.TellMissingComponentWiringPermission(player, blockType);
                    return(false);
                }

                break;
            }

            case TileID.InletPump:
            case TileID.OutletPump: {
                DPoint originTileLocation = new DPoint(location.X - 1, location.Y - 1);
                if (!TerrariaUtils.Tiles.IsObjectWired(originTileLocation, new DPoint(2, 2)))
                {
                    break;
                }
                PumpConfig pumpConfig;
                if (!this.Config.PumpConfigs.TryGetValue(paint, out pumpConfig))
                {
                    break;
                }
                if (string.IsNullOrEmpty(pumpConfig.WirePermission))
                {
                    break;
                }

                if (!player.Group.HasPermission(pumpConfig.WirePermission))
                {
                    player.SendTileSquareEx(location, 10);

                    if (dropItem)
                    {
                        int itemTypeToDrop = ItemID.OutletPump;
                        if (blockType == ItemID.InletPump)
                        {
                            itemTypeToDrop = ItemID.InletPump;
                        }

                        Item.NewItem(location.X * TerrariaUtils.TileSize, location.Y * TerrariaUtils.TileSize, 0, 0, itemTypeToDrop);
                    }

                    this.TellMissingComponentWiringPermission(player, blockType);
                    return(false);
                }

                break;
            }

            case AdvancedCircuits.BlockType_WirelessTransmitter: {
                if (!AdvancedCircuits.IsComponentWiredByPort(location, new DPoint(1, 1)))
                {
                    break;
                }
                WirelessTransmitterConfig transmitterConfig;
                if (!this.Config.WirelessTransmitterConfigs.TryGetValue(paint, out transmitterConfig))
                {
                    break;
                }

                if (!player.Group.HasPermission(transmitterConfig.WirePermission))
                {
                    player.SendTileSquareEx(location, 1);

                    if (dropItem)
                    {
                        Item.NewItem(location.X * TerrariaUtils.TileSize, location.Y * TerrariaUtils.TileSize, 0, 0, ItemID.AdamantiteOre);
                    }

                    this.TellMissingComponentWiringPermission(player, blockType);
                    return(false);
                }

                break;
            }

            case ItemID.Teleporter: {
                DPoint originTileLocation = new DPoint(location.X - 1, location.Y - 1);
                if (!TerrariaUtils.Tiles.IsObjectWired(originTileLocation, new DPoint(3, 1)))
                {
                    break;
                }

                if (!player.Group.HasPermission(AdvancedCircuitsPlugin.WireTeleporter_Permission))
                {
                    player.SendTileSquareEx(location, 10);

                    if (dropItem)
                    {
                        Item.NewItem(location.X * TerrariaUtils.TileSize, location.Y * TerrariaUtils.TileSize, 0, 0, ItemID.Teleporter);
                    }

                    this.TellMissingComponentWiringPermission(player, blockType);
                    return(false);
                }

                break;
            }
            }

            return(true);
        }
Beispiel #12
0
        public bool HandleTileEdit(TSPlayer player, TileEditType editType, int blockType, DPoint location, int objectStyle)
        {
            switch (editType)
            {
            case TileEditType.PlaceTile: {
                switch (blockType)
                {
                case AdvancedCircuits.BlockType_WirelessTransmitter:
                    if (
                        AdvancedCircuits.IsComponentWiredByPort(location, new DPoint(1, 1)) &&
                        !this.Metadata.WirelessTransmitters.ContainsKey(location)
                        )
                    {
                        this.Metadata.WirelessTransmitters.Add(location, player.Name);
                    }

                    break;
                }

                break;
            }

            case TileEditType.PlaceWire:
            case TileEditType.PlaceWireBlue:
            case TileEditType.PlaceWireGreen: {
                // Check if we just wired an unregistered component's port.
                foreach (DPoint adjacentTileLocation in AdvancedCircuits.EnumerateComponentPortLocations(location, new DPoint(1, 1)))
                {
                    ITile tile = TerrariaUtils.Tiles[adjacentTileLocation];
                    if (tile.active() && tile.type == AdvancedCircuits.BlockType_WirelessTransmitter)
                    {
                        if (!this.Metadata.WirelessTransmitters.ContainsKey(adjacentTileLocation))
                        {
                            this.Metadata.WirelessTransmitters.Add(adjacentTileLocation, player.Name);
                        }
                    }
                }

                break;
            }

            case TileEditType.TileKill:
            case TileEditType.TileKillNoItem: {
                if (!TerrariaUtils.Tiles[location].active())
                {
                    break;
                }

                switch (TerrariaUtils.Tiles[location].type)
                {
                case TileID.Timers: {
                    if (this.Metadata.ActiveTimers.ContainsKey(location))
                    {
                        this.Metadata.ActiveTimers.Remove(location);
                    }

                    break;
                }

                case TileID.GrandfatherClocks: {
                    ObjectMeasureData measureData = TerrariaUtils.Tiles.MeasureObject(location);
                    if (this.Metadata.Clocks.ContainsKey(measureData.OriginTileLocation))
                    {
                        this.Metadata.Clocks.Remove(measureData.OriginTileLocation);
                    }

                    break;
                }

                case AdvancedCircuits.BlockType_Swapper: {
                    if (this.Metadata.Swappers.ContainsKey(location))
                    {
                        this.Metadata.Swappers.Remove(location);
                    }

                    break;
                }

                case AdvancedCircuits.BlockType_ANDGate:
                case AdvancedCircuits.BlockType_ORGate:
                case AdvancedCircuits.BlockType_XORGate: {
                    if (this.Metadata.GateStates.ContainsKey(location))
                    {
                        this.Metadata.GateStates.Remove(location);
                    }

                    break;
                }

                case AdvancedCircuits.BlockType_BlockActivator: {
                    if (this.Metadata.BlockActivators.ContainsKey(location))
                    {
                        this.Metadata.BlockActivators.Remove(location);
                    }

                    break;
                }

                case AdvancedCircuits.BlockType_WirelessTransmitter: {
                    if (this.Metadata.WirelessTransmitters.ContainsKey(location))
                    {
                        this.Metadata.WirelessTransmitters.Remove(location);
                    }

                    break;
                }
                }

                break;
            }
            }

            return(false);
        }
Beispiel #13
0
        public void HandleGameUpdate()
        {
            this.frameCounter++;

            if (this.frameCounter % CircuitHandler.TimerUpdateFrameRate == 0)
            {
                List <DPoint> timersToDelete = null;
                List <KeyValuePair <DPoint, ActiveTimerMetadata> > timersToProcess = null;

                foreach (KeyValuePair <DPoint, ActiveTimerMetadata> activeTimer in this.WorldMetadata.ActiveTimers)
                {
                    DPoint timerLocation = activeTimer.Key;
                    ActiveTimerMetadata timerMetadata = activeTimer.Value;

                    ITile timerTile = TerrariaUtils.Tiles[timerLocation];
                    if (timerMetadata == null || !timerTile.active() || timerTile.type != TileID.Timers)
                    {
                        if (timersToDelete == null)
                        {
                            timersToDelete = new List <DPoint>();
                        }

                        timersToDelete.Add(timerLocation);
                        continue;
                    }

                    if (timerMetadata.FramesLeft <= 0)
                    {
                        if (timersToProcess == null)
                        {
                            timersToProcess = new List <KeyValuePair <DPoint, ActiveTimerMetadata> >();
                        }

                        timersToProcess.Add(activeTimer);
                        timerMetadata.FramesLeft = AdvancedCircuits.MeasureTimerFrameTime(timerLocation);

                        continue;
                    }

                    timerMetadata.FramesLeft -= CircuitHandler.TimerUpdateFrameRate;
                }

                if (timersToProcess != null)
                {
                    DateTime now = DateTime.UtcNow;

                    foreach (KeyValuePair <DPoint, ActiveTimerMetadata> activeTimer in timersToProcess)
                    {
                        SignalType signalType;
                        // Is Advanced Circuit?
                        if (!TerrariaUtils.Tiles[activeTimer.Key].HasWire())
                        {
                            signalType = SignalType.On;
                        }
                        else
                        {
                            signalType = SignalType.Swap;
                        }

                        try {
                            CircuitProcessingResult result = this.ProcessCircuit(null, activeTimer.Key, signalType, false);
                            // If the circuit had errors or if it reached its max activity time, deactivate the timer.
                            if (
                                result.CancellationReason != CircuitCancellationReason.None || (
                                    this.Config.MaxTimerActivityTime != TimeSpan.Zero &&
                                    (now - activeTimer.Value.TimeOfRegistration) >= this.Config.MaxTimerActivityTime
                                    )
                                )
                            {
                                ObjectMeasureData measureData = TerrariaUtils.Tiles.MeasureObject(activeTimer.Key);
                                this.RegisterUnregisterTimer(result.TriggeringPlayer, measureData, false);
                                TerrariaUtils.Tiles.SetObjectState(measureData, false);
                            }
                        } catch (Exception ex) {
                            this.PluginTrace.WriteLineError("Circuit processing for a Timer at {0} failed. See inner exception for details.\n{1}", activeTimer.Key, ex.ToString());
                        }
                    }
                }

                if (timersToDelete != null)
                {
                    foreach (DPoint timerLocation in timersToDelete)
                    {
                        this.WorldMetadata.ActiveTimers.Remove(timerLocation);
                    }
                }
            }

            if (this.frameCounter % CircuitHandler.ClockUpdateFrameRate == 0)
            {
                bool isDaylight      = (Main.dayTime && Main.time >= 7200 && Main.time <= 46800);
                bool dayTimeChanged  = (Main.dayTime != this.isDayTime);
                bool daylightChanged = (this.isDaylight != isDaylight);

                if (dayTimeChanged || daylightChanged)
                {
                    List <DPoint> clocksToRemove = null;

                    foreach (KeyValuePair <DPoint, GrandfatherClockMetadata> clock in this.WorldMetadata.Clocks)
                    {
                        DPoint clockLocation = clock.Key;
                        ITile  clockTile     = TerrariaUtils.Tiles[clockLocation];

                        if (!clockTile.active() || clockTile.type != TileID.GrandfatherClocks)
                        {
                            if (clocksToRemove == null)
                            {
                                clocksToRemove = new List <DPoint>();
                            }

                            clocksToRemove.Add(clock.Key);
                            continue;
                        }

                        bool signal;
                        switch ((PaintColor)TerrariaUtils.Tiles[clockLocation].color())
                        {
                        case AdvancedCircuits.Paint_Clock_ByDaylight:
                            if (!daylightChanged)
                            {
                                continue;
                            }

                            signal = !isDaylight;
                            break;

                        case AdvancedCircuits.Paint_Clock_ByNighttimeAndBloodmoon:
                            if (!dayTimeChanged)
                            {
                                continue;
                            }

                            signal = !Main.dayTime && Main.bloodMoon;
                            break;

                        case AdvancedCircuits.Paint_Clock_ByNighttimeAndFullmoon:
                            if (!dayTimeChanged)
                            {
                                continue;
                            }

                            signal = !Main.dayTime && Main.moonPhase == 0;
                            break;

                        default:
                            if (!dayTimeChanged)
                            {
                                continue;
                            }

                            signal = !Main.dayTime;
                            break;
                        }

                        try {
                            TSPlayer triggeringPlayer = null;
                            if (clock.Value.TriggeringPlayerName != null)
                            {
                                triggeringPlayer = TShockEx.GetPlayerByName(clock.Value.TriggeringPlayerName);
                            }
                            if (triggeringPlayer == null)
                            {
                                triggeringPlayer = TSPlayer.Server;
                            }

                            this.ProcessCircuit(triggeringPlayer, clockLocation, AdvancedCircuits.BoolToSignal(signal), false);
                        } catch (Exception ex) {
                            this.PluginTrace.WriteLineError(
                                "Circuit processing for a Grandfather Clock at {0} failed. See inner exception for details.\n{1}",
                                clockLocation, ex.ToString()
                                );
                        }
                    }

                    if (clocksToRemove != null)
                    {
                        foreach (DPoint clockLocation in clocksToRemove)
                        {
                            this.WorldMetadata.Clocks.Remove(clockLocation);
                        }
                    }

                    if (dayTimeChanged)
                    {
                        this.isDayTime = Main.dayTime;
                    }
                    if (daylightChanged)
                    {
                        this.isDaylight = isDaylight;
                    }
                }

                if (this.frameCounter >= 100000)
                {
                    this.frameCounter = 0;
                }
            }
        }
Beispiel #14
0
        protected void NotifyPlayer(CircuitProcessingResult result)
        {
            TSPlayer player = result.TriggeringPlayer;

            if (player == TSPlayer.Server)
            {
                return;
            }

            switch (result.WarnReason)
            {
            case CircuitWarnReason.SignalesTooManyPumps:
                player.SendWarningMessage(string.Format(
                                              "Warning: This circuit tried to signal {0} Pumps, though the allowed maximum is {1}.",
                                              result.SignaledPumps, this.Config.MaxPumpsPerCircuit
                                              ));
                break;

            case CircuitWarnReason.SignalesTooManyTraps:
                player.SendWarningMessage(string.Format(
                                              "Warning: This circuit tried to signal {0} Traps, though the allowed maximum is {1}.",
                                              result.SignaledTraps, this.Config.MaxTrapsPerCircuit
                                              ));
                break;

            case CircuitWarnReason.SignalesTooManyStatues:
                player.SendWarningMessage(string.Format(
                                              "Warning: This circuit tried to signal {0} Statues, though the allowed maximum is {1}.",
                                              result.SignaledStatues, this.Config.MaxStatuesPerCircuit
                                              ));
                break;

            case CircuitWarnReason.InsufficientPermissionToSignalComponent:
                player.SendWarningMessage("Warning: You don't have the required permission to signal");
                player.SendWarningMessage(string.Format(
                                              "the component \"{0}\".", AdvancedCircuits.GetComponentName(result.WarnRelatedComponentType)
                                              ));
                break;

            case CircuitWarnReason.BlockActivatorChangedTooManyBlocks:
                player.SendWarningMessage("Warning: A \"Block Activator\" component tried to change more");
                player.SendWarningMessage(string.Format(
                                              "blocks than the allowed maximum of {0} blocks.", this.Config.BlockActivatorConfig.MaxChangeableBlocks
                                              ));
                break;
            }

            switch (result.CancellationReason)
            {
            case CircuitCancellationReason.ExceededMaxLength:
                player.SendErrorMessage("Error: Circuit processing cancelled because it exceeded the maximum length of ");
                player.SendErrorMessage(string.Format("{0} wires.", this.Config.MaxCircuitLength));
                break;

            case CircuitCancellationReason.SignaledSameComponentTooOften:
                if (result.CancellationRelatedComponentType == -1)
                {
                    player.SendErrorMessage("Error: Circuit processing cancelled because a component was signaled too often.");
                }
                else
                {
                    player.SendErrorMessage("Error: Circuit processing cancelled because the component");
                    player.SendErrorMessage(string.Format(
                                                "\"{0}\" was signaled too often. Check your circuit for loops.", AdvancedCircuits.GetComponentName(result.CancellationRelatedComponentType)
                                                ));
                }

                break;
            }
        }
Beispiel #15
0
 public static bool IsComponentWiredByPort(ObjectMeasureData measureData)
 {
     return(AdvancedCircuits.IsComponentWiredByPort(measureData.OriginTileLocation, measureData.Size));
 }