Пример #1
0
    public override void OnDestruction(StrikeType hitType, int damageValue)
    {
        //Gets called every time the player hits this enemy.
        if (!enemyBehavior.isStaggered)
        {
            return;
        }
        foreach (StrikeType strike in immunityList)
        {
            if (hitType == strike)
            {
                return;
            }
        }
        int modifiedDamageValue = damageValue;

        foreach (StrikeType strike in vulnerabilityList)
        {
            if (hitType == strike)
            {
                modifiedDamageValue *= 2;
            }
        }
        if ((currentHealth -= modifiedDamageValue) <= 0)
        {
            enemyBehavior.OnDeath();
        }
        else
        {
            GetComponent <Animator>().SetBool("Damaged", true);
        }
    }
 public void EnableBlock(StrikeType direction)
 {
     //Starts blocking and resets relevant statistics
     blockDirection   = direction;
     blockActiveTimer = 0f;
     blockActive      = true;
 }
Пример #3
0
 public void EnableAttackArea(StrikeType type)
 {
     //Plays an attack sound and enables the attack raycast
     swordWoosher.PlayWooshSound();
     activeStrikeType = type;
     attackActive     = true;
 }
Пример #4
0
        void OnExplosiveThrown(BasePlayer player, BaseEntity entity)
        {
            if (toggleList.ContainsKey(player.userID) && entity is SupplySignal)
            {
                StrikeType type = toggleList[player.userID];
                toggleList.Remove(player.userID);
                AddCooldownData(player, type);

                entity.CancelInvoke((entity as SupplySignal).Explode);
                entity.Invoke(entity.KillMessage, 30f);
                timer.Once(3, () =>
                {
                    Effect.server.Run("assets/bundled/prefabs/fx/smoke_signal_full.prefab", entity, 0, new Vector3(), new Vector3());
                    Vector3 pos = entity.GetEstimatedWorldPosition();
                    switch (type)
                    {
                    case StrikeType.Strike:
                        SendReply(player, string.Format(msg("strikeConfirmed", player.UserIDString), pos));
                        CallStrike(pos);
                        return;

                    case StrikeType.Squad:
                        SendReply(player, string.Format(msg("strikeConfirmed", player.UserIDString), pos));
                        CallSquad(pos);
                        return;
                    }
                });
            }
        }
Пример #5
0
        public string PlayStrikeTurn(StrikeType strikeType)
        {
            try
            {
                if (IsPlayer1Turn)
                {
                    Player1.Strike(strikeType);
                    IsPlayer1Turn = false;
                    return($"{strikeType.ToString()} from player 1");
                }

                else
                {
                    Player2.Strike(strikeType);
                    IsPlayer1Turn = true;
                    return($"{strikeType.ToString()} from player 2");
                }
            }
            catch (Exception exception)
            {
                if (exception is NoCoinException)
                {
                    var output = DeclareWinner();
                    return(output);
                }

                else
                {
                    throw exception;
                }
            }
        }
Пример #6
0
        internal static void FillNodeInfoDeribit(InteractivePointActive ip,
                                                 double f, double dT, IOptionStrikePair sInfo,
                                                 StrikeType optionType, OptionPxMode optPxMode,
                                                 double optPx, double optQty, double optSigma, DateTime optTime, bool returnPct, double riskfreeRatePct, double scaleMult)
        {
            // Вызов базовой реализации
            FillNodeInfo(ip, f, dT, sInfo, optionType, optPxMode, optPx, optQty, optSigma, optTime, returnPct, riskfreeRatePct);

            // Заменяю тултип, чтобы в нем были и биткойны и доллары
            var opTypeStr   = String.Intern(optionType.ToString());
            var opTypeSpace = String.Intern(new string(' ', opTypeStr.Length));

            // Пробелы по виду занимают меньше места, чем буквы, поэтому чуть-чуть подравниваю?
            opTypeSpace += "  ";
            if (optQty > 0)
            {
                ip.Tooltip = String.Format(CultureInfo.InvariantCulture,
                                           " K:{0}; IV:{1:###0.00}%\r\n" +
                                           " {2} px(B) {3:##0.0000} qty {4}\r\n" +
                                           " {5} px($) {6:######0.00} qty {4}",
                                           sInfo.Strike, optSigma * Constants.PctMult, opTypeStr, optPx, optQty,
                                           opTypeSpace, optPx * scaleMult);
            }
            else
            {
                ip.Tooltip = String.Format(CultureInfo.InvariantCulture,
                                           " K:{0}; IV:{1:###0.00}%\r\n" +
                                           " {2} px(B) {3:##0.0000}\r\n" +
                                           " {4} px($) {5:######0.00}",
                                           sInfo.Strike, optSigma * Constants.PctMult, opTypeStr, optPx,
                                           opTypeSpace, optPx * scaleMult);
            }
        }
Пример #7
0
 public abstract bool DecideCrushedThrough(
     Agent attackerAgent,
     Agent defenderAgent,
     float totalAttackEnergy,
     Agent.UsageDirection attackDirection,
     StrikeType strikeType,
     WeaponComponentData defendItem,
     bool isPassiveUsageHit);
Пример #8
0
        public GridVolSurface(DateTime originDate, double[] strikes, DateTime[] expiries, double[][] vols,
                              StrikeType strikeType, Interpolator1DType strikeInterpType, Interpolator1DType timeInterpType,
                              DayCountBasis timeBasis)
        {
            StrikeType             = strikeType;
            StrikeInterpolatorType = strikeInterpType;
            TimeInterpolatorType   = timeInterpType;
            TimeBasis = timeBasis;

            Build(originDate, strikes, expiries, vols);
        }
 public virtual void OnDestruction(StrikeType hitType, int damageValue)
 {
     foreach (StrikeType strike in immunityList)
     {
         if (hitType == strike)
         {
             return;
         }
     }
     Destroy(gameObject);
 }
Пример #10
0
        internal static void FillNodeInfo(InteractivePointActive ip,
                                          double f, double dT, IOptionStrikePair sInfo,
                                          StrikeType optionType, OptionPxMode optPxMode,
                                          double optSigma, bool returnPct, bool isVisiblePoints, double scaleMult, double riskfreeRatePct)
        {
            if (optionType == StrikeType.Any)
            {
                throw new ArgumentException("Option type 'Any' is not supported.", "optionType");
            }

            bool   isCall = (optionType == StrikeType.Call);
            double optPx  = FinMath.GetOptionPrice(f, sInfo.Strike, dT, optSigma, 0, isCall);

            // Сразу переводим котировку из баксов в битки
            optPx /= scaleMult;

            // ReSharper disable once UseObjectOrCollectionInitializer
            SmileNodeInfo nodeInfo = new SmileNodeInfo();

            nodeInfo.F            = f;
            nodeInfo.dT           = dT;
            nodeInfo.RiskFreeRate = riskfreeRatePct;
            nodeInfo.Sigma        = returnPct ? optSigma * Constants.PctMult : optSigma;
            nodeInfo.OptPx        = optPx;
            nodeInfo.Strike       = sInfo.Strike;
            // Сюда мы приходим когда хотим торговать, поэтому обращение к Security уместно
            nodeInfo.Security   = (optionType == StrikeType.Put) ? sInfo.Put.Security : sInfo.Call.Security;
            nodeInfo.PxMode     = optPxMode;
            nodeInfo.OptionType = optionType;
            nodeInfo.Pair       = sInfo;
            //nodeInfo.ScriptTime = optTime;
            nodeInfo.CalendarTime = DateTime.Now;

            nodeInfo.Symbol   = nodeInfo.Security.Symbol;
            nodeInfo.DSName   = nodeInfo.Security.SecurityDescription.DSName;
            nodeInfo.Expired  = nodeInfo.Security.SecurityDescription.Expired;
            nodeInfo.FullName = nodeInfo.Security.SecurityDescription.FullName;

            ip.Tag = nodeInfo;
            //ip.Color = Colors.Yellow;
            ip.IsActive     = isVisiblePoints;
            ip.Geometry     = Geometries.Ellipse;
            ip.DragableMode = DragableMode.None;
            //ip.Value = new System.Windows.Point(sInfo.Strike, nodeInfo.Sigma);
            // Поскольку цены скорее всего расчетные, показываю на 1 знак болььше, чем объявлена точность в инструменте
            int    decim    = Math.Max(0, nodeInfo.Security.Decimals + 1);
            string optPxStr = optPx.ToString("N" + decim, CultureInfo.InvariantCulture);

            ip.Tooltip = String.Format(CultureInfo.InvariantCulture,
                                       " K: {0}; IV: {1:#0.00}%\r\n   {2} px {3}",
                                       sInfo.Strike, optSigma * Constants.PctMult, optionType, optPx);
        }
 public bool OnPlayerStruck(int damage, StrikeType strikeType, BasicEnemyBehavior source)
 {
     //Checks if the players block is active and if the block direction is equal to the direction of the hit received.
     if (!blockActive || blockDirection != strikeType)
     {
         playerStats.GetDamaged(damage);
         return(true);
     }
     else
     {
         //Checks if the player blocked for a short enough time to stagger the enemy. The time is detemined by the Players Equipment as defined in the PlayerCharacter
         bool wasPerfectBlock = (blockActiveTimer <= playerStats.GetActiveCharacter().staggerWindow);
         source.OnBlocked(wasPerfectBlock);
         return(false);
     }
 }
