Ejemplo n.º 1
0
        //Environment Constructor
        public AngryBallsEnvironment()
        {
            //Initialize the Buttons
            playPauseButton = new PlayPauseButton(gameState);
            builderButton = new BuilderButton(gameState);

            background = Game1.environmentBackground;
            border = Game1.borderImage;
            bigCog = Game1.bigCog;
            clawOpen = Game1.clawOpen;
            Input = new InputManager();
            map = new Map();
            //justClicked = false;
            toolBox = new ToolBox();
            gameState = GameState.run;
            angryBall = new FarseerBall(ballStartPose);

            //Physics Bodies for Walls
            leftWall = BodyFactory.CreateRectangle(Game1.world, UnitConverter.toSimSpace(10), UnitConverter.toSimSpace(2450), 1.0f, leftWallPosition);
            leftWall.BodyType = BodyType.Static;
            rightWall = BodyFactory.CreateRectangle(Game1.world, UnitConverter.toSimSpace(10), UnitConverter.toSimSpace(2550), 1.0f, rightWallPosition);
            rightWall.BodyType = BodyType.Static;
            ceiling = BodyFactory.CreateRectangle(Game1.world, UnitConverter.toSimSpace(960), UnitConverter.toSimSpace(10), 1.0f, ceilingPosition);
            ceiling.BodyType = BodyType.Static;
            floor = BodyFactory.CreateRectangle(Game1.world, UnitConverter.toSimSpace(960), UnitConverter.toSimSpace(10), 1.0f, floorPosition);
            floor.BodyType = BodyType.Static;
        }
Ejemplo n.º 2
0
	private void Start()
	{
		Screen.sleepTimeout = SleepTimeout.SystemSetting;
		toolBox = ToolBox.Instance;
		MenuButton.ClickMenuButton += ClickMenuButton;
		toolBox.download.AddObserver(this);
		toolBox.data.ResetData();
		toolBox.loadingScreen.enable(false);
	}
Ejemplo n.º 3
0
	public RouteNavigation(CustomLineRenderer line, LineRenderer directLine, GoogleMapNavigation nav)
	{
		lineRenderer = line;
		mapNavigation = nav;
		directLineRenderer = directLine;
		toolBox = ToolBox.Instance;
		data = toolBox.data;
		goal = data.route.Waypoints[data.route.Start];
		if (goal.Destinations.Count > 0)
		{
			nextGoal = data.route.Waypoints[goal.Destinations[0]];
		}
		toolBox.download.AddObserver(this);
	}
Ejemplo n.º 4
0
	private void Start()
	{
		routeNavigation = new RouteNavigation(lineRenderer, directLineRenderer, this);
		toolBox = ToolBox.Instance;
		directLineRenderer.enabled = true;
		toolBox.loadingScreen.enable(true);
		userGPSLocation = new GeoCoordinate();
		projection = new MercatorProjection(zoom);
		mapImageSize = MapSize(Screen.width, Screen.height);
		mapExpandRatio = Screen.width / mapImageSize.x;
		mapLimit = new Vector2(Screen.width / 4, Screen.height / 4);
		toolBox.sensorManager.gps.AddObserver(this);
		toolBox.sensorManager.orientation.AddObserver(this);
		toolBox.download.AddObserver(this);
	}
Ejemplo n.º 5
0
        protected override void CreateGUI()
        {
            controlContainer = new GUIFrame(new RectTransform(new Vector2(Sonar.controlBoxSize.X, 1 - Sonar.controlBoxSize.Y * 2), GuiFrame.RectTransform, Anchor.CenterLeft), "ItemUI");
            var paddedControlContainer = new GUIFrame(new RectTransform(controlContainer.Rect.Size - GUIStyle.ItemFrameMargin, controlContainer.RectTransform, Anchor.Center)
            {
                AbsoluteOffset = GUIStyle.ItemFrameOffset
            }, style: null);

            var steeringModeArea = new GUIFrame(new RectTransform(new Vector2(1, 0.4f), paddedControlContainer.RectTransform, Anchor.TopLeft), style: null);

            steeringModeSwitch = new GUIButton(new RectTransform(new Vector2(0.2f, 1), steeringModeArea.RectTransform), string.Empty, style: "SwitchVertical")
            {
                Selected   = autoPilot,
                Enabled    = true,
                ClickSound = GUISoundType.UISwitch,
                OnClicked  = (button, data) =>
                {
                    button.Selected = !button.Selected;
                    AutoPilot       = button.Selected;
                    if (GameMain.Client != null)
                    {
                        unsentChanges = true;
                        user          = Character.Controlled;
                    }
                    return(true);
                }
            };
            var steeringModeRightSide = new GUIFrame(new RectTransform(new Vector2(1.0f - steeringModeSwitch.RectTransform.RelativeSize.X, 0.8f), steeringModeArea.RectTransform, Anchor.CenterLeft)
            {
                RelativeOffset = new Vector2(steeringModeSwitch.RectTransform.RelativeSize.X, 0)
            }, style: null);

            manualPilotIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.45f), steeringModeRightSide.RectTransform, Anchor.TopLeft),
                                                  TextManager.Get("SteeringManual"), font: GUI.SubHeadingFont, style: "IndicatorLightRedSmall")
            {
                Selected = !autoPilot,
                Enabled  = false
            };
            autopilotIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.45f), steeringModeRightSide.RectTransform, Anchor.BottomLeft),
                                                TextManager.Get("SteeringAutoPilot"), font: GUI.SubHeadingFont, style: "IndicatorLightRedSmall")
            {
                Selected = autoPilot,
                Enabled  = false
            };
            manualPilotIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
            autopilotIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
            GUITextBlock.AutoScaleAndNormalize(manualPilotIndicator.TextBlock, autopilotIndicator.TextBlock);

            var autoPilotControls       = new GUIFrame(new RectTransform(new Vector2(0.75f, 0.62f), paddedControlContainer.RectTransform, Anchor.BottomCenter), "OutlineFrame");
            var paddedAutoPilotControls = new GUIFrame(new RectTransform(new Vector2(0.92f, 0.88f), autoPilotControls.RectTransform, Anchor.Center), style: null);

            maintainPosTickBox = new GUITickBox(new RectTransform(new Vector2(1, 0.333f), paddedAutoPilotControls.RectTransform, Anchor.TopCenter),
                                                TextManager.Get("SteeringMaintainPos"), font: GUI.SmallFont, style: "GUIRadioButton")
            {
                Enabled    = autoPilot,
                Selected   = maintainPos,
                OnSelected = tickBox =>
                {
                    if (maintainPos != tickBox.Selected)
                    {
                        unsentChanges = true;
                        user          = Character.Controlled;
                        maintainPos   = tickBox.Selected;
                        if (maintainPos)
                        {
                            if (controlledSub == null)
                            {
                                posToMaintain = null;
                            }
                            else
                            {
                                posToMaintain = controlledSub.WorldPosition;
                            }
                        }
                        else if (!LevelEndSelected && !LevelStartSelected)
                        {
                            AutoPilot = false;
                        }
                        if (!maintainPos)
                        {
                            posToMaintain = null;
                        }
                    }
                    return(true);
                }
            };
            int textLimit = (int)(MathHelper.Clamp(25 * GUI.xScale, 15, 35));

            levelStartTickBox = new GUITickBox(new RectTransform(new Vector2(1, 0.333f), paddedAutoPilotControls.RectTransform, Anchor.Center),
                                               GameMain.GameSession?.StartLocation == null ? "" : ToolBox.LimitString(GameMain.GameSession.StartLocation.Name, textLimit),
                                               font: GUI.SmallFont, style: "GUIRadioButton")
            {
                Enabled    = autoPilot,
                Selected   = levelStartSelected,
                OnSelected = tickBox =>
                {
                    if (levelStartSelected != tickBox.Selected)
                    {
                        unsentChanges      = true;
                        user               = Character.Controlled;
                        levelStartSelected = tickBox.Selected;
                        levelEndSelected   = !levelStartSelected;
                        if (levelStartSelected)
                        {
                            UpdatePath();
                        }
                        else if (!MaintainPos && !LevelEndSelected)
                        {
                            AutoPilot = false;
                        }
                    }
                    return(true);
                }
            };

            levelEndTickBox = new GUITickBox(new RectTransform(new Vector2(1, 0.333f), paddedAutoPilotControls.RectTransform, Anchor.BottomCenter),
                                             (GameMain.GameSession?.EndLocation == null || Level.IsLoadedOutpost) ? "" : ToolBox.LimitString(GameMain.GameSession.EndLocation.Name, textLimit),
                                             font: GUI.SmallFont, style: "GUIRadioButton")
            {
                Enabled    = autoPilot,
                Selected   = levelEndSelected,
                Visible    = GameMain.GameSession?.EndLocation != null,
                OnSelected = tickBox =>
                {
                    if (levelEndSelected != tickBox.Selected)
                    {
                        unsentChanges      = true;
                        user               = Character.Controlled;
                        levelEndSelected   = tickBox.Selected;
                        levelStartSelected = !levelEndSelected;
                        if (levelEndSelected)
                        {
                            UpdatePath();
                        }
                        else if (!MaintainPos && !LevelStartSelected)
                        {
                            AutoPilot = false;
                        }
                    }
                    return(true);
                }
            };
            maintainPosTickBox.RectTransform.IsFixedSize = levelStartTickBox.RectTransform.IsFixedSize = levelEndTickBox.RectTransform.IsFixedSize = false;
            maintainPosTickBox.RectTransform.MaxSize     = levelStartTickBox.RectTransform.MaxSize = levelEndTickBox.RectTransform.MaxSize =
                new Point(int.MaxValue, paddedAutoPilotControls.Rect.Height / 3);
            maintainPosTickBox.RectTransform.MinSize = levelStartTickBox.RectTransform.MinSize = levelEndTickBox.RectTransform.MinSize =
                Point.Zero;

            GUITextBlock.AutoScaleAndNormalize(scaleHorizontal: false, scaleVertical: true, maintainPosTickBox.TextBlock, levelStartTickBox.TextBlock, levelEndTickBox.TextBlock);

            GUIRadioButtonGroup destinations = new GUIRadioButtonGroup();

            destinations.AddRadioButton((int)Destination.MaintainPos, maintainPosTickBox);
            destinations.AddRadioButton((int)Destination.LevelStart, levelStartTickBox);
            destinations.AddRadioButton((int)Destination.LevelEnd, levelEndTickBox);
            destinations.Selected = (int)(maintainPos ? Destination.MaintainPos :
                                          levelStartSelected ? Destination.LevelStart : Destination.LevelEnd);

            // Status ->
            statusContainer = new GUIFrame(new RectTransform(Sonar.controlBoxSize, GuiFrame.RectTransform, Anchor.BottomLeft)
            {
                RelativeOffset = Sonar.controlBoxOffset
            }, "ItemUI");
            var paddedStatusContainer = new GUIFrame(new RectTransform(statusContainer.Rect.Size - GUIStyle.ItemFrameMargin, statusContainer.RectTransform, Anchor.Center, isFixedSize: false)
            {
                AbsoluteOffset = GUIStyle.ItemFrameOffset
            }, style: null);

            var elements = GUI.CreateElements(3, new Vector2(1f, 0.333f), paddedStatusContainer.RectTransform, rt => new GUIFrame(rt, style: null), Anchor.TopCenter, relativeSpacing: 0.01f);
            List <GUIComponent> leftElements = new List <GUIComponent>(), centerElements = new List <GUIComponent>(), rightElements = new List <GUIComponent>();

            for (int i = 0; i < elements.Count; i++)
            {
                var e     = elements[i];
                var group = new GUILayoutGroup(new RectTransform(Vector2.One, e.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft)
                {
                    RelativeSpacing = 0.01f,
                    Stretch         = true
                };
                var left   = new GUIFrame(new RectTransform(new Vector2(0.45f, 1), group.RectTransform), style: null);
                var center = new GUIFrame(new RectTransform(new Vector2(0.15f, 1), group.RectTransform), style: null);
                var right  = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.8f), group.RectTransform), style: null);
                leftElements.Add(left);
                centerElements.Add(center);
                rightElements.Add(right);
                string leftText = string.Empty, centerText = string.Empty;
                GUITextBlock.TextGetterHandler rightTextGetter = null;
                switch (i)
                {
                case 0:
                    leftText        = TextManager.Get("DescentVelocity");
                    centerText      = $"({TextManager.Get("KilometersPerHour")})";
                    rightTextGetter = () =>
                    {
                        Vector2 vel          = controlledSub == null ? Vector2.Zero : controlledSub.Velocity;
                        var     realWorldVel = ConvertUnits.ToDisplayUnits(vel.Y * Physics.DisplayToRealWorldRatio) * 3.6f;
                        return(((int)(-realWorldVel)).ToString());
                    };
                    break;

                case 1:
                    leftText        = TextManager.Get("Velocity");
                    centerText      = $"({TextManager.Get("KilometersPerHour")})";
                    rightTextGetter = () =>
                    {
                        Vector2 vel          = controlledSub == null ? Vector2.Zero : controlledSub.Velocity;
                        var     realWorldVel = ConvertUnits.ToDisplayUnits(vel.X * Physics.DisplayToRealWorldRatio) * 3.6f;
                        return(((int)realWorldVel).ToString());
                    };
                    break;

                case 2:
                    leftText        = TextManager.Get("Depth");
                    centerText      = $"({TextManager.Get("Meter")})";
                    rightTextGetter = () =>
                    {
                        Vector2 pos            = controlledSub == null ? Vector2.Zero : controlledSub.Position;
                        float   realWorldDepth = Level.Loaded == null ? 0.0f : Math.Abs(pos.Y - Level.Loaded.Size.Y) * Physics.DisplayToRealWorldRatio;
                        return(((int)realWorldDepth).ToString());
                    };
                    break;
                }
                new GUITextBlock(new RectTransform(Vector2.One, left.RectTransform), leftText, font: GUI.SubHeadingFont, wrap: leftText.Contains(' '), textAlignment: Alignment.CenterRight);
                new GUITextBlock(new RectTransform(Vector2.One, center.RectTransform), centerText, font: GUI.Font, textAlignment: Alignment.Center)
                {
                    Padding = Vector4.Zero
                };
                var digitalFrame = new GUIFrame(new RectTransform(Vector2.One, right.RectTransform), style: "DigitalFrameDark");
                new GUITextBlock(new RectTransform(Vector2.One * 0.85f, digitalFrame.RectTransform, Anchor.Center), "12345", GUI.Style.TextColorDark, GUI.DigitalFont, Alignment.CenterRight)
                {
                    TextGetter = rightTextGetter
                };
            }
            GUITextBlock.AutoScaleAndNormalize(leftElements.SelectMany(e => e.GetAllChildren <GUITextBlock>()));
            GUITextBlock.AutoScaleAndNormalize(centerElements.SelectMany(e => e.GetAllChildren <GUITextBlock>()));
            GUITextBlock.AutoScaleAndNormalize(rightElements.SelectMany(e => e.GetAllChildren <GUITextBlock>()));

            //docking interface ----------------------------------------------------
            float dockingButtonSize = 1.1f;
            float elementScale      = 0.6f;

            dockingContainer = new GUIFrame(new RectTransform(Sonar.controlBoxSize, GuiFrame.RectTransform, Anchor.BottomLeft, scaleBasis: ScaleBasis.Smallest)
            {
                RelativeOffset = new Vector2(Sonar.controlBoxOffset.X + 0.05f, Sonar.controlBoxOffset.Y)
            }, style: null);

            dockText      = TextManager.Get("label.navterminaldock", fallBackTag: "captain.dock");
            undockText    = TextManager.Get("label.navterminalundock", fallBackTag: "captain.undock");
            dockingButton = new GUIButton(new RectTransform(new Vector2(elementScale), dockingContainer.RectTransform, Anchor.Center), dockText, style: "PowerButton")
            {
                OnClicked = (btn, userdata) =>
                {
                    if (GameMain.GameSession?.Campaign is CampaignMode campaign)
                    {
                        if (Level.IsLoadedOutpost &&
                            DockingSources.Any(d => d.Docked && (d.DockingTarget?.Item.Submarine?.Info?.IsOutpost ?? false)))
                        {
                            // Undocking from an outpost
                            campaign.CampaignUI.SelectTab(CampaignMode.InteractionType.Map);
                            campaign.ShowCampaignUI = true;
                            return(false);
                        }
                        else if (!Level.IsLoadedOutpost && DockingModeEnabled && ActiveDockingSource != null &&
                                 !ActiveDockingSource.Docked && DockingTarget?.Item?.Submarine == Level.Loaded.StartOutpost && (DockingTarget?.Item?.Submarine?.Info.IsOutpost ?? false))
                        {
                            // Docking to an outpost
                            var subsToLeaveBehind = campaign.GetSubsToLeaveBehind(Item.Submarine);
                            if (subsToLeaveBehind.Any())
                            {
                                enterOutpostPrompt = new GUIMessageBox(
                                    TextManager.GetWithVariable("enterlocation", "[locationname]", DockingTarget.Item.Submarine.Info.Name),
                                    TextManager.Get(subsToLeaveBehind.Count == 1 ? "LeaveSubBehind" : "LeaveSubsBehind"),
                                    new string[] { TextManager.Get("yes"), TextManager.Get("no") });
                            }
                            else
                            {
                                enterOutpostPrompt = new GUIMessageBox("",
                                                                       TextManager.GetWithVariable("campaignenteroutpostprompt", "[locationname]", DockingTarget.Item.Submarine.Info.Name),
                                                                       new string[] { TextManager.Get("yes"), TextManager.Get("no") });
                            }
                            enterOutpostPrompt.Buttons[0].OnClicked += (btn, userdata) =>
                            {
                                SendDockingSignal();
                                enterOutpostPrompt.Close();
                                return(true);
                            };
                            enterOutpostPrompt.Buttons[1].OnClicked += enterOutpostPrompt.Close;
                            return(false);
                        }
                    }
                    SendDockingSignal();

                    return(true);
                }
            };
            void SendDockingSignal()
            {
                if (GameMain.Client == null)
                {
                    item.SendSignal(0, "1", "toggle_docking", sender: null);
                }
                else
                {
                    dockingNetworkMessagePending = true;
                    item.CreateClientEvent(this);
                }
            }

            dockingButton.Font = GUI.SubHeadingFont;
            dockingButton.TextBlock.RectTransform.MaxSize = new Point((int)(dockingButton.Rect.Width * 0.7f), int.MaxValue);
            dockingButton.TextBlock.AutoScaleHorizontal   = true;

            var    style        = GUI.Style.GetComponentStyle("DockingButtonUp");
            Sprite buttonSprite = style.Sprites.FirstOrDefault().Value.FirstOrDefault()?.Sprite;
            Point  buttonSize   = buttonSprite != null?buttonSprite.size.ToPoint() : new Point(149, 52);

            Point horizontalButtonSize = buttonSize.Multiply(elementScale * GUI.Scale * dockingButtonSize);
            Point verticalButtonSize   = horizontalButtonSize.Flip();
            var   leftButton           = new GUIButton(new RectTransform(verticalButtonSize, dockingContainer.RectTransform, Anchor.CenterLeft), "", style: "DockingButtonLeft")
            {
                OnClicked = NudgeButtonClicked,
                UserData  = -Vector2.UnitX
            };
            var rightButton = new GUIButton(new RectTransform(verticalButtonSize, dockingContainer.RectTransform, Anchor.CenterRight), "", style: "DockingButtonRight")
            {
                OnClicked = NudgeButtonClicked,
                UserData  = Vector2.UnitX
            };
            var upButton = new GUIButton(new RectTransform(horizontalButtonSize, dockingContainer.RectTransform, Anchor.TopCenter), "", style: "DockingButtonUp")
            {
                OnClicked = NudgeButtonClicked,
                UserData  = Vector2.UnitY
            };
            var downButton = new GUIButton(new RectTransform(horizontalButtonSize, dockingContainer.RectTransform, Anchor.BottomCenter), "", style: "DockingButtonDown")
            {
                OnClicked = NudgeButtonClicked,
                UserData  = -Vector2.UnitY
            };

            // Sonar area
            steerArea = new GUICustomComponent(new RectTransform(Sonar.GUISizeCalculation, GuiFrame.RectTransform, Anchor.CenterRight, scaleBasis: ScaleBasis.Smallest),
                                               (spriteBatch, guiCustomComponent) => { DrawHUD(spriteBatch, guiCustomComponent.Rect); }, null);
            steerRadius = steerArea.Rect.Width / 2;

            pressureWarningText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), steerArea.RectTransform, Anchor.Center, Pivot.TopCenter),
                                                   TextManager.Get("SteeringDepthWarning"), Color.Red, GUI.LargeFont, Alignment.Center)
            {
                Visible = false
            };
            // Tooltip/helper text
            tipContainer = new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.1f), steerArea.RectTransform, Anchor.BottomCenter, Pivot.TopCenter)
                                            , "", font: GUI.Font, wrap: true, style: "GUIToolTip", textAlignment: Alignment.Center)
            {
                AutoScaleHorizontal = true
            };
            noPowerTip = TextManager.Get("SteeringNoPowerTip");
            autoPilotMaintainPosTip = TextManager.Get("SteeringAutoPilotMaintainPosTip");
            autoPilotLevelStartTip  = TextManager.GetWithVariable("SteeringAutoPilotLocationTip", "[locationname]",
                                                                  GameMain.GameSession?.StartLocation == null ? "Start" : GameMain.GameSession.StartLocation.Name);
            autoPilotLevelEndTip = TextManager.GetWithVariable("SteeringAutoPilotLocationTip", "[locationname]",
                                                               GameMain.GameSession?.EndLocation == null ? "End" : GameMain.GameSession.EndLocation.Name);
        }
