Esempio n. 1
0
        protected Tasks chooseTaskHw(MyInfo info)
        {
            var ratios = new Ratios();

            if (info.CPU < Tasks.CPU.Max)
            {
                ratios[Tasks.CPU] = info.CPU;
            }
            if (info.HDD < Tasks.HDD.Max)
            {
                ratios[Tasks.HDD] = info.HDD;
            }
            if (info.Internet < Tasks.Internet.Max)
            {
                ratios[Tasks.Internet] = info.Internet;
            }
            if (info.RAM < Tasks.RAM.Max)
            {
                ratios[Tasks.RAM] = info.RAM;
            }

            if (ratios.Count == 0)
            {
                return(null); // all HW stats are fully upgraded
            }
            var ordered = ratios.OrderBy(r => r.Value);
            var task    = ordered.First();

            return(task.Key);
        }
Esempio n. 2
0
 public virtual void DumpBody(XmlWriter writer, bool alpha)
 {
     writer.WriteAttributeString("spread-mode", SpreadMode.ToString());
     writer.WriteAttributeString("interpolation-mode", InterpolationMode.ToString());
     writer.WriteElementString("ratios", Ratios.Join());
     writer.WriteElementString("colors", Colors.ToHtmlHex(alpha));
 }
Esempio n. 3
0
        //---------------------------------------------------------------------------
        public double CalcInstantaneousIncidentRadiation(double hour)
        {
            // return So * ratios.value(hour) * (1 + Math.Sin(2 * Math.PI * (hour - sunrise) / dayLength + 1.5 * Math.PI)) /
            //     (dayLength * 3600);

            return((So * Ratios.Value(hour) * Math.PI * Math.Sin(Math.PI * (hour - Sunrise) / DayLength)) / (2 * DayLength * 3600));
        }
Esempio n. 4
0
 public override int GetHashCode()
 {
     unchecked
     {
         int result = base.GetHashCode();
         result = (result * 397) ^ PeakCountRatio.GetHashCode();
         result = (result * 397) ^ (RetentionTime.HasValue ? RetentionTime.Value.GetHashCode() : 0);
         result = (result * 397) ^ (StartRetentionTime.HasValue ? StartRetentionTime.Value.GetHashCode() : 0);
         result = (result * 397) ^ (EndRetentionTime.HasValue ? EndRetentionTime.Value.GetHashCode() : 0);
         result = (result * 397) ^ (Fwhm.HasValue ? Fwhm.Value.GetHashCode() : 0);
         result = (result * 397) ^ (Area.HasValue ? Area.Value.GetHashCode() : 0);
         result = (result * 397) ^ (AreaMs1.HasValue ? AreaMs1.Value.GetHashCode() : 0);
         result = (result * 397) ^ (AreaFragment.HasValue ? AreaFragment.Value.GetHashCode() : 0);
         result = (result * 397) ^ (BackgroundArea.HasValue ? BackgroundArea.Value.GetHashCode() : 0);
         result = (result * 397) ^ (BackgroundAreaMs1.HasValue ? BackgroundAreaMs1.Value.GetHashCode() : 0);
         result = (result * 397) ^ (BackgroundAreaFragment.HasValue ? BackgroundAreaFragment.Value.GetHashCode() : 0);
         result = (result * 397) ^ (Height.HasValue ? Height.Value.GetHashCode() : 0);
         result = (result * 397) ^ Ratios.GetHashCodeDeep();
         result = (result * 397) ^ (Truncated.HasValue ? Truncated.Value.GetHashCode() : 0);
         result = (result * 397) ^ Identified.GetHashCode();
         result = (result * 397) ^ (LibraryDotProduct.HasValue ? LibraryDotProduct.Value.GetHashCode() : 0);
         result = (result * 397) ^ (IsotopeDotProduct.HasValue ? IsotopeDotProduct.Value.GetHashCode() : 0);
         result = (result * 397) ^ OptimizationStep;
         result = (result * 397) ^ Annotations.GetHashCode();
         result = (result * 397) ^ UserSet.GetHashCode();
         return(result);
     }
 }