Пример #12
0
        internal static void FillNodeInfo(InteractivePointActive ip,
                                          double f, double dT, IOptionStrikePair sInfo,
                                          StrikeType optionType, OptionPxMode optPxMode,
                                          double optSigma, bool returnPct, bool isVisiblePoints, double riskfreeRatePct)
        {
            if (optionType == StrikeType.Any)
            {
                throw new ArgumentException("Option type 'Any' is not supported.", "optionType");
            }

            bool   isCall = (optionType == StrikeType.Call);
            double optPx  = FinMath.GetOptionPrice(f, sInfo.Strike, dT, optSigma, 0, isCall);

            // ReSharper disable once UseObjectOrCollectionInitializer
            SmileNodeInfo nodeInfo = new SmileNodeInfo();

            nodeInfo.F            = f;
            nodeInfo.dT           = dT;
            nodeInfo.RiskFreeRate = riskfreeRatePct;
            nodeInfo.Sigma        = returnPct ? optSigma * Constants.PctMult : optSigma;
            nodeInfo.OptPx        = optPx;
            nodeInfo.Strike       = sInfo.Strike;
            // Сюда мы приходим когда хотим торговать, поэтому обращение к Security уместно
            nodeInfo.Security   = (optionType == StrikeType.Put) ? sInfo.Put.Security : sInfo.Call.Security;
            nodeInfo.PxMode     = optPxMode;
            nodeInfo.OptionType = optionType;
            nodeInfo.Pair       = sInfo;
            //nodeInfo.ScriptTime = optTime;
            nodeInfo.CalendarTime = DateTime.Now;

            nodeInfo.Symbol   = nodeInfo.Security.Symbol;
            nodeInfo.DSName   = nodeInfo.Security.SecurityDescription.DSName;
            nodeInfo.Expired  = nodeInfo.Security.SecurityDescription.Expired;
            nodeInfo.FullName = nodeInfo.Security.SecurityDescription.FullName;

            ip.Tag          = nodeInfo;
            ip.Color        = AlphaColors.Yellow;
            ip.IsActive     = isVisiblePoints;
            ip.Geometry     = Geometries.Ellipse;
            ip.DragableMode = DragableMode.None;
            //ip.Value = new System.Windows.Point(sInfo.Strike, nodeInfo.Sigma);
            ip.Tooltip = String.Format(CultureInfo.InvariantCulture,
                                       "F:{0}; K:{1}; IV:{2:#0.00}%\r\n{3} px {4}",
                                       f, sInfo.Strike, optSigma * Constants.PctMult, optionType, optPx);
        }
Пример #13
0
        protected static void FillNodeInfo(InteractivePointLight ip,
                                           double f, double dT, IOptionStrikePair sInfo,
                                           StrikeType optionType, OptionPxMode optPxMode,
                                           double optSigma, bool returnPct, double pctRate)
        {
            if (optionType == StrikeType.Any)
            {
                throw new ArgumentException("Option type 'Any' is not supported.", "optionType");
            }

            bool   isCall = (optionType == StrikeType.Call);
            double optPx  = FinMath.GetOptionPrice(f, sInfo.Strike, dT, optSigma, pctRate, isCall);

            // ReSharper disable once UseObjectOrCollectionInitializer
            SmileNodeInfo nodeInfo = new SmileNodeInfo();

            nodeInfo.F            = f;
            nodeInfo.dT           = dT;
            nodeInfo.RiskFreeRate = pctRate;
            nodeInfo.Sigma        = returnPct ? optSigma * Constants.PctMult : optSigma;
            nodeInfo.OptPx        = optPx;
            nodeInfo.Strike       = sInfo.Strike;
            nodeInfo.Security     = (optionType == StrikeType.Put) ? sInfo.Put.Security : sInfo.Call.Security;
            nodeInfo.PxMode       = optPxMode;
            nodeInfo.OptionType   = optionType;
            nodeInfo.Pair         = sInfo;
            //nodeInfo.ScriptTime = optTime;
            nodeInfo.CalendarTime = DateTime.Now;

            nodeInfo.Symbol   = nodeInfo.Security.Symbol;
            nodeInfo.DSName   = nodeInfo.Security.SecurityDescription.DSName;
            nodeInfo.FullName = nodeInfo.Security.SecurityDescription.FullName;
            nodeInfo.Expired  = nodeInfo.Security.SecurityDescription.Expired;

            ip.Tag   = nodeInfo;
            ip.Value = new Point(sInfo.Strike, nodeInfo.Sigma);

            if (ip is InteractivePointActive)
            {
                InteractivePointActive ipa = (InteractivePointActive)ip;
                ipa.Tooltip = String.Format("K:{0}; IV:{1:#0.00}%\r\n{2} {3} @ {4}",
                                            sInfo.Strike, optSigma * Constants.PctMult, optionType, optPx, DefaultOptQty);
            }
        }
Пример #14
0
        private bool CanBuyStrike(BasePlayer player, StrikeType type)
        {
            Dictionary <string, int> costToBuy = type == StrikeType.Strike ? configData.Buy.StrikeCost : configData.Buy.SquadCost;

            foreach (var item in costToBuy)
            {
                if (item.Key == "RP")
                {
                    if (ServerRewards)
                    {
                        if ((int)ServerRewards.Call("CheckPoints", player.userID) < item.Value)
                        {
                            SendReply(player, string.Format(msg("buyItem", player.UserIDString), item.Value, item.Key));
                            Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.denied.prefab", player.transform.position);
                            return(false);
                        }
                    }
                }
                if (item.Key == "Economics")
                {
                    if (Economics)
                    {
                        if ((double)Economics.Call("GetPlayerMoney", player.userID) < item.Value)
                        {
                            SendReply(player, string.Format(msg("buyItem", player.UserIDString), item.Value, item.Key));
                            Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.denied.prefab", player.transform.position);
                            return(false);
                        }
                    }
                }
                if (shortnameToId.ContainsKey(item.Key))
                {
                    if (player.inventory.GetAmount(shortnameToId[item.Key]) < item.Value)
                    {
                        SendReply(player, string.Format(msg("buyItem", player.UserIDString), item.Value, shortnameToDn[item.Key]));
                        Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.denied.prefab", player.transform.position);
                        return(false);
                    }
                }
            }
            Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.updated.prefab", player.transform.position);
            return(true);
        }