Ejemplo n.º 6
0
    private void TakeTaxi(FlightMaster fm, string taxiNodeName)
    {
        string clickNodeLua = "TakeTaxiNode(" + Lua.LuaDoString <int>("for i=0,120 do if string.find(TaxiNodeName(i),'" + taxiNodeName.Replace("'", "\\'") + "') then return i end end", "").ToString() + ")";

        Logger.LogDebug(clickNodeLua);
        Lua.LuaDoString(clickNodeLua, false);
        Thread.Sleep(500);

        // 5 tries to click on node if it failed
        for (int i = 1; i <= 5; i++)
        {
            if (ObjectManager.Me.IsCast)
            {
                Usefuls.WaitIsCasting();
                i = 1;
                Logger.Log("You're casting, wait");
                continue;
            }

            if (ObjectManager.Me.IsOnTaxi || Main.inPause)
            {
                break;
            }
            else
            {
                Logger.Log($"Taking taxi failed. Retrying ({i}/5)");
                Lua.LuaDoString($"CloseTaxiMap(); CloseGossip();");
                Main.errorTooFarAwayFromTaxiStand = false;
                Thread.Sleep(500);
                if (WFMMoveInteract.GoInteractwithFM(fm))
                {
                    Thread.Sleep(500);
                }
                Usefuls.SelectGossipOption(GossipOptionsType.taxi);
                Thread.Sleep(500);
                Lua.LuaDoString(clickNodeLua, false);
                Thread.Sleep(500);
            }
        }

        if (Main.inPause)
        {
            return;
        }

        if (Main.errorTooFarAwayFromTaxiStand)
        {
            ToolBox.PausePlugin("Taking taxi failed (error clicking node)");
        }
        else
        {
            Logger.Log($"Flying to {taxiNodeName}");
        }

        Thread.Sleep(Usefuls.Latency + 500);
        Main.shouldTakeFlight             = false;
        Main.errorTooFarAwayFromTaxiStand = false;
        Thread.Sleep(Usefuls.Latency + 500);

        if (!ObjectManager.Me.IsOnTaxi)
        {
            ToolBox.PausePlugin("Taking taxi failed");
        }
    }
Ejemplo n.º 7
0
        //Environment Constructor
        public AngryBallsEnvironment()
        {
            //Instantiate the Buttons
            gameState = GameState.initialize;
            playPauseButton = new PlayPauseButton(gameState);
            resetButton = new ResetButton(gameState);
            builderButton = new BuilderButton(gameState);
            saveButton = new SaveButton(gameState);
            loadButton = new LoadButton(gameState);

            // Instantiate Dialog Box
            dialog = new Dialog(loadButton, saveButton);

            //Instantiate Start Positions for environment items
            clawopenPosition = clawStartPosition;
            ballStartPose = new Vector2(clawStartPosition.X + 47, clawStartPosition.Y + 150);

            //Instantiate local images
            background = Game1.environmentBackground;
            border = Game1.borderImage;
            bigCogImage = Game1.bigCog;
            bigCogOrigin = new Vector2(bigCogImage.Width / 2, bigCogImage.Height / 2);
            springImage = Game1.springImage;
            chickenImage = Game1.chickenImage;
            clawOpen = Game1.clawOpen;

            //Instantiate environment containers
            Input = new InputManager();
            map = new Map();
            toolBox = new ToolBox();
        }
Ejemplo n.º 8
0
    private void OnDestroy()
    {
        ToolBox toolbox = ToolBox.Instance;

        toolbox.volverAtras();
    }
Ejemplo n.º 9
0
        public static void ServerRead(IReadMessage msg, Client c)
        {
            c.KickAFKTimer = 0.0f;

            UInt16          ID   = msg.ReadUInt16();
            ChatMessageType type = (ChatMessageType)msg.ReadByte();
            string          txt;

            Character        orderTargetCharacter = null;
            Entity           orderTargetEntity    = null;
            OrderChatMessage orderMsg             = null;
            OrderTarget      orderTargetPosition  = null;

            if (type == ChatMessageType.Order)
            {
                int orderIndex = msg.ReadByte();
                orderTargetCharacter = Entity.FindEntityByID(msg.ReadUInt16()) as Character;
                orderTargetEntity    = Entity.FindEntityByID(msg.ReadUInt16()) as Entity;
                int orderOptionIndex = msg.ReadByte();
                if (msg.ReadBoolean())
                {
                    var x    = msg.ReadSingle();
                    var y    = msg.ReadSingle();
                    var hull = Entity.FindEntityByID(msg.ReadUInt16()) as Hull;
                    orderTargetPosition = new OrderTarget(new Vector2(x, y), hull, true);
                }

                if (orderIndex < 0 || orderIndex >= Order.PrefabList.Count)
                {
                    DebugConsole.ThrowError($"Invalid order message from client \"{c.Name}\" - order index out of bounds ({orderIndex}, {orderOptionIndex}).");
                    if (NetIdUtils.IdMoreRecent(ID, c.LastSentChatMsgID))
                    {
                        c.LastSentChatMsgID = ID;
                    }
                    return;
                }

                Order  order       = Order.PrefabList[orderIndex];
                string orderOption = orderOptionIndex < 0 || orderOptionIndex >= order.Options.Length ? "" : order.Options[orderOptionIndex];
                orderMsg = new OrderChatMessage(order, orderOption, orderTargetPosition ?? orderTargetEntity as ISpatialEntity, orderTargetCharacter, c.Character);
                txt      = orderMsg.Text;
            }
            else
            {
                txt = msg.ReadString() ?? "";
            }

            if (!NetIdUtils.IdMoreRecent(ID, c.LastSentChatMsgID))
            {
                return;
            }

            c.LastSentChatMsgID = ID;

            if (txt.Length > MaxLength)
            {
                txt = txt.Substring(0, MaxLength);
            }

            c.LastSentChatMessages.Add(txt);
            if (c.LastSentChatMessages.Count > 10)
            {
                c.LastSentChatMessages.RemoveRange(0, c.LastSentChatMessages.Count - 10);
            }

            float similarity = 0.0f;

            for (int i = 0; i < c.LastSentChatMessages.Count; i++)
            {
                float closeFactor = 1.0f / (c.LastSentChatMessages.Count - i);

                if (string.IsNullOrEmpty(txt))
                {
                    similarity += closeFactor;
                }
                else
                {
                    int levenshteinDist = ToolBox.LevenshteinDistance(txt, c.LastSentChatMessages[i]);
                    similarity += Math.Max((txt.Length - levenshteinDist) / (float)txt.Length * closeFactor, 0.0f);
                }
            }
            //order/report messages can be sent a little faster than normal messages without triggering the spam filter
            if (orderMsg != null)
            {
                similarity *= 0.25f;
            }

            bool isOwner = GameMain.Server.OwnerConnection != null && c.Connection == GameMain.Server.OwnerConnection;

            if (similarity + c.ChatSpamSpeed > 5.0f && !isOwner)
            {
                GameMain.Server.KarmaManager.OnSpamFilterTriggered(c);

                c.ChatSpamCount++;
                if (c.ChatSpamCount > 3)
                {
                    //kick for spamming too much
                    GameMain.Server.KickClient(c, TextManager.Get("SpamFilterKicked"));
                }
                else
                {
                    ChatMessage denyMsg = Create("", TextManager.Get("SpamFilterBlocked"), ChatMessageType.Server, null);
                    c.ChatSpamTimer = 10.0f;
                    GameMain.Server.SendDirectChatMessage(denyMsg, c);
                }
                return;
            }

            c.ChatSpamSpeed += similarity + 0.5f;

            if (c.ChatSpamTimer > 0.0f && !isOwner)
            {
                ChatMessage denyMsg = Create("", TextManager.Get("SpamFilterBlocked"), ChatMessageType.Server, null);
                c.ChatSpamTimer = 10.0f;
                GameMain.Server.SendDirectChatMessage(denyMsg, c);
                return;
            }

            if (type == ChatMessageType.Order)
            {
                if (c.Character == null || c.Character.SpeechImpediment >= 100.0f || c.Character.IsDead)
                {
                    return;
                }
                if (orderMsg.Order.TargetAllCharacters)
                {
                    HumanAIController.ReportProblem(orderMsg.Sender, orderMsg.Order);
                }
                else if (orderTargetCharacter != null)
                {
                    var order = orderTargetPosition == null ?
                                new Order(orderMsg.Order.Prefab, orderTargetEntity, orderMsg.Order.Prefab?.GetTargetItemComponent(orderTargetEntity as Item), orderMsg.Sender) :
                                new Order(orderMsg.Order.Prefab, orderTargetPosition, orderMsg.Sender);
                    orderTargetCharacter.SetOrder(order, orderMsg.OrderOption, orderMsg.Sender);
                }
                GameMain.Server.SendOrderChatMessage(orderMsg);
            }
            else
            {
                GameMain.Server.SendChatMessage(txt, null, c);
            }
        }
