Clamp() public static method

public static Clamp ( double v, double l, double h ) : double
v double
l double
h double
return double
Beispiel #1
0
        internal override void Draw(SpriteBatch _, GameTime gameTime)
        {
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied);
            var lanIpSize = game.Fonts.Get(MonoGame_Engine.Font.DebugFont).MeasureString(lanIp);

            spriteBatch.DrawString(game.Fonts.Get(MonoGame_Engine.Font.DebugFont), lanIp, new Vector2((game.Screen.CanvasWidth - lanIpSize.X) / 2, game.Screen.CanvasHeight - 20), Color.White);

            for (int i = 0; i < 4; i++)
            {
                pos[i].X = i % 2 == 0 ? ScreenBorder : game.Screen.CanvasWidth - ScreenBorder - chars[i].Width;
                pos[i].Y = i / 2 == 0 ? ScreenBorder : game.Screen.CanvasHeight - ScreenBorder - chars[i].Height;

                if (game.MainScene.Players.Count > i)
                {
                    var player = game.MainScene.Players[i];

                    var fx    = i % 2 == 0 ? SpriteEffects.None : SpriteEffects.FlipHorizontally;
                    var alpha = (gameTime.TotalGameTime.TotalMilliseconds % 300 < 150) ? 0.2f : 1.0f;
                    var color = new Color(1f, 1f, 1f, player.IsInvincible ? alpha : 1f);
                    spriteBatch.Draw(chars[i], pos[i], null, color, 0, Vector2.Zero, Vector2.One, fx, 0);

                    if (!player.IsAlive)
                    {
                        var text           = "You died!\r\nPress Button to join";
                        var textPosXOffset = i % 2 == 0 ? pos[i].X + chars[i].Width : pos[i].X;
                        var textPosYOffset = i / 2 == 0 ? pos[i].Y : pos[i].Y + chars[i].Height - chars[2].Height;
                        DrawTextBox(i, spriteBatch, text, new Vector2(textPosXOffset, textPosYOffset), new Color(player.BaseColor, alpha));
                    }
                    else if (player.EventTextTime > TimeSpan.Zero)
                    {
                        player.EventTextTime -= gameTime.ElapsedGameTime;
                        var textPosXOffset = i % 2 == 0 ? pos[i].X + chars[i].Width : pos[i].X;
                        var textPosYOffset = i / 2 == 0 ? pos[i].Y : pos[i].Y + chars[i].Height - chars[2].Height;
                        DrawTextBox(i, spriteBatch, player.EventText, new Vector2(textPosXOffset, textPosYOffset), player.BaseColor);
                    }
                }
            }

            const float minDistance  = 2000;
            const float blendInMagic = 0.1f;
            float       offset       = MathHelper.Clamp((this.distanceToMotherShip - (minDistance)), -100 / blendInMagic, 0) * blendInMagic;

            //if (distanceToMotherShip > minDistance)
            {
                const float preMultiplier  = 0.0005f;
                const float postMultiplier = 200f;
                const float log            = 5;
                const float max            = 400;
                var         position       = (float)Math.Log(distanceToMotherShip * preMultiplier, log) * postMultiplier;
                position = MathHelper.Clamp(position, 0, max);
                var left      = game.Screen.CanvasWidth / 2 - max / 2;
                var rigth     = game.Screen.CanvasWidth / 2 + max / 2;
                var indicator = position + left;

                spriteBatch.Draw(distanceScale, new Vector2(left, offset));
                distanceMarker.Draw(spriteBatch, new Vector2(indicator, offset + distanceMarker.Height / 2), 0f);
            }

            if (game.MainScene.Players.Count == 0)
            {
                Title.Draw(spriteBatch, gameTime);
            }

            spriteBatch.End();
        }
Beispiel #2
0
        protected override void Update()
        {
            base.Update();

            border.Alpha = (float)MathHelper.Clamp((HitObject.StartTime - Time.Current) / 500, 0, 1);
        }