Пример #15
0
        public GridVolSurface(DateTime originDate, double[] strikes, DateTime[] expiries, double[][] vols,
                              StrikeType strikeType, Interpolator1DType strikeInterpType, Interpolator1DType timeInterpType,
                              DayCountBasis timeBasis, string[] pillarLabels = null) : base()
        {
            StrikeType             = strikeType;
            StrikeInterpolatorType = strikeInterpType;
            TimeInterpolatorType   = timeInterpType;
            TimeBasis = timeBasis;

            if (pillarLabels == null)
            {
                PillarLabels = expiries.Select(x => x.ToString("yyyy-MM-dd")).ToArray();
            }
            else
            {
                PillarLabels = pillarLabels;
            }

            Build(originDate, strikes, expiries, vols);
        }
Пример #16
0
        private void AddCooldownData(BasePlayer player, StrikeType type)
        {
            if (!configData.Cooldown.Enabled)
            {
                return;
            }

            if (!storedData.cooldowns.ContainsKey(player.userID))
            {
                storedData.cooldowns.Add(player.userID, new CooldownData());
            }

            if (type == StrikeType.Strike)
            {
                storedData.cooldowns[player.userID].strikeCd = GrabCurrentTime() + configData.Cooldown.Strike;
            }
            else
            {
                storedData.cooldowns[player.userID].squadCd = GrabCurrentTime() + configData.Cooldown.Squad;
            }
        }
Пример #17
0
        protected static void FillNodeInfo(InteractivePointActive ip,
                                           double f, double dT, IOptionStrikePair sInfo,
                                           StrikeType optionType, OptionPxMode optPxMode,
                                           double optSigma, bool returnPct, bool isVisiblePoints)
        {
            if (optionType == StrikeType.Any)
            {
                throw new ArgumentException("Option type 'Any' is not supported.", "optionType");
            }

            bool   isCall = (optionType == StrikeType.Call);
            double optPx  = FinMath.GetOptionPrice(f, sInfo.Strike, dT, optSigma, 0, isCall);

            SmileNodeInfo nodeInfo = new SmileNodeInfo();

            nodeInfo.F          = f;
            nodeInfo.dT         = dT;
            nodeInfo.Sigma      = returnPct ? optSigma * Constants.PctMult : optSigma;
            nodeInfo.OptPx      = optPx;
            nodeInfo.Strike     = sInfo.Strike;
            nodeInfo.Security   = (optionType == StrikeType.Put) ? sInfo.Put.Security : sInfo.Call.Security;
            nodeInfo.PxMode     = optPxMode;
            nodeInfo.OptionType = optionType;
            nodeInfo.Pair       = sInfo;
            //nodeInfo.ScriptTime = optTime;
            nodeInfo.CalendarTime = DateTime.Now;

            nodeInfo.Symbol  = nodeInfo.Security.Symbol;
            nodeInfo.Expired = nodeInfo.Security.SecurityDescription.Expired;

            ip.Tag          = nodeInfo;
            ip.Color        = AlphaColors.Yellow;
            ip.IsActive     = isVisiblePoints;
            ip.Geometry     = Geometries.Ellipse;
            ip.DragableMode = DragableMode.None;
            //ip.Value = new System.Windows.Point(sInfo.Strike, nodeInfo.Sigma);
            ip.Tooltip = String.Format("F:{0}; K:{1}; IV:{2:#0.00}%\r\n{3} {4} @ {5}",
                                       f, sInfo.Strike, optSigma * Constants.PctMult, optionType, optPx, DefaultOptQty);
        }
Пример #18
0
        private void BuyStrike(BasePlayer player, StrikeType type)
        {
            Dictionary <string, int> costToBuy = type == StrikeType.Strike ? configData.Buy.StrikeCost : configData.Buy.SquadCost;

            foreach (var item in costToBuy)
            {
                if (item.Key == "RP")
                {
                    if (ServerRewards)
                    {
                        ServerRewards.Call("TakePoints", player.userID, item.Value);
                    }
                }
                if (item.Key == "Economics")
                {
                    if (Economics)
                    {
                        Economics.Call("Withdraw", player.userID, (double)item.Value);
                    }
                }
                if (shortnameToId.ContainsKey(item.Key))
                {
                    player.inventory.Take(null, shortnameToId[item.Key], item.Value);
                }
            }
            if (type == StrikeType.Strike)
            {
                CallStrike(player.transform.position);
                SendReply(player, string.Format(msg("strikeConfirmed", player.UserIDString), player.transform.position));
            }
            else
            {
                CallSquad(player.transform.position);
                SendReply(player, string.Format(msg("squadConfirmed", player.UserIDString), player.transform.position));
            }
        }
Пример #19
0
        internal static IStrike GetStrikeType(StrikeType strikeType)
        {
            switch (strikeType)
            {
            case StrikeType.Strike:
            {
                if (StrikeTypes.ContainsKey(strikeType))
                {
                    return(StrikeTypes.GetValueOrDefault(strikeType));
                }
                else
                {
                    var strike = new SingleStrike();
                    StrikeTypes.Add(strikeType, strike);
                    return(strike);
                }
            }

            case StrikeType.MultiStrike:
            {
                if (StrikeTypes.ContainsKey(strikeType))
                {
                    return(StrikeTypes.GetValueOrDefault(strikeType));
                }
                else
                {
                    var strike = new MultiStrike();
                    StrikeTypes.Add(strikeType, strike);
                    return(strike);
                }
            }

            case StrikeType.RedStrike:
            {
                if (StrikeTypes.ContainsKey(strikeType))
                {
                    return(StrikeTypes.GetValueOrDefault(strikeType));
                }
                else
                {
                    var strike = new RedStrike();
                    StrikeTypes.Add(strikeType, strike);
                    return(strike);
                }
            }

            case StrikeType.StrikerStrike:
            {
                if (StrikeTypes.ContainsKey(strikeType))
                {
                    return(StrikeTypes.GetValueOrDefault(strikeType));
                }
                else
                {
                    var strike = new StrikerStrike();
                    StrikeTypes.Add(strikeType, strike);
                    return(strike);
                }
            }

            case StrikeType.DefunctStrike:
            {
                if (StrikeTypes.ContainsKey(strikeType))
                {
                    return(StrikeTypes.GetValueOrDefault(strikeType));
                }
                else
                {
                    var strike = new DefunctStrike();
                    StrikeTypes.Add(strikeType, strike);
                    return(strike);
                }
            }

            case StrikeType.None:
            {
                if (StrikeTypes.ContainsKey(strikeType))
                {
                    return(StrikeTypes.GetValueOrDefault(strikeType));
                }
                else
                {
                    var strike = new NoneStrike();
                    StrikeTypes.Add(strikeType, strike);
                    return(strike);
                }
            }
            }

            return(null);
        }
Пример #20
0
 public void SetAttackType(StrikeType type)
 {
     activeStrikeType = type;
 }
Пример #21
0
 public Node(ushort value, StrikeType type, Node prevNode)
 {
     Value    = value;
     Type     = type;
     PrevNode = prevNode;
 }
Пример #22
0
        internal void Strike(StrikeType strikeType)
        {
            var strike = StrikeFactory.GetStrikeType(strikeType);

            CarromBoard.Striker.Strike(this, strike);
        }
Пример #23
0
        /// <summary>
        /// Метод под флаг TemplateTypes.INTERACTIVESPLINE
        /// </summary>
        public InteractiveSeries Execute(InteractiveSeries smile, IOptionSeries optSer, double scaleMult, int barNum)
        {
            if ((smile == null) || (optSer == null))
            {
                return(Constants.EmptySeries);
            }

            int barsCount = m_context.BarsCount;

            if (!m_context.IsLastBarUsed)
            {
                barsCount--;
            }
            if (barNum < barsCount - 1)
            {
                return(Constants.EmptySeries);
            }

            SmileInfo oldInfo = smile.GetTag <SmileInfo>();

            if ((oldInfo == null) || (oldInfo.ContinuousFunction == null))
            {
                return(Constants.EmptySeries);
            }

            double futPx = oldInfo.F;
            double dT    = oldInfo.dT;

            if (m_executeCommand)
            {
                string msg = String.Format("[{0}.StartButton] Strike: {1}", GetType().Name, m_strike);
                m_context.Log(msg, MessageType.Info, false);
            }

            #region 1. Список страйков
            HashSet <string> serList = StrikeList;
            serList.Clear();

            IOptionStrikePair[] pairs;
            if (Double.IsNaN(m_strikeStep) || (m_strikeStep <= Double.Epsilon))
            {
                pairs = optSer.GetStrikePairs().ToArray();
            }
            else
            {
                // Выделяем страйки, которые нацело делятся на StrikeStep
                pairs = (from p in optSer.GetStrikePairs()
                         let test = m_strikeStep * Math.Round(p.Strike / m_strikeStep)
                                    where DoubleUtil.AreClose(p.Strike, test)
                                    select p).ToArray();

                // [2015-12-24] Если шаг страйков по ошибке задан совершенно неправильно,
                // то в коллекцию ставим все имеющиеся страйки.
                // Пользователь потом разберется
                if (pairs.Length <= 0)
                {
                    pairs = optSer.GetStrikePairs().ToArray();
                }
            }
            //if (pairs.Length < 2)
            //    return Constants.EmptyListDouble;

            foreach (IOptionStrikePair pair in pairs)
            {
                double k = pair.Strike;
                serList.Add(k.ToString(StrikeFormat, CultureInfo.InvariantCulture));
            }
            #endregion 1. Список страйков

            InteractiveSeries        res           = Constants.EmptySeries;
            List <InteractiveObject> controlPoints = new List <InteractiveObject>();

            #region 2. Формируем улыбку просто для отображения текущего положения потенциальной котировки
            // При нулевом рабочем объёме не утруждаемся рисованием лишних линий
            if (!DoubleUtil.IsZero(m_qty))
            {
                for (int j = 0; j < pairs.Length; j++)
                {
                    var    pair  = pairs[j];
                    double sigma = oldInfo.ContinuousFunction.Value(pair.Strike) + m_shiftIv;
                    if (!DoubleUtil.IsPositive(sigma))
                    {
                        //string msg = String.Format("[DEBUG:{0}] Invalid sigma:{1} for strike:{2}", GetType().Name, sigma, nodeInfo.Strike);
                        //m_context.Log(msg, MessageType.Warning, true);
                        continue;
                    }

                    //bool isCall = (futPx <= pair.Strike);
                    bool isCall;
                    if (m_optionType == StrikeType.Call)
                    {
                        isCall = true;
                    }
                    else if (m_optionType == StrikeType.Put)
                    {
                        isCall = false;
                    }
                    else
                    {
                        isCall = (futPx <= pair.Strike);
                    }

                    StrikeType optionType = isCall ? StrikeType.Call : StrikeType.Put;
                    Contract.Assert(pair.Tick < 1, $"#1 На тестовом контуре Дерибит присылает неправильный шаг цены! Tick:{pair.Tick}; Decimals:{pair.Put.Security.Decimals}");
                    double theorOptPxDollars = FinMath.GetOptionPrice(futPx, pair.Strike, dT, sigma, oldInfo.RiskFreeRate, isCall);
                    // Сразу(!!!) переводим котировку из баксов в битки
                    double theorOptPxBitcoins = theorOptPxDollars / scaleMult;

                    // Сдвигаем цену в долларах (с учетом ш.ц. в баксах)
                    theorOptPxDollars += m_shiftPriceStep * pair.Tick * scaleMult;
                    theorOptPxDollars  = Math.Round(theorOptPxDollars / (pair.Tick * scaleMult)) * (pair.Tick * scaleMult);

                    // Сдвигаем цену в биткойнах (с учетом ш.ц. в битках)
                    theorOptPxBitcoins += m_shiftPriceStep * pair.Tick;
                    theorOptPxBitcoins  = Math.Round(theorOptPxBitcoins / pair.Tick) * pair.Tick;
                    if ((!DoubleUtil.IsPositive(theorOptPxBitcoins)) || (!DoubleUtil.IsPositive(theorOptPxDollars)))
                    {
                        //string msg = String.Format("[DEBUG:{0}] Invalid theorOptPx:{1} for strike:{2}", GetType().Name, theorOptPx, nodeInfo.Strike);
                        //m_context.Log(msg, MessageType.Warning, true);
                        continue;
                    }

                    // Пересчитываем сигму обратно, ЕСЛИ мы применили сдвиг цены в абсолютном выражении
                    if (m_shiftPriceStep != 0)
                    {
                        // Обратный пересчет в волатильность
                        sigma = FinMath.GetOptionSigma(futPx, pair.Strike, dT, theorOptPxDollars, oldInfo.RiskFreeRate, isCall);
                        if (!DoubleUtil.IsPositive(sigma))
                        {
                            //string msg = String.Format("[DEBUG:{0}] Invalid sigma:{1} for strike:{2}", GetType().Name, sigma, nodeInfo.Strike);
                            //m_context.Log(msg, MessageType.Warning, true);
                            continue;
                        }
                    }

                    // ReSharper disable once UseObjectOrCollectionInitializer
                    SmileNodeInfo nodeInfo = new SmileNodeInfo();
                    var           secDesc  = isCall ? pair.CallFinInfo.Security : pair.PutFinInfo.Security;
                    nodeInfo.F            = oldInfo.F;
                    nodeInfo.dT           = oldInfo.dT;
                    nodeInfo.RiskFreeRate = oldInfo.RiskFreeRate;
                    nodeInfo.Strike       = pair.Strike;
                    nodeInfo.Sigma        = sigma;
                    nodeInfo.OptPx        = theorOptPxBitcoins;
                    nodeInfo.OptionType   = isCall ? StrikeType.Call : StrikeType.Put;
                    nodeInfo.Pair         = pair;

                    nodeInfo.Symbol   = secDesc.Name;
                    nodeInfo.DSName   = secDesc.DSName;
                    nodeInfo.Expired  = secDesc.Expired;
                    nodeInfo.FullName = secDesc.FullName;

                    // ReSharper disable once UseObjectOrCollectionInitializer
                    InteractivePointActive tmp = new InteractivePointActive();

                    tmp.IsActive     = true;
                    tmp.ValueX       = pair.Strike;
                    tmp.ValueY       = sigma;
                    tmp.DragableMode = DragableMode.Yonly;
                    tmp.Tooltip      = String.Format(CultureInfo.InvariantCulture,
                                                     " F: {0}\r\n K: {1}; IV: {2:P2}\r\n {3} px {4}",
                                                     futPx, pair.Strike, sigma, optionType, theorOptPxBitcoins);

                    tmp.Tag = nodeInfo;

                    //tmp.Color = Colors.White;
                    if (m_qty > 0)
                    {
                        tmp.Geometry = Geometries.Triangle;
                    }
                    else if (m_qty < 0)
                    {
                        tmp.Geometry = Geometries.TriangleDown;
                    }
                    else
                    {
                        tmp.Geometry = Geometries.None;
                    }

                    InteractiveObject obj = new InteractiveObject();
                    obj.Anchor = tmp;

                    controlPoints.Add(obj);
                }

                // ReSharper disable once UseObjectOrCollectionInitializer
                res = new InteractiveSeries(); // Здесь так надо -- мы делаем новую улыбку
                res.ControlPoints = new ReadOnlyCollection <InteractiveObject>(controlPoints);

                // ReSharper disable once UseObjectOrCollectionInitializer
                SmileInfo sInfo = new SmileInfo();
                sInfo.F            = futPx;
                sInfo.dT           = dT;
                sInfo.Expiry       = oldInfo.Expiry;
                sInfo.ScriptTime   = oldInfo.ScriptTime;
                sInfo.RiskFreeRate = oldInfo.RiskFreeRate;
                sInfo.BaseTicker   = oldInfo.BaseTicker;

                res.Tag = sInfo;

                if (controlPoints.Count > 0)
                {
                    res.ClickEvent -= InteractiveSplineOnQuoteIvEvent;
                    res.ClickEvent += InteractiveSplineOnQuoteIvEvent;

                    m_clickableSeries = res;
                }
            }
            #endregion 2. Формируем улыбку просто для отображения текущего положения потенциальной котировки

            PositionsManager posMan = PositionsManager.GetManager(m_context);
            if (m_cancelAllLong)
            {
                posMan.DropAllLongIvTargets(m_context);
            }
            if (m_cancelAllShort)
            {
                posMan.DropAllShortIvTargets(m_context);
            }

            #region 4. Котирование
            {
                var longTargets  = posMan.GetIvTargets(true);
                var shortTargets = posMan.GetIvTargets(false);
                var ivTargets    = longTargets.Union(shortTargets).ToList();
                for (int j = 0; j < ivTargets.Count; j++)
                {
                    var ivTarget = ivTargets[j];

                    // PROD-6102 - Требуется точное совпадение опционной серии
                    if (optSer.ExpirationDate.Date != ivTarget.SecInfo.Expiry.Date)
                    {
                        // Вывести предупреждение???
                        continue;
                    }

                    IOptionStrikePair pair;
                    double            k = ivTarget.SecInfo.Strike;
                    if (!optSer.TryGetStrikePair(k, out pair))
                    {
                        // Вывести предупреждение???
                        continue;
                    }

                    double      sigma;
                    QuoteIvMode quoteMode = ivTarget.QuoteMode;
                    if (quoteMode == QuoteIvMode.Absolute)
                    {
                        sigma = ivTarget.EntryIv;
                    }
                    else
                    {
                        sigma = oldInfo.ContinuousFunction.Value(k) + ivTarget.EntryIv;
                        if (!DoubleUtil.IsPositive(sigma))
                        {
                            //string msg = String.Format("[DEBUG:{0}] Invalid sigma:{1} for strike:{2}", GetType().Name, sigma, nodeInfo.Strike);
                            //m_context.Log(msg, MessageType.Warning, true);
                            continue;
                        }
                    }

                    //bool isCall = (futPx <= pair.Strike);
                    // Определяю тип опциона на основании информации в Задаче
                    StrikeType taskOptionType = StrikeType.Any;
                    if (ivTarget.SecInfo.StrikeType.HasValue)
                    {
                        taskOptionType = ivTarget.SecInfo.StrikeType.Value;
                    }

                    bool isCall;
                    if (taskOptionType == StrikeType.Call)
                    {
                        isCall = true;
                    }
                    else if (taskOptionType == StrikeType.Put)
                    {
                        isCall = false;
                    }
                    else
                    {
                        isCall = (futPx <= pair.Strike); // Это аварийная ситуация?
                    }
                    StrikeType optionType = isCall ? StrikeType.Call : StrikeType.Put;
                    Contract.Assert(pair.Tick < 1, $"#3 На тестовом контуре Дерибит присылает неправильный шаг цены! Tick:{pair.Tick}; Decimals:{pair.Put.Security.Decimals}");
                    double theorOptPxDollars = FinMath.GetOptionPrice(futPx, pair.Strike, dT, sigma, oldInfo.RiskFreeRate, isCall);
                    // Сразу(!!!) переводим котировку из баксов в битки
                    double theorOptPxBitcoins = theorOptPxDollars / scaleMult;

                    // Сдвигаем цену в долларах (с учетом ш.ц. в баксах)
                    theorOptPxDollars += ivTarget.EntryShiftPrice * pair.Tick * scaleMult;
                    theorOptPxDollars  = Math.Round(theorOptPxDollars / (pair.Tick * scaleMult)) * (pair.Tick * scaleMult);

                    // Сдвигаем цену в биткойнах (с учетом ш.ц. в битках)
                    theorOptPxBitcoins += ivTarget.EntryShiftPrice * pair.Tick;
                    theorOptPxBitcoins  = Math.Round(theorOptPxBitcoins / pair.Tick) * pair.Tick;
                    if ((!DoubleUtil.IsPositive(theorOptPxBitcoins)) || (!DoubleUtil.IsPositive(theorOptPxDollars)))
                    {
                        //string msg = String.Format("[DEBUG:{0}] Invalid theorOptPx:{1} for strike:{2}", GetType().Name, theorOptPx, nodeInfo.Strike);
                        //m_context.Log(msg, MessageType.Warning, true);
                        continue;
                    }

                    IOptionStrike optStrike = isCall ? pair.Call : pair.Put;
                    ISecurity     sec       = optStrike.Security;
                    double        totalQty  = posMan.GetTotalQty(sec, m_context.BarsCount, TotalProfitAlgo.AllPositions, ivTarget.IsLong);
                    // Поскольку котирование страйка по волатильности -- это вопрос набора нужного количества СТРЕДДЛОВ,
                    // то учитывать надо суммарный объём опционов как в колах, так и в путах.
                    // НО ЗАДАЧУ-ТО Я СТАВЛЮ ДЛЯ КОНКРЕТНОГО ИНСТРУМЕНТА!
                    // Как быть?
                    //double totalQty = posMan.GetTotalQty(pair.Put.Security, m_context.BarsCount, TotalProfitAlgo.AllPositions, ivTarget.IsLong);
                    //totalQty += posMan.GetTotalQty(pair.Call.Security, m_context.BarsCount, TotalProfitAlgo.AllPositions, ivTarget.IsLong);
                    double targetQty = Math.Abs(ivTarget.TargetShares) - totalQty;
                    // Если имеется дробный LotTick (как в Дерибит к примеру), то надо предварительно округлить
                    targetQty = sec.RoundShares(targetQty);
                    if (targetQty > 0)
                    {
                        string note = String.Format(CultureInfo.InvariantCulture,
                                                    "{0}; ActQty:{1}; Px:{2}; IV:{3:P2}",
                                                    ivTarget.EntryNotes, targetQty, theorOptPxBitcoins, sigma);
                        if (ivTarget.IsLong)
                        {
                            posMan.BuyAtPrice(m_context, sec, targetQty, theorOptPxBitcoins, ivTarget.EntrySignalName, note);
                        }
                        else
                        {
                            posMan.SellAtPrice(m_context, sec, targetQty, theorOptPxBitcoins, ivTarget.EntrySignalName, note);
                        }
                    }
                    else
                    {
                        string msg = String.Format(CultureInfo.InvariantCulture,
                                                   "IvTarget cancelled. SignalName:{0}; Notes:{1}", ivTarget.EntrySignalName, ivTarget.EntryNotes);
                        posMan.CancelVolatility(m_context, ivTarget, msg);

                        // TODO: потом убрать из ГЛ
                        m_context.Log(msg, MessageType.Info, true, new Dictionary <string, object> {
                            { "VOLATILITY_ORDER_CANCELLED", msg }
                        });
                    }
                }
            }
            #endregion 4. Котирование

            #region 5. Торговля
            if (m_executeCommand && (!DoubleUtil.IsZero(m_qty)))
            {
                double k;
                if ((!Double.TryParse(m_strike, out k)) &&
                    (!Double.TryParse(m_strike, NumberStyles.Any, CultureInfo.InvariantCulture, out k)))
                {
                    return(res);
                }

                var pair = (from p in pairs where DoubleUtil.AreClose(k, p.Strike) select p).SingleOrDefault();
                if (pair == null)
                {
                    return(res);
                }

                InteractiveObject obj = (from o in controlPoints where DoubleUtil.AreClose(k, o.Anchor.ValueX) select o).SingleOrDefault();
                if (obj == null)
                {
                    return(res);
                }

                // TODO: для режима котирования в абсолютных числах сделать отдельную ветку
                //double iv = obj.Anchor.ValueY;
                const QuoteIvMode QuoteMode = QuoteIvMode.Relative;
                if (posMan.BlockTrading)
                {
                    string msg = String.Format(RM.GetString("OptHandlerMsg.PositionsManager.TradingBlocked"),
                                               m_context.Runtime.TradeName + ":QuoteIv");
                    m_context.Log(msg, MessageType.Warning, true);
                    return(res);
                }

                // Выбираю тип инструмента пут или колл?
                bool isCall;
                if (m_optionType == StrikeType.Call)
                {
                    isCall = true;
                }
                else if (m_optionType == StrikeType.Put)
                {
                    isCall = false;
                }
                else
                {
                    isCall = (futPx <= k);
                }

                double iv     = m_shiftIv;
                int    shift  = m_shiftPriceStep;
                var    option = isCall ? pair.Call : pair.Put;
                if (m_qty > 0)
                {
                    // Пересчитываю целочисленный параметр Qty в фактические лоты конкретного инструмента
                    double actQty  = m_qty * option.LotTick;
                    string sigName = String.Format(CultureInfo.InvariantCulture,
                                                   "Qty:{0}; IV:{1:P2}+{2}; dT:{3}; Mode:{4}", actQty, iv, shift, dT, QuoteMode);
                    posMan.BuyVolatility(m_context, option, Math.Abs(actQty), QuoteMode, iv, shift, "BuyVola", sigName);

                    m_context.Log(sigName, MessageType.Info, false);
                }
                else if (m_qty < 0)
                {
                    // Пересчитываю целочисленный параметр Qty в фактические лоты конкретного инструмента
                    double actQty  = m_qty * option.LotTick;
                    string sigName = String.Format(CultureInfo.InvariantCulture,
                                                   "Qty:{0}; IV:{1:P2}+{2}; dT:{3}; Mode:{4}", actQty, iv, shift, dT, QuoteMode);
                    posMan.SellVolatility(m_context, option, Math.Abs(actQty), QuoteMode, iv, shift, "SellVola", sigName);

                    m_context.Log(sigName, MessageType.Info, false);
                }
            }
            #endregion 5. Торговля

            return(res);
        }
 internal static float SpeedGraphFunction(this Mission __instance, float progress, StrikeType strikeType, Agent.UsageDirection attackDir)
 {
     throw new NotImplementedException("Need to patch first");
 }
Пример #25
0
 static bool Prefix(WeaponComponentData weapon, StrikeType strikeType, float baseMagnitude, ref float __result)
 {
     __result = baseMagnitude;
     return(false);
 }
Пример #26
0
        /// <summary>
        /// Метод под флаг TemplateTypes.INTERACTIVESPLINE
        /// </summary>
        public InteractiveSeries Execute(InteractiveSeries smile, IOptionSeries optSer, InteractiveSeries quoteIv, double scaleMult, int barNum)
        {
            if ((smile == null) || (optSer == null))
            {
                return(Constants.EmptySeries);
            }

            int barsCount = m_context.BarsCount;

            if (!m_context.IsLastBarUsed)
            {
                barsCount--;
            }
            if (barNum < barsCount - 1)
            {
                return(Constants.EmptySeries);
            }

            SmileInfo oldInfo = smile.GetTag <SmileInfo>();

            if ((oldInfo == null) || (oldInfo.ContinuousFunction == null))
            {
                return(Constants.EmptySeries);
            }

            double futPx = oldInfo.F;
            double dT    = oldInfo.dT;

            // 1. Формируем маркеры заявок
            List <InteractiveObject> controlPoints          = new List <InteractiveObject>();
            PositionsManager         posMan                 = PositionsManager.GetManager(m_context);
            IList <PositionsManager.IvTargetInfo> ivTargets = posMan.GetIvTargets(m_isLong, true);

            for (int j = 0; j < ivTargets.Count; j++)
            {
                var ivTarget = ivTargets[j];

                // PROD-6102 - Требуется точное совпадение опционной серии
                if (optSer.ExpirationDate.Date != ivTarget.SecInfo.Expiry.Date)
                {
                    // Вывести предупреждение???
                    continue;
                }

                IOptionStrikePair pair;
                double            k = ivTarget.SecInfo.Strike;
                if (!optSer.TryGetStrikePair(k, out pair))
                {
                    // Вывести предупреждение???
                    continue;
                }

                double      sigma;
                QuoteIvMode quoteMode = ivTarget.QuoteMode;
                if (quoteMode == QuoteIvMode.Absolute)
                {
                    sigma = ivTarget.EntryIv;
                }
                else
                {
                    sigma = oldInfo.ContinuousFunction.Value(k) + ivTarget.EntryIv;
                    if (!DoubleUtil.IsPositive(sigma))
                    {
                        //string msg = String.Format("[DEBUG:{0}] Invalid sigma:{1} for strike:{2}", GetType().Name, sigma, nodeInfo.Strike);
                        //m_context.Log(msg, MessageType.Warning, true);
                        continue;
                    }
                }

                bool isCall = (futPx <= k);
                if ((ivTarget.SecInfo.StrikeType != null) &&
                    (ivTarget.SecInfo.StrikeType.Value != StrikeType.Any))
                {
                    isCall = (ivTarget.SecInfo.StrikeType.Value == StrikeType.Call);
                }
                StrikeType optionType = isCall ? StrikeType.Call : StrikeType.Put;
                Contract.Assert(pair.Tick < 1, $"На тестовом контуре Дерибит присылает неправильный шаг цены! Tick:{pair.Tick}; Decimals:{pair.Put.Security.Decimals}");
                double theorOptPxDollars = FinMath.GetOptionPrice(futPx, pair.Strike, dT, sigma, oldInfo.RiskFreeRate, isCall);
                // Сразу(!!!) переводим котировку из баксов в битки
                double theorOptPxBitcoins = theorOptPxDollars / scaleMult;

                // Сдвигаем цену в долларах (с учетом ш.ц. в баксах)
                theorOptPxDollars += ivTarget.EntryShiftPrice * pair.Tick * scaleMult;
                theorOptPxDollars  = Math.Round(theorOptPxDollars / (pair.Tick * scaleMult)) * (pair.Tick * scaleMult);

                // Сдвигаем цену в биткойнах (с учетом ш.ц. в битках)
                theorOptPxBitcoins += ivTarget.EntryShiftPrice * pair.Tick;
                theorOptPxBitcoins  = Math.Round(theorOptPxBitcoins / pair.Tick) * pair.Tick;
                if ((!DoubleUtil.IsPositive(theorOptPxBitcoins)) || (!DoubleUtil.IsPositive(theorOptPxDollars)))
                {
                    //string msg = String.Format("[DEBUG:{0}] Invalid theorOptPx:{1} for strike:{2}", GetType().Name, theorOptPx, nodeInfo.Strike);
                    //m_context.Log(msg, MessageType.Warning, true);
                    continue;
                }

                // Пересчитываем сигму обратно, ЕСЛИ мы применили сдвиг цены в абсолютном выражении
                if (ivTarget.EntryShiftPrice != 0)
                {
                    sigma = FinMath.GetOptionSigma(futPx, pair.Strike, dT, theorOptPxDollars, oldInfo.RiskFreeRate, isCall);
                    if (!DoubleUtil.IsPositive(sigma))
                    {
                        //string msg = String.Format("[DEBUG:{0}] Invalid sigma:{1} for strike:{2}", GetType().Name, sigma, nodeInfo.Strike);
                        //m_context.Log(msg, MessageType.Warning, true);
                        continue;
                    }
                }

                double totalQty;
                if (isCall)
                {
                    totalQty = posMan.GetTotalQty(pair.Call.Security, m_context.BarsCount, TotalProfitAlgo.AllPositions, ivTarget.IsLong);
                }
                else
                {
                    totalQty = posMan.GetTotalQty(pair.Put.Security, m_context.BarsCount, TotalProfitAlgo.AllPositions, ivTarget.IsLong);
                }
                double targetQty = Math.Abs(ivTarget.TargetShares) - totalQty;

                // ReSharper disable once UseObjectOrCollectionInitializer
                InteractivePointActive tmp = new InteractivePointActive();

                // Попробуем по-простому?
                tmp.Tag = ivTarget;

                tmp.IsActive     = true;
                tmp.ValueX       = k;
                tmp.ValueY       = sigma;
                tmp.DragableMode = DragableMode.None;
                if (ivTarget.EntryShiftPrice == 0)
                {
                    tmp.Tooltip = String.Format(CultureInfo.InvariantCulture,
                                                " F: {0}\r\n K: {1}; IV: {2:P2}\r\n {3} px {4} rIV {5:P2} @ {6}",
                                                futPx, k, sigma, optionType, theorOptPxBitcoins, ivTarget.EntryIv, targetQty);
                }
                else
                {
                    string shiftStr = (ivTarget.EntryShiftPrice > 0) ? "+" : "-";
                    shiftStr    = shiftStr + Math.Abs(ivTarget.EntryShiftPrice) + "ps";
                    tmp.Tooltip = String.Format(CultureInfo.InvariantCulture,
                                                " F: {0}\r\n K: {1}; IV: {2:P2}\r\n {3} px {4} rIV {5:P2} {6} @ {7}",
                                                futPx, k, sigma, optionType, theorOptPxBitcoins, ivTarget.EntryIv, shiftStr, targetQty);
                }

                //tmp.Color = Colors.White;
                //if (m_qty > 0)
                //    tmp.Geometry = Geometries.Triangle;
                //else if (m_qty < 0)
                //    tmp.Geometry = Geometries.TriangleDown;
                //else
                //    tmp.Geometry = Geometries.None;

                InteractiveObject obj = new InteractiveObject();
                obj.Anchor = tmp;

                controlPoints.Add(obj);
            }

            // ReSharper disable once UseObjectOrCollectionInitializer
            InteractiveSeries res = new InteractiveSeries(); // Здесь так надо -- мы делаем новую улыбку

            res.ControlPoints = new ReadOnlyCollection <InteractiveObject>(controlPoints);

            if (controlPoints.Count > 0)
            {
                res.ClickEvent -= InteractiveSplineOnClickEvent;
                res.ClickEvent += InteractiveSplineOnClickEvent;

                m_clickableSeries = res;
            }

            return(res);
        }
        internal static bool GetDefendCollisionResultsAuxPrefix(Mission __instance, Agent attackerAgent, Agent defenderAgent,
                                                                CombatCollisionResult collisionResult, int weaponKind, int currentUsageIndex, bool isAlternativeAttack,
                                                                StrikeType strikeType, Agent.UsageDirection attackDirection, float currentAttackSpeed, float collisionDistanceOnWeapon,
                                                                float attackProgress, bool attackIsParried, ref float defenderStunPeriod, ref float attackerStunPeriod, ref bool crushedThrough,
                                                                ref bool chamber)
        {
            ItemObject          itemFromWeaponKind  = ItemObject.GetItemFromWeaponKind(weaponKind);
            WeaponComponentData weaponComponentData = (itemFromWeaponKind != null) ? itemFromWeaponKind.GetWeaponWithUsageIndex(currentUsageIndex) : null;
            EquipmentIndex      wieldedItemIndex    = defenderAgent.GetWieldedItemIndex(Agent.HandIndex.OffHand);

            if (wieldedItemIndex == EquipmentIndex.None)
            {
                wieldedItemIndex = defenderAgent.GetWieldedItemIndex(Agent.HandIndex.MainHand);
            }
            WeaponComponentData weaponComponentData2 = (wieldedItemIndex != EquipmentIndex.None) ? defenderAgent.Equipment[wieldedItemIndex].CurrentUsageItem : null;
            float num = 10f;

            attackerStunPeriod = ((strikeType == StrikeType.Thrust) ? ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunPeriodAttackerThrust) : ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunPeriodAttackerSwing));
            chamber            = false;
            float num2 = 0f;

            if (weaponComponentData != null)
            {
                float z    = attackerAgent.GetCurWeaponOffset().z;
                float num3 = weaponComponentData.GetRealWeaponLength() + z;
                num2 = MBMath.ClampFloat((0.2f + collisionDistanceOnWeapon) / num3, 0.1f, 0.98f);
                float exraLinearSpeed = MissionReversePatches.ComputeRelativeSpeedDiffOfAgents(attackerAgent, defenderAgent);
                float num4;
                if (strikeType == StrikeType.Thrust)
                {
                    num4 = CombatStatCalculator.CalculateBaseBlowMagnitudeForThrust((float)itemFromWeaponKind.PrimaryWeapon.ThrustSpeed / 11.7647057f * MissionReversePatches.SpeedGraphFunction(Mission.Current, attackProgress, strikeType, attackDirection), itemFromWeaponKind.Weight, exraLinearSpeed);
                }
                else
                {
                    num4 = CombatStatCalculator.CalculateBaseBlowMagnitudeForSwing((float)itemFromWeaponKind.PrimaryWeapon.SwingSpeed / 4.5454545f * MissionReversePatches.SpeedGraphFunction(Mission.Current, strikeType, attackDirection), weaponComponentData.GetRealWeaponLength(), itemFromWeaponKind.Weight, weaponComponentData.Inertia, weaponComponentData.CenterOfMass, num2, exraLinearSpeed);
                }
                if (strikeType == StrikeType.Thrust)
                {
                    num4 *= 0.8f;
                }
                else if (attackDirection == Agent.UsageDirection.AttackUp)
                {
                    num4 *= 1.25f;
                }
                num += num4;
            }
            float num5 = 1f;

            defenderStunPeriod = num * ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunMomentumTransferFactor);
            if (weaponComponentData2 != null)
            {
                if (weaponComponentData2.IsShield)
                {
                    float managedParameter = ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunDefendWeaponWeightOffsetShield);
                    num5 += managedParameter * weaponComponentData2.Item.Weight;
                }
                else
                {
                    num5 = 0.9f;
                    float managedParameter2 = ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunDefendWeaponWeightMultiplierWeaponWeight);
                    num5 += managedParameter2 * weaponComponentData2.Item.Weight;
                    ItemObject.ItemTypeEnum itemType = weaponComponentData2.Item.ItemType;
                    if (itemType == ItemObject.ItemTypeEnum.TwoHandedWeapon)
                    {
                        managedParameter2 = ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunDefendWeaponWeightBonusTwoHanded);
                    }
                    else if (itemType == ItemObject.ItemTypeEnum.Polearm)
                    {
                        num5 += ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunDefendWeaponWeightBonusPolearm);
                    }
                }
                if (collisionResult == CombatCollisionResult.Parried)
                {
                    attackerStunPeriod += 0.1f;
                    num5 += ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunDefendWeaponWeightBonusActiveBlocked);


                    if (GCOToolbox.GCOToolbox.MeleeBalance.GCOCheckHyperArmorConfiguration(defenderAgent))
                    {
                        GCOToolbox.GCOToolbox.MeleeBalance.CreateHyperArmorBuff(defenderAgent);
                    }
                }
                else if (collisionResult == CombatCollisionResult.Blocked)
                {
                    if (GCOToolbox.GCOToolbox.MeleeBalance.GCOCheckHyperArmorConfiguration(defenderAgent))
                    {
                        GCOToolbox.GCOToolbox.MeleeBalance.CreateHyperArmorBuff(defenderAgent);
                    }
                }
                else if (collisionResult == CombatCollisionResult.ChamberBlocked)
                {
                    attackerStunPeriod += 0.2f;
                    num5   += ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunDefendWeaponWeightBonusChamberBlocked);
                    chamber = true;
                }
            }
            if (!defenderAgent.GetIsLeftStance())
            {
                num5 += ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunDefendWeaponWeightBonusRightStance);
            }
            defenderStunPeriod /= num5;
            float managedParameter3 = ManagedParameters.Instance.GetManagedParameter(ManagedParametersEnum.StunPeriodMax);

            attackerStunPeriod = Math.Min(attackerStunPeriod, managedParameter3);
            defenderStunPeriod = Math.Min(defenderStunPeriod, managedParameter3);
            crushedThrough     = (num > 38f && defenderStunPeriod > managedParameter3 - 0.03f && num2 > 0.5f);
            MissionGameModels.Current.AgentApplyDamageModel.CalculateEffects(attackerAgent, ref crushedThrough);
            if (chamber)
            {
                crushedThrough = false;
            }

            return(false);
        }
Пример #28
0
 public static void DecideCrushedThrough(Agent attackerAgent, Agent defenderAgent, float totalAttackEnergy, Agent.UsageDirection attackDirection, StrikeType strikeType, WeaponComponentData defendItem, bool isPassiveUsage, ref bool __result)
 {
     if ((attackerAgent?.IsPlayerControlled ?? false) &&
         BannerlordCheatsSettings.Instance.AlwaysCrushThroughShields)
     {
         __result = true;
     }
 }
Пример #29
0
        void cmdAirstrike(BasePlayer player, string command, string[] args)
        {
            if (args.Length == 0)
            {
                SendReply(player, string.Format("Airstrike  v.{0}", Version));
                if (HasPermission(player, "airstrike.signal.strike"))
                {
                    SendReply(player, msg("help1", player.UserIDString));
                }
                if (HasPermission(player, "airstrike.signal.squad"))
                {
                    SendReply(player, msg("help2", player.UserIDString));
                }
                if (HasPermission(player, "airstrike.purchase.strike"))
                {
                    SendReply(player, msg("help3", player.UserIDString));
                }
                if (HasPermission(player, "airstrike.purchase.squad"))
                {
                    SendReply(player, msg("help4", player.UserIDString));
                }
                if (HasPermission(player, "airstrike.chat.strike"))
                {
                    SendReply(player, msg("help5", player.UserIDString));
                    SendReply(player, msg("help6", player.UserIDString));
                    SendReply(player, msg("help7", player.UserIDString));
                }
                if (HasPermission(player, "airstrike.chat.squad"))
                {
                    SendReply(player, msg("help8", player.UserIDString));
                    SendReply(player, msg("help9", player.UserIDString));
                    SendReply(player, msg("help10", player.UserIDString));
                }
                return;
            }
            if (args.Length >= 2)
            {
                var        time = GrabCurrentTime();
                StrikeType type = args[1].ToLower() == "squad" ? StrikeType.Squad : StrikeType.Strike;

                if (!HasPermission(player, "airstrike.ignorecooldown"))
                {
                    if (configData.Cooldown.Enabled)
                    {
                        CooldownData data;
                        if (storedData.cooldowns.TryGetValue(player.userID, out data))
                        {
                            double nextUse = type == StrikeType.Strike ? data.strikeCd : data.squadCd;
                            if (nextUse > time)
                            {
                                double remaining = nextUse - time;
                                SendReply(player, string.Format(msg("onCooldown", player.UserIDString), FormatTime(remaining)));
                                return;
                            }
                        }
                    }
                }
                switch (args[0].ToLower())
                {
                case "signal":
                    if ((type == StrikeType.Strike && configData.Other.SignalStrike) || (type == StrikeType.Squad && configData.Other.SignalSquad))
                    {
                        if (!HasPermission(player, $"airstrike.signal.{type.ToString().ToLower()}"))
                        {
                            SendReply(player, msg("noPerms", player.UserIDString));
                            return;
                        }
                    }
                    if (toggleList.ContainsKey(player.userID))
                    {
                        toggleList[player.userID] = type;
                    }
                    else
                    {
                        toggleList.Add(player.userID, type);
                    }
                    SendReply(player, msg("signalReady", player.UserIDString));
                    return;

                case "buy":
                    if ((type == StrikeType.Strike && configData.Buy.PermissionStrike) || (type == StrikeType.Squad && configData.Buy.PermissionSquad))
                    {
                        if (!HasPermission(player, $"airstrike.purchase.{type.ToString().ToLower()}"))
                        {
                            SendReply(player, msg("noPerms", player.UserIDString));
                            return;
                        }
                    }
                    if (CanBuyStrike(player, type))
                    {
                        BuyStrike(player, type);
                        AddCooldownData(player, type);
                    }
                    return;

                case "call":
                    if (HasPermission(player, $"airstrike.chat.{type.ToString().ToLower()}"))
                    {
                        Vector3 position;
                        if (args.Length == 4)
                        {
                            float x, z;
                            if (!float.TryParse(args[2], out x) || !float.TryParse(args[3], out z))
                            {
                                SendReply(player, msg("invCoords", player.UserIDString));
                                return;
                            }
                            else
                            {
                                position = new Vector3(x, 0, z);
                            }
                        }
                        else if (args.Length == 3)
                        {
                            var players = FindPlayer(args[2]);
                            if (players.Count > 1)
                            {
                                SendReply(player, msg("multiplePlayers", player.UserIDString));
                                return;
                            }
                            else if (players.Count == 0)
                            {
                                SendReply(player, msg("noPlayers", player.UserIDString));
                                return;
                            }
                            else
                            {
                                position = players[0].transform.position;
                            }
                        }
                        else
                        {
                            position = player.transform.position;
                        }

                        if (type == StrikeType.Strike)
                        {
                            CallStrike(position);
                            SendReply(player, string.Format(msg("strikeConfirmed", player.UserIDString), position));
                        }
                        else
                        {
                            CallSquad(position);
                            SendReply(player, string.Format(msg("squadConfirmed", player.UserIDString), position));
                        }
                        AddCooldownData(player, type);
                    }
                    else
                    {
                        SendReply(player, msg("noPerms", player.UserIDString));
                    }
                    return;

                default:
                    break;
                }
            }
        }