Ejemplo n.º 10
0
        partial void InitProjSpecific(XElement element)
        {
            int viewSize         = (int)Math.Min(GuiFrame.Rect.Width - 150, GuiFrame.Rect.Height * 0.9f);
            var controlContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.35f), GuiFrame.RectTransform, Anchor.CenterLeft)
            {
                MinSize = new Point(150, 0), AbsoluteOffset = new Point((int)(viewSize * 0.99f), (int)(viewSize * 0.05f))
            }, "SonarFrame");
            var paddedControlContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), controlContainer.RectTransform, Anchor.Center))
            {
                RelativeSpacing = 0.03f,
                Stretch         = true
            };

            statusContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GuiFrame.RectTransform, Anchor.BottomLeft)
            {
                MinSize = new Point(150, 0), AbsoluteOffset = new Point((int)(viewSize * 0.9f), 0)
            }, "SonarFrame");
            var paddedStatusContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), statusContainer.RectTransform, Anchor.Center))
            {
                RelativeSpacing = 0.03f,
                Stretch         = true
            };

            manualTickBox = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.3f), paddedControlContainer.RectTransform),
                                           TextManager.Get("SteeringManual"), style: "GUIRadioButton")
            {
                Selected   = true,
                OnSelected = (GUITickBox box) =>
                {
                    AutoPilot     = !box.Selected;
                    unsentChanges = true;
                    user          = Character.Controlled;

                    return(true);
                }
            };
            autopilotTickBox = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.3f), paddedControlContainer.RectTransform),
                                              TextManager.Get("SteeringAutoPilot"), style: "GUIRadioButton")
            {
                OnSelected = (GUITickBox box) =>
                {
                    AutoPilot = box.Selected;
                    if (AutoPilot && MaintainPos)
                    {
                        posToMaintain = controlledSub != null ?
                                        controlledSub.WorldPosition :
                                        item.Submarine == null ? item.WorldPosition : item.Submarine.WorldPosition;
                    }
                    unsentChanges = true;
                    user          = Character.Controlled;

                    return(true);
                }
            };

            GUIRadioButtonGroup modes = new GUIRadioButtonGroup();

            modes.AddRadioButton(Mode.AutoPilot, autopilotTickBox);
            modes.AddRadioButton(Mode.Manual, manualTickBox);
            modes.Selected = Mode.Manual;

            var autoPilotControls       = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.6f), paddedControlContainer.RectTransform), "InnerFrame");
            var paddedAutoPilotControls = new GUILayoutGroup(new RectTransform(new Vector2(0.8f), autoPilotControls.RectTransform, Anchor.Center))
            {
                Stretch         = true,
                RelativeSpacing = 0.03f
            };

            maintainPosTickBox = new GUITickBox(new RectTransform(new Vector2(0.2f, 0.2f), paddedAutoPilotControls.RectTransform),
                                                TextManager.Get("SteeringMaintainPos"), font: GUI.SmallFont)
            {
                Enabled    = false,
                Selected   = maintainPos,
                OnSelected = tickBox =>
                {
                    if (maintainPos != tickBox.Selected)
                    {
                        unsentChanges = true;
                        user          = Character.Controlled;
                        maintainPos   = tickBox.Selected;
                        if (maintainPos)
                        {
                            if (controlledSub == null)
                            {
                                posToMaintain = null;
                            }
                            else
                            {
                                posToMaintain = controlledSub.WorldPosition;
                            }
                        }
                        else if (!LevelEndSelected && !LevelStartSelected)
                        {
                            AutoPilot = false;
                        }
                        if (!maintainPos)
                        {
                            posToMaintain = null;
                        }
                    }
                    return(true);
                }
            };

            levelStartTickBox = new GUITickBox(new RectTransform(new Vector2(0.2f, 0.2f), paddedAutoPilotControls.RectTransform),
                                               GameMain.GameSession?.StartLocation == null ? "" : ToolBox.LimitString(GameMain.GameSession.StartLocation.Name, 20),
                                               font: GUI.SmallFont)
            {
                Enabled    = false,
                Selected   = levelStartSelected,
                OnSelected = tickBox =>
                {
                    if (levelStartSelected != tickBox.Selected)
                    {
                        unsentChanges      = true;
                        user               = Character.Controlled;
                        levelStartSelected = tickBox.Selected;
                        levelEndSelected   = !levelStartSelected;
                        if (levelStartSelected)
                        {
                            UpdatePath();
                        }
                        else if (!MaintainPos && !LevelEndSelected)
                        {
                            AutoPilot = false;
                        }
                    }
                    return(true);
                }
            };

            levelEndTickBox = new GUITickBox(new RectTransform(new Vector2(0.2f, 0.2f), paddedAutoPilotControls.RectTransform),
                                             GameMain.GameSession?.EndLocation == null ? "" : ToolBox.LimitString(GameMain.GameSession.EndLocation.Name, 20),
                                             font: GUI.SmallFont)
            {
                Enabled    = false,
                Selected   = levelEndSelected,
                OnSelected = tickBox =>
                {
                    if (levelEndSelected != tickBox.Selected)
                    {
                        unsentChanges      = true;
                        user               = Character.Controlled;
                        levelEndSelected   = tickBox.Selected;
                        levelStartSelected = !levelEndSelected;
                        if (levelEndSelected)
                        {
                            UpdatePath();
                        }
                        else if (!MaintainPos && !LevelStartSelected)
                        {
                            AutoPilot = false;
                        }
                    }
                    return(true);
                }
            };

            autoPilotControlsDisabler = new GUIFrame(new RectTransform(Vector2.One, autoPilotControls.RectTransform), "InnerFrame");

            GUIRadioButtonGroup destinations = new GUIRadioButtonGroup();

            destinations.AddRadioButton(Destination.MaintainPos, maintainPosTickBox);
            destinations.AddRadioButton(Destination.LevelStart, levelStartTickBox);
            destinations.AddRadioButton(Destination.LevelEnd, levelEndTickBox);
            destinations.Selected = maintainPos        ? Destination.MaintainPos :
                                    levelStartSelected ? Destination.LevelStart  : Destination.LevelEnd;

            string steeringVelX  = TextManager.Get("SteeringVelocityX");
            string steeringVelY  = TextManager.Get("SteeringVelocityY");
            string steeringDepth = TextManager.Get("SteeringDepth");

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), "")
            {
                TextGetter = () =>
                {
                    Vector2 vel          = controlledSub == null ? Vector2.Zero : controlledSub.Velocity;
                    var     realWorldVel = ConvertUnits.ToDisplayUnits(vel.Y * Physics.DisplayToRealWorldRatio) * 3.6f;
                    return(steeringVelY.Replace("[kph]", ((int)-realWorldVel).ToString()));
                }
            };
            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), "")
            {
                TextGetter = () =>
                {
                    Vector2 vel          = controlledSub == null ? Vector2.Zero : controlledSub.Velocity;
                    var     realWorldVel = ConvertUnits.ToDisplayUnits(vel.X * Physics.DisplayToRealWorldRatio) * 3.6f;
                    return(steeringVelX.Replace("[kph]", ((int)realWorldVel).ToString()));
                }
            };
            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), "")
            {
                TextGetter = () =>
                {
                    Vector2 pos            = controlledSub == null ? Vector2.Zero : controlledSub.Position;
                    float   realWorldDepth = Level.Loaded == null ? 0.0f : Math.Abs(pos.Y - Level.Loaded.Size.Y) * Physics.DisplayToRealWorldRatio;
                    return(steeringDepth.Replace("[m]", ((int)realWorldDepth).ToString()));
                }
            };

            pressureWarningText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), TextManager.Get("SteeringDepthWarning"), Color.Red)
            {
                Visible = false
            };

            tipContainer = new GUITextBlock(new RectTransform(new Vector2(0.25f, 0.12f), GuiFrame.RectTransform, Anchor.BottomLeft)
            {
                MinSize = new Point(150, 0), RelativeOffset = new Vector2(0.0f, -0.05f)
            }, "", wrap: true, style: "GUIToolTip")
            {
                AutoScale = true
            };

            noPowerTip = TextManager.Get("SteeringNoPowerTip");
            autoPilotMaintainPosTip = TextManager.Get("SteeringAutoPilotMaintainPosTip");
            autoPilotLevelStartTip  = TextManager.GetWithVariable("SteeringAutoPilotLocationTip", "[locationname]",
                                                                  GameMain.GameSession?.StartLocation == null ? "Start" : GameMain.GameSession.StartLocation.Name);
            autoPilotLevelEndTip = TextManager.GetWithVariable("SteeringAutoPilotLocationTip", "[locationname]",
                                                               GameMain.GameSession?.EndLocation == null ? "End" : GameMain.GameSession.EndLocation.Name);

            steerArea = new GUICustomComponent(new RectTransform(new Point(viewSize), GuiFrame.RectTransform, Anchor.CenterLeft),
                                               (spriteBatch, guiCustomComponent) => { DrawHUD(spriteBatch, guiCustomComponent.Rect); }, null);

            //docking interface ----------------------------------------------------
            dockingContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GuiFrame.RectTransform, Anchor.BottomLeft)
            {
                MinSize = new Point(150, 0), AbsoluteOffset = new Point((int)(viewSize * 0.9f), 0)
            }, style: null);
            var paddedDockingContainer = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), dockingContainer.RectTransform, Anchor.Center), style: null);

            //TODO: add new texts for these ("Dock" & "Undock")
            dockText      = TextManager.Get("captain.dock");
            undockText    = TextManager.Get("captain.undock");
            dockingButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.5f), paddedDockingContainer.RectTransform, Anchor.Center), dockText, style: "GUIButtonLarge")
            {
                OnClicked = (btn, userdata) =>
                {
                    if (GameMain.Client == null)
                    {
                        item.SendSignal(0, "1", "toggle_docking", sender: Character.Controlled);
                    }
                    else
                    {
                        dockingNetworkMessagePending = true;
                        item.CreateClientEvent(this);
                    }
                    return(true);
                }
            };
            dockingButton.Font = GUI.SmallFont;

            var leftButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.5f), paddedDockingContainer.RectTransform, Anchor.CenterLeft), "")
            {
                OnClicked = NudgeButtonClicked,
                UserData  = -Vector2.UnitX
            };

            new GUIImage(new RectTransform(new Vector2(0.7f), leftButton.RectTransform, Anchor.Center), "GUIButtonHorizontalArrow").SpriteEffects = SpriteEffects.FlipHorizontally;
            var rightButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.5f), paddedDockingContainer.RectTransform, Anchor.CenterRight), "")
            {
                OnClicked = NudgeButtonClicked,
                UserData  = Vector2.UnitX
            };

            new GUIImage(new RectTransform(new Vector2(0.7f), rightButton.RectTransform, Anchor.Center), "GUIButtonHorizontalArrow");
            var upButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.2f), paddedDockingContainer.RectTransform, Anchor.TopCenter), "")
            {
                OnClicked = NudgeButtonClicked,
                UserData  = Vector2.UnitY
            };

            new GUIImage(new RectTransform(new Vector2(0.7f), upButton.RectTransform, Anchor.Center), "GUIButtonVerticalArrow");
            var downButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.2f), paddedDockingContainer.RectTransform, Anchor.BottomCenter), "")
            {
                OnClicked = NudgeButtonClicked,
                UserData  = -Vector2.UnitY
            };

            new GUIImage(new RectTransform(new Vector2(0.7f), downButton.RectTransform, Anchor.Center), "GUIButtonVerticalArrow").SpriteEffects = SpriteEffects.FlipVertically;

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "steeringindicator":
                    steeringIndicator = new Sprite(subElement);
                    break;

                case "maintainposindicator":
                    maintainPosIndicator = new Sprite(subElement);
                    break;

                case "maintainposoriginindicator":
                    maintainPosOriginIndicator = new Sprite(subElement);
                    break;
                }
            }
        }
Ejemplo n.º 11
0
 private void ViewToolbox_Unchecked(object sender, RoutedEventArgs e)
 {
     ToolBox?.Hide();
 }
Ejemplo n.º 12
0
        private void ContextMenu_Replace()
        {
            FormatEnum fileType = PersonaFile.GameData.Type;

            OpenFileDialog OFD  = new OpenFileDialog();
            string         name = PersonaFile.Name.Replace('/', '+');

            OFD.Filter          = $"RAW(*{Path.GetExtension(name)})|*{Path.GetExtension(name)}";
            OFD.CheckFileExists = true;
            OFD.CheckPathExists = true;
            OFD.Multiselect     = false;

            if (PersonaFile.GameData is IImage)
            {
                OFD.Filter += $"|PNG (*.png)|*.png";
            }
            if (PersonaFile.GameData is ITable)
            {
                OFD.Filter += $"|XML data table (*.xml)|*.xml";
            }
            if (PersonaFile.GameData is BMD)
            {
                OFD.Filter += $"|Persona Text Project (*.ptp)|*.ptp";
            }

            if (OFD.ShowDialog() == true)
            {
                if (OFD.FilterIndex == 1)
                {
                    var item = GameFormatHelper.OpenFile(PersonaFile.Name, File.ReadAllBytes(OFD.FileName), fileType);

                    if (item != null)
                    {
                        PersonaFile.GameData = item.GameData;
                    }
                }
                else
                {
                    string ext = Path.GetExtension(OFD.FileName);
                    if (ext.Equals(".png", StringComparison.CurrentCultureIgnoreCase))
                    {
                        PersonaEditorTools.OpenImageFile(PersonaFile, OFD.FileName);
                    }
                    else if (ext.Equals(".xml", StringComparison.CurrentCultureIgnoreCase))
                    {
                        PersonaEditorTools.OpenTableFile(PersonaFile, OFD.FileName);
                    }
                    else if (ext.Equals(".ptp", StringComparison.CurrentCultureIgnoreCase))
                    {
                        var result = ToolBox.Show(ToolBoxType.OpenPTP);
                        if (result == ToolBoxResult.Ok)
                        {
                            PersonaEditorTools.OpenPTPFile(PersonaFile, OFD.FileName, Static.EncodingManager.GetPersonaEncoding(ApplicationSettings.AppSetting.Default.OpenPTP_Font));
                        }
                    }
                    else
                    {
                        throw new Exception("OpenPersonaFileDialog");
                    }
                }

                Update(_personaFile);
                if (_isSelected)
                {
                    ItemAction?.Invoke(this, UserTreeViewItemEventEnum.Selected);
                }
            }
        }
Ejemplo n.º 13
0
        public static void ServerRead(NetIncomingMessage msg, Client c)
        {
            UInt16 ID  = msg.ReadUInt16();
            string txt = msg.ReadString();

            if (txt == null)
            {
                txt = "";
            }

            if (!NetIdUtils.IdMoreRecent(ID, c.lastSentChatMsgID))
            {
                return;
            }

            c.lastSentChatMsgID = ID;

            if (txt.Length > MaxLength)
            {
                txt = txt.Substring(0, MaxLength);
            }

            c.lastSentChatMessages.Add(txt);
            if (c.lastSentChatMessages.Count > 10)
            {
                c.lastSentChatMessages.RemoveRange(0, c.lastSentChatMessages.Count - 10);
            }

            float similarity = 0.0f;

            for (int i = 0; i < c.lastSentChatMessages.Count; i++)
            {
                float closeFactor     = 1.0f / (c.lastSentChatMessages.Count - i);
                int   levenshteinDist = ToolBox.LevenshteinDistance(txt, c.lastSentChatMessages[i]);
                similarity += Math.Max((txt.Length - levenshteinDist) / (float)txt.Length * closeFactor, 0.0f);
            }

            if (similarity + c.ChatSpamSpeed > 5.0f)
            {
                c.ChatSpamCount++;

                if (c.ChatSpamCount > 3)
                {
                    //kick for spamming too much
                    GameMain.Server.KickClient(c);
                }
                else
                {
                    ChatMessage denyMsg = ChatMessage.Create("", "You have been blocked by the spam filter. Try again after 10 seconds.", ChatMessageType.Server, null);
                    c.ChatSpamTimer = 10.0f;
                    GameMain.Server.SendChatMessage(denyMsg, c);
                }
                return;
            }

            c.ChatSpamSpeed += similarity + 0.5f;

            if (c.ChatSpamTimer > 0.0f)
            {
                ChatMessage denyMsg = ChatMessage.Create("", "You have been blocked by the spam filter. Try again after 10 seconds.", ChatMessageType.Server, null);
                c.ChatSpamTimer = 10.0f;
                GameMain.Server.SendChatMessage(denyMsg, c);
                return;
            }

            GameMain.Server.SendChatMessage(txt, null, c);
        }
Ejemplo n.º 14
0
        private void ContextMenu_SaveAs()
        {
            SaveFileDialog SFD = new SaveFileDialog();

            SFD.OverwritePrompt = true;
            SFD.AddExtension    = false;
            SFD.FileName        = PersonaFile.Name.Replace('/', '+');
            SFD.Filter          = $"RAW(*{Path.GetExtension(SFD.FileName)})|*{Path.GetExtension(SFD.FileName)}";

            if (PersonaFile.GameData is IImage)
            {
                SFD.Filter += $"|PNG (*.png)|*.png";
            }
            if (PersonaFile.GameData is ITable)
            {
                SFD.Filter += $"|XML data table (*.xml)|*.xml";
            }
            if (PersonaFile.GameData is BMD)
            {
                SFD.Filter += $"|Persona Text Project (*.ptp)|*.ptp";
            }
            if (PersonaFile.GameData is PTP)
            {
                SFD.Filter += $"|BMD Text File (*.bmd)|*.bmd";
            }

            SFD.InitialDirectory = Path.GetDirectoryName(Static.OpenedFile);
            if (SFD.ShowDialog() == true)
            {
                if (SFD.FilterIndex == 1)
                {
                    File.WriteAllBytes(SFD.FileName, PersonaFile.GameData.GetData());
                }
                else
                {
                    string ext = Path.GetExtension(SFD.FileName);
                    if (ext.Equals(".png", StringComparison.CurrentCultureIgnoreCase))
                    {
                        PersonaEditorCMD.PersonaEditorTools.SaveImageFile(PersonaFile, SFD.FileName);
                    }
                    else if (ext.Equals(".ptp", StringComparison.CurrentCultureIgnoreCase))
                    {
                        var result = ToolBox.Show(ToolBoxType.SaveAsPTP);
                        if (result == ToolBoxResult.Ok)
                        {
                            PersonaEncoding temp = ApplicationSettings.AppSetting.Default.SaveAsPTP_CO2N ? Static.EncodingManager.GetPersonaEncoding(ApplicationSettings.AppSetting.Default.SaveAsPTP_Font) : null;
                            PersonaEditorCMD.PersonaEditorTools.SavePTPFile(PersonaFile, SFD.FileName, temp);
                        }
                    }
                    else if (ext.Equals(".bmd", StringComparison.CurrentCultureIgnoreCase))
                    {
                        Encoding encoding = Static.EncodingManager.GetPersonaEncoding(ApplicationSettings.AppSetting.Default.PTPNewDefault);
                        BMD      bmd      = new BMD(PersonaFile.GameData as PTP, encoding);
                        File.WriteAllBytes(SFD.FileName, bmd.GetData());
                    }
                    else if (ext.Equals(".xml", StringComparison.CurrentCultureIgnoreCase))
                    {
                        PersonaEditorCMD.PersonaEditorTools.SaveTableFile(PersonaFile, SFD.FileName);
                    }
                    else
                    {
                        throw new Exception("SavePersonaFileDialog");
                    }
                }
            }
        }
Ejemplo n.º 15
0
        private bool SelectItem(Character user, FabricationRecipe selectedItem)
        {
            selectedItemFrame.ClearChildren();

            var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), selectedItemFrame.RectTransform, Anchor.Center))
            {
                RelativeSpacing = 0.03f, Stretch = true
            };

            /*var itemIcon = selectedItem.TargetItem.InventoryIcon ?? selectedItem.TargetItem.sprite;
             * if (itemIcon != null)
             * {
             *  GUIImage img = new GUIImage(new RectTransform(new Point(40, 40), paddedFrame.RectTransform),
             *      itemIcon, scaleToFit: true)
             *  {
             *      Color = selectedItem.TargetItem.InventoryIconColor
             *  };
             * }*/
            var nameBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
                                             selectedItem.TargetItem.Name, textAlignment: Alignment.CenterLeft);

            if (!string.IsNullOrWhiteSpace(selectedItem.TargetItem.Description))
            {
                var description = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
                                                   selectedItem.TargetItem.Description,
                                                   font: GUI.SmallFont, wrap: true);
                if (description.Rect.Height > paddedFrame.Rect.Height * 0.4f)
                {
                    description.Wrap  = false;
                    description.Text  = description.WrappedText.Split('\n').First() + "...";
                    nameBlock.ToolTip = description.ToolTip = selectedItem.TargetItem.Description;
                    description.RectTransform.MaxSize = new Point(int.MaxValue, (int)description.Font.MeasureString(description.Text).Y);
                }
            }

            List <Skill> inadequateSkills = new List <Skill>();

            if (user != null)
            {
                inadequateSkills = selectedItem.RequiredSkills.FindAll(skill => user.GetSkillLevel(skill.Identifier) < skill.Level);
            }

            if (selectedItem.RequiredSkills.Any())
            {
                string text = TextManager.Get("FabricatorRequiredSkills") + ":\n";
                foreach (Skill skill in selectedItem.RequiredSkills)
                {
                    text += "   - " + TextManager.Get("SkillName." + skill.Identifier) + " " + TextManager.Get("Lvl").ToLower() + " " + skill.Level;
                    if (skill != selectedItem.RequiredSkills.Last())
                    {
                        text += "\n";
                    }
                }
                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), text,
                                 textColor: inadequateSkills.Any() ? Color.Red : Color.LightGreen, font: GUI.SmallFont);
            }

            float degreeOfSuccess = user == null ? 0.0f : DegreeOfSuccess(user, selectedItem.RequiredSkills);

            if (degreeOfSuccess > 0.5f)
            {
                degreeOfSuccess = 1.0f;
            }

            float  requiredTime     = user == null ? selectedItem.RequiredTime : GetRequiredTime(selectedItem, user);
            string requiredTimeText = TextManager.Get("FabricatorRequiredTime") + ": " + ToolBox.SecondsToReadableTime(requiredTime);

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
                             requiredTimeText, textColor: ToolBox.GradientLerp(degreeOfSuccess, Color.Red, Color.Yellow, Color.LightGreen), font: GUI.SmallFont);

            return(true);
        }
Ejemplo n.º 16
0
        private static void Main(string[] args)
        {
            // Register exit handler
            Console.CancelKeyPress += new ConsoleCancelEventHandler(KeyHandler);

            cmd = ParseArgs(args);
#if !DEBUG
            if (cmd.type == CommandType.None)
            {
                PrintHelpMessage();
                return;
            }
#else
            inputFile         = "avatars.txt";
            cmd.type          = CommandType.Download;
            cmd.ignoreDeleted = true;
#endif

            Debug.LogText("[INFO      ] Opening database...\t\t\t");
            database = new OldVrcDb();
            if (!database.Open($"URI=file:{Directory.GetCurrentDirectory()}\\data.db"))
            {
                Debug.LogLine("ERROR", ConsoleColor.Red);
                return;
            }
            Debug.LogLine("Done.", ConsoleColor.Green);

            Debug.LogText("[INFO      ] Initializing database...\t\t\t");
            if (!database.Init())
            {
                Debug.LogLine("ERROR", ConsoleColor.Red);
                database.Close();
                return;
            }
            Debug.LogLine("Done.", ConsoleColor.Green);

            client = new ApiClient();

            var idsToDownload = new List <VrcId>();

            // Read database
            {
                Debug.LogText("[INFO      ] Reading ids from database...\t\t");
                var ids = cmd.ignoreDeleted ? database.GetAllIds(false) : database.GetAllIds();
                Debug.LogLine($"Got {ids.Length} ids", ConsoleColor.Green);
                downloadedAssets.AddRange(ids);
            }

            if (cmd.type == CommandType.ExtractIds)
            {
                File.WriteAllLines("extractedids.txt", downloadedAssets.Select(i => i.ToString()));
                foreach (var id in downloadedAssets)
                {
                    Console.WriteLine(id);
                }

                return;
            }

            {
                Debug.LogText("[INFO      ] Reading deleted ids from database...\t");
                var ids = database.GetAllIds(true);
                Debug.LogLine($"Got {ids.Length} ids", ConsoleColor.Green);
                inactiveIds.AddRange(ids);
            }

            if (cmd.type == CommandType.Download)
            {
                // Read input avatar list
                Debug.LogText($"[INFO      ] Reading file...\t\t\t\t");
                string text = File.ReadAllText(inputFile);
                Debug.LogLine($"Read {ToolBox.FormatLog((ulong)text.Length, 'B')}", ConsoleColor.Green);


                Debug.LogText("[INFO      ] Parsing file...\t\t\t\t");
                if (!RipperTools.TryGetVrcIdList(text, out var ids))
                {
                    Debug.LogLine("ERROR", ConsoleColor.Red);
                    PrintHelpMessage();
                    Cleanup();
                    return;
                }
                Debug.LogLine($"Got {ids.Length} ids", ConsoleColor.Green);

                Debug.LogText("[INFO      ] Queueing ids...\t\t\t\t");
                idsToDownload.AddRange(ids);
                Debug.LogLine("Done.", ConsoleColor.Green);

                Debug.LogText("[INFO      ] Removing known ids...\t\t\t");
                idsToDownload = idsToDownload.Except(downloadedAssets).Except(inactiveIds).ToList();
                Debug.LogLine("Done.", ConsoleColor.Green);
            }
            else if (cmd.type == CommandType.Update)
            {
                idsToDownload.AddRange(downloadedAssets);
            }
            else if (cmd.type == CommandType.Refresh)
            {
                idsToDownload.AddRange(downloadedAssets);
                downloadedAssets.Clear();
            }


            Debug.LogText("[INFO      ] Removing duplicates...\t\t\t");
            inactiveIds      = inactiveIds.Distinct().ToList();
            idsToDownload    = idsToDownload.Distinct().ToList();
            downloadedAssets = downloadedAssets.Distinct().ToList();
            Debug.LogLine("Done.", ConsoleColor.Green);

            // TODO IMPLEMENTME: currently just lists found vrchat ids
            if (cmd.type == CommandType.Attach)
            {
                while (!CleanupDone())
                {
                    if (RipperTools.TryGetVrcCacheEntries(true, out var entries))
                    {
                        entries.RemoveAll(m => downloadedAssets.Contains(m.id));

                        foreach (var entry in entries)
                        {
                            Debug.LogLine(entry.id.ToString());
                            downloadedAssets.Add(entry.id);
                        }

                        Thread.Sleep(libParseDelayTimeInMs);
                    }
                    else
                    {
                        Thread.Sleep(libCheckDelayTimeInMs);
                    }
                }
            }
            else
            {
                Debug.LogText("[INFO      ] Starting requets...\t\t\t");
                Debug.LogLine($"{idsToDownload.Count} ids queued", ConsoleColor.Green);
                foreach (var id in idsToDownload)
                {
                    if (CleanupDone())
                    {
                        break;
                    }

                    try
                    {
                        switch (id.IdType)
                        {
                        case VrcId.VrcIdType.Avatar:
                            client.GetAvatarById(id, RipAvatar, DisableId);
                            Thread.Sleep(apiDelayTimeInMs);
                            break;

                        case VrcId.VrcIdType.World:
                            client.GetWorldById(id, RipWorld, DisableId);
                            Thread.Sleep(apiDelayTimeInMs);
                            break;

                        case VrcId.VrcIdType.User:
                        case VrcId.VrcIdType.LegacyUser:
                            //database.AddUser();
                            //Thread.Sleep(apiDelayTimeInMs);
                            break;

                        default:
                            Debug.LogLine($"[UNPARSABLE] Skipping {id}", ConsoleColor.Yellow);
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.LogLine($"[EXCEPTION ] Failed to get {id}:\n\t{ex.Message}", ConsoleColor.Red, false, true);
                        break;
                    }
                }
            }
            // Exit after all processes are done
            protector.ExitAfterProcs();
            Cleanup();
        }
Ejemplo n.º 17
0
        private bool SelectItem(Character user, FabricationRecipe selectedItem)
        {
            selectedItemFrame.ClearChildren();
            selectedItemReqsFrame.ClearChildren();

            var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.9f), selectedItemFrame.RectTransform, Anchor.Center))
            {
                RelativeSpacing = 0.03f
            };
            var paddedReqFrame = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.9f), selectedItemReqsFrame.RectTransform, Anchor.Center))
            {
                RelativeSpacing = 0.03f
            };

            /*var itemIcon = selectedItem.TargetItem.InventoryIcon ?? selectedItem.TargetItem.sprite;
             * if (itemIcon != null)
             * {
             *  GUIImage img = new GUIImage(new RectTransform(new Point(40, 40), paddedFrame.RectTransform),
             *      itemIcon, scaleToFit: true)
             *  {
             *      Color = selectedItem.TargetItem.InventoryIconColor
             *  };
             * }*/
            var nameBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
                                             selectedItem.TargetItem.Name, textAlignment: Alignment.CenterLeft, textColor: Color.Aqua, font: GUI.SubHeadingFont)
            {
                AutoScaleHorizontal = true
            };

            nameBlock.Padding = new Vector4(0, nameBlock.Padding.Y, nameBlock.Padding.Z, nameBlock.Padding.W);

            if (!string.IsNullOrWhiteSpace(selectedItem.TargetItem.Description))
            {
                var description = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
                                                   selectedItem.TargetItem.Description,
                                                   font: GUI.SmallFont, wrap: true);
                description.Padding = new Vector4(0, description.Padding.Y, description.Padding.Z, description.Padding.W);

                while (description.Rect.Height + nameBlock.Rect.Height > paddedFrame.Rect.Height)
                {
                    var lines     = description.WrappedText.Split('\n');
                    var newString = string.Join('\n', lines.Take(lines.Length - 1));
                    description.Text = newString.Substring(0, newString.Length - 4) + "...";
                    description.CalculateHeightFromText();
                    description.ToolTip = selectedItem.TargetItem.Description;
                }
            }

            List <Skill> inadequateSkills = new List <Skill>();

            if (user != null)
            {
                inadequateSkills = selectedItem.RequiredSkills.FindAll(skill => user.GetSkillLevel(skill.Identifier) < skill.Level);
            }

            if (selectedItem.RequiredSkills.Any())
            {
                string text = "";
                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedReqFrame.RectTransform),
                                 TextManager.Get("FabricatorRequiredSkills"), textColor: inadequateSkills.Any() ? GUI.Style.Red : GUI.Style.Green, font: GUI.SubHeadingFont)
                {
                    AutoScaleHorizontal = true,
                };
                foreach (Skill skill in selectedItem.RequiredSkills)
                {
                    text += TextManager.Get("SkillName." + skill.Identifier) + " " + TextManager.Get("Lvl").ToLower() + " " + skill.Level;
                    if (skill != selectedItem.RequiredSkills.Last())
                    {
                        text += "\n";
                    }
                }
                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedReqFrame.RectTransform), text, font: GUI.SmallFont);
            }

            float degreeOfSuccess = user == null ? 0.0f : DegreeOfSuccess(user, selectedItem.RequiredSkills);

            if (degreeOfSuccess > 0.5f)
            {
                degreeOfSuccess = 1.0f;
            }

            float requiredTime = user == null ? selectedItem.RequiredTime : GetRequiredTime(selectedItem, user);

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedReqFrame.RectTransform),
                             TextManager.Get("FabricatorRequiredTime"), textColor: ToolBox.GradientLerp(degreeOfSuccess, GUI.Style.Red, Color.Yellow, GUI.Style.Green), font: GUI.SubHeadingFont)
            {
                AutoScaleHorizontal = true,
            };

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedReqFrame.RectTransform), ToolBox.SecondsToReadableTime(requiredTime),
                             font: GUI.SmallFont);
            return(true);
        }
Ejemplo n.º 18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            EChart chart = EChartsCtrl1.chart;

            chart.IsExtendMap = true;
            chart.SVGPath     = "svg/jinzhongBuilding.svg";
            Title title = new Title();

            title.Text            = "测试用";
            title.TextStyle       = new TextStyle();
            title.TextStyle.Color = Color.Aqua;

            chart.SetTitle(title);

            Legend legend = new Legend();

            legend.BackgroundColor = Color.AntiqueWhite;
            legend.Data            = new string[] { "group1" };

            chart.SetLegend(legend);

            chart.SetColor(new Color[] { Color.Blue });

            ToolBox tb = new ToolBox();

            tb.Show              = true;
            tb.Feature           = new Option.ToolBoxButton.Feature();
            tb.Feature.Mark      = new Option.ToolBoxButton.Mark();
            tb.Feature.Mark.Show = true;

            tb.Feature.Restore      = new Option.ToolBoxButton.Restore();
            tb.Feature.Restore.Show = true;

            tb.Feature.SaveAsImage      = new Option.ToolBoxButton.SaveAsImage();
            tb.Feature.SaveAsImage.Show = true;
            chart.SetToolBox(tb);

            wwb.ECharts.Option.ToolTip tt = new wwb.ECharts.Option.ToolTip();
            tt.Trigger   = TriggerType.Item;
            tt.Formatter = new StringFormatter("{b}");
            chart.SetToolTip(tt);



            Series s1 = new Series();

            s1.Data                          = new string[0];
            s1.Name                          = "group1";
            s1.ItemStyle                     = new ItemStyle();
            s1.ItemStyle.Normal              = new Normal();
            s1.ItemStyle.Normal.Color        = Color.Gold;
            s1.ItemStyle.Normal.Label        = new wwb.ECharts.Option.Label();
            s1.ItemStyle.Normal.Label.Show   = true;
            s1.ItemStyle.Emphasis            = new Emphasis();
            s1.ItemStyle.Emphasis.Label      = new wwb.ECharts.Option.Label();
            s1.ItemStyle.Emphasis.Label.Show = true;
            s1.Type                          = EChartsTypes.Map;
            s1.Roam                          = true;
            s1.MarkPoint                     = new MarkPoint();
            s1.MarkPoint.Symbol              = SymbolType.Circle;
            s1.MarkPoint.SymbolSize          = 3;

            List <MarkPointDataItem> list = new List <MarkPointDataItem>();

            list.Add(new MarkPointDataItem("张三", 44, 71));
            list.Add(new MarkPointDataItem("李四", 84, 71));

            s1.MarkPoint.Data = list.ToArray();

            s1.MarkLine                                 = new MarkLine();
            s1.MarkLine.Effect                          = new Effect();
            s1.MarkLine.Effect.Show                     = true;
            s1.MarkLine.Effect.Loop                     = true;
            s1.MarkLine.Effect.Color                    = Color.HotPink;
            s1.MarkLine.Symbol                          = new SymbolType[] { SymbolType.Circle, SymbolType.Arrow };
            s1.MarkLine.ItemStyle                       = new ItemStyle();
            s1.MarkLine.ItemStyle.Normal                = new Normal();
            s1.MarkLine.ItemStyle.Normal.BorderWidth    = 1;
            s1.MarkLine.ItemStyle.Normal.LineStyle      = new LineStyle();
            s1.MarkLine.ItemStyle.Normal.LineStyle.Type = LineStyleType.Solid;

            //List<MarkLineDataItem> lineList = new List<MarkLineDataItem>();
            //lineList.Add(new MarkLineDataItem(new MarkPointDataItem("A", 88, 222), new MarkPointDataItem("B", 44, 232)));
            //s1.MarkLine.Data = lineList.ToArray();
            MarkPointDataItem[,] lineArr =
            {
                { new MarkPointDataItem("A",  88, 222), new MarkPointDataItem("B",  44, 232) },
                { new MarkPointDataItem("C", 123, 222), new MarkPointDataItem("D", 123, 282) }
            };
            s1.MarkLine.Data = lineArr;


            Series s2 = new Series();

            s2.Data                       = new string[0];
            s2.Type                       = EChartsTypes.Map;
            s2.MarkPoint                  = new MarkPoint();
            s2.MarkPoint.Effect           = new Effect();
            s2.MarkPoint.Effect.Show      = true;
            s2.MarkPoint.Effect.ScaleSize = 8;
            s2.MarkPoint.Effect.Color     = Color.DeepSkyBlue;
            s2.MarkPoint.Data             = (new List <MarkPointDataItem>()
            {
                new MarkPointDataItem("MMM", 33, 99), new MarkPointDataItem("aaaaaaaa", 66, 123)
            }).ToArray();
            s2.MarkPoint.Symbol           = SymbolType.EmptyDiamond;
            List <Series> slist = new List <Series>();

            slist.Add(s1);
            slist.Add(s2);
            chart.SetSeries(slist.ToArray());
        }
Ejemplo n.º 19
0
 private void ViewToolbox_Checked(object sender, RoutedEventArgs e)
 {
     ToolBox?.Show();
 }
Ejemplo n.º 20
0
        public void CreatePreviewWindow(GUIFrame frame)
        {
            frame.ClearChildren();

            if (frame == null)
            {
                return;
            }

            var previewContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.98f), frame.RectTransform, Anchor.Center))
            {
                Stretch = true
            };

            var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), previewContainer.RectTransform, Anchor.CenterLeft), ServerName, font: GUI.LargeFont)
            {
                ToolTip = ServerName
            };

            title.Text = ToolBox.LimitString(title.Text, title.Font, (int)(title.Rect.Width * 0.85f));

            GUITickBox favoriteTickBox = new GUITickBox(new RectTransform(new Vector2(0.15f, 0.8f), title.RectTransform, Anchor.CenterRight),
                                                        "", null, "GUIServerListFavoriteTickBox")
            {
                Selected   = Favorite,
                ToolTip    = TextManager.Get(Favorite ? "removefromfavorites" : "addtofavorites"),
                OnSelected = (tickbox) =>
                {
                    if (tickbox.Selected)
                    {
                        GameMain.ServerListScreen.AddToFavoriteServers(this);
                    }
                    else
                    {
                        GameMain.ServerListScreen.RemoveFromFavoriteServers(this);
                    }
                    tickbox.ToolTip = TextManager.Get(tickbox.Selected ? "removefromfavorites" : "addtofavorites");
                    return(true);
                }
            };

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), previewContainer.RectTransform),
                             TextManager.AddPunctuation(':', TextManager.Get("ServerListVersion"), string.IsNullOrEmpty(GameVersion) ? TextManager.Get("Unknown") : GameVersion));

            PlayStyle playStyle = PlayStyle ?? Networking.PlayStyle.Serious;

            Sprite playStyleBannerSprite      = ServerListScreen.PlayStyleBanners[(int)playStyle];
            float  playStyleBannerAspectRatio = playStyleBannerSprite.SourceRect.Width / playStyleBannerSprite.SourceRect.Height;
            var    playStyleBanner            = new GUIImage(new RectTransform(new Point(previewContainer.Rect.Width, (int)(previewContainer.Rect.Width / playStyleBannerAspectRatio)), previewContainer.RectTransform),
                                                             playStyleBannerSprite, null, true);

            var playStyleName = new GUITextBlock(new RectTransform(new Vector2(0.15f, 0.0f), playStyleBanner.RectTransform)
            {
                RelativeOffset = new Vector2(0.01f, 0.06f)
            },
                                                 TextManager.AddPunctuation(':', TextManager.Get("serverplaystyle"), TextManager.Get("servertag." + playStyle)), textColor: Color.White,
                                                 font: GUI.SmallFont, textAlignment: Alignment.Center,
                                                 color: ServerListScreen.PlayStyleColors[(int)playStyle], style: "GUISlopedHeader");

            playStyleName.RectTransform.NonScaledSize = (playStyleName.Font.MeasureString(playStyleName.Text) + new Vector2(20, 5) * GUI.Scale).ToPoint();
            playStyleName.RectTransform.IsFixedSize   = true;

            var content = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.6f), previewContainer.RectTransform))
            {
                Stretch = true
            };
            // playstyle tags -----------------------------------------------------------------------------

            var playStyleContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), content.RectTransform), isHorizontal: true)
            {
                Stretch         = true,
                RelativeSpacing = 0.01f,
                CanBeFocused    = true
            };

            var playStyleTags = GetPlayStyleTags();

            foreach (string tag in playStyleTags)
            {
                if (!ServerListScreen.PlayStyleIcons.ContainsKey(tag))
                {
                    continue;
                }

                new GUIImage(new RectTransform(Vector2.One, playStyleContainer.RectTransform),
                             ServerListScreen.PlayStyleIcons[tag], scaleToFit: true)
                {
                    ToolTip = TextManager.Get("servertagdescription." + tag),
                    Color   = ServerListScreen.PlayStyleIconColors[tag]
                };
            }

            playStyleContainer.Recalculate();

            // -----------------------------------------------------------------------------

            float elementHeight = 0.075f;

            // Spacing
            new GUIFrame(new RectTransform(new Vector2(1.0f, 0.025f), content.RectTransform), style: null);

            var serverMsg = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform))
            {
                ScrollBarVisible = true
            };
            var msgText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverMsg.Content.RectTransform), ServerMessage, font: GUI.SmallFont, wrap: true)
            {
                CanBeFocused = false
            };

            serverMsg.Content.RectTransform.SizeChanged += () => { msgText.CalculateHeightFromText(); };
            msgText.RectTransform.SizeChanged           += () => { serverMsg.UpdateScrollBarSize(); };

            var gameMode = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), content.RectTransform), TextManager.Get("GameMode"));

            new GUITextBlock(new RectTransform(Vector2.One, gameMode.RectTransform),
                             TextManager.Get(string.IsNullOrEmpty(GameMode) ? "Unknown" : "GameMode." + GameMode, returnNull: true) ?? GameMode,
                             textAlignment: Alignment.Right);

            /*var traitors = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), bodyContainer.RectTransform), TextManager.Get("Traitors"));
             * new GUITextBlock(new RectTransform(Vector2.One, traitors.RectTransform), TextManager.Get(!TraitorsEnabled.HasValue ? "Unknown" : TraitorsEnabled.Value.ToString()), textAlignment: Alignment.Right);*/

            var subSelection = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), content.RectTransform), TextManager.Get("ServerListSubSelection"));

            new GUITextBlock(new RectTransform(Vector2.One, subSelection.RectTransform), TextManager.Get(!SubSelectionMode.HasValue ? "Unknown" : SubSelectionMode.Value.ToString()), textAlignment: Alignment.Right);

            var modeSelection = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), content.RectTransform), TextManager.Get("ServerListModeSelection"));

            new GUITextBlock(new RectTransform(Vector2.One, modeSelection.RectTransform), TextManager.Get(!ModeSelectionMode.HasValue ? "Unknown" : ModeSelectionMode.Value.ToString()), textAlignment: Alignment.Right);

            if (gameMode.TextSize.X + gameMode.GetChild <GUITextBlock>().TextSize.X > gameMode.Rect.Width ||
                subSelection.TextSize.X + subSelection.GetChild <GUITextBlock>().TextSize.X > subSelection.Rect.Width ||
                modeSelection.TextSize.X + modeSelection.GetChild <GUITextBlock>().TextSize.X > modeSelection.Rect.Width)
            {
                gameMode.Font = subSelection.Font = modeSelection.Font = GUI.SmallFont;
                gameMode.GetChild <GUITextBlock>().Font = subSelection.GetChild <GUITextBlock>().Font = modeSelection.GetChild <GUITextBlock>().Font = GUI.SmallFont;
            }

            var allowSpectating = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), content.RectTransform), TextManager.Get("ServerListAllowSpectating"))
            {
                CanBeFocused = false
            };

            if (!AllowSpectating.HasValue)
            {
                new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), allowSpectating.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center);
            }
            else
            {
                allowSpectating.Selected = AllowSpectating.Value;
            }

            var allowRespawn = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), content.RectTransform), TextManager.Get("ServerSettingsAllowRespawning"))
            {
                CanBeFocused = false
            };

            if (!AllowRespawn.HasValue)
            {
                new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), allowRespawn.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center);
            }
            else
            {
                allowRespawn.Selected = AllowRespawn.Value;
            }

            /*var voipEnabledTickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), bodyContainer.RectTransform), TextManager.Get("serversettingsvoicechatenabled"))
             * {
             *  CanBeFocused = false
             * };
             * if (!VoipEnabled.HasValue)
             *  new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), voipEnabledTickBox.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center);
             * else
             *  voipEnabledTickBox.Selected = VoipEnabled.Value;*/

            var usingWhiteList = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), content.RectTransform), TextManager.Get("ServerListUsingWhitelist"))
            {
                CanBeFocused = false
            };

            if (!UsingWhiteList.HasValue)
            {
                new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), usingWhiteList.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center);
            }
            else
            {
                usingWhiteList.Selected = UsingWhiteList.Value;
            }


            content.RectTransform.SizeChanged += () =>
            {
                GUITextBlock.AutoScaleAndNormalize(allowSpectating.TextBlock, allowRespawn.TextBlock, usingWhiteList.TextBlock);
            };

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform),
                             TextManager.Get("ServerListContentPackages"), textAlignment: Alignment.Center, font: GUI.SubHeadingFont);

            var contentPackageList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), content.RectTransform))
            {
                ScrollBarVisible = true
            };

            if (ContentPackageNames.Count == 0)
            {
                new GUITextBlock(new RectTransform(Vector2.One, contentPackageList.Content.RectTransform), TextManager.Get("Unknown"), textAlignment: Alignment.Center)
                {
                    CanBeFocused = false
                };
            }
            else
            {
                List <string> availableWorkshopUrls = new List <string>();
                for (int i = 0; i < ContentPackageNames.Count; i++)
                {
                    var packageText = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.15f), contentPackageList.Content.RectTransform)
                    {
                        MinSize = new Point(0, 15)
                    },
                                                     ContentPackageNames[i])
                    {
                        Enabled = false
                    };
                    if (i < ContentPackageHashes.Count)
                    {
                        if (GameMain.Config.SelectedContentPackages.Any(cp => cp.MD5hash.Hash == ContentPackageHashes[i]))
                        {
                            packageText.Selected = true;
                            continue;
                        }

                        //matching content package found, but it hasn't been enabled
                        if (ContentPackage.List.Any(cp => cp.MD5hash.Hash == ContentPackageHashes[i]))
                        {
                            packageText.TextColor = GUI.Style.Orange;
                            packageText.ToolTip   = TextManager.GetWithVariable("ServerListContentPackageNotEnabled", "[contentpackage]", ContentPackageNames[i]);
                        }
                        //workshop download link found
                        else if (i < ContentPackageWorkshopUrls.Count && !string.IsNullOrEmpty(ContentPackageWorkshopUrls[i]))
                        {
                            availableWorkshopUrls.Add(ContentPackageWorkshopUrls[i]);
                            packageText.TextColor = Color.Yellow;
                            packageText.ToolTip   = TextManager.GetWithVariable("ServerListIncompatibleContentPackageWorkshopAvailable", "[contentpackage]", ContentPackageNames[i]);
                        }
                        else //no package or workshop download link found, tough luck
                        {
                            packageText.TextColor = GUI.Style.Red;
                            packageText.ToolTip   = TextManager.GetWithVariables("ServerListIncompatibleContentPackage",
                                                                                 new string[2] {
                                "[contentpackage]", "[hash]"
                            }, new string[2] {
                                ContentPackageNames[i], ContentPackageHashes[i]
                            });
                        }
                    }
                }
                if (availableWorkshopUrls.Count > 0)
                {
                    var workshopBtn = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), content.RectTransform), TextManager.Get("ServerListSubscribeMissingPackages"))
                    {
                        ToolTip   = TextManager.Get(SteamManager.IsInitialized ? "ServerListSubscribeMissingPackagesTooltip" : "ServerListSubscribeMissingPackagesTooltipNoSteam"),
                        Enabled   = SteamManager.IsInitialized,
                        OnClicked = (btn, userdata) =>
                        {
                            GameMain.SteamWorkshopScreen.SubscribeToPackages(availableWorkshopUrls);
                            GameMain.SteamWorkshopScreen.Select();
                            return(true);
                        }
                    };
                    workshopBtn.TextBlock.AutoScaleHorizontal = true;
                }
            }

            // -----------------------------------------------------------------------------

            foreach (GUIComponent c in content.Children)
            {
                if (c is GUITextBlock textBlock)
                {
                    textBlock.Padding = Vector4.Zero;
                }
            }
        }
Ejemplo n.º 21
0
        protected GUIComponent CreateInfoFrame(string title, string text, int width = 300, int height = 80, string anchorStr = "", bool hasButton = false, Action callback = null, Action showVideo = null)
        {
            if (hasButton)
            {
                height += 60;
            }

            Anchor anchor = Anchor.TopRight;

            if (anchorStr != string.Empty)
            {
                Enum.TryParse(anchorStr, out anchor);
            }

            width  = (int)(width * GUI.Scale);
            height = (int)(height * GUI.Scale);

            string wrappedText = ToolBox.WrapText(text, width, GUI.Font);

            height += (int)GUI.Font.MeasureString(wrappedText).Y;

            if (title.Length > 0)
            {
                height += (int)GUI.Font.MeasureString(title).Y + (int)(150 * GUI.Scale);
            }

            var background = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center), style: "GUIBackgroundBlocker");

            var infoBlock = new GUIFrame(new RectTransform(new Point(width, height), background.RectTransform, anchor));

            infoBlock.Flash(GUI.Style.Green);

            var infoContent = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), infoBlock.RectTransform, Anchor.Center))
            {
                Stretch         = true,
                AbsoluteSpacing = 5
            };

            if (title.Length > 0)
            {
                var titleBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContent.RectTransform),
                                                  title, font: GUI.LargeFont, textAlignment: Alignment.Center, textColor: new Color(253, 174, 0));
                titleBlock.RectTransform.IsFixedSize = true;
            }

            List <RichTextData> richTextData = RichTextData.GetRichTextData(text, out text);
            GUITextBlock        textBlock;

            if (richTextData == null)
            {
                textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContent.RectTransform), " " + text, wrap: true);
            }
            else
            {
                textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContent.RectTransform), richTextData, " " + text, wrap: true);
            }

            textBlock.RectTransform.IsFixedSize = true;
            infoBoxClosedCallback = callback;

            if (hasButton)
            {
                var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), infoContent.RectTransform), isHorizontal: true)
                {
                    RelativeSpacing = 0.1f
                };
                buttonContainer.RectTransform.IsFixedSize = true;

                if (showVideo != null)
                {
                    buttonContainer.Stretch = true;
                    var videoButton = new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), buttonContainer.RectTransform),
                                                    TextManager.Get("Video"), style: "GUIButtonLarge")
                    {
                        OnClicked = (GUIButton button, object obj) =>
                        {
                            showVideo();
                            return(true);
                        }
                    };
                }
                else
                {
                    buttonContainer.Stretch     = false;
                    buttonContainer.ChildAnchor = Anchor.Center;
                }

                var okButton = new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), buttonContainer.RectTransform),
                                             TextManager.Get("OK"), style: "GUIButtonLarge")
                {
                    OnClicked = CloseInfoFrame
                };
            }

            infoBlock.RectTransform.NonScaledSize = new Point(infoBlock.Rect.Width, (int)(infoContent.Children.Sum(c => c.Rect.Height + infoContent.AbsoluteSpacing) / infoContent.RectTransform.RelativeSize.Y));

            GUI.PlayUISound(GUISoundType.UIMessage);

            return(background);
        }
Ejemplo n.º 22
0
        private void ReadClientSteamAuthRequest(NetIncomingMessage inc, NetConnection senderConnection, out ulong clientSteamID)
        {
            clientSteamID = 0;
            if (!Steam.SteamManager.USE_STEAM)
            {
                DebugConsole.Log("Received a Steam auth request from " + senderConnection.RemoteEndPoint + ". Steam authentication not required, handling auth normally.");
                //not using steam, handle auth normally
                HandleClientAuthRequest(senderConnection, 0);
                return;
            }

            if (senderConnection == OwnerConnection)
            {
                //the client is the owner of the server, no need for authentication
                //(it would fail with a "duplicate request" error anyway)
                HandleClientAuthRequest(senderConnection, 0);
                return;
            }

            clientSteamID = inc.ReadUInt64();
            int authTicketLength = inc.ReadInt32();

            inc.ReadBytes(authTicketLength, out byte[] authTicketData);

            DebugConsole.Log("Received a Steam auth request");
            DebugConsole.Log("  Steam ID: " + clientSteamID);
            DebugConsole.Log("  Auth ticket length: " + authTicketLength);
            DebugConsole.Log("  Auth ticket data: " +
                             ((authTicketData == null) ? "null" : ToolBox.LimitString(string.Concat(authTicketData.Select(b => b.ToString("X2"))), 16)));

            if (senderConnection != OwnerConnection &&
                serverSettings.BanList.IsBanned(senderConnection.RemoteEndPoint.Address, clientSteamID))
            {
                return;
            }
            ulong steamID = clientSteamID;

            if (unauthenticatedClients.Any(uc => uc.Connection == inc.SenderConnection))
            {
                var steamAuthedClient = unauthenticatedClients.Find(uc =>
                                                                    uc.Connection == inc.SenderConnection &&
                                                                    uc.SteamID == steamID &&
                                                                    uc.SteamAuthStatus == Facepunch.Steamworks.ServerAuth.Status.OK);
                if (steamAuthedClient != null)
                {
                    DebugConsole.Log("Client already authenticated, sending AUTH_RESPONSE again...");
                    HandleClientAuthRequest(inc.SenderConnection, steamID);
                }
                DebugConsole.Log("Steam authentication already pending...");
                return;
            }

            if (authTicketData == null)
            {
                DebugConsole.Log("Invalid request");
                return;
            }

            unauthenticatedClients.RemoveAll(uc => uc.Connection == senderConnection);
            int nonce        = CryptoRandom.Instance.Next();
            var unauthClient = new UnauthenticatedClient(senderConnection, nonce, clientSteamID)
            {
                AuthTimer = 20
            };

            unauthenticatedClients.Add(unauthClient);

            if (!Steam.SteamManager.StartAuthSession(authTicketData, clientSteamID))
            {
                unauthenticatedClients.Remove(unauthClient);
                if (GameMain.Config.RequireSteamAuthentication)
                {
                    unauthClient.Connection.Disconnect(DisconnectReason.SteamAuthenticationFailed.ToString());
                    Log("Disconnected unauthenticated client (Steam ID: " + steamID + "). Steam authentication failed.", ServerLog.MessageType.ServerMessage);
                }
                else
                {
                    DebugConsole.Log("Steam authentication failed, skipping to basic auth...");
                    HandleClientAuthRequest(senderConnection);
                    return;
                }
            }

            return;
        }