Esempio n. 5
0
        private void removeAllButton_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show(
                "Are you sure you want to remove all torque curve points? "
                + "Any changes made to the current power curves will be undone.",
                "Remove All Torque Curves", MessageBoxButtons.YesNo, MessageBoxIcon.Warning
                );

            // If yes is not selected, get outta here!
            if (result != DialogResult.Yes)
            {
                return;
            }

            // Remove all ratios
            Ratios.Clear();

            // Flag change
            RatiosChanged = true;

            // Clear out any old items
            ratioListView.Items.Clear();

            // Force a chart redraw
            torqueBox_ValueChanged(this, EventArgs.Empty);
        }
Esempio n. 6
0
        protected Tasks chooseTask(MyInfo info)
        {
            var hwTask = chooseTaskHw(info);

            if (hwTask != null)
            {
                return(hwTask);
            }

            var total = info.Firewall + info.Antivirus + info.SDK
                        + info.IPSpoofing + info.Spam + info.Scan + info.Spyware;

            var ratios = new Ratios
            {
                { Tasks.Firewall, (double)info.Firewall / total },
                { Tasks.Antivirus, (double)info.Antivirus / total },
                { Tasks.Sdk, (double)info.SDK / total },
                { Tasks.IPSpoofing, (double)info.IPSpoofing / total },
                { Tasks.Spam, (double)info.Spam / total },
                { Tasks.Scan, (double)info.Scan / total },
                { Tasks.Spyware, (double)info.Spyware / total },
            };

            Tasks t = Tasks.Sdk;

            foreach (var key in ratios.Keys.ToList())
            {
                ratios[key] = percents[key] - ratios[key];
            }

            var asdf = ratios.OrderByDescending(r => r.Value).ToList();
            var c    = asdf.First();

            return(c.Key);
        }
Esempio n. 7
0
    // Use this for initialization
    void Start()
    {
        questText             = GetComponent <Text>();
        ratios                = ratiosObj.GetComponent <Ratios>();
        ConnectionInfosObject = GameObject.Find("ConnectionInfos");
        t = delayFirstQuest;
        txtBox.GetComponent <Image>().enabled = false;
        InvokeRepeating("CheckCompletionQuests", 1.0f, 1.0f);


        foreach (var quest in quests)
        {
            if (quest.tutorialQuestNumber == 0)
            {
                enoughQuests = true;
            }
        }

        if (myQuestPlayerData.Count != 0)
        {
            delayFirstQuest = 1;
        }

        if (quests.Count < 2)
        {
            enoughQuests = false;
        }
    }
        public HttpResponseMessage UpdateRatios(HttpRequestMessage request, [FromBody] Ratios ratiosModel)
        {
            return(GetHttpResponse(request, () =>
            {
                var ratios = _MPRCoreService.UpdateRatios(ratiosModel);

                return request.CreateResponse <Ratios>(HttpStatusCode.OK, ratios);
            }));
        }
Esempio n. 9
0
        internal void CalculateCompensationComponents(Ratios ratios)
        {
            decimal material  = TobaccoQuantityDec - this[DisposalEnum.OverusageInKg];
            decimal dust      = this[DisposalEnum.Dust] = (material * Convert.ToDecimal(ratios.dustRatio)).Round2Decimals();
            decimal shMenthol = this[DisposalEnum.SHMenthol] = (material * Convert.ToDecimal(ratios.shMentholRatio)).Round2Decimals();
            decimal waste     = this[DisposalEnum.Waste] = (material * Convert.ToDecimal(ratios.wasteRatio)).Round2Decimals();

            this[DisposalEnum.TobaccoInCigaretess] = material - shMenthol - waste - dust;
        }