Пример #30
0
        void ccmdAirstrike(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null)
            {
                return;
            }
            if (arg.Args == null || arg.Args.Length == 0)
            {
                SendReply(arg, "airstrike strike <x> <z> - Call a airstrike to the target position");
                SendReply(arg, "airstrike squad <x> <z> - Call a squadstrike to the target position");
                SendReply(arg, "airstrike strike <playername> - Call a airstrike to the target player");
                SendReply(arg, "airstrike squad <playername> - Call a squadstrike to the target player");
                SendReply(arg, "airstrike strike random - Call a random airstrike");
                SendReply(arg, "airstrike squad random - Call a random squadstrike");
                return;
            }

            StrikeType type = arg.Args[0].ToLower() == "squad" ? StrikeType.Squad : StrikeType.Strike;

            Vector3 position = Vector3.zero;

            if (arg.Args[1].ToLower() == "random")
            {
                position = GetRandomPosition();
            }
            else if (arg.Args.Length == 3)
            {
                float x, z;
                if (!float.TryParse(arg.Args[1], out x) || !float.TryParse(arg.Args[2], out z))
                {
                    SendReply(arg, "Invalid co-ordinates set. You must enter number values for X and Z");
                    return;
                }
                else
                {
                    position = new Vector3(x, 0, z);
                }
            }
            else if (arg.Args.Length == 2)
            {
                var players = FindPlayer(arg.Args[1]);
                if (players.Count > 1)
                {
                    SendReply(arg, "Multiple players found");
                    return;
                }
                else if (players.Count == 0)
                {
                    SendReply(arg, "No players found");
                    return;
                }
                else
                {
                    position = players[0].transform.position;
                }
            }

            if (type == StrikeType.Strike)
            {
                CallStrike(position);
                SendReply(arg, string.Format("Airstrike confirmed at co-ordinates: {0}!", position));
            }
            else
            {
                CallSquad(position);
                SendReply(arg, string.Format("Squadstrike confirmed at co-ordinates: {0}!", position));
            }
        }