Ejemplo n.º 23
0
        protected override void CombatRotation()
        {
            base.CombatRotation();
            WoWUnit Target = ObjectManager.Target;
            bool    _shouldBeInterrupted = ToolBox.TargetIsCasting();
            bool    _inMeleeRange        = Target.GetDistance < 6f;
            bool    _saveRage            = Cleave.KnownSpell &&
                                           ObjectManager.GetNumberAttackPlayer() > 1 &&
                                           ToolBox.GetNbEnemiesClose(15f) > 1 &&
                                           settings.UseCleave ||
                                           Execute.KnownSpell && Target.HealthPercent < 40 ||
                                           Bloodthirst.KnownSpell && ObjectManager.Me.Rage < 40 && Target.HealthPercent > 50;

            // Force melee
            if (_combatMeleeTimer.IsReady)
            {
                RangeManager.SetRangeToMelee();
            }

            // Check if we need to interrupt
            if (_shouldBeInterrupted)
            {
                _fightingACaster = true;
                RangeManager.SetRangeToMelee();
                if (!_casterEnemies.Contains(Target.Name))
                {
                    _casterEnemies.Add(Target.Name);
                }
            }

            // Check Auto-Attacking
            ToolBox.CheckAutoAttack(Attack);

            // Intercept
            if (InBerserkStance() &&
                ObjectManager.Target.GetDistance > 12f &&
                ObjectManager.Target.GetDistance < 24f &&
                cast.OnTarget(Intercept))
            {
                return;
            }

            // Battle stance
            if (InBerserkStance() &&
                Me.Rage < 10 &&
                !settings.PrioritizeBerserkStance &&
                ObjectManager.GetNumberAttackPlayer() > 1 &&
                !_fightingACaster &&
                cast.OnSelf(BattleStance))
            {
                return;
            }

            // Berserker stance
            if (settings.PrioritizeBerserkStance &&
                !InBerserkStance() &&
                ObjectManager.GetNumberAttackPlayer() < 2 &&
                cast.OnSelf(BerserkerStance))
            {
                return;
            }

            // Fighting a caster
            if (_fightingACaster &&
                !InBerserkStance() &&
                Me.Rage < 20 &&
                ObjectManager.GetNumberAttackPlayer() < 2 &&
                cast.OnSelf(BerserkerStance))
            {
                return;
            }

            // Interrupt
            if (_shouldBeInterrupted &&
                InBerserkStance())
            {
                Thread.Sleep(Main.humanReflexTime);
                if (cast.OnTarget(Pummel))
                {
                    return;
                }
            }

            // Victory Rush
            if (cast.OnTarget(VictoryRush))
            {
                return;
            }

            // Rampage
            if ((!Me.HaveBuff("Rampage") || Me.HaveBuff("Rampage") && ToolBox.BuffTimeLeft("Rampage") < 10) &&
                cast.OnTarget(Rampage))
            {
                return;
            }

            // Berserker Rage
            if (InBerserkStance() &&
                Target.HealthPercent > 70 &&
                cast.OnSelf(BerserkerRage))
            {
                return;
            }

            // Execute
            if (cast.OnTarget(Execute))
            {
                return;
            }

            // Overpower
            if (Overpower.IsSpellUsable)
            {
                Thread.Sleep(Main.humanReflexTime);
                if (cast.OnTarget(Overpower))
                {
                    return;
                }
            }

            // Bloodthirst
            if (_inMeleeRange &&
                cast.OnTarget(Bloodthirst))
            {
                return;
            }

            // Whirlwind
            if (_inMeleeRange &&
                InBerserkStance() &&
                Me.Rage > 30 &&
                cast.OnTarget(Whirlwind))
            {
                return;
            }

            // Sweeping Strikes
            if (_inMeleeRange &&
                ObjectManager.GetNumberAttackPlayer() > 1 &&
                ToolBox.GetNbEnemiesClose(15f) > 1 &&
                cast.OnTarget(SweepingStrikes))
            {
                return;
            }

            // Retaliation
            if (_inMeleeRange && ObjectManager.GetNumberAttackPlayer() > 1 &&
                ToolBox.GetNbEnemiesClose(15f) > 1)
            {
                if (cast.OnTarget(Retaliation) && (!SweepingStrikes.IsSpellUsable || !SweepingStrikes.KnownSpell))
                {
                    return;
                }
            }

            // Cleave
            if (_inMeleeRange &&
                ObjectManager.GetNumberAttackPlayer() > 1 &&
                ToolBox.GetNbEnemiesClose(15f) > 1 &&
                (!SweepingStrikes.IsSpellUsable || !SweepingStrikes.KnownSpell) &&
                ObjectManager.Me.Rage > 40 &&
                settings.UseCleave &&
                cast.OnTarget(Cleave))
            {
                return;
            }

            // Blood Rage
            if (settings.UseBloodRage &&
                Me.HealthPercent > 90 &&
                cast.OnSelf(BloodRage))
            {
                return;
            }

            // Hamstring
            if ((Target.CreatureTypeTarget == "Humanoid" || Target.Name.Contains("Plainstrider")) &&
                _inMeleeRange &&
                settings.UseHamstring &&
                Target.HealthPercent < 40 &&
                !Target.HaveBuff("Hamstring") &&
                cast.OnTarget(Hamstring))
            {
                return;
            }

            // Commanding Shout
            if (!Me.HaveBuff("Commanding Shout") &&
                settings.UseCommandingShout &&
                cast.OnSelf(CommandingShout))
            {
                return;
            }

            // Battle Shout
            if (!Me.HaveBuff("Battle Shout") &&
                (!settings.UseCommandingShout || !CommandingShout.KnownSpell) &&
                cast.OnSelf(BattleShout))
            {
                return;
            }

            // Rend
            if (!Target.HaveBuff("Rend") &&
                _inMeleeRange &&
                settings.UseRend &&
                Target.HealthPercent > 25 &&
                cast.OnTarget(Rend))
            {
                return;
            }

            // Demoralizing Shout
            if (settings.UseDemoralizingShout &&
                !Target.HaveBuff("Demoralizing Shout") &&
                !Target.HaveBuff("Demoralizing Roar") &&
                (ObjectManager.GetNumberAttackPlayer() > 1 || ToolBox.GetNbEnemiesClose(15f) <= 0) &&
                _inMeleeRange &&
                cast.OnSelf(DemoralizingShout))
            {
                return;
            }

            // Heroic Strike (after whirlwind)
            if (_inMeleeRange &&
                Whirlwind.KnownSpell &&
                !HeroicStrikeOn() &&
                Me.Rage > 60 &&
                cast.OnTarget(HeroicStrike))
            {
                return;
            }

            // Heroic Strike (before whirlwind)
            if (_inMeleeRange &&
                !Whirlwind.KnownSpell &&
                !HeroicStrikeOn() &&
                (!_saveRage || Me.Rage > 60) &&
                cast.OnTarget(HeroicStrike))
            {
                return;
            }
        }
Ejemplo n.º 24
0
        public ItemComponent(Item item, XElement element)
        {
            this.item              = item;
            originalElement        = element;
            name                   = element.Name.ToString();
            SerializableProperties = SerializableProperty.GetProperties(this);
            requiredItems          = new Dictionary <RelatedItem.RelationType, List <RelatedItem> >();
            requiredSkills         = new List <Skill>();

#if CLIENT
            sounds = new Dictionary <ActionType, List <ItemSound> >();
#endif

            SelectKey = InputType.Select;

            try
            {
                string selectKeyStr = element.GetAttributeString("selectkey", "Select");
                selectKeyStr = ToolBox.ConvertInputType(selectKeyStr);
                SelectKey    = (InputType)Enum.Parse(typeof(InputType), selectKeyStr, true);
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Invalid select key in " + element + "!", e);
            }

            PickKey = InputType.Select;

            try
            {
                string pickKeyStr = element.GetAttributeString("pickkey", "Select");
                pickKeyStr = ToolBox.ConvertInputType(pickKeyStr);
                PickKey    = (InputType)Enum.Parse(typeof(InputType), pickKeyStr, true);
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Invalid pick key in " + element + "!", e);
            }

            SerializableProperties = SerializableProperty.DeserializeProperties(this, element);
            ParseMsg();

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "requireditem":
                case "requireditems":
                    RelatedItem ri = RelatedItem.Load(subElement, item.Name);
                    if (ri != null)
                    {
                        if (!requiredItems.ContainsKey(ri.Type))
                        {
                            requiredItems.Add(ri.Type, new List <RelatedItem>());
                        }
                        requiredItems[ri.Type].Add(ri);
                    }
                    else
                    {
                        DebugConsole.ThrowError("Error in item config \"" + item.ConfigFile + "\" - component " + GetType().ToString() + " requires an item with no identifiers.");
                    }
                    break;

                case "requiredskill":
                case "requiredskills":
                    if (subElement.Attribute("name") != null)
                    {
                        DebugConsole.ThrowError("Error in item config \"" + item.ConfigFile + "\" - skill requirement in component " + GetType().ToString() + " should use a skill identifier instead of the name of the skill.");
                        continue;
                    }

                    string skillIdentifier = subElement.GetAttributeString("identifier", "");
                    requiredSkills.Add(new Skill(skillIdentifier, subElement.GetAttributeInt("level", 0)));
                    break;

                case "statuseffect":
                    var statusEffect = StatusEffect.Load(subElement, item.Name);

                    if (statusEffectLists == null)
                    {
                        statusEffectLists = new Dictionary <ActionType, List <StatusEffect> >();
                    }

                    List <StatusEffect> effectList;
                    if (!statusEffectLists.TryGetValue(statusEffect.type, out effectList))
                    {
                        effectList = new List <StatusEffect>();
                        statusEffectLists.Add(statusEffect.type, effectList);
                    }

                    effectList.Add(statusEffect);

                    break;

                case "aitarget":
                    AITarget = new AITarget(item, subElement)
                    {
                        Enabled = isActive
                    };
                    break;

                default:
                    if (LoadElemProjSpecific(subElement))
                    {
                        break;
                    }
                    ItemComponent ic = Load(subElement, item, item.ConfigFile, false);
                    if (ic == null)
                    {
                        break;
                    }

                    ic.Parent = this;
                    item.AddComponent(ic);
                    break;
                }
            }
        }
        protected override void CombatRotation()
        {
            base.CombatRotation();
            WoWUnit Target = ObjectManager.Target;

            // PARTY Remove Curse
            if (settings.PartyRemoveCurse)
            {
                List <AIOPartyMember> needRemoveCurse = AIOParty.GroupAndRaid
                                                        .FindAll(m => ToolBox.HasCurseDebuff(m.Name))
                                                        .ToList();
                if (needRemoveCurse.Count > 0 && cast.OnFocusUnit(RemoveCurse, needRemoveCurse[0]))
                {
                    return;
                }
            }

            // Ice Barrier
            if (Me.HealthPercent < 50 &&
                cast.OnSelf(IceBarrier))
            {
                return;
            }

            // Ice Lance
            if ((Target.HaveBuff("Frostbite") || Target.HaveBuff("Frost Nova")) &&
                cast.OnTarget(IceLance))
            {
                return;
            }

            // Use Mana Stone
            if (Me.ManaPercentage < 20 &&
                _foodManager.UseManaStone())
            {
                return;
            }

            // Evocation
            if (Me.ManaPercentage < 15 &&
                AIORadar.CloseUnitsTargetingMe.Count <= 0 &&
                cast.OnSelf(Evocation))
            {
                Usefuls.WaitIsCasting();
                return;
            }

            // Cone of Cold
            if (ToolBox.GetNbEnemiesClose(10f) > 2 &&
                cast.OnTarget(ConeOfCold))
            {
                return;
            }

            // Icy Veins
            if (Target.HealthPercent < 100 &&
                Me.ManaPercentage > 10 &&
                !SummonWaterElemental.IsSpellUsable &&
                cast.OnSelf(IcyVeins))
            {
                return;
            }

            // Arcane Power
            if (Target.HealthPercent < 100 &&
                Me.ManaPercentage > 10 &&
                cast.OnSelf(ArcanePower))
            {
                return;
            }

            // Presence of Mind
            if (!Me.HaveBuff("Presence of Mind") &&
                Target.HealthPercent < 100 &&
                cast.OnSelf(PresenceOfMind))
            {
                return;
            }
            if (Me.HaveBuff("Presence of Mind"))
            {
                if (cast.OnTarget(ArcaneBlast) || cast.OnTarget(Frostbolt))
                {
                    Usefuls.WaitIsCasting();
                    return;
                }
            }

            // Cold Snap
            if (SummonWaterElemental.GetCurrentCooldown > 0 &&
                !ObjectManager.Pet.IsValid &&
                Me.ManaPercentage > 10 &&
                !Me.HaveBuff(IcyVeins.Name) &&
                cast.OnSelf(ColdSnap))
            {
                return;
            }

            // Summon Water Elemental
            if (cast.OnSelf(SummonWaterElemental))
            {
                return;
            }

            // FrostBolt
            if (cast.OnTarget(Frostbolt))
            {
                return;
            }

            // Stop wand if banned
            if (ToolBox.UsingWand() &&
                UnitImmunities.Contains(ObjectManager.Target, "Shoot") &&
                cast.OnTarget(UseWand))
            {
                return;
            }

            // Spell if wand banned
            if (UnitImmunities.Contains(ObjectManager.Target, "Shoot"))
            {
                if (cast.OnTarget(ArcaneBlast) || cast.OnTarget(ArcaneMissiles) || cast.OnTarget(Frostbolt) || cast.OnTarget(Fireball))
                {
                    return;
                }
            }

            // Use Wand
            if (!ToolBox.UsingWand() &&
                _iCanUseWand &&
                !cast.IsBackingUp &&
                !MovementManager.InMovement)
            {
                if (cast.OnTarget(UseWand, false))
                {
                    return;
                }
            }
        }