Beispiel #3
0
        private static void UpdateWaterFlowSounds(float deltaTime)
        {
            if (FlowSounds.Count == 0)
            {
                return;
            }

            float[] targetFlowLeft  = new float[FlowSounds.Count];
            float[] targetFlowRight = new float[FlowSounds.Count];

            Vector2 listenerPos = new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y);

            foreach (Gap gap in Gap.GapList)
            {
                Vector2 diff = gap.WorldPosition - listenerPos;
                if (Math.Abs(diff.X) < FlowSoundRange && Math.Abs(diff.Y) < FlowSoundRange)
                {
                    if (gap.Open < 0.01f)
                    {
                        continue;
                    }
                    float gapFlow = Math.Abs(gap.LerpedFlowForce.X) + Math.Abs(gap.LerpedFlowForce.Y) * 2.5f;
                    if (!gap.IsRoomToRoom)
                    {
                        gapFlow *= 2.0f;
                    }
                    if (gapFlow < 10.0f)
                    {
                        continue;
                    }

                    if (gap.linkedTo.Count == 2 && gap.linkedTo[0] is Hull hull1 && gap.linkedTo[1] is Hull hull2)
                    {
                        //no flow sounds between linked hulls (= rooms consisting of multiple hulls)
                        if (hull1.linkedTo.Contains(hull2))
                        {
                            continue;
                        }
                        if (hull1.linkedTo.Any(h => h.linkedTo.Contains(hull1) && h.linkedTo.Contains(hull2)))
                        {
                            continue;
                        }
                        if (hull2.linkedTo.Any(h => h.linkedTo.Contains(hull1) && h.linkedTo.Contains(hull2)))
                        {
                            continue;
                        }
                    }

                    int flowSoundIndex = (int)Math.Floor(MathHelper.Clamp(gapFlow / MaxFlowStrength, 0, FlowSounds.Count));
                    flowSoundIndex = Math.Min(flowSoundIndex, FlowSounds.Count - 1);

                    float dist        = diff.Length();
                    float distFallOff = dist / FlowSoundRange;
                    if (distFallOff >= 0.99f)
                    {
                        continue;
                    }

                    //flow at the left side
                    if (diff.X < 0)
                    {
                        targetFlowLeft[flowSoundIndex] += 1.0f - distFallOff;
                    }
                    else
                    {
                        targetFlowRight[flowSoundIndex] += 1.0f - distFallOff;
                    }
                }
            }

            for (int i = 0; i < FlowSounds.Count; i++)
            {
                flowVolumeLeft[i] = (targetFlowLeft[i] < flowVolumeLeft[i]) ?
                                    Math.Max(targetFlowLeft[i], flowVolumeLeft[i] - deltaTime) :
                                    Math.Min(targetFlowLeft[i], flowVolumeLeft[i] + deltaTime * 10.0f);
                flowVolumeRight[i] = (targetFlowRight[i] < flowVolumeRight[i]) ?
                                     Math.Max(targetFlowRight[i], flowVolumeRight[i] - deltaTime) :
                                     Math.Min(targetFlowRight[i], flowVolumeRight[i] + deltaTime * 10.0f);

                if (flowVolumeLeft[i] < 0.05f && flowVolumeRight[i] < 0.05f)
                {
                    if (flowSoundChannels[i] != null)
                    {
                        flowSoundChannels[i].Dispose();
                        flowSoundChannels[i] = null;
                    }
                }
                else
                {
                    Vector2 soundPos = new Vector2(GameMain.SoundManager.ListenerPosition.X + (flowVolumeRight[i] - flowVolumeLeft[i]) * 100, GameMain.SoundManager.ListenerPosition.Y);
                    if (flowSoundChannels[i] == null || !flowSoundChannels[i].IsPlaying)
                    {
                        flowSoundChannels[i]         = FlowSounds[i].Play(1.0f, FlowSoundRange, soundPos);
                        flowSoundChannels[i].Looping = true;
                    }
                    flowSoundChannels[i].Gain     = Math.Max(flowVolumeRight[i], flowVolumeLeft[i]);
                    flowSoundChannels[i].Position = new Vector3(soundPos, 0.0f);
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Sets the vibration motor speeds on the controller device if supported.
        /// </summary>
        /// <param name="index">Index for the controller you want to query.</param>
        /// <param name="leftMotor">The speed of the left motor, between 0.0 and 1.0. This motor is a low-frequency motor.</param>
        /// <param name="rightMotor">The speed of the right motor, between 0.0 and 1.0. This motor is a high-frequency motor.</param>
        /// <param name="leftTrigger">(Xbox One controller only) The speed of the left trigger motor, between 0.0 and 1.0. This motor is a high-frequency motor.</param>
        /// <param name="rightTrigger">(Xbox One controller only) The speed of the right trigger motor, between 0.0 and 1.0. This motor is a high-frequency motor.</param>
        /// <returns>Returns true if the vibration motors were set.</returns>
        public static bool SetVibration(int index, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger)
        {
            if (index < 0 || index >= PlatformGetMaxNumberOfGamePads())
            {
                return(false);
            }

            return(PlatformSetVibration(index, MathHelper.Clamp(leftMotor, 0.0f, 1.0f), MathHelper.Clamp(rightMotor, 0.0f, 1.0f), MathHelper.Clamp(leftTrigger, 0.0f, 1.0f), MathHelper.Clamp(rightTrigger, 0.0f, 1.0f)));
        }
Beispiel #5
0
 private void LockCmaera()
 {
     _position.X = MathHelper.Clamp(Position.X, 0, TileMap.WidthInPixels - _viewportRectangle.Width);
     _position.Y = MathHelper.Clamp(Position.Y, 0, TileMap.HeightInPixels - _viewportRectangle.Height);
 }
Beispiel #6
0
            public int Parse(byte[] buf, int at, int length)
            {
                #if Full_API
                var start = at + 1 /*Skip player id */;

                //                var playerId = (int)buf[at++];
                //            if (Main.netMode == 2)
                //            {
                //                num6 = bufferId;
                //            }

                SkinVariant = (int)MathHelper.Clamp((float)buf[start++], 0, 7);
                Hair        = (int)buf[start++];
                if (Hair >= 134)
                {
                    Hair = 0;
                }

                int len = 0;
                while (true)
                {
                    len += buf[start] & 0x7F;
                    if (buf[start++] > 127)
                    {
                        len <<= 7;
                    }
                    else
                    {
                        break;
                    }
                }

                Name = System.Text.Encoding.UTF8.GetString(buf, start, len).Trim();

                HairDye = buf[start++];
                BitsByte bitsByte = buf[start++];
                HideVisual = new bool[10];
                for (int num7 = 0; num7 < 8; num7++)
                {
                    HideVisual[num7] = bitsByte[num7];
                }
                bitsByte = buf[start++];
                for (int num8 = 0; num8 < 2; num8++)
                {
                    HideVisual[num8 + 8] = bitsByte[num8];
                }
                HideMisc        = buf[start++];
                HairColor       = ParseColor(buf, ref start);
                SkinColor       = ParseColor(buf, ref start);
                EyeColor        = ParseColor(buf, ref start);
                ShirtColor      = ParseColor(buf, ref start);
                UnderShirtColor = ParseColor(buf, ref start);
                PantsColor      = ParseColor(buf, ref start);
                ShoeColor       = ParseColor(buf, ref start);
                BitsByte bitsByte2 = buf[start++];
                Difficulty = 0;
                if (bitsByte2[0])
                {
                    Difficulty += 1;
                }
                if (bitsByte2[1])
                {
                    Difficulty += 2;
                }
                if (Difficulty > 2)
                {
                    Difficulty = 2;
                }
                ExtraAccessory = bitsByte2[2];

                return(start - at);
                #else
                return(0);
                #endif
            }
Beispiel #7
0
 static private float DenormalizeLog(float f, float min, float max)
 {
     return(MathHelper.Clamp(MathHelper.InterpLog(f, min, max), min, max));
 }
Beispiel #8
0
        public static void Draw(SpriteBatch spriteBatch, Character character, Camera cam)
        {
            if (GUI.DisableHUD)
            {
                return;
            }

            character.CharacterHealth.Alignment = Alignment.Right;

            if (GameMain.GameSession?.CrewManager != null)
            {
                orderIndicatorCount.Clear();
                foreach (Pair <Order, float> timedOrder in GameMain.GameSession.CrewManager.ActiveOrders)
                {
                    DrawOrderIndicator(spriteBatch, cam, character, timedOrder.First, MathHelper.Clamp(timedOrder.Second / 10.0f, 0.2f, 1.0f));
                }

                if (character.CurrentOrder != null)
                {
                    DrawOrderIndicator(spriteBatch, cam, character, character.CurrentOrder, 1.0f);
                }
            }

            foreach (Character.ObjectiveEntity objectiveEntity in character.ActiveObjectiveEntities)
            {
                DrawObjectiveIndicator(spriteBatch, cam, character, objectiveEntity, 1.0f);
            }

            foreach (Item brokenItem in brokenItems)
            {
                if (brokenItem.NonInteractable)
                {
                    continue;
                }
                float   dist    = Vector2.Distance(character.WorldPosition, brokenItem.WorldPosition);
                Vector2 drawPos = brokenItem.DrawPosition;
                float   alpha   = Math.Min((1000.0f - dist) / 1000.0f * 2.0f, 1.0f);
                if (alpha <= 0.0f)
                {
                    continue;
                }
                GUI.DrawIndicator(spriteBatch, drawPos, cam, 100.0f, GUI.BrokenIcon,
                                  Color.Lerp(GUI.Style.Red, GUI.Style.Orange * 0.5f, brokenItem.Condition / brokenItem.MaxCondition) * alpha);
            }

            if (!character.IsIncapacitated && character.Stun <= 0.0f)
            {
                if (character.FocusedCharacter != null && character.FocusedCharacter.CanBeSelected)
                {
                    DrawCharacterHoverTexts(spriteBatch, cam, character);
                }

                if (character.FocusedItem != null)
                {
                    if (focusedItem != character.FocusedItem)
                    {
                        focusedItemOverlayTimer = Math.Min(1.0f, focusedItemOverlayTimer);
                        shouldRecreateHudTexts  = true;
                    }
                    focusedItem = character.FocusedItem;
                }

                if (focusedItem != null && focusedItemOverlayTimer > ItemOverlayDelay)
                {
                    Vector2 circlePos  = cam.WorldToScreen(focusedItem.DrawPosition);
                    float   circleSize = Math.Max(focusedItem.Rect.Width, focusedItem.Rect.Height) * 1.5f;
                    circleSize = MathHelper.Clamp(circleSize, 45.0f, 100.0f) * Math.Min((focusedItemOverlayTimer - 1.0f) * 5.0f, 1.0f);
                    if (circleSize > 0.0f)
                    {
                        Vector2 scale = new Vector2(circleSize / GUI.Style.FocusIndicator.FrameSize.X);
                        GUI.Style.FocusIndicator.Draw(spriteBatch,
                                                      (int)((focusedItemOverlayTimer - 1.0f) * GUI.Style.FocusIndicator.FrameCount * 3.0f),
                                                      circlePos,
                                                      Color.LightBlue * 0.3f,
                                                      origin: GUI.Style.FocusIndicator.FrameSize.ToVector2() / 2,
                                                      rotate: (float)Timing.TotalTime,
                                                      scale: scale);
                    }

                    if (!GUI.DisableItemHighlights && !Inventory.DraggingItemToWorld)
                    {
                        bool shiftDown = PlayerInput.KeyDown(Keys.LeftShift) || PlayerInput.KeyDown(Keys.RightShift);
                        if (shouldRecreateHudTexts || heldDownShiftWhenGotHudTexts != shiftDown)
                        {
                            shouldRecreateHudTexts       = true;
                            heldDownShiftWhenGotHudTexts = shiftDown;
                        }
                        var hudTexts = focusedItem.GetHUDTexts(character, shouldRecreateHudTexts);
                        shouldRecreateHudTexts = false;

                        int dir = Math.Sign(focusedItem.WorldPosition.X - character.WorldPosition.X);

                        Vector2 textSize      = GUI.Font.MeasureString(focusedItem.Name);
                        Vector2 largeTextSize = GUI.SubHeadingFont.MeasureString(focusedItem.Name);

                        Vector2 startPos = cam.WorldToScreen(focusedItem.DrawPosition);
                        startPos.Y -= (hudTexts.Count + 1) * textSize.Y;
                        if (focusedItem.Sprite != null)
                        {
                            startPos.X += (int)(circleSize * 0.4f * dir);
                            startPos.Y -= (int)(circleSize * 0.4f);
                        }

                        Vector2 textPos = startPos;
                        if (dir == -1)
                        {
                            textPos.X -= largeTextSize.X;
                        }

                        float alpha = MathHelper.Clamp((focusedItemOverlayTimer - ItemOverlayDelay) * 2.0f, 0.0f, 1.0f);

                        GUI.DrawString(spriteBatch, textPos, focusedItem.Name, GUI.Style.TextColor * alpha, Color.Black * alpha * 0.7f, 2, font: GUI.SubHeadingFont);
                        startPos.X += dir * 10.0f * GUI.Scale;
                        textPos.X  += dir * 10.0f * GUI.Scale;
                        textPos.Y  += largeTextSize.Y;
                        foreach (ColoredText coloredText in hudTexts)
                        {
                            if (dir == -1)
                            {
                                textPos.X = (int)(startPos.X - GUI.SmallFont.MeasureString(coloredText.Text).X);
                            }
                            GUI.DrawString(spriteBatch, textPos, coloredText.Text, coloredText.Color * alpha, Color.Black * alpha * 0.7f, 2, GUI.SmallFont);
                            textPos.Y += textSize.Y;
                        }
                    }
                }

                foreach (HUDProgressBar progressBar in character.HUDProgressBars.Values)
                {
                    progressBar.Draw(spriteBatch, cam);
                }
            }

            if (character.SelectedConstruction != null &&
                (character.CanInteractWith(Character.Controlled.SelectedConstruction) || Screen.Selected == GameMain.SubEditorScreen))
            {
                character.SelectedConstruction.DrawHUD(spriteBatch, cam, Character.Controlled);
            }

            if (character.Inventory != null)
            {
                for (int i = 0; i < character.Inventory.Items.Length - 1; i++)
                {
                    var item = character.Inventory.Items[i];
                    if (item == null || character.Inventory.SlotTypes[i] == InvSlotType.Any)
                    {
                        continue;
                    }

                    foreach (ItemComponent ic in item.Components)
                    {
                        if (ic.DrawHudWhenEquipped)
                        {
                            ic.DrawHUD(spriteBatch, character);
                        }
                    }
                }
            }
            bool mouseOnPortrait = false;

            if (character.Stun <= 0.1f && !character.IsDead)
            {
                if (CharacterHealth.OpenHealthWindow == null && character.SelectedCharacter == null)
                {
                    if (character.Info != null && !character.ShouldLockHud())
                    {
                        character.Info.DrawBackground(spriteBatch);
                        character.Info.DrawJobIcon(spriteBatch,
                                                   new Rectangle(
                                                       (int)(HUDLayoutSettings.BottomRightInfoArea.X + HUDLayoutSettings.BottomRightInfoArea.Width * 0.05f),
                                                       (int)(HUDLayoutSettings.BottomRightInfoArea.Y + HUDLayoutSettings.BottomRightInfoArea.Height * 0.1f),
                                                       (int)(HUDLayoutSettings.BottomRightInfoArea.Width / 2),
                                                       (int)(HUDLayoutSettings.BottomRightInfoArea.Height * 0.7f)));
                        character.Info.DrawPortrait(spriteBatch, HUDLayoutSettings.PortraitArea.Location.ToVector2(), new Vector2(-12 * GUI.Scale, 4 * GUI.Scale), targetWidth: HUDLayoutSettings.PortraitArea.Width, true);
                    }
                    mouseOnPortrait = HUDLayoutSettings.BottomRightInfoArea.Contains(PlayerInput.MousePosition) && !character.ShouldLockHud();
                    if (mouseOnPortrait)
                    {
                        GUI.UIGlow.Draw(spriteBatch, HUDLayoutSettings.BottomRightInfoArea, GUI.Style.Green * 0.5f);
                    }
                }
                if (ShouldDrawInventory(character))
                {
                    character.Inventory.Locked = LockInventory(character);
                    character.Inventory.DrawOwn(spriteBatch);
                    character.Inventory.CurrentLayout = CharacterHealth.OpenHealthWindow == null && character.SelectedCharacter == null ?
                                                        CharacterInventory.Layout.Default :
                                                        CharacterInventory.Layout.Right;
                }
            }

            if (!character.IsIncapacitated && character.Stun <= 0.0f)
            {
                if (character.IsHumanoid && character.SelectedCharacter != null && character.SelectedCharacter.Inventory != null)
                {
                    if (character.SelectedCharacter.CanInventoryBeAccessed)
                    {
                        ///character.Inventory.CurrentLayout = Alignment.Left;
                        character.SelectedCharacter.Inventory.CurrentLayout = CharacterInventory.Layout.Left;
                        character.SelectedCharacter.Inventory.DrawOwn(spriteBatch);
                    }
                    else
                    {
                        //character.Inventory.CurrentLayout = (CharacterHealth.OpenHealthWindow == null) ? Alignment.Center : Alignment.Left;
                    }
                    if (CharacterHealth.OpenHealthWindow == character.SelectedCharacter.CharacterHealth)
                    {
                        character.SelectedCharacter.CharacterHealth.Alignment = Alignment.Left;
                        character.SelectedCharacter.CharacterHealth.DrawStatusHUD(spriteBatch);
                    }
                }
                else if (character.Inventory != null)
                {
                    //character.Inventory.CurrentLayout = (CharacterHealth.OpenHealthWindow == null) ? Alignment.Center : Alignment.Left;
                }
            }

            if (mouseOnPortrait)
            {
                GUIComponent.DrawToolTip(
                    spriteBatch,
                    character.Info?.Job == null ? character.DisplayName : character.DisplayName + " (" + character.Info.Job.Name + ")",
                    HUDLayoutSettings.PortraitArea);
            }
        }
Beispiel #9
0
        private void UpdatePlayer(GameTime gameTime)
        {
            player.Update(gameTime);

            if (player.Active)
            {
                // Windows 8 Touch Gestures for MonoGame
                while (TouchPanel.IsGestureAvailable)
                {
                    GestureSample gesture = TouchPanel.ReadGesture();

                    if (gesture.GestureType == GestureType.FreeDrag)
                    {
                        player.Position += gesture.Delta;
                    }
                }

                //Get Mouse State then Capture the Button type and Respond Button Press
                Vector2 mousePosition = new Vector2(currentMouseState.X, currentMouseState.Y);

                if (currentMouseState.LeftButton == ButtonState.Pressed)
                {
                    Vector2 posDelta = mousePosition - player.Position;

                    posDelta.Normalize();
                    posDelta *= playerMoveSpeed;

                    if ((mousePosition - player.Position).Length() <= playerMoveSpeed)
                    {
                        player.Position = mousePosition;
                    }
                    else
                    {
                        player.Position += posDelta;
                    }
                }

                // Get Thumbstick Controls
                player.Position.X += currentGamePadState.ThumbSticks.Left.X * playerMoveSpeed;
                player.Position.Y -= currentGamePadState.ThumbSticks.Left.Y * playerMoveSpeed;

                // Use the Keyboard / Dpad
                if (currentKeyboardState.IsKeyDown(Keys.Left) || currentKeyboardState.IsKeyDown(Keys.A) ||
                    currentGamePadState.DPad.Left == ButtonState.Pressed)
                {
                    player.Position.X -= playerMoveSpeed;
                }
                if (currentKeyboardState.IsKeyDown(Keys.Right) || currentKeyboardState.IsKeyDown(Keys.D) ||
                    currentGamePadState.DPad.Right == ButtonState.Pressed)
                {
                    player.Position.X += playerMoveSpeed;
                }
                if (currentKeyboardState.IsKeyDown(Keys.Up) || currentKeyboardState.IsKeyDown(Keys.W) ||
                    currentGamePadState.DPad.Up == ButtonState.Pressed)
                {
                    player.Position.Y -= playerMoveSpeed;
                }
                if (currentKeyboardState.IsKeyDown(Keys.Down) || currentKeyboardState.IsKeyDown(Keys.S) ||
                    currentGamePadState.DPad.Down == ButtonState.Pressed)
                {
                    player.Position.Y += playerMoveSpeed;
                }
                if (currentKeyboardState.IsKeyDown(Keys.Space) || currentGamePadState.Buttons.X == ButtonState.Pressed)
                {
                    FirePlayerLaser(gameTime);
                }

                // Make sure that the player does not go out of bounds
                player.Position.X = MathHelper.Clamp(player.Position.X, player.Width / 2, GraphicsDevice.Viewport.Width - player.Width / 2);
                player.Position.Y = MathHelper.Clamp(player.Position.Y, player.Height / 2, GraphicsDevice.Viewport.Height - player.Height / 2 + 20);
            }
            else if (!isGameEnded)
            {
                AddExplosion(allyExplosionTexture, player.Position, 2.5f);
                playerExplosionSound.SoundEffectInstance.Play();
                isGameEnded = true;
            }
        }
Beispiel #10
0
        partial void ExplodeProjSpecific(Vector2 worldPosition, Hull hull)
        {
            if (shockwave)
            {
                GameMain.ParticleManager.CreateParticle("shockwave", worldPosition,
                                                        Vector2.Zero, 0.0f, hull);
            }

            hull = hull ?? Hull.FindHull(worldPosition, useWorldCoordinates: true);
            bool underwater = hull == null || worldPosition.Y < hull.WorldSurface;

            if (underwater && underwaterBubble)
            {
                var underwaterExplosion = GameMain.ParticleManager.CreateParticle("underwaterexplosion", worldPosition, Vector2.Zero, 0.0f, hull);
                if (underwaterExplosion != null)
                {
                    underwaterExplosion.Size      *= MathHelper.Clamp(attack.Range / 150.0f, 0.5f, 10.0f);
                    underwaterExplosion.StartDelay = 0.0f;
                }
            }

            for (int i = 0; i < attack.Range * 0.1f; i++)
            {
                if (!underwater)
                {
                    float particleSpeed = Rand.Range(0.0f, 1.0f);
                    particleSpeed = particleSpeed * particleSpeed * attack.Range;

                    if (flames)
                    {
                        float particleScale = MathHelper.Clamp(attack.Range * 0.0025f, 0.5f, 2.0f);
                        var   flameParticle = GameMain.ParticleManager.CreateParticle("explosionfire",
                                                                                      ClampParticlePos(worldPosition + Rand.Vector((float)System.Math.Sqrt(Rand.Range(0.0f, attack.Range))), hull),
                                                                                      Rand.Vector(Rand.Range(0.0f, particleSpeed)), 0.0f, hull);
                        if (flameParticle != null)
                        {
                            flameParticle.Size *= particleScale;
                        }
                    }
                    if (smoke)
                    {
                        var smokeParticle = GameMain.ParticleManager.CreateParticle(Rand.Range(0.0f, 1.0f) < 0.5f ? "explosionsmoke" : "smoke",
                                                                                    ClampParticlePos(worldPosition + Rand.Vector((float)System.Math.Sqrt(Rand.Range(0.0f, attack.Range))), hull),
                                                                                    Rand.Vector(Rand.Range(0.0f, particleSpeed)), 0.0f, hull);
                    }
                }
                else if (underwaterBubble)
                {
                    Vector2 bubblePos = Rand.Vector(Rand.Range(0.0f, attack.Range * 0.5f));

                    GameMain.ParticleManager.CreateParticle("risingbubbles", worldPosition + bubblePos,
                                                            Vector2.Zero, 0.0f, hull);

                    if (i < attack.Range * 0.02f)
                    {
                        var underwaterExplosion = GameMain.ParticleManager.CreateParticle("underwaterexplosion", worldPosition + bubblePos,
                                                                                          Vector2.Zero, 0.0f, hull);
                        if (underwaterExplosion != null)
                        {
                            underwaterExplosion.Size *= MathHelper.Clamp(attack.Range / 300.0f, 0.5f, 2.0f) * Rand.Range(0.8f, 1.2f);
                        }
                    }
                }

                if (sparks)
                {
                    GameMain.ParticleManager.CreateParticle("spark", worldPosition,
                                                            Rand.Vector(Rand.Range(500.0f, 800.0f)), 0.0f, hull);
                }
            }

            if (hull != null && !string.IsNullOrWhiteSpace(decal) && decalSize > 0.0f)
            {
                hull.AddDecal(decal, worldPosition, decalSize);
            }

            if (flash)
            {
                float displayRange = attack.Range;
                if (displayRange < 0.1f)
                {
                    return;
                }

                var light = new LightSource(worldPosition, displayRange, Color.LightYellow, null);
                CoroutineManager.StartCoroutine(DimLight(light));
            }
        }
Beispiel #11
0
        /// <summary>
        /// The update checks for successful ghost selection against the selection render. Successful ones are hidden, and a new one is displayed.
        /// New renders are made each time a new ghost appears on the screen.
        /// </summary>
        /// <param name="gameTime">The game time</param>
        public override void Update(GameTime gameTime)
        {
            MouseState ms = Mouse.GetState();

            if (selectableList[0].selected && (Gesture == ManipMode.GRAB || Gesture == ManipMode.SELECTGRAB))
            {
                Ray ray = XNAHelper.CalculateCursorRay(CursorPos, camera.GetProjectionMatrix(), camera.GetViewMatrix(), game.GraphicsDevice);
                selectableList[0].position   = Vector3.Lerp(selectableList[0].position, ray.Position + (ray.Direction * ratio), (float)gameTime.ElapsedGameTime.TotalSeconds * 8);
                selectableList[0].position.Y = MathHelper.Clamp(selectableList[0].position.Y, ymin, ymax);
                selectableList[0].position.Z = MathHelper.Clamp(selectableList[0].position.Z, zmin, zmax);
                selectableList[0].position.X = xFixed;
            }

            if ((Gesture == ManipMode.SELECT || Gesture == ManipMode.SELECTGRAB) && LastGesture == ManipMode.NONE)
            {
                Rectangle source              = new Rectangle((int)(CursorPos.X - Game1.cursorArea / 2), (int)(CursorPos.Y - Game1.cursorArea / 2), (int)Game1.cursorArea, (int)Game1.cursorArea);
                Color[]   retrieved           = new Color[(int)(Game1.cursorArea * Game1.cursorArea)];
                bool      selectionSuccessful = false;

                try {
                    flatRender.GetData <Color>(0, source, retrieved, 0, (int)(Game1.cursorArea * Game1.cursorArea));
                    //We increment by 2 as an optimization measure, as those values are going to be pretty consistent.
                    for (int i = 0; i < retrieved.Length; i += 2)
                    {
                        if (retrieved[i] == this.selectionColor)
                        {
                            selectableList[0].selected = true;
                            selectionSuccessful        = true;
                            Ray ray = XNAHelper.CalculateCursorRay(new Vector2(ms.X, ms.Y), camera.GetProjectionMatrix(), camera.GetViewMatrix(), game.GraphicsDevice);
                            ratio = Vector3.Distance(ray.Position, selectableList[0].position)
                                    / Vector3.Distance(ray.Position, ray.Position + new Vector3(ray.Direction.X, 0, 0));
                            ((GEntity)selectableList[0]).waiting = true;
                        }
                    }
                    if (selectionSuccessful)
                    {
                        DataLogger.Environment = LoggingEnvironment.YESSELECT;
                    }
                    else
                    {
                        DataLogger.Environment = LoggingEnvironment.NOSELECT;
                    }
                } catch (ArgumentException) {
                    Console.Error.WriteLine("Mouse Click outside Bounds!");
                }
            }

            if (Gesture == ManipMode.NONE && LastGesture != ManipMode.NONE)
            {
                if (((Cage)draggableList[0]).Contains(selectableList[0].position))
                {
                    selectableList[0].selected = false;
                    sceneryList.Insert(0, selectableList[0]);
                    selectableList.RemoveAt(0);
                    ((Firefly)sceneryList[0]).standardColor = Color.Yellow;
                    ((Firefly)sceneryList[0]).RemoveGlow();
                    DataLogger.Environment = LoggingEnvironment.YESDROP;
                    if (selectableList.Count == 0)
                    {
                        complete = true;
                    }
                    else
                    {
                        ((Firefly)selectableList[0]).standardColor = Color.Orange;
                    }
                }
                else
                {
                    DataLogger.Environment = LoggingEnvironment.NODROP;
                }
                renderRequested = true;
            }

            base.Update(gameTime);
        }
        void UpdateRoomToRoom(float deltaTime, Hull hull1, Hull hull2)
        {
            Vector2 subOffset = Vector2.Zero;

            if (hull1.Submarine != Submarine)
            {
                subOffset = Submarine.Position - hull1.Submarine.Position;
            }
            else if (hull2.Submarine != Submarine)
            {
                subOffset = hull2.Submarine.Position - Submarine.Position;
            }

            if (hull1.WaterVolume <= 0.0 && hull2.WaterVolume <= 0.0)
            {
                return;
            }

            float size = IsHorizontal ? rect.Height : rect.Width;

            //a variable affecting the water flow through the gap
            //the larger the gap is, the faster the water flows
            float sizeModifier = size / 100.0f * open;

            //horizontal gap (such as a regular door)
            if (IsHorizontal)
            {
                higherSurface = Math.Max(hull1.Surface, hull2.Surface + subOffset.Y);
                float delta = 0.0f;

                //water level is above the lower boundary of the gap
                if (Math.Max(hull1.Surface + hull1.WaveY[hull1.WaveY.Length - 1], hull2.Surface + subOffset.Y + hull2.WaveY[0]) > rect.Y - size)
                {
                    int dir = (hull1.Pressure > hull2.Pressure + subOffset.Y) ? 1 : -1;

                    //water flowing from the righthand room to the lefthand room
                    if (dir == -1)
                    {
                        if (!(hull2.WaterVolume > 0.0f))
                        {
                            return;
                        }
                        lowerSurface = hull1.Surface - hull1.WaveY[hull1.WaveY.Length - 1];
                        //delta = Math.Min((room2.water.pressure - room1.water.pressure) * sizeModifier, Math.Min(room2.water.Volume, room2.Volume));
                        //delta = Math.Min(delta, room1.Volume - room1.water.Volume + Water.MaxCompress);

                        flowTargetHull = hull1;

                        //make sure not to move more than what the room contains
                        delta = Math.Min(((hull2.Pressure + subOffset.Y) - hull1.Pressure) * 5.0f * sizeModifier, Math.Min(hull2.WaterVolume, hull2.Volume));

                        //make sure not to place more water to the target room than it can hold
                        delta              = Math.Min(delta, hull1.Volume * Hull.MaxCompress - (hull1.WaterVolume));
                        hull1.WaterVolume += delta;
                        hull2.WaterVolume -= delta;
                        if (hull1.WaterVolume > hull1.Volume)
                        {
                            hull1.Pressure = Math.Max(hull1.Pressure, (hull1.Pressure + hull2.Pressure + subOffset.Y) / 2);
                        }

                        flowForce = new Vector2(-delta, 0.0f);
                    }
                    else if (dir == 1)
                    {
                        if (!(hull1.WaterVolume > 0.0f))
                        {
                            return;
                        }
                        lowerSurface = hull2.Surface - hull2.WaveY[hull2.WaveY.Length - 1];

                        flowTargetHull = hull2;

                        //make sure not to move more than what the room contains
                        delta = Math.Min((hull1.Pressure - (hull2.Pressure + subOffset.Y)) * 5.0f * sizeModifier, Math.Min(hull1.WaterVolume, hull1.Volume));

                        //make sure not to place more water to the target room than it can hold
                        delta              = Math.Min(delta, hull2.Volume * Hull.MaxCompress - (hull2.WaterVolume));
                        hull1.WaterVolume -= delta;
                        hull2.WaterVolume += delta;
                        if (hull2.WaterVolume > hull2.Volume)
                        {
                            hull2.Pressure = Math.Max(hull2.Pressure, ((hull1.Pressure - subOffset.Y) + hull2.Pressure) / 2);
                        }

                        flowForce = new Vector2(delta, 0.0f);
                    }

                    if (delta > 100.0f && subOffset == Vector2.Zero)
                    {
                        float avg = (hull1.Surface + hull2.Surface) / 2.0f;

                        if (hull1.WaterVolume < hull1.Volume / Hull.MaxCompress &&
                            hull1.Surface + hull1.WaveY[hull1.WaveY.Length - 1] < rect.Y)
                        {
                            hull1.WaveVel[hull1.WaveY.Length - 1] = (avg - (hull1.Surface + hull1.WaveY[hull1.WaveY.Length - 1])) * 0.1f;
                            hull1.WaveVel[hull1.WaveY.Length - 2] = hull1.WaveVel[hull1.WaveY.Length - 1];
                        }

                        if (hull2.WaterVolume < hull2.Volume / Hull.MaxCompress &&
                            hull2.Surface + hull2.WaveY[0] < rect.Y)
                        {
                            hull2.WaveVel[0] = (avg - (hull2.Surface + hull2.WaveY[0])) * 0.1f;
                            hull2.WaveVel[1] = hull2.WaveVel[0];
                        }
                    }
                }
            }
            else
            {
                //lower room is full of water
                if (hull2.Pressure + subOffset.Y > hull1.Pressure && hull2.WaterVolume > 0.0f)
                {
                    float delta = Math.Min(hull2.WaterVolume - hull2.Volume + (hull2.Volume * Hull.MaxCompress), deltaTime * 8000.0f * sizeModifier);

                    //make sure not to place more water to the target room than it can hold
                    if (hull1.WaterVolume + delta > hull1.Volume * Hull.MaxCompress)
                    {
                        delta -= (hull1.WaterVolume + delta) - (hull1.Volume * Hull.MaxCompress);
                    }

                    delta              = Math.Max(delta, 0.0f);
                    hull1.WaterVolume += delta;
                    hull2.WaterVolume -= delta;

                    flowForce = new Vector2(
                        0.0f,
                        Math.Min(Math.Min((hull2.Pressure + subOffset.Y) - hull1.Pressure, 200.0f), delta));

                    flowTargetHull = hull1;

                    if (hull1.WaterVolume > hull1.Volume)
                    {
                        hull1.Pressure = Math.Max(hull1.Pressure, (hull1.Pressure + (hull2.Pressure + subOffset.Y)) / 2);
                    }
                }
                //there's water in the upper room, drop to lower
                else if (hull1.WaterVolume > 0)
                {
                    flowTargetHull = hull2;

                    //make sure the amount of water moved isn't more than what the room contains
                    float delta = Math.Min(hull1.WaterVolume, deltaTime * 25000f * sizeModifier);

                    //make sure not to place more water to the target room than it can hold
                    if (hull2.WaterVolume + delta > hull2.Volume * Hull.MaxCompress)
                    {
                        delta -= (hull2.WaterVolume + delta) - (hull2.Volume * Hull.MaxCompress);
                    }
                    hull1.WaterVolume -= delta;
                    hull2.WaterVolume += delta;

                    flowForce = new Vector2(
                        hull1.WaveY[hull1.GetWaveIndex(rect.X)] - hull1.WaveY[hull1.GetWaveIndex(rect.Right)],
                        MathHelper.Clamp(-delta, -200.0f, 0.0f));

                    if (hull2.WaterVolume > hull2.Volume)
                    {
                        hull2.Pressure = Math.Max(hull2.Pressure, ((hull1.Pressure - subOffset.Y) + hull2.Pressure) / 2);
                    }
                }
            }

            if (open > 0.0f)
            {
                if (hull1.WaterVolume > hull1.Volume / Hull.MaxCompress && hull2.WaterVolume > hull2.Volume / Hull.MaxCompress)
                {
                    float avgLethality = (hull1.LethalPressure + hull2.LethalPressure) / 2.0f;
                    hull1.LethalPressure = avgLethality;
                    hull2.LethalPressure = avgLethality;
                }
                else
                {
                    hull1.LethalPressure = 0.0f;
                    hull2.LethalPressure = 0.0f;
                }
            }
        }
Beispiel #13
0
 public static int Clamp(int value)
 {
     return MathHelper.Clamp(value, 0, UnitMax);
 }
        public static void ExportHitsounds(List <HitsoundEvent> hitsounds, string baseBeatmap, string exportFolder, string exportMapName, GameMode exportGameMode, bool useGreenlines, bool useStoryboard)
        {
            var     editor  = EditorReaderStuff.GetNewestVersionOrNot(baseBeatmap);
            Beatmap beatmap = editor.Beatmap;

            if (useStoryboard)
            {
                beatmap.StoryboardSoundSamples.Clear();
                foreach (var h in hitsounds.Where(h => !string.IsNullOrEmpty(h.Filename)))
                {
                    beatmap.StoryboardSoundSamples.Add(new StoryboardSoundSample((int)Math.Round(h.Time), 0, h.Filename, h.Volume * 100));
                }
            }
            else
            {
                // Make new timing points
                // Add red lines
                var redlines = beatmap.BeatmapTiming.Redlines;
                List <TimingPointsChange> timingPointsChanges = redlines.Select(tp =>
                                                                                new TimingPointsChange(tp, mpb: true, meter: true, unInherited: true, omitFirstBarLine: true))
                                                                .ToList();

                // Add hitsound stuff
                // Replace all hitobjects with the hitsounds
                beatmap.HitObjects.Clear();
                foreach (HitsoundEvent h in hitsounds)
                {
                    if (useGreenlines)
                    {
                        TimingPoint tp = beatmap.BeatmapTiming.GetTimingPointAtTime(h.Time + 5).Copy();
                        tp.Offset      = h.Time;
                        tp.SampleIndex = h.CustomIndex;
                        h.CustomIndex  = 0; // Set it to default value because it gets handled by greenlines now
                        tp.Volume      = Math.Round(tp.Volume * h.Volume);
                        h.Volume       = 0; // Set it to default value because it gets handled by greenlines now
                        timingPointsChanges.Add(new TimingPointsChange(tp, index: true, volume: true));
                    }

                    beatmap.HitObjects.Add(new HitObject(h.Pos, h.Time, 5, h.GetHitsounds(), h.SampleSet, h.Additions,
                                                         h.CustomIndex, h.Volume * 100, h.Filename));
                }

                // Replace the old timingpoints
                beatmap.BeatmapTiming.Clear();
                TimingPointsChange.ApplyChanges(beatmap.BeatmapTiming, timingPointsChanges);
            }

            // Change version to hitsounds
            beatmap.General["StackLeniency"] = new TValue("0.0");
            beatmap.General["Mode"]          = new TValue(((int)exportGameMode).ToInvariant());
            beatmap.Metadata["Version"]      = new TValue(exportMapName);

            if (exportGameMode == GameMode.Mania)
            {
                // Count the number of distinct X positions
                int numXPositions = new HashSet <double>(hitsounds.Select(h => h.Pos.X)).Count;
                int numKeys       = MathHelper.Clamp(numXPositions, 1, 18);

                beatmap.Difficulty["CircleSize"] = new TValue(numKeys.ToInvariant());
            }
            else
            {
                beatmap.Difficulty["CircleSize"] = new TValue("4");
            }

            // Save the file to the export folder
            editor.SaveFile(Path.Combine(exportFolder, beatmap.GetFileName()));
        }
Beispiel #15
0
        public override void Update(GameTime gameTime)
        {
            for (int i = 0; i < _menuItems.Count; i++)
            {
                if (_menuItems[i].Position.Contains(MonsterGame.Instance.Scaler.ScaleInput(InputManager.CurrentState.Position.ToVector2()).ToPoint()))
                {
                    _selectedIndex = i;
                }
            }

            switch (_state)
            {
            case TitleState.Select:
                if (InputManager.CurrentState.Start)
                {
                    switch (_selectedIndex)
                    {
                    case 0:
                        AudioManager.SoundEffectInstances[AudioManager.Cue.TitleScreenMusic].Stop();
                        AudioManager.SoundEffectInstances[AudioManager.Cue.Start].Play();
                        _state = TitleState.Start;
                        break;

                    case 1:
                        MonsterGame.Instance.SetState(GameState.Achievements);
                        break;

                    case 2:
                        MonsterGame.Instance.SetState(GameState.Leaderboard);
                        break;

                    default:
                        AudioManager.SoundEffects[AudioManager.Cue.MenuSelect].Play();
                        break;
                    }
                }

                if (InputManager.CurrentState.Up)
                {
                    _selectedIndex = MathHelper.Clamp(_selectedIndex - 1, 0, _menuItems.Count - 1);
                    AudioManager.SoundEffects[AudioManager.Cue.MenuUpDown].Play();
                }
                if (InputManager.CurrentState.Down)
                {
                    _selectedIndex = MathHelper.Clamp(_selectedIndex + 1, 0, _menuItems.Count - 1);
                    AudioManager.SoundEffects[AudioManager.Cue.MenuUpDown].Play();
                }
                break;

            case TitleState.Start:
                if (AudioManager.SoundEffectInstances[AudioManager.Cue.Start].State != SoundState.Playing)
                {
                    MonsterGame.Instance.SetState(GameState.GameScreen);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            _gamerCard.SetUserProfile(XboxLiveManager.Profile);
            _gamerCard.Update(gameTime);

            FontManager.YPosition = 500;
        }
Beispiel #16
0
        /// <summary>
        /// Sets the vibration motor speeds on the controller device if supported.
        /// </summary>
        /// <param name="playerIndex">Player index that identifies the controller to set.</param>
        /// <param name="leftMotor">The speed of the left motor, between 0.0 and 1.0. This motor is a low-frequency motor.</param>
        /// <param name="rightMotor">The speed of the right motor, between 0.0 and 1.0. This motor is a high-frequency motor.</param>
        /// <returns>Returns true if the vibration motors were set.</returns>
        public static bool SetVibration(PlayerIndex playerIndex, float leftMotor, float rightMotor)
        {
            // Make sure the player index is in range.
            var index = (int)playerIndex;

            if (index < (int)PlayerIndex.One || index > (int)PlayerIndex.Four)
            {
                throw new InvalidOperationException();
            }

            return(PlatformSetVibration(index, MathHelper.Clamp(leftMotor, 0.0f, 1.0f), MathHelper.Clamp(rightMotor, 0.0f, 1.0f)));
        }
Beispiel #17
0
        public override void Update(float deltaTime, Camera cam)
        {
            if (GameMain.Server != null && nextServerLogWriteTime != null)
            {
                if (Timing.TotalTime >= (float)nextServerLogWriteTime)
                {
                    GameServer.Log(lastUser + " adjusted reactor settings: " +
                                   "Temperature: " + (int)temperature +
                                   ", Fission rate: " + (int)fissionRate +
                                   ", Cooling rate: " + (int)coolingRate +
                                   ", Cooling rate: " + coolingRate +
                                   ", Shutdown temp: " + shutDownTemp +
                                   (autoTemp ? ", Autotemp ON" : ", Autotemp OFF"),
                                   ServerLog.MessageType.ItemInteraction);

                    nextServerLogWriteTime = null;
                    lastServerLogWriteTime = (float)Timing.TotalTime;
                }
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, null);

            fissionRate = Math.Min(fissionRate, AvailableFuel);

            float heat            = 80 * fissionRate * (AvailableFuel / 2000.0f);
            float heatDissipation = 50 * coolingRate + Math.Max(ExtraCooling, 5.0f);

            float deltaTemp = (((heat - heatDissipation) * 5) - temperature) / 10000.0f;

            Temperature = temperature + deltaTemp;

            if (temperature > fireTemp && temperature - deltaTemp < fireTemp)
            {
                Vector2 baseVel = Rand.Vector(300.0f);
                for (int i = 0; i < 10; i++)
                {
                    var particle = GameMain.ParticleManager.CreateParticle("spark", item.WorldPosition,
                                                                           baseVel + Rand.Vector(100.0f), 0.0f, item.CurrentHull);

                    if (particle != null)
                    {
                        particle.Size *= Rand.Range(0.5f, 1.0f);
                    }
                }

                new FireSource(item.WorldPosition);
            }

            if (temperature > meltDownTemp)
            {
                MeltDown();
                return;
            }
            else if (temperature == 0.0f)
            {
                if (powerUpTask == null || powerUpTask.IsFinished)
                {
                    powerUpTask = new PropertyTask(item, IsRunning, 50.0f, "Power up the reactor");
                }
            }

            load = 0.0f;

            List <Connection> connections = item.Connections;

            if (connections != null && connections.Count > 0)
            {
                foreach (Connection connection in connections)
                {
                    if (!connection.IsPower)
                    {
                        continue;
                    }
                    foreach (Connection recipient in connection.Recipients)
                    {
                        Item it = recipient.Item as Item;
                        if (it == null)
                        {
                            continue;
                        }

                        PowerTransfer pt = it.GetComponent <PowerTransfer>();
                        if (pt == null)
                        {
                            continue;
                        }

                        load = Math.Max(load, pt.PowerLoad);
                    }
                }
            }

            //item.Condition -= temperature * deltaTime * 0.00005f;

            if (temperature > shutDownTemp)
            {
                CoolingRate += 0.5f;
                FissionRate -= 0.5f;
            }
            else if (autoTemp)
            {
                //take deltaTemp into account to slow down the change in temperature when getting closer to the desired value
                float target = temperature + deltaTemp * 100.0f;

                //-1.0f in order to gradually turn down both rates when the target temperature is reached
                FissionRate += (MathHelper.Clamp(load - target, -10.0f, 10.0f) - 1.0f) * deltaTime;
                CoolingRate += (MathHelper.Clamp(target - load, -5.0f, 5.0f) - 1.0f) * deltaTime;
            }

            //the power generated by the reactor is equal to the temperature
            currPowerConsumption = -temperature * powerPerTemp;

            if (item.CurrentHull != null)
            {
                //the sound can be heard from 20 000 display units away when running at full power
                item.CurrentHull.SoundRange = Math.Max(temperature * 2, item.CurrentHull.AiTarget.SoundRange);
            }

            UpdateGraph(deltaTime);

            ExtraCooling  = 0.0f;
            AvailableFuel = 0.0f;

            item.SendSignal(0, ((int)temperature).ToString(), "temperature_out", null);

            sendUpdateTimer = Math.Max(sendUpdateTimer - deltaTime, 0.0f);

            if (unsentChanges && sendUpdateTimer <= 0.0f)
            {
                if (GameMain.Server != null)
                {
                    item.CreateServerEvent(this);
                }
                else if (GameMain.Client != null)
                {
                    item.CreateClientEvent(this);
                }

                sendUpdateTimer = NetworkUpdateInterval;
                unsentChanges   = false;
            }
        }
Beispiel #18
0
        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            HandleInput(gameTime);

            if (recenter)
            {
                Recenter(gameTime);
                recenter = false;
            }
            else
            {
                // tratar da rotacao e posicao do tank
                _turnAmount       = MathHelper.Clamp(_turnAmount, -1, 1);
                _facingDirection += _turnAmount * _rotationSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
                //_facingDirection = MathHelper.WrapAngle(FacingDirection);
            }

            _facingDirectionMatrix = Matrix.CreateRotationY(_facingDirection);

            if (_camera is ChaseCamera)
            {
                UpdateChaseCameraDirection((ChaseCamera)_camera);
            }

            Vector3 velocity = Vector3.Transform(_movement, _orientation);

            velocity *= _maxSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

            Vector3 newPosition = Position + velocity;

            // calculate tank orientation
            Vector3 normal;

            normal = _terrain.GetInterpolatedNormalAt(newPosition.X, newPosition.Z);

            UpdateTankOrientation(normal);
            UpdateTankTurretOrientation(normal);
            UpdateTankCanonOrientation(normal);

            //calculate wheel rotation
            float distanceMoved = Vector3.Distance(_position, newPosition);
            float theta         = distanceMoved / _tankWheelRadius;
            int   rollDirection = _movement.Z < 0 ? 1 : -1;

            wheelRollMatrix *= Matrix.CreateRotationX(theta * rollDirection);

            _position = newPosition;

            _position.Y = _terrain.GetInterpolatedHeightAt(_position.X, _position.Z);

            if (distanceMoved > 0 && !soundIsPlaying)
            {
                _soundTankGoInstance.Play();
                soundIsPlaying = true;
            }
            else
            {
                _soundTankGoInstance.Stop();
            }

            if (_camera != null)
            {
                UpdateCamera(gameTime);
            }

            UpdateCanonManager(gameTime);
            UpdateTank(gameTime);

            base.Update(gameTime);
        }
Beispiel #19
0
        private string TransformProperties(PropertyTransformerVm vm, BackgroundWorker worker, DoWorkEventArgs _) {
            bool doFilterMatch = vm.MatchFilter != -1 && vm.EnableFilters;
            bool doFilterRange = (vm.MinTimeFilter != -1 || vm.MaxTimeFilter != -1) && vm.EnableFilters;
            double min = vm.MinTimeFilter == -1 ? double.NegativeInfinity : vm.MinTimeFilter;
            double max = vm.MaxTimeFilter == -1 ? double.PositiveInfinity : vm.MaxTimeFilter;

            var reader = EditorReaderStuff.GetFullEditorReaderOrNot();

            foreach (string path in vm.ExportPaths) {
                Editor editor;
                if (Path.GetExtension(path) == ".osb") {
                    editor = new StoryboardEditor(path);
                } else {
                    editor = EditorReaderStuff.GetNewestVersionOrNot(path, reader);
                }

                if (editor is BeatmapEditor beatmapEditor) {
                    Beatmap beatmap = beatmapEditor.Beatmap;

                    List<TimingPointsChange> timingPointsChanges = new List<TimingPointsChange>();
                    foreach (TimingPoint tp in beatmap.BeatmapTiming.TimingPoints) {
                        // Offset
                        if (vm.TimingpointOffsetMultiplier != 1 || vm.TimingpointOffsetOffset != 0) {
                            if (Filter(tp.Offset, tp.Offset, doFilterMatch, doFilterRange, vm.MatchFilter, min, max)) {
                                tp.Offset = Math.Round(tp.Offset * vm.TimingpointOffsetMultiplier +
                                                       vm.TimingpointOffsetOffset);
                            }
                        }

                        // BPM
                        if (vm.TimingpointBPMMultiplier != 1 || vm.TimingpointBPMOffset != 0) {
                            if (tp.Uninherited) {
                                if (Filter(tp.GetBpm(), tp.Offset, doFilterMatch, doFilterRange, vm.MatchFilter, min,
                                    max)) {
                                    double newBPM = tp.GetBpm() * vm.TimingpointBPMMultiplier + vm.TimingpointBPMOffset;
                                    newBPM = vm.ClipProperties
                                        ? MathHelper.Clamp(newBPM, 15, 10000)
                                        : newBPM; // Clip the value if specified
                                    tp.MpB = 60000 / newBPM;
                                }
                            }
                        }

                        // Slider Velocity
                        if (vm.TimingpointSVMultiplier != 1 || vm.TimingpointSVOffset != 0) {
                            if (Filter(beatmap.BeatmapTiming.GetSvMultiplierAtTime(tp.Offset), tp.Offset, doFilterMatch,
                                doFilterRange, vm.MatchFilter, min, max)) {
                                TimingPoint tpchanger = tp.Copy();
                                double newSV =
                                    beatmap.BeatmapTiming.GetSvMultiplierAtTime(tp.Offset) *
                                    vm.TimingpointSVMultiplier + vm.TimingpointSVOffset;
                                newSV = vm.ClipProperties
                                    ? MathHelper.Clamp(newSV, 0.1, 10)
                                    : newSV; // Clip the value if specified
                                tpchanger.MpB = -100 / newSV;
                                timingPointsChanges.Add(new TimingPointsChange(tpchanger, mpb: true));
                            }
                        }

                        // Index
                        if (vm.TimingpointIndexMultiplier != 1 || vm.TimingpointIndexOffset != 0) {
                            if (Filter(tp.SampleIndex, tp.Offset, doFilterMatch, doFilterRange, vm.MatchFilter, min,
                                max)) {
                                int newIndex =
                                    (int) Math.Round(tp.SampleIndex * vm.TimingpointIndexMultiplier +
                                                     vm.TimingpointIndexOffset);
                                tp.SampleIndex = vm.ClipProperties ? MathHelper.Clamp(newIndex, 0, 100) : newIndex;
                            }
                        }

                        // Volume
                        if (vm.TimingpointVolumeMultiplier != 1 || vm.TimingpointVolumeOffset != 0) {
                            if (Filter(tp.Volume, tp.Offset, doFilterMatch, doFilterRange, vm.MatchFilter, min, max)) {
                                int newVolume =
                                    (int) Math.Round(tp.Volume * vm.TimingpointVolumeMultiplier +
                                                     vm.TimingpointVolumeOffset);
                                tp.Volume = vm.ClipProperties ? MathHelper.Clamp(newVolume, 5, 100) : newVolume;
                            }
                        }
                    }

                    UpdateProgressBar(worker, 20);

                    // Hitobject time
                    if (vm.HitObjectTimeMultiplier != 1 || vm.HitObjectTimeOffset != 0) {
                        foreach (HitObject ho in beatmap.HitObjects) {
                            if (Filter(ho.Time, ho.Time, doFilterMatch, doFilterRange, vm.MatchFilter, min, max)) {
                                ho.Time = Math.Round(ho.Time * vm.HitObjectTimeMultiplier + vm.HitObjectTimeOffset);
                            }

                            // Transform end time of hold notes and spinner
                            if ((ho.IsHoldNote || ho.IsSpinner) &&
                                Filter(ho.EndTime, ho.EndTime, doFilterMatch, doFilterRange, vm.MatchFilter, min,
                                    max)) {
                                ho.EndTime = Math.Round(ho.Time * vm.HitObjectTimeMultiplier + vm.HitObjectTimeOffset);
                            }
                        }
                    }

                    UpdateProgressBar(worker, 30);

                    // Bookmark time
                    if (vm.BookmarkTimeMultiplier != 1 || vm.BookmarkTimeOffset != 0) {
                        List<double> newBookmarks = new List<double>();
                        List<double> bookmarks = beatmap.GetBookmarks();
                        foreach (double bookmark in bookmarks) {
                            if (Filter(bookmark, bookmark, doFilterMatch, doFilterRange, vm.MatchFilter, min, max)) {
                                newBookmarks.Add(
                                    Math.Round(bookmark * vm.BookmarkTimeMultiplier + vm.BookmarkTimeOffset));
                            }
                            else {
                                newBookmarks.Add(bookmark);
                            }
                        }

                        beatmap.SetBookmarks(newBookmarks);
                    }

                    UpdateProgressBar(worker, 40);

                    // Storyboarded event time
                    if (vm.SBEventTimeMultiplier != 1 || vm.SBEventTimeOffset != 0) {
                        foreach (Event ev in beatmap.StoryboardLayerBackground.Concat(beatmap.StoryboardLayerFail)
                            .Concat(beatmap.StoryboardLayerPass).Concat(beatmap.StoryboardLayerForeground)
                            .Concat(beatmap.StoryboardLayerOverlay)) {
                            TransformEventTime(ev, vm.SBEventTimeMultiplier, vm.SBEventTimeOffset, doFilterMatch,
                                doFilterRange, vm.MatchFilter, min, max);
                        }
                    }

                    UpdateProgressBar(worker, 50);

                    // Storyboarded sample time
                    if (vm.SBSampleTimeMultiplier != 1 || vm.SBSampleTimeOffset != 0) {
                        foreach (StoryboardSoundSample ss in beatmap.StoryboardSoundSamples) {
                            if (Filter(ss.StartTime, ss.StartTime, doFilterMatch, doFilterRange, vm.MatchFilter, min,
                                max)) {
                                ss.StartTime =
                                    (int) Math.Round(ss.StartTime * vm.SBSampleTimeMultiplier + vm.SBSampleTimeOffset);
                            }
                        }
                    }

                    UpdateProgressBar(worker, 60);

                    // Break time
                    if (vm.BreakTimeMultiplier != 1 || vm.BreakTimeOffset != 0) {
                        foreach (Break br in beatmap.BreakPeriods) {
                            if (Filter(br.StartTime, br.StartTime, doFilterMatch, doFilterRange, vm.MatchFilter, min,
                                max)) {
                                br.StartTime =
                                    (int) Math.Round(br.StartTime * vm.BreakTimeMultiplier + vm.BreakTimeOffset);
                            }

                            if (Filter(br.EndTime, br.EndTime, doFilterMatch, doFilterRange, vm.MatchFilter, min,
                                max)) {
                                br.EndTime = (int) Math.Round(br.EndTime * vm.BreakTimeMultiplier + vm.BreakTimeOffset);
                            }
                        }
                    }

                    UpdateProgressBar(worker, 70);

                    // Video start time
                    if (vm.VideoTimeMultiplier != 1 || vm.VideoTimeOffset != 0) {
                        foreach (Event ev in beatmap.BackgroundAndVideoEvents) {
                            if (ev is Video video) {
                                if (Filter(video.StartTime, video.StartTime, doFilterMatch, doFilterRange,
                                    vm.MatchFilter, min, max)) {
                                    video.StartTime =
                                        (int) Math.Round(video.StartTime * vm.VideoTimeMultiplier + vm.VideoTimeOffset);
                                }
                            }
                        }
                    }

                    UpdateProgressBar(worker, 80);

                    // Preview point time
                    if (vm.PreviewTimeMultiplier != 1 || vm.PreviewTimeOffset != 0) {
                        if (beatmap.General.ContainsKey("PreviewTime") &&
                            beatmap.General["PreviewTime"].IntValue != -1) {
                            var previewTime = beatmap.General["PreviewTime"].DoubleValue;
                            if (Filter(previewTime, previewTime, doFilterMatch, doFilterRange, vm.MatchFilter, min,
                                max)) {
                                var newPreviewTime =
                                    Math.Round(previewTime * vm.PreviewTimeMultiplier + vm.PreviewTimeOffset);
                                beatmap.General["PreviewTime"].SetDouble(newPreviewTime);
                            }
                        }
                    }

                    UpdateProgressBar(worker, 90);

                    TimingPointsChange.ApplyChanges(beatmap.BeatmapTiming, timingPointsChanges);

                    // Save the file
                    beatmapEditor.SaveFile();

                    UpdateProgressBar(worker, 100);
                } else if (editor is StoryboardEditor storyboardEditor) {
                    StoryBoard storyboard = storyboardEditor.StoryBoard;
                    
                    // Storyboarded event time
                    if (vm.SBEventTimeMultiplier != 1 || vm.SBEventTimeOffset != 0) {
                        foreach (Event ev in storyboard.StoryboardLayerBackground.Concat(storyboard.StoryboardLayerFail)
                            .Concat(storyboard.StoryboardLayerPass).Concat(storyboard.StoryboardLayerForeground)
                            .Concat(storyboard.StoryboardLayerOverlay)) {
                            TransformEventTime(ev, vm.SBEventTimeMultiplier, vm.SBEventTimeOffset, doFilterMatch,
                                doFilterRange, vm.MatchFilter, min, max);
                        }
                    }

                    UpdateProgressBar(worker, 50);

                    // Storyboarded sample time
                    if (vm.SBSampleTimeMultiplier != 1 || vm.SBSampleTimeOffset != 0) {
                        foreach (StoryboardSoundSample ss in storyboard.StoryboardSoundSamples) {
                            if (Filter(ss.StartTime, ss.StartTime, doFilterMatch, doFilterRange, vm.MatchFilter, min,
                                max)) {
                                ss.StartTime =
                                    (int)Math.Round(ss.StartTime * vm.SBSampleTimeMultiplier + vm.SBSampleTimeOffset);
                            }
                        }
                    }

                    UpdateProgressBar(worker, 70);

                    // Video start time
                    if (vm.VideoTimeMultiplier != 1 || vm.VideoTimeOffset != 0) {
                        foreach (Event ev in storyboard.BackgroundAndVideoEvents) {
                            if (ev is Video video) {
                                if (Filter(video.StartTime, video.StartTime, doFilterMatch, doFilterRange,
                                    vm.MatchFilter, min, max)) {
                                    video.StartTime =
                                        (int)Math.Round(video.StartTime * vm.VideoTimeMultiplier + vm.VideoTimeOffset);
                                }
                            }
                        }
                    }

                    UpdateProgressBar(worker, 90);

                    // Save the file
                    storyboardEditor.SaveFile();

                    UpdateProgressBar(worker, 100);
                }
            }

            return "Done!";
        }
Beispiel #20
0
 public virtual void DealDamage(int damage)
 {
     health -= (int)(damage - MathHelper.Clamp(defense, 0, damage - 1));
 }
Beispiel #21
0
        /// <summary>
        ///     Allows the game to run logic such as updating the world.
        /// </summary>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
                Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            var screenBounds = GraphicsDevice.Viewport.Bounds;
            var touchState   = Keyboard.GetState();

            //Down paddle control
            if (touchState.IsKeyDown(Keys.Left))
            {
                PaddleBottom.X -= (float)(PaddleBottom.Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
            }
            if (touchState.IsKeyDown(Keys.Right))
            {
                PaddleBottom.X += (float)(PaddleBottom.Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
            }

            //Top paddle control
            if (touchState.IsKeyDown(Keys.A))
            {
                PaddleTop.X -= (float)(PaddleTop.Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
                _paddleAi    = false;
            }
            if (touchState.IsKeyDown(Keys.D))
            {
                PaddleTop.X += (float)(PaddleTop.Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
                _paddleAi    = false;
            }

            if (_paddleAi)
            {
                PaddleTop.X = MathHelper.Lerp(PaddleTop.X, PaddleTop.X + PaddleAI.Move(PaddleTop, Ball) * (float)(PaddleTop.Speed * gameTime.ElapsedGameTime.TotalMilliseconds), Ball.GetElement(0).Speed > 1 ? 1 : (Ball.GetElement(0).Speed / 1.2f));
            }

            //Limit paddle position
            PaddleBottom.X =
                MathHelper.Clamp(PaddleBottom.X, screenBounds.Left, screenBounds.Right - PaddleBottom.Width);
            PaddleTop.X = MathHelper.Clamp(PaddleTop.X, screenBounds.Left, screenBounds.Right - PaddleTop.Width);

            foreach (var ball in Ball)
            {
                //Ball movement
                var ballPositionChange =
                    ball.Direction * (float)(gameTime.ElapsedGameTime.TotalMilliseconds * ball.Speed);
                ball.X += ballPositionChange.X;
                ball.Y += ballPositionChange.Y;

                // Ball hitting side walls
                if (CollisionDetector.Overlaps(ball, Walls.GetElement(0)) ||
                    CollisionDetector.Overlaps(ball, Walls.GetElement(1)))
                {
                    HitSound.Play(0.2f, 0, 0);
                    ball.Direction.invertX();
                    if (ball.Speed < GameConstants.DefaultMaxBallSpeed)
                    {
                        ball.Speed *= ball.BumpSpeedIncreaseFactor;
                    }
                }

                // Ball hitting goals
                if (CollisionDetector.Overlaps(ball, Goals.GetElement(0)))
                {
                    Score.Player1++;
                    if (Ball.Count == 1)
                    {
                        ResetBall();
                    }
                    else
                    {
                        Ball.Remove(ball);
                    }
                }
                if (CollisionDetector.Overlaps(ball, Goals.GetElement(1)))
                {
                    Score.Player2++;
                    if (Ball.Count == 1)
                    {
                        ResetBall();
                    }
                    else
                    {
                        Ball.Remove(ball);
                    }
                }

                // Ball hitting paddles
                if (CollisionDetector.Overlaps(ball, PaddleTop) || CollisionDetector.Overlaps(ball, PaddleBottom))
                {
                    HitSound.Play(0.2f, 0, 0);
                    ball.Direction.invertY();
                    if (ball.Speed < GameConstants.DefaultMaxBallSpeed)
                    {
                        ball.Speed *= ball.BumpSpeedIncreaseFactor;
                    }

                    if (ball == Ball.GetElement(0))
                    {
                        SpawnPickups();
                    }
                }

                if (Timer.Equals("0"))
                {
                    foreach (var pickup in Pickups)
                    {
                        if (!CollisionDetector.Overlaps(ball, pickup))
                        {
                            continue;
                        }
                        pickup.Activate(this);
                        Pickups.Remove(pickup);
                    }
                }
            }

            //Ball outside of the screen
            if (!new Rectangle(-GameConstants.WallDefaultSize, -GameConstants.WallDefaultSize,
                               screenBounds.Width + GameConstants.WallDefaultSize,
                               screenBounds.Height + GameConstants.WallDefaultSize)
                .Intersects(new Rectangle((int)Ball.GetElement(0).X, (int)Ball.GetElement(0).Y,
                                          Ball.GetElement(0).Width, Ball.GetElement(0).Height)))
            {
                ResetBall();
            }

            base.Update(gameTime);
        }
Beispiel #22
0
        public virtual void Update(GameTime gameTime)
        {
            float elapsedSeconds      = (float)gameTime.ElapsedGameTime.TotalSeconds;
            float elapsedMilliseconds = (float)gameTime.ElapsedGameTime.Milliseconds;

            position += elapsedMilliseconds * velocity;
            Vector2 p = new Vector2(MathHelper.Clamp(position.X, width / 2, Game1.WINDOW_WIDTH - width / 2), MathHelper.Clamp(position.Y, height / 2, Game1.WINDOW_HEIGHT - height / 2));

            position = p;

            List <Player> tile = GridManager.GridTile(position);

            if (gridTile != tile)
            {
                gridTile.Remove(this);
                tile.Add(this);
                gridTile = tile;
            }

            if (!moving)
            {
                playerAnimation.Stop();
            }
            else
            {
                playerAnimation.Play();
            }
            if (health <= 0)
            {
                isAlive = false;
                gridTile.Remove(this);
            }
            playerAnimation.UpdateFrame(elapsedSeconds);
        }
 public void SetAlpha(float whenOver, float whenOut)
 {
     alphaOver = MathHelper.Clamp(whenOver, 0f, 1f);
     alphaOut  = MathHelper.Clamp(whenOut, 0f, 1f);
 }
Beispiel #24
0
        public static void Update(GameTime gameTime, float timer)
        {
            IsUpdating = true;

            //CleanList();

            foreach (var entity in Entities)
            {
                //  var collision = CheckCollision(entity);

                switch (entity)
                {
                case MainPlayer mp:
                    //check if player has been hit.
                    if (mp.Invulnerable == true)
                    {
                        if (playerStatusChecked == false)
                        {
                            playerStatusChecked = true;
                            playerStartNoDamage = gameTime.TotalGameTime;
                        }

                        if (gameTime.TotalGameTime - playerStartNoDamage >= playerInvulnerable)
                        {
                            mp.Invulnerable     = false;
                            playerStatusChecked = false;
                        }
                    }
                    //Prevent player from going out of bounds
                    mp.Position.X = MathHelper.Clamp(entity.Position.X, GameArt.MainPlayer.Width, GameRoot.GraphicsDevice.Viewport.Width);
                    mp.Position.Y = MathHelper.Clamp(entity.Position.Y, 0, GameRoot.GraphicsDevice.Viewport.Height - GameArt.MainPlayer.Height);
                    break;

                case StandardEnemy se:
                    if (se.Position.X > 0 && se.Position.X < GameRoot.GraphicsDevice.Viewport.Width && se.Position.Y > 0 && se.Position.Y < GameRoot.GraphicsDevice.Viewport.Height)
                    {
                        se.Onscreen = true;
                    }
                    else
                    {
                        //if onscreen is true, but we are now off screen, time to delete.
                        if (se.Onscreen == true)
                        {
                            se.Die(se);
                        }
                    }
                    break;

                case GameBoss gb:
                    if (gb.Position.X > 0 && gb.Position.X < GameRoot.GraphicsDevice.Viewport.Width && gb.Position.Y > 0 && gb.Position.Y < GameRoot.GraphicsDevice.Viewport.Height)
                    {
                        gb.Onscreen = true;
                    }
                    else
                    {
                        //if onscreen is true, but we are now off screen, time to delete.
                        if (gb.Onscreen == true)
                        {
                            gb.Die(gb);
                        }
                    }
                    break;

                case PlayerBullet pb:
                    //check if bullet has gone out of bounds
                    if (pb.Position.X > GameRoot.GraphicsDevice.Viewport.Width || pb.Position.Y < 0)
                    {
                        pb.Die(pb);
                    }
                    break;
                }



                entity.Update(gameTime, Entities);
            }

            if (EntitiesToRemove != null)
            {
                foreach (var entity in EntitiesToRemove)
                {
                    Entities.Remove(entity);
                }

                EntitiesToRemove.Clear();
            }



            // IMPLEMENT NEXT TIME
            //// 5 seconds of loading - then start with phase one
            //// Phase1 from  3 - 48 seconds (45 seconds)
            //// normal enemies the whole time
            //if (gameTime.TotalGameTime.TotalSeconds == 3)
            //{
            //    Phase1();
            //}
            //else if (gameTime.TotalGameTime.TotalSeconds == 48)
            //{
            //    //for now clear enemies and bring out mid boss
            //    Entities.Clear();

            //    //Mid boss fight (technically, bullets from phase one do not clear)
            //    MidBoss();
            //}
            //else if (gameTime.TotalGameTime.TotalSeconds == 75)
            //{
            //    Entities.Clear();

            //    //regular enemies again
            //    Phase2();
            //}
            //else if (gameTime.TotalGameTime.TotalSeconds == 92)
            //{
            //    Entities.Clear();

            //    //There's a cutscene here before starting the boss battle.
            //}
            //else if (gameTime.TotalGameTime.TotalSeconds == 95)
            //{
            //    //B
            //}
            //if (gameTime.TotalGameTime.TotalSeconds == 15)
            //{
            //    Entities.Clear();
            //}

            IsUpdating = false;

            foreach (var entity in AddedEntities)
            {
                Entities.Add(entity);
            }

            AddedEntities.Clear();

            // remove any expired entities.
            // Entities = Entities.Where(x => x.IsActive()).ToList();
        }
Beispiel #25
0
        private void FindAndCaculateFromAdvancedStatic(GridSimulationData simData)
        {
            // Instead of using uniform distribution of support between all fixed nodes, calculate non-uniform distribution based on vectors for few closest nodes
            // Use this distribution when setting support weight and transferring mass
            // SupportingWeights: x * support
            // ? TransferMass: x * numStaticBlocksForCurrentDynamicBlock * TransferMass

            int keepLookingDistance = (int)ClosestDistanceThreshold; // How far keep looking when closest static block is found

            simData.Queue.Clear();

            // Set initial distance to max for all dynamic
            foreach (var dyn in simData.DynamicBlocks)
            {
                dyn.Distance = int.MaxValue;
            }

            // Wide search from all static blocks
            foreach (var stat in simData.StaticBlocks)
            {
                stat.Distance = 0;
                var path = new PathInfo()
                {
                    EndNode = stat, StartNode = stat, Distance = 0, DirectionRatio = 1
                };
#if ENHANCED_DEBUG
                path.PathNodes.Add(stat);
#endif
                simData.Queue.Enqueue(path);
            }

            while (simData.Queue.Count > 0)
            {
                var path = simData.Queue.Dequeue();
                foreach (var neighbour in path.EndNode.Neighbours)
                {
                    if (neighbour.IsStatic)
                    {
                        continue;
                    }

                    PathInfo neighbourPath;
                    if (!neighbour.Paths.TryGetValue(path.StartNode, out neighbourPath))
                    {
                        if ((path.Distance - keepLookingDistance) <= neighbour.Distance)
                        {
                            neighbour.Distance = Math.Min(neighbour.Distance, path.Distance);

                            neighbourPath           = new PathInfo();
                            neighbourPath.Distance  = path.Distance + 1;
                            neighbourPath.StartNode = path.StartNode;
                            neighbourPath.EndNode   = neighbour;
#if ENHANCED_DEBUG
                            neighbourPath.PathNodes = path.PathNodes.ToList();
                            neighbourPath.PathNodes.Add(neighbour);
#endif
                            neighbourPath.Parents.Add(path);
                            float t = neighbour.PhysicalMaterial.HorisontalTransmissionMultiplier * path.EndNode.PhysicalMaterial.HorisontalTransmissionMultiplier;

                            float massRatio = MathHelper.Clamp(path.EndNode.Mass / (neighbour.Mass + path.EndNode.Mass), 0, 1);

                            t *= neighbour.Mass * massRatio; //Horisontal transmission is very low on weak objects (floor, roof). Should be correctly get from mount point area
                            float[] horisontalTransmission = new float[] { t, 1, t };

                            int component = ((Vector3D)(neighbour.Pos - path.EndNode.Pos)).AbsMaxComponent();
                            neighbourPath.DirectionRatio = path.DirectionRatio * DirectionRatios[component] * horisontalTransmission[component];
                            neighbour.Paths.Add(path.StartNode, neighbourPath);
                            simData.Queue.Enqueue(neighbourPath);
                            path.StartNode.OwnedPaths.Push(neighbourPath);
                        }
                    }
                    else if (neighbourPath.Distance == path.Distance + 1) // Another path with same length
                    {
                        neighbourPath.Parents.Add(path);
                    }
                }
            }



            // Iterate all dynamic blocks and calculate support ratio for each static
            foreach (var dyn in simData.DynamicBlocks)
            {
                dyn.PathCount = 1;

                if (dyn.Pos == new Vector3I(-6, 6, 0))
                {
                }
                // Uniform distribution
                //foreach (var s in dyn.Paths)
                //{
                //    s.Value.Ratio = 1.0f / dyn.Paths.Count;
                //}
                //continue;

                // Non-uniform distribution
                // Calculate angle between one vector and all other
                // Split weight support based on sum angle ratio
                float totalAngles = 0;
                if (dyn.Paths.Count > 1)
                {
                    foreach (var s in dyn.Paths)
                    {
                        Vector3 localVector1 = (dyn.Pos - s.Value.StartNode.Pos) * m_grid.GridSize;
                        Vector3 worldVector1 = Vector3.TransformNormal(localVector1, m_grid.WorldMatrix);

                        // float sumAngle = 0;
                        float sumAngleReduced = 0;
                        foreach (var s2 in dyn.Paths)
                        {
                            if (s.Key == s2.Key)
                            {
                                continue;
                            }

                            Vector3 localVector2 = (dyn.Pos - s2.Value.StartNode.Pos) * m_grid.GridSize;
                            Vector3 worldVector2 = Vector3.TransformNormal(localVector2, m_grid.WorldMatrix);
                            float   angle        = MyUtils.GetAngleBetweenVectorsAndNormalise(worldVector1, worldVector2);

                            float dot1 = Math.Abs(Vector3.Normalize(worldVector1).Dot(Vector3.Up));
                            float dot2 = Math.Abs(Vector3.Normalize(worldVector2).Dot(Vector3.Up));

                            float lowerBound = 0.1f;
                            dot1 = MathHelper.Lerp(lowerBound, 1, dot1);
                            dot2 = MathHelper.Lerp(lowerBound, 1, dot2);

                            float reducedAngle = angle;

                            if (!MyPetaInputComponent.OLD_SI)
                            {
                                //Reduce dependent on gravity
                                reducedAngle = angle * dot1 * s.Value.DirectionRatio;
                            }

                            //sumAngle += angle;
                            sumAngleReduced += reducedAngle;
                        }
                        s.Value.Ratio = sumAngleReduced;
                        totalAngles  += sumAngleReduced;
                    }

                    foreach (var s in dyn.Paths)
                    {
                        if (totalAngles > 0)
                        {
                            s.Value.Ratio /= totalAngles;
                            if (s.Value.Ratio < 0.000001f)
                            {
                                s.Value.Ratio = 0;
                            }
                        }
                        else
                        {
                            s.Value.Ratio = 1;
                        }
                    }
                }
                else
                {
                    foreach (var s in dyn.Paths)
                    {
                        s.Value.Ratio = 1.0f;
                    }
                }
            }

            // Iterate all static blocks and calculate support mass and mass transfer
            foreach (var staticBlock in simData.StaticBlocks)
            {
                // Initial mass and ratio
                foreach (var path in staticBlock.OwnedPaths)
                {
                    path.EndNode.TransferMass = 0;
                }

                // For each block in path (ordered by distance, furthest first)
                while (staticBlock.OwnedPaths.Count > 0)
                {
                    var pathInfo = staticBlock.OwnedPaths.Pop();
                    var node     = pathInfo.EndNode;

                    Debug.Assert(pathInfo.StartNode == staticBlock, "Wrong path");
                    Debug.Assert(!node.IsStatic, "Static node unexpected");

                    float outgoing = node.TransferMass + node.Mass * pathInfo.Ratio;
                    //float outgoindTotal = 0;
                    //foreach (var p in pathInfo.Parents)
                    //    outgoindTotal += p.DirectionRatio;

                    if (node.Pos == new Vector3I(-1, 1, 0))
                    {
                    }


                    float outgoingPerParent = outgoing / pathInfo.Parents.Count;

                    foreach (var parent in pathInfo.Parents)
                    {
                        var delta = parent.EndNode.Pos - node.Pos; // Node to parent
                        int index, parentIndex;
                        if (delta.X + delta.Y + delta.Z > 0)
                        {
                            index       = delta.Y + delta.Z * 2; // UnitX = 0, UnitY = 1, UnitZ = 2
                            parentIndex = index + 3;
                        }
                        else
                        {
                            index       = -delta.X * 3 - delta.Y * 4 - delta.Z * 5; // // -UnitX = 3, -UnitY = 4, -UnitZ = 5
                            parentIndex = index - 3;
                        }

                        //outgoingPerParent = outgoing * parent.DirectionRatio / outgoindTotal;

#if ENHANCED_DEBUG
                        node.OutgoingNodeswWithWeights[index].Add(new Tuple <Node, float>(parent.EndNode, outgoingPerParent));
#endif
                        if (index == 0 || index == 2 || index == 3 || index == 5)
                        {
                            node.SupportingWeights[index] -= node.PhysicalMaterial.HorisontalFragility * outgoingPerParent;
                        }
                        else
                        {
                            node.SupportingWeights[index] -= outgoingPerParent;
                        }

                        if (parentIndex == 0 || parentIndex == 2 || parentIndex == 3 || parentIndex == 5)
                        {
                            parent.EndNode.SupportingWeights[parentIndex] += parent.EndNode.PhysicalMaterial.HorisontalFragility * outgoingPerParent;
                        }
                        else
                        {
                            parent.EndNode.SupportingWeights[parentIndex] += outgoingPerParent;
                        }
#if ENHANCED_DEBUG
                        parent.EndNode.SupportingNodeswWithWeights[parentIndex].Add(new Tuple <Node, float>(node, outgoingPerParent));
#endif


                        parent.EndNode.TransferMass += outgoingPerParent;
                    }
                    node.TransferMass -= outgoing;
                }
            }


            using (Stats.Timing.Measure("SI - Sum", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag))
            {
                foreach (var node in simData.All)
                {
                    //node.Value.TotalSupportingWeight = 0;
                }

                foreach (var node in simData.All)
                {
                    if (node.Key == new Vector3I(-1, 1, 0))
                    {
                    }

                    float sum = 0;
                    for (int i = 0; i < 6; i++)
                    {
                        float sideWeight = node.Value.SupportingWeights[i];

                        sum += Math.Abs(sideWeight);
                        //sum = Math.Max(sum, Math.Abs(node.Value.SupportingWeights[i]));
                    }

                    if (!(sum == 0 && node.Value.PathCount == 0))
                    {
                        // sum = sum * 2 - 1;
                        node.Value.TotalSupportingWeight += node.Value.IsStatic ? 0 : (sum * 0.5f / node.Value.PathCount);
                    }
                }

                // Idea behind blur:
                // When block is supporting too much weight, it deforms still supports something, but allows neighbour block to support more weight, thus sharing support
                List <Node> supportingNeighbours = new List <Node>();
                foreach (var node in simData.All)
                {
                    supportingNeighbours.Clear();

                    float totalSharedSupport = node.Value.TotalSupportingWeight;
                    float totalMass          = node.Value.Mass;

                    foreach (var neighbour in node.Value.Neighbours)
                    {
                        bool isHorisontalNeighbour = neighbour.Pos.Y == node.Key.Y;
                        bool isVerticallySupported = neighbour.Paths.Any(x => (x.Key.Pos.X == node.Key.X && x.Key.Pos.Z == node.Key.Z));

                        if (isHorisontalNeighbour && isVerticallySupported)
                        {
                            totalSharedSupport += neighbour.TotalSupportingWeight;
                            totalMass          += neighbour.Mass;
                            supportingNeighbours.Add(neighbour);
                        }
                    }

                    if (supportingNeighbours.Count > 0)
                    {
                        float supportPerNode = totalSharedSupport / totalMass;
                        foreach (var neighbour in supportingNeighbours)
                        {
                            neighbour.TotalSupportingWeight = supportPerNode * neighbour.Mass;
                        }
                        node.Value.TotalSupportingWeight = supportPerNode * node.Value.Mass;
                    }
                }

                foreach (var node in simData.All)
                {
                    simData.TotalMax = Math.Max(simData.TotalMax, node.Value.TotalSupportingWeight);
                }

                // var timeMs = (Stopwatch.GetTimestamp() - ts) / (float)Stopwatch.Frequency * 1000.0f;
                //Console.WriteLine(String.Format("Generated structural integrity, time: {0}ms, object name: {1}", timeMs, m_grid.ToString()));
            }
        }
Beispiel #26
0
        public override void Update(float distance)
        {
            Vector3 currentTranslation = AxisTranslation * MathHelper.Clamp(distance, Min, Max);

            currentTransform = Matrix4.CreateTranslation(currentTranslation);
        }
Beispiel #27
0
        private static void UpdateWaterAmbience(float ambienceVolume, float deltaTime)
        {
            if (GameMain.SoundManager.Disabled)
            {
                return;
            }

            //how fast the sub is moving, scaled to 0.0 -> 1.0
            float movementSoundVolume = 0.0f;

            float insideSubFactor = 0.0f;

            foreach (Submarine sub in Submarine.Loaded)
            {
                float movementFactor = (sub.Velocity == Vector2.Zero) ? 0.0f : sub.Velocity.Length() / 10.0f;
                movementFactor = MathHelper.Clamp(movementFactor, 0.0f, 1.0f);

                if (Character.Controlled == null || Character.Controlled.Submarine != sub)
                {
                    float dist = Vector2.Distance(GameMain.GameScreen.Cam.WorldViewCenter, sub.WorldPosition);
                    movementFactor /= Math.Max(dist / 1000.0f, 1.0f);
                    insideSubFactor = Math.Max(1.0f / Math.Max(dist / 1000.0f, 1.0f), insideSubFactor);
                }
                else
                {
                    insideSubFactor = 1.0f;
                }

                movementSoundVolume = Math.Max(movementSoundVolume, movementFactor);
                if (!MathUtils.IsValid(movementSoundVolume))
                {
                    string errorMsg = "Failed to update water ambience volume - submarine's movement value invalid (" + movementSoundVolume + ", sub velocity: " + sub.Velocity + ")";
                    DebugConsole.Log(errorMsg);
                    GameAnalyticsManager.AddErrorEventOnce("SoundPlayer.UpdateWaterAmbience:InvalidVolume", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    movementSoundVolume = 0.0f;
                }
            }

            for (int i = 0; i < 3; i++)
            {
                float volume = 0.0f;
                Sound sound  = null;
                switch (i)
                {
                case 0:
                    volume = ambienceVolume * (1.0f - movementSoundVolume) * insideSubFactor;
                    sound  = waterAmbienceIn;
                    break;

                case 1:
                    volume = ambienceVolume * movementSoundVolume * insideSubFactor;
                    sound  = waterAmbienceMoving;
                    break;

                case 2:
                    volume = 1.0f - insideSubFactor;
                    sound  = waterAmbienceOut;
                    break;
                }

                if ((waterAmbienceChannels[i] == null || !waterAmbienceChannels[i].IsPlaying) && volume > 0.01f)
                {
                    waterAmbienceChannels[i]         = sound.Play(volume, "waterambience");
                    waterAmbienceChannels[i].Looping = true;
                }
                else if (waterAmbienceChannels[i] != null)
                {
                    waterAmbienceChannels[i].Gain += deltaTime * Math.Sign(volume - waterAmbienceChannels[i].Gain);
                    if (waterAmbienceChannels[i].Gain < 0.01f)
                    {
                        waterAmbienceChannels[i].FadeOutAndDispose();
                    }
                }
            }
        }
Beispiel #28
0
 private float calculateGap(float value) => MathHelper.Clamp(value, 0, target_clamp) * targetBreakMultiplier;
Beispiel #29
0
        // tick: renders one frame
        public void Tick()
        {
            screen.Clear(0);
            //move the lights
            if (dir % 2 == 0)
            {
                lightbuffer[0]  += TW(0.1f);
                lightbuffer[5]  -= TW(0.1f);
                lightbuffer[11] += TW(0.1f);
                lightbuffer[16] -= TW(0.1f);
            }
            else
            {
                lightbuffer[0]  -= TW(0.1f);
                lightbuffer[5]  += TW(0.1f);
                lightbuffer[11] -= TW(0.1f);
                lightbuffer[16] += TW(0.1f);
            }
            if (TW(worldsize) < lightbuffer[0] || lightbuffer[0] < TX(-worldsize))
            {
                dir++;
            }
            Thread t1 = new Thread(() =>
            {
                plot(TX((-worldsize + (0f / 8f * worldsize * 2))), TX((-worldsize + (1f / 8f * worldsize * 2))));
            });
            Thread t2 = new Thread(() =>
            {
                plot(TX((-worldsize + (1f / 8f * worldsize * 2))), TX((-worldsize + (2f / 8f * worldsize * 2))));
            });
            Thread t3 = new Thread(() =>
            {
                plot(TX((-worldsize + (2f / 8f * worldsize * 2))), TX((-worldsize + (3f / 8f * worldsize * 2))));
            });
            Thread t4 = new Thread(() =>
            {
                plot(TX((-worldsize + (3f / 8f * worldsize * 2))), TX((-worldsize + (4f / 8f * worldsize * 2))));
            });
            Thread t5 = new Thread(() =>
            {
                plot(TX((-worldsize + (4f / 8f * worldsize * 2))), TX((-worldsize + (5f / 8f * worldsize * 2))));
            });
            Thread t6 = new Thread(() =>
            {
                plot(TX((-worldsize + (5f / 8f * worldsize * 2))), TX((-worldsize + (6f / 8f * worldsize * 2))));
            });
            Thread t7 = new Thread(() =>
            {
                plot(TX((-worldsize + (6f / 8f * worldsize * 2))), TX((-worldsize + (7f / 8f * worldsize * 2))));
            });
            Thread t8 = new Thread(() =>
            {
                plot(TX((-worldsize + (7f / 8f * worldsize * 2))), (TX((-worldsize + (8f / 8f * worldsize * 2)))) - 1);
            });

            tarr[0] = t1;
            tarr[1] = t2;
            tarr[2] = t3;
            tarr[3] = t4;
            tarr[4] = t5;
            tarr[5] = t6;
            tarr[6] = t7;
            tarr[7] = t8;
            for (int td = 0; td < tarr.Length; td++)
            {
                tarr[td].Start();
            }
            for (int td = 0; td < tarr.Length; td++)
            {
                tarr[td].Join();
            }
            for (int i = 0; i < (screen.width - 1); i++)
            {
                for (int j = 0; j < (screen.height - 1); j++)
                {
                    screen.Plot(i, j, MixColor(MathHelper.Clamp(floatbuffer[i, j][0], 0, 1), MathHelper.Clamp(floatbuffer[i, j][1], 0, 1), MathHelper.Clamp(floatbuffer[i, j][2], 0, 1)));
                }
            }
            primitivesDraw();
        }
Beispiel #30
0
        /// <summary>
        /// Interpolates the positional error of a physics body towards zero.
        /// </summary>
        public static Vector2 InterpolateSimPositionError(Vector2 simPositionError, float?smoothingFactor = null)
        {
            float lengthSqr = simPositionError.LengthSquared();

            //correct immediately if the error is very large
            if (lengthSqr > 100.0f)
            {
                return(Vector2.Zero);
            }
            float positionSmoothingFactor = smoothingFactor ?? MathHelper.Lerp(0.95f, 0.8f, MathHelper.Clamp(lengthSqr, 0.0f, 1.0f));

            return(simPositionError *= positionSmoothingFactor);
        }