Esempio n. 10
0
        private void ratioListView_KeyDown(object sender, KeyEventArgs e)
        {
            if (ratioListView.SelectedItems.Count == 0)
            {
                return;
            }

            ListViewItem item  = ratioListView.SelectedItems[0];
            int          index = (int)item.Tag;

            if (e.KeyCode == Keys.Delete)
            {
                // Remove torque ratio
                Ratios.RemoveAt(index);

                // Flag change
                RatiosChanged = true;

                // Force Points Redraw
                PopulateTorqueRatios();

                // Force a chart redraw
                torqueBox_ValueChanged(this, EventArgs.Empty);

                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Enter)
            {
                TorqueRatio ratio = Ratios[index];
                using (TorqueCurveForm frm = new TorqueCurveForm((int)torqueBox.Value, ratio))
                {
                    // Show form
                    var result = frm.ShowDialog();
                    if (result == DialogResult.Yes)
                    {
                        // Grab Ratio
                        TorqueRatio values = frm.GetRatio();

                        // Create the new Ratio
                        ratio.RpmLevel = values.RpmLevel;
                        ratio.Ratio    = values.Ratio;

                        // Flag change
                        RatiosChanged = true;

                        // Force Points Redraw
                        PopulateTorqueRatios();

                        // Force a chart redraw
                        torqueBox_ValueChanged(this, EventArgs.Empty);
                    }
                }

                e.Handled = true;
            }
        }
Esempio n. 11
0
        private void FixRatios()
        {
            double min        = Ratios.Min();
            double conversion = 1.0 / min;

            for (int i = 0; i < Ratios.Count(); i++)
            {
                Ratios[i] *= conversion;
            }
        }
Esempio n. 12
0
 /// <summary>
 /// Disposals the analysis.
 /// </summary>
 /// <param name="entities">The <see cref="Entities"/>.</param>
 /// <param name="ratios">The ratios.</param>
 /// <param name="overusageRatios">The over-usage.</param>
 internal void CalculateOveruse(Entities entities, Ratios ratios, double overusageRatios)
 {
     if (overusageRatios > 0)
     {
         this[DisposalEnum.OverusageInKg] = (TobaccoQuantityDec * Convert.ToDecimal(overusageRatios)).Round2Decimals();
     }
     else
     {
         this[DisposalEnum.OverusageInKg] = 0;
     }
 }
Esempio n. 13
0
 public CategRatio(int id, Category firstCateg, Category secondCateg, Ratio ratio)// todo autoid
 {
     _id          = id;
     _firstCateg  = firstCateg;
     _secondCateg = secondCateg;
     _ratio       = ratio;
     if (Ratios.Contains(this))
     {
         throw new Exception("Попытка второй раз добавить отношение");                       //todo отношения между 2 категориями должны добавляться только 1 раз
     }
 }
Esempio n. 14
0
 void Start()
 {
     ratios = GameObject.Find("Ratios").GetComponent <Ratios>();
     if (ratios)
     {
         ratios.totalFood         += food;
         ratios.totalFuel         += fuel;
         ratios.totalConstruction += construction;
         ratios.totalMedicine     += medicine;
         ratios.totalCulture      += culture;
     }
 }
Esempio n. 15
0
        internal void IncreaseOveruse(decimal _AddingCff, Ratios ratios)
        {
            decimal overuseInKg = (TobaccoQuantityDec * _AddingCff).Round2Decimals();

            this[DisposalEnum.OverusageInKg] += overuseInKg;
            decimal material = TobaccoQuantityDec - this[DisposalEnum.OverusageInKg];

            if (material < 0)
            {
                throw new CAS.SmartFactory.IPR.WebsiteModel.IPRDataConsistencyException("Material.IncreaseOveruse", "There is not enough tobacco to correct overuse", null, "Operation has been aborted");
            }
        }
Esempio n. 16
0
        public List <double> DistributeDouble(double d)
        {
            List <double> res = new List <double>(Ratios.Count);
            double        sum = Ratios.Sum();

            foreach (var r in Ratios)
            {
                double part = d / sum * r;
                res.Add(part);
            }

            return(res);
        }
        public HttpResponseMessage GetRatios(HttpRequestMessage request, int ratiosId)
        {
            return(GetHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;

                Ratios ratios = _MPRCoreService.GetRatios(ratiosId);

                // notice no need to create a seperate model object since CaptionMapping entity will do just fine
                response = request.CreateResponse <Ratios>(HttpStatusCode.OK, ratios);

                return response;
            }));
        }
Esempio n. 18
0
 public Game(int myId, int playerCount, int zoneCount)
 {
     MY_ID      = myId;
     NB_PLAYERS = playerCount;
     ZoneCount  = zoneCount;
     map        = new Map(zoneCount);
     podsData   = new PodsData();
     ratios     = new Ratios();
     moves      = new Moves();
     roles      = new List <IRole>()
     {
         new Attacker(), new Defender(), new Explorer()
     };
 }