Ejemplo n.º 26
0
        public void ParseBG(string filePath)
        {
            PreParse(filePath);

            switch (FileName)
            {
            case ("MAPBG"):
                width = 320;
                break;

            case ("MENUBG"):
                width = 192;
                break;
            }
            height = Mathf.FloorToInt((FileSize - 512) / width);

            Color[] col = new Color[256];
            for (int i = 0; i < 256; ++i)
            {
                col[i] = ToolBox.BitColorConverter(buffer.ReadUInt16());
            }


            if (FileName == "MENUBG")
            {
                List <Color> cluts = new List <Color>();
                List <Color> cl2   = new List <Color>();
                while (buffer.BaseStream.Position + 4 < buffer.BaseStream.Length)
                {
                    byte[] b     = buffer.ReadBytes(4);
                    byte   lt    = b[0];
                    byte   rt    = b[2];
                    int    blank = lt * 4;
                    int    pix   = rt * 4;
                    if (buffer.BaseStream.Position + pix <= buffer.BaseStream.Length)
                    {
                        for (uint y = 0; y < blank; y++)
                        {
                            cl2.Add(Color.black);
                        }

                        for (uint y = 0; y < pix; y++)
                        {
                            cl2.Add(col[buffer.ReadByte()]);
                        }
                    }
                    if (buffer.BaseStream.Position == buffer.BaseStream.Length)
                    {
                        break;
                    }
                }
                for (uint y = 0; y < width; y++)
                {
                    List <Color> line = cl2.GetRange((int)y * width, width);
                    line.Reverse();
                    cluts.AddRange(line);
                }


                cluts.Reverse();

                height = cluts.Count / width;
                Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
                tex.SetPixels(cluts.ToArray());
                tex.Apply();

                byte[] bytes = tex.EncodeToPNG();
                ToolBox.DirExNorCreate(Application.dataPath + "/../Assets/Resources/Textures/BG/");
                File.WriteAllBytes(Application.dataPath + "/../Assets/Resources/Textures/BG/" + FileName + width + ".png", bytes);
            }
            else
            {
                List <Color> cluts = new List <Color>();
                for (uint x = 0; x < height; x++)
                {
                    List <Color> cl2 = new List <Color>();
                    for (uint y = 0; y < width; y++)
                    {
                        cl2.Add(col[buffer.ReadByte()]);
                    }
                    cl2.Reverse();
                    cluts.AddRange(cl2);
                }
                cluts.Reverse();
                Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
                tex.SetPixels(cluts.ToArray());
                tex.Apply();

                byte[] bytes = tex.EncodeToPNG();
                ToolBox.DirExNorCreate(Application.dataPath + "/../Assets/Resources/Textures/BG/");
                File.WriteAllBytes(Application.dataPath + "/../Assets/Resources/Textures/BG/" + FileName + ".png", bytes);
            }
        }
Ejemplo n.º 27
0
        private void ProcessItem(Item targetItem, IEnumerable <Item> inputItems, List <DeconstructItem> validDeconstructItems, bool allowRemove = true)
        {
            // In multiplayer, the server handles the deconstruction into new items
            if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
            {
                return;
            }

            if (user != null && !user.Removed)
            {
                var abilityTargetItem = new AbilityItem(targetItem);
                user.CheckTalents(AbilityEffectType.OnItemDeconstructed, abilityTargetItem);
            }

            if (targetItem.Prefab.RandomDeconstructionOutput)
            {
                int        amount = targetItem.Prefab.RandomDeconstructionOutputAmount;
                List <int> deconstructItemIndexes = new List <int>();
                for (int i = 0; i < validDeconstructItems.Count; i++)
                {
                    deconstructItemIndexes.Add(i);
                }
                List <float>           commonness = validDeconstructItems.Select(i => i.Commonness).ToList();
                List <DeconstructItem> products   = new List <DeconstructItem>();

                for (int i = 0; i < amount; i++)
                {
                    if (deconstructItemIndexes.Count < 1)
                    {
                        break;
                    }
                    var itemIndex = ToolBox.SelectWeightedRandom(deconstructItemIndexes, commonness, Rand.RandSync.Unsynced);
                    products.Add(validDeconstructItems[itemIndex]);
                    var removeIndex = deconstructItemIndexes.IndexOf(itemIndex);
                    deconstructItemIndexes.RemoveAt(removeIndex);
                    commonness.RemoveAt(removeIndex);
                }

                foreach (DeconstructItem deconstructProduct in products)
                {
                    CreateDeconstructProduct(deconstructProduct, inputItems);
                }
            }
            else
            {
                foreach (DeconstructItem deconstructProduct in validDeconstructItems)
                {
                    CreateDeconstructProduct(deconstructProduct, inputItems);
                }
            }

            void CreateDeconstructProduct(DeconstructItem deconstructProduct, IEnumerable <Item> inputItems)
            {
                float percentageHealth = targetItem.Condition / targetItem.MaxCondition;

                if (percentageHealth < deconstructProduct.MinCondition || percentageHealth > deconstructProduct.MaxCondition)
                {
                    return;
                }

                if (!(MapEntityPrefab.Find(null, deconstructProduct.ItemIdentifier) is ItemPrefab itemPrefab))
                {
                    DebugConsole.ThrowError("Tried to deconstruct item \"" + targetItem.Name + "\" but couldn't find item prefab \"" + deconstructProduct.ItemIdentifier + "\"!");
                    return;
                }

                float condition = deconstructProduct.CopyCondition ?
                                  percentageHealth * itemPrefab.Health :
                                  itemPrefab.Health * Rand.Range(deconstructProduct.OutConditionMin, deconstructProduct.OutConditionMax);

                if (DeconstructItemsSimultaneously && deconstructProduct.RequiredOtherItem.Length > 0)
                {
                    foreach (Item otherItem in inputItems)
                    {
                        if (targetItem == otherItem)
                        {
                            continue;
                        }
                        if (deconstructProduct.RequiredOtherItem.Any(r => otherItem.HasTag(r) || r.Equals(otherItem.Prefab.Identifier, StringComparison.OrdinalIgnoreCase)))
                        {
                            user.CheckTalents(AbilityEffectType.OnGeneticMaterialCombinedOrRefined);
                            foreach (Character character in Character.GetFriendlyCrew(user))
                            {
                                character.CheckTalents(AbilityEffectType.OnCrewGeneticMaterialCombinedOrRefined);
                            }

                            var geneticMaterial1 = targetItem.GetComponent <GeneticMaterial>();
                            var geneticMaterial2 = otherItem.GetComponent <GeneticMaterial>();
                            if (geneticMaterial1 != null && geneticMaterial2 != null)
                            {
                                if (geneticMaterial1.Combine(geneticMaterial2, user))
                                {
                                    inputContainer.Inventory.RemoveItem(otherItem);
                                    OutputContainer.Inventory.RemoveItem(otherItem);
                                    Entity.Spawner.AddToRemoveQueue(otherItem);
                                }
                                allowRemove = false;
                                return;
                            }
                            inputContainer.Inventory.RemoveItem(otherItem);
                            OutputContainer.Inventory.RemoveItem(otherItem);
                            Entity.Spawner.AddToRemoveQueue(otherItem);
                        }
                    }
                }

                int amount = 1;

                if (user != null && !user.Removed)
                {
                    var itemsCreated = new AbilityValueItem(amount, targetItem.Prefab);
                    user.CheckTalents(AbilityEffectType.OnItemDeconstructedMaterial, itemsCreated);
                    amount = (int)itemsCreated.Value;

                    // used to spawn items directly into the deconstructor
                    var itemContainer = new AbilityItemPrefabItem(item, targetItem.Prefab);
                    user.CheckTalents(AbilityEffectType.OnItemDeconstructedInventory, itemContainer);
                }

                for (int i = 0; i < amount; i++)
                {
                    Entity.Spawner.AddToSpawnQueue(itemPrefab, outputContainer.Inventory, condition, onSpawned: (Item spawnedItem) =>
                    {
                        for (int i = 0; i < outputContainer.Capacity; i++)
                        {
                            var containedItem = outputContainer.Inventory.GetItemAt(i);
                            if (containedItem?.Combine(spawnedItem, null) ?? false)
                            {
                                break;
                            }
                        }
                        PutItemsToLinkedContainer();
                    });
                }
            }

            if (targetItem.AllowDeconstruct && allowRemove)
            {
                //drop all items that are inside the deconstructed item
                foreach (ItemContainer ic in targetItem.GetComponents <ItemContainer>())
                {
                    if (ic?.Inventory == null || ic.RemoveContainedItemsOnDeconstruct)
                    {
                        continue;
                    }
                    ic.Inventory.AllItemsMod.ForEach(containedItem => outputContainer.Inventory.TryPutItem(containedItem, user: null));
                }
                inputContainer.Inventory.RemoveItem(targetItem);
                Entity.Spawner.AddToRemoveQueue(targetItem);
                MoveInputQueue();
                PutItemsToLinkedContainer();
            }
            else
            {
                if (!outputContainer.Inventory.CanBePut(targetItem) || (Entity.Spawner?.IsInRemoveQueue(targetItem) ?? false))
                {
                    targetItem.Drop(dropper: null);
                }
                else
                {
                    outputContainer.Inventory.TryPutItem(targetItem, user: null, createNetworkEvent: true);
                }
            }
        }
Ejemplo n.º 28
0
        public void ParseWEP(BinaryReader buffer)
        {
            numPallets = 7;
            uint texMapSize = buffer.ReadUInt32();

            buffer.ReadByte();
            width     = buffer.ReadByte() * 2;
            height    = buffer.ReadByte() * 2;
            numColors = buffer.ReadByte();
            List <List <Color32> > pallets = new List <List <Color32> >();

            if (numColors > 0)
            {
                List <Color32> handleColors = new List <Color32>();
                for (uint i = 0; i < (int)(numColors / 3); i++)
                {
                    handleColors.Add(ToolBox.BitColorConverter(buffer.ReadUInt16()));
                }

                for (uint h = 0; h < numPallets; h++)
                {
                    List <Color32> colors = new List <Color32>();
                    colors.AddRange(handleColors);
                    for (uint i = 0; i < (int)(numColors / 3) * 2; i++)
                    {
                        colors.Add(ToolBox.BitColorConverter(buffer.ReadUInt16()));
                    }

                    pallets.Add(colors);
                }
            }
            List <int> cluts = new List <int>();

            for (uint x = 0; x < height; x++)
            {
                List <int> cl2 = new List <int>();
                for (uint y = 0; y < width; y++)
                {
                    cl2.Add(buffer.ReadByte());
                }
                cl2.Reverse();
                cluts.AddRange(cl2);
            }
            cluts.Reverse();

            textures = new List <Texture2D>();
            for (int h = 0; h < numPallets; h++)
            {
                List <Color> colors = new List <Color>();
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        if (cluts[(int)((y * width) + x)] < numColors)
                        {
                            colors.Add(pallets[h][cluts[(int)((y * width) + x)]]);
                        }
                        else
                        {
                            colors.Add(Color.clear);
                        }
                    }
                }

                Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
                tex.SetPixels(colors.ToArray());
                tex.Apply();
                textures.Add(tex);
            }
            textures.Add(textures[0]);
        }
Ejemplo n.º 29
0
	private void Start()
	{
		toolBox = ToolBox.Instance;
		data = toolBox.data;
	}
Ejemplo n.º 30
0
        public void ParseSHP(BinaryReader buffer, bool vc = false)
        {
            numPallets = 2;
            uint texMapSize = buffer.ReadUInt32();
            byte unk        = buffer.ReadByte();

            width     = buffer.ReadByte() * 2;
            height    = buffer.ReadByte() * 2;
            numColors = buffer.ReadByte();


            if (UseDebug)
            {
                Debug.LogWarning(string.Concat("Parse SHP Texture => texMapSize : ", texMapSize, "   unk : ", unk,
                                               "   width : ", width, "   height : ", height, "   numColors : ", numColors));
            }

            // Parse SHP 37 Texture => texMapSize : 33156   unk : 1   width : 128   height : 256   numColors : 160
            // Parse SHP 65 Texture => texMapSize : 32804   unk : 16   width : 128   height : 256   numColors : 16
            if (!vc)
            {
                List <List <Color32> > pallets = new List <List <Color32> >();
                if (numColors > 0)
                {
                    for (uint h = 0; h < numPallets; h++)
                    {
                        List <Color32> colors = new List <Color32>();
                        for (uint i = 0; i < numColors; i++)
                        {
                            colors.Add(ToolBox.BitColorConverter(buffer.ReadUInt16()));
                        }

                        pallets.Add(colors);
                    }
                }
                List <int> cluts = new List <int>();
                for (uint x = 0; x < height; x++)
                {
                    List <int> cl2 = new List <int>();
                    for (uint y = 0; y < width; y++)
                    {
                        cl2.Add(buffer.ReadByte());
                    }
                    cl2.Reverse();
                    cluts.AddRange(cl2);
                }
                cluts.Reverse();

                textures = new List <Texture2D>();
                for (int h = 0; h < numPallets; h++)
                {
                    List <Color> colors = new List <Color>();
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            if (cluts[(int)((y * width) + x)] < numColors)
                            {
                                colors.Add(pallets[h][cluts[(int)((y * width) + x)]]);
                            }
                            else
                            {
                                colors.Add(Color.clear);
                            }
                        }
                    }

                    Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
                    tex.SetPixels(colors.ToArray());
                    tex.Apply();
                    textures.Add(tex);
                }
            }
            else
            {
                numPallets = 2;
                List <List <Color32> > pallets = new List <List <Color32> >();
                if (numColors > 0)
                {
                    for (uint h = 0; h < numPallets; h++)
                    {
                        List <Color32> colors = new List <Color32>();
                        for (uint i = 0; i < numColors; i++)
                        {
                            colors.Add(ToolBox.BitColorConverter(buffer.ReadUInt16()));
                        }

                        pallets.Add(colors);
                    }
                }

                List <int> cluts = new List <int>();
                for (uint x = 0; x < height; x++)
                {
                    List <int> cl2 = new List <int>();
                    for (uint y = 0; y < width; y++)
                    {
                        byte id = buffer.ReadByte();
                        byte l  = (byte)Mathf.RoundToInt(id / 16);
                        byte r  = (byte)(id % 16);
                        cl2.Add(r);
                        cl2.Add(l);
                    }
                    cl2.Reverse();
                    cluts.AddRange(cl2);
                }
                cluts.Reverse();

                textures = new List <Texture2D>();
                for (int h = 0; h < numPallets; h++)
                {
                    List <Color> colors = new List <Color>();
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width * 2; x++)
                        {
                            if (cluts[(int)((y * width * 2) + x)] < numColors)
                            {
                                colors.Add(pallets[h][cluts[(int)((y * width * 2) + x)]]);
                            }
                            else
                            {
                                colors.Add(Color.clear);
                            }
                        }
                    }

                    Texture2D tex = new Texture2D(width * 2, height, TextureFormat.ARGB32, false);
                    tex.SetPixels(colors.ToArray());
                    tex.Apply();
                    textures.Add(tex);
                }


                width *= 2;
            }
        }
Ejemplo n.º 31
0
 public void Levenshtein()
 {
     Assert.AreEqual(0, ToolBox.Levenshtein("x", "x"));
 }
Ejemplo n.º 32
0
	private void Awake()
	{
		Screen.sleepTimeout = SleepTimeout.NeverSleep;
		toolBox = ToolBox.Instance;
	}