Esempio n. 19
0
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (editEnvIpAddr.Text.Equals(String.Empty) || editFlyIpAddr.Text.Equals(String.Empty))
            {
                MessageBox.Show("IP地址不能为空", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (editEnvPort.Text.Equals(String.Empty) || editFlyPort.Text.Equals(String.Empty))
            {
                MessageBox.Show("端口不能为空", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (!settingManager.SaveNetworkSetting(editEnvIpAddr.Text, int.Parse(editEnvPort.Text), editFlyIpAddr.Text, int.Parse(editFlyPort.Text),
                                                   int.Parse(editMaxPoint.Text)))
            {
                MessageBox.Show("保存网络配置失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            Ratios ratios = new Ratios
            {
                fire         = double.Parse(editSlowFire.Text),
                slowTemp     = double.Parse(editSlowTemp.Text),
                slowPress    = double.Parse(editSlowPressure.Text),
                fastShake    = double.Parse(editFastShake.Text),
                fastLash     = double.Parse(editFastLash.Text),
                fastNoise    = double.Parse(editFastNoise.Text),
                tailPress    = double.Parse(editTailPressure.Text),
                tailShake    = double.Parse(editTailShake.Text),
                tailTemp     = double.Parse(editTailTemp.Text),
                tailNoise    = double.Parse(editTailNoise.Text),
                fireFix      = double.Parse(editSlowFireFix.Text),
                slowTempFix  = double.Parse(editSlowTempFix.Text),
                slowPressFix = double.Parse(editSlowPressureFix.Text),
                fastShakeFix = double.Parse(editFastShakeFix.Text),
                fastLashFix  = double.Parse(editFastLashFix.Text),
                fastNoiseFix = double.Parse(editFastNoiseFix.Text),
                tailPressFix = double.Parse(editTailPressureFix.Text),
                tailShakeFix = double.Parse(editTailShakeFix.Text),
                tailTempFix  = double.Parse(editTailTempFix.Text),
                tailNoiseFix = double.Parse(editTailNoiseFix.Text)
            };

            if (!settingManager.SaveRatios(ratios))
            {
                MessageBox.Show("保存系数配置失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Close();
        }
Esempio n. 20
0
        internal decimal RemoveOveruseIfPossible(List <Material> _2Add, Ratios ratios)
        {
            decimal _ret = 0;

            if (this[DisposalEnum.OverusageInKg] > Settings.MinimalOveruse)
            {
                _2Add.Add(this);
            }
            else
            {
                _ret = this[DisposalEnum.OverusageInKg];
                this[DisposalEnum.OverusageInKg] = 0;
            }
            return(_ret);
        }
Esempio n. 21
0
        public List <int> DistributeInt(int i)
        {
            List <int> res = new List <int>(Ratios.Count);

            double sum = Ratios.Sum();

            int remaining = i;

            foreach (var r in Ratios)
            {
                int part = Math.Min(remaining, (int)Math.Round(i / sum * r));
                res.Add(part);
                remaining -= part;
            }

            return(res);
        }
Esempio n. 22
0
        /// <summary>
        /// Fills the torque ratio Listview
        /// </summary>
        private void PopulateTorqueRatios()
        {
            // Clear out any old items
            ratioListView.Items.Clear();

            int i = 1;

            foreach (TorqueRatio ratio in Ratios.OrderBy(x => x.RpmLevel))
            {
                ListViewItem item = new ListViewItem(i.ToString());
                item.SubItems.Add(ratio.RpmLevel.ToString());
                item.SubItems.Add(Math.Round(ratio.Ratio * 100, 2).ToString(Program.NumberFormat));
                item.Tag = Ratios.IndexOf(ratio);
                ratioListView.Items.Add(item);
                i++;
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Replaces a card with a new card, using the same ratio as the old card.
 /// Returns false if the old card cannot be found on the deck.
 /// </summary>
 /// <param name="oldCard"></param>
 /// <param name="newCard"></param>
 public bool ReplaceCard(R4UCard oldCard, R4UCard newCard)
 {
     if (newCard == null)
     {
         return(false);
     }
     else if (Ratios.TryGetValue(oldCard, out int oldRatio))
     {
         Ratios[newCard] = oldRatio;
         Ratios.Remove(oldCard);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Esempio n. 24
0
        private void addPointButton_Click(object sender, EventArgs e)
        {
            using (TorqueCurveForm frm = new TorqueCurveForm((int)torqueBox.Value))
            {
                var result = frm.ShowDialog();
                if (result == DialogResult.Yes)
                {
                    // Create the new Ratio
                    TorqueRatio ratio = frm.GetRatio();
                    Ratios.Add(ratio);

                    // Flag change
                    RatiosChanged = true;

                    // Force Points Redraw
                    PopulateTorqueRatios();

                    // Force a chart redraw
                    torqueBox_ValueChanged(this, EventArgs.Empty);
                }
            }
        }
Esempio n. 25
0
        private void removePointButton_Click(object sender, EventArgs e)
        {
            if (ratioListView.SelectedItems.Count == 0)
            {
                return;
            }

            // Remove torque ratio
            ListViewItem item  = ratioListView.SelectedItems[0];
            int          index = (int)item.Tag;

            Ratios.RemoveAt(index);

            // Flag change
            RatiosChanged = true;

            // Force Points Redraw
            PopulateTorqueRatios();

            // Force a chart redraw
            torqueBox_ValueChanged(this, EventArgs.Empty);
        }
        public HttpResponseMessage DeleteRatios(HttpRequestMessage request, [FromBody] int ratiosId)
        {
            return(GetHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;

                // not that calling the WCF service here will authenticate access to the data
                Ratios ratios = _MPRCoreService.GetRatios(ratiosId);

                if (ratios != null)
                {
                    _MPRCoreService.DeleteRatios(ratiosId);

                    response = request.CreateResponse(HttpStatusCode.OK);
                }
                else
                {
                    response = request.CreateErrorResponse(HttpStatusCode.NotFound, "No Ratios found under that ID.");
                }

                return response;
            }));
        }
Esempio n. 27
0
 public override int GetHashCode()
 {
     unchecked
     {
         int result = base.GetHashCode();
         result = (result * 397) ^ (MassError.HasValue ? MassError.Value.GetHashCode() : 0);
         result = (result * 397) ^ RetentionTime.GetHashCode();
         result = (result * 397) ^ StartRetentionTime.GetHashCode();
         result = (result * 397) ^ EndRetentionTime.GetHashCode();
         result = (result * 397) ^ Area.GetHashCode();
         result = (result * 397) ^ BackgroundArea.GetHashCode();
         result = (result * 397) ^ Height.GetHashCode();
         result = (result * 397) ^ Fwhm.GetHashCode();
         result = (result * 397) ^ IsFwhmDegenerate.GetHashCode();
         result = (result * 397) ^ Identified.GetHashCode();
         result = (result * 397) ^ (IsTruncated.HasValue ? IsTruncated.Value.GetHashCode() : 0);
         result = (result * 397) ^ Rank;
         result = (result * 397) ^ Ratios.GetHashCodeDeep();
         result = (result * 397) ^ OptimizationStep.GetHashCode();
         result = (result * 397) ^ Annotations.GetHashCode();
         result = (result * 397) ^ UserSet.GetHashCode();
         return(result);
     }
 }
Esempio n. 28
0
        private void resetPointsButton_Click(object sender, EventArgs e)
        {
            if (Ratios.Count > 0)
            {
                var result = MessageBox.Show(
                    "Are you sure you want to reset the torque curve points to the default values? "
                    + "Any changes made to the current power curves will be undone.",
                    "Reset Torque Curve", MessageBoxButtons.YesNo, MessageBoxIcon.Warning
                    );

                // If yes is not selected, get outta here!
                if (result != DialogResult.Yes)
                {
                    return;
                }

                // Remove all ratios
                Ratios.Clear();

                // Flag change
                RatiosChanged = true;
            }

            // Lock button
            resetPointsButton.Enabled = false;

            // Add default ratios
            Ratios.Add(new TorqueRatio()
            {
                Ratio = 0, RpmLevel = 300
            });
            Ratios.Add(new TorqueRatio()
            {
                Ratio = 0.5, RpmLevel = 440
            });
            Ratios.Add(new TorqueRatio()
            {
                Ratio = 1, RpmLevel = 1100
            });
            Ratios.Add(new TorqueRatio()
            {
                Ratio = 1, RpmLevel = 1400
            });
            Ratios.Add(new TorqueRatio()
            {
                Ratio = 0.77, RpmLevel = 1900
            });
            Ratios.Add(new TorqueRatio()
            {
                Ratio = 0.5, RpmLevel = 2400
            });
            Ratios.Add(new TorqueRatio()
            {
                Ratio = 0, RpmLevel = 2600
            });

            // Force Points Redraw
            PopulateTorqueRatios();

            // Force a chart redraw
            torqueBox_ValueChanged(this, EventArgs.Empty);

            // Enable Button
            resetPointsButton.Enabled = true;
        }
Esempio n. 29
0
        public EngineForm(Engine engine = null)
        {
            // Create form controls
            InitializeComponent();
            headerPanel.BackColor = Color.FromArgb(51, 53, 53);
            chart1.ChartAreas[0].AxisX.Interval = 300;

            NewEngine = engine == null;
            Engine    = engine ?? new Engine();
            Sorter    = new ListViewColumnSorter(truckListView)
            {
                Order = SortOrder.Ascending
            };

            // Setup metrics
            if (Program.Config.UnitSystem == UnitSystem.Metric)
            {
                labelTorque.Text                 = "Newton Metres:";
                labelPeakTorque.Text             = "Peak N·m RPM:";
                chart1.ChartAreas[0].AxisY.Title = "Newton Metres";
                maxTorqueLabel.Text              = "Max Newton Metres:";
            }

            // Add each sound to the lists
            using (AppDatabase db = new AppDatabase())
            {
                foreach (EngineSeries model in db.EngineSeries.OrderBy(x => x.ToString()))
                {
                    engineModelBox.Items.Add(model);
                    if (!NewEngine && model.Id == Engine.SeriesId)
                    {
                        engineModelBox.SelectedIndex = engineModelBox.Items.Count - 1;
                    }
                }

                if (!NewEngine)
                {
                    Ratios.AddRange(engine.TorqueRatios);
                }
                else
                {
                    Ratios.Add(new TorqueRatio()
                    {
                        Ratio = 0, RpmLevel = 300
                    });
                    Ratios.Add(new TorqueRatio()
                    {
                        Ratio = 0.5, RpmLevel = 440
                    });
                    Ratios.Add(new TorqueRatio()
                    {
                        Ratio = 1, RpmLevel = 1100
                    });
                    Ratios.Add(new TorqueRatio()
                    {
                        Ratio = 1, RpmLevel = 1400
                    });
                    Ratios.Add(new TorqueRatio()
                    {
                        Ratio = 0.77, RpmLevel = 1900
                    });
                    Ratios.Add(new TorqueRatio()
                    {
                        Ratio = 0.5, RpmLevel = 2400
                    });
                    Ratios.Add(new TorqueRatio()
                    {
                        Ratio = 0, RpmLevel = 2600
                    });
                }

                // Grab a list of trucks that use this engine
                List <int> trucks = new List <int>();
                if (!NewEngine)
                {
                    trucks.AddRange(engine.ItemOf.Select(x => x.TruckId));
                }

                // Add trucks to the truck list
                foreach (var truck in db.Trucks)
                {
                    ListViewItem item = new ListViewItem(truck.Name);
                    item.Tag     = truck.Id;
                    item.Checked = trucks.Contains(truck.Id);
                    truckListView.Items.Add(item);
                }
            }

            // Are we editing an engine?
            if (!NewEngine)
            {
                // Set form values
                unitNameBox.Text            = engine.UnitName;
                engineNameBox.Text          = engine.Name;
                unlockBox.Value             = engine.Unlock;
                priceBox.Value              = engine.Price;
                horsepowerBox.Value         = engine.Horsepower;
                peakRPMBox.Value            = engine.PeakRpm;
                idleRpmBox.Value            = engine.IdleRpm;
                rpmLimitBox.Value           = engine.RpmLimit;
                neutralRpmBox.Value         = engine.RpmLimitNeutral;
                brakeStrengthBox.Value      = engine.BrakeStrength;
                brakePositionsBox.Value     = engine.BrakePositions;
                automaticDSCheckBox.Checked = engine.BrakeDownshift;
                rpmRangeBox1.Value          = engine.MinRpmRange_LowGear;
                rpmRangeBox2.Value          = engine.MaxRpmRange_LowGear;
                rpmRangeBox3.Value          = engine.MinRpmRange_HighGear;
                rpmRangeBox4.Value          = engine.MaxRpmRange_HighGear;
                rpmRangeBox5.Value          = engine.LowRpmRange_PowerBoost;
                rpmRangeBox6.Value          = engine.HighRpmRange_PowerBoost;
                fileDefaultsTextBox.Lines   = engine.Defaults;
                fileOverridesTextBox.Lines  = engine.Overrides;
                fileCommentTextBox.Lines    = engine.Comment;
                filenameTextBox.Text        = engine.FileName;
                conflictsTextBox.Lines      = engine.Conflicts;
                engineBrakeLow.Value        = engine.LowRpmRange_EngineBrake;
                engineBrakeHigh.Value       = engine.HighRpmRange_EngineBrake;
                resistanceBox.Value         = engine.ResistanceTorque;
                consumptionBox.Value        = engine.FuelConsumption * 100;
                adBlueConsumption.Value     = engine.AdblueConsumption;
                adBlueNoPowerLimit.Value    = engine.NoAdbluePowerLimit;

                // Set torque last, to update the chart
                torqueBox.Value = (Program.Config.UnitSystem == UnitSystem.Imperial)
                    ? engine.Torque
                    : engine.NewtonMetres;
            }

            // Fill torque ratios
            PopulateTorqueRatios();

            // Fill Conflicts
            PopulateTransmissions();

            if (NewEngine)
            {
                // Force change to update graph
                torqueBox.Value = (Program.Config.UnitSystem == UnitSystem.Imperial)
                    ? 1650 :
                                  Metrics.TorqueToNewtonMeters(1650m);
            }
        }
Esempio n. 30
0
        private void importButton_Click(object sender, EventArgs e)
        {
            // Request the user supply the steam library path
            var dialog = new OpenFileDialog();

            dialog.Title  = "Engine SII File Import";
            dialog.Filter = "SiiNunit|*.sii";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    var document = new SiiDocument(typeof(AccessoryEngineData));

                    using (FileStream stream = File.OpenRead(dialog.FileName))
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            // Read the file contents
                            string contents = reader.ReadToEnd().Trim();
                            document.Load(contents);

                            // Grab the engine object
                            List <string> objects = new List <string>(document.Definitions.Keys);
                            if (objects.Count == 0)
                            {
                                MessageBox.Show("Unable to find any engine data in this sii document!",
                                                "Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning
                                                );
                                return;
                            }

                            // Grab the engine
                            var engine = document.GetDefinition <AccessoryEngineData>(objects[0]);

                            // === Set form values
                            int len = objects[0].IndexOf('.');
                            unitNameBox.Text     = objects[0].Substring(0, len);
                            engineNameBox.Text   = engine.Name;
                            filenameTextBox.Text = Path.GetFileName(dialog.FileName);
                            unlockBox.SetValueInRange(engine.UnlockLevel);
                            priceBox.SetValueInRange(engine.Price);
                            neutralRpmBox.SetValueInRange(engine?.RpmLimitNeutral ?? 2200);
                            rpmLimitBox.SetValueInRange((decimal)engine.RpmLimit);
                            idleRpmBox.SetValueInRange(engine?.IdleRpm ?? 650);
                            brakeStrengthBox.SetValueInRange((decimal)engine.BrakeStrength);
                            brakePositionsBox.SetValueInRange(engine.BrakePositions);
                            automaticDSCheckBox.Checked = engine.BrakeDownshift == 1;

                            // Misc
                            if (engine.RpmRangeEngineBrake.X > 0f)
                            {
                                engineBrakeLow.SetValueInRange((int)engine.RpmRangeEngineBrake.X);
                                engineBrakeHigh.SetValueInRange((int)engine.RpmRangeEngineBrake.Y);
                            }
                            consumptionBox.SetValueInRange((decimal)engine.FuelConsumption * 100);
                            adBlueConsumption.SetValueInRange((decimal)engine.AdblueConsumption);
                            adBlueNoPowerLimit.SetValueInRange((decimal)engine.NoAdbluePowerLimit);
                            conflictsTextBox.Lines = engine?.Conflicts ?? new string[] { };

                            // Tab 3
                            if (engine.RpmRange_LowGear.X > 0f)
                            {
                                rpmRangeBox1.SetValueInRange((int)engine.RpmRange_LowGear.X);
                                rpmRangeBox2.SetValueInRange((int)engine.RpmRange_LowGear.Y);
                            }
                            if (engine.RpmRange_HighGear.X > 0f)
                            {
                                rpmRangeBox3.SetValueInRange((int)engine.RpmRange_HighGear.X);
                                rpmRangeBox4.SetValueInRange((int)engine.RpmRange_HighGear.Y);
                            }
                            if (engine.RpmRange_PowerBoost.X > 0f)
                            {
                                rpmRangeBox5.SetValueInRange((int)engine.RpmRange_PowerBoost.X);
                                rpmRangeBox6.SetValueInRange((int)engine.RpmRange_PowerBoost.Y);
                            }

                            // Parse Horsepower
                            Regex reg = new Regex("^(?<hp>[0-9]+)", RegexOptions.Multiline);
                            if (reg.IsMatch(engine.Info[0]))
                            {
                                horsepowerBox.SetValueInRange(Int32.Parse(reg.Match(engine.Info[0]).Groups["hp"].Value));
                            }

                            if (engine.TorqueCurves?.Length > 0)
                            {
                                // Clear torque curves
                                chart1.Series[0].Points.Clear();
                                ratioListView.Items.Clear();
                                Ratios.Clear();

                                // Set new torque curves
                                foreach (Vector2 vector in engine.TorqueCurves)
                                {
                                    TorqueRatio ratio = new TorqueRatio();
                                    ratio.RpmLevel = (int)vector.X;
                                    ratio.Ratio    = Math.Round(vector.Y, 4);
                                    Ratios.Add(ratio);
                                }

                                // Fill ratio view
                                PopulateTorqueRatios();
                            }

                            // Set torque value
                            torqueBox.SetValueInRange((Program.Config.UnitSystem == UnitSystem.Imperial)
                            ? Metrics.NewtonMetersToTorque((decimal)engine.Torque, torqueBox.DecimalPlaces)
                            : Math.Round((decimal)engine.Torque, torqueBox.DecimalPlaces)
                                                      );

                            // Defaults (skip sounds)
                            if (engine.Defaults != null)
                            {
                                fileDefaultsTextBox.Lines = (from x in engine.Defaults where !x.Contains("/sound/") select x).ToArray();
                            }

                            // Overrides (skip sounds)
                            if (engine.Overrides != null)
                            {
                                fileOverridesTextBox.Lines = (from x in engine.Overrides where !x.Contains("/sound/") select x).ToArray();
                            }

                            // Alert the user
                            MessageBox.Show(
                                $"Successfully imported the engine \"{engine.Name}\"! You must now select an engine series for this engine.",
                                "Import Successful", MessageBoxButtons.OK, MessageBoxIcon.Information
                                );
                        }
                }
                catch (SiiSyntaxException ex)
                {
                    StringBuilder builder = new StringBuilder("A Syntax error occured while parsing the sii file!");
                    builder.AppendLine();
                    builder.AppendLine();
                    builder.AppendLine($"Message: {ex.Message.Replace("\0", "\\0")}");
                    builder.AppendLine();
                    builder.AppendLine($"Line: {ex.Span.Start.Line}");
                    builder.AppendLine($"Column: {ex.Span.Start.Column}");
                    MessageBox.Show(builder.ToString(), "Sii Syntax Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (SiiException ex)
                {
                    StringBuilder builder = new StringBuilder("Failed to parse the sii file.");
                    builder.AppendLine();
                    builder.AppendLine($"Message: {ex.Message}");
                    MessageBox.Show(builder.ToString(), "Sii Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "An Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }