Beispiel #1
0
        /// <summary>
        /// Writes an attribute to the StringBuilder if the attribute type exists in the sounds list.
        /// </summary>
        /// <param name="sounds">The list of sound attributes and their sounds for this package</param>
        /// <param name="classMap">A ruuning list of objects that will be later written to the buffer.</param>
        /// <param name="builder">The current string buffer</param>
        private static void WriteAttribute <TSound>(SoundInfo info,
                                                    Dictionary <SoundAttribute, List <TSound> > sounds,
                                                    Dictionary <string, Sound> classMap,
                                                    SiiFileBuilder builder) where TSound : Sound
        {
            // Only add the sound if it exists (obviously)
            List <TSound> soundList;

            if (sounds.TryGetValue(info.AttributeType, out soundList))
            {
                if (info.IsArray)
                {
                    int    i    = 0;
                    string name = info.AttributeName;
                    foreach (var snd in soundList)
                    {
                        // Write attribute line
                        string sname = info.StructName + i++;
                        builder.WriteLineIf(info.Indexed, $"{name}[{i - 1}]: {sname}", $"{name}[]: {sname}");

                        // Add to classmap
                        classMap.Add(sname, snd);
                    }
                }
                else
                {
                    // Write attribute line
                    builder.WriteAttribute(info.AttributeName, info.StructName, false);

                    // Add to classmap
                    classMap.Add(info.StructName, soundList[0]);
                }

                // Trailing line?
                builder.WriteLineIf(info.AppendLineAfter);
            }
        }
Beispiel #2
0
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            // Check UnitName
            // Check for a valid identifier string
            if (!SiiFileBuilder.IsValidUnitName(unitNameBox.Text))
            {
                // Tell the user this isnt allowed
                MessageBox.Show(
                    "Invalid Engine Sii Unit Name. Tokens must be 1 to 12 characters in length, seperated by a dot, "
                    + "and contain alpha-numeric or underscores only",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning
                    );

                return;
            }

            // Check engine name
            if (engineNameBox.Text.Length < 2 || engineNameBox.Text.Contains('"'))
            {
                // Tell the user this isnt allowed
                MessageBox.Show(
                    "Invalid Engine Name string. The name must be at least 2 characters long and contain no quotes",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning
                    );

                return;
            }

            // Set new attribute values
            Engine.SeriesId                 = ((EngineSeries)engineModelBox.SelectedItem).Id;
            Engine.UnitName                 = unitNameBox.Text.Trim();
            Engine.Name                     = engineNameBox.Text.Trim();
            Engine.Price                    = (int)priceBox.Value;
            Engine.Unlock                   = (int)unlockBox.Value;
            Engine.Horsepower               = (int)horsepowerBox.Value;
            Engine.PeakRpm                  = (int)peakRPMBox.Value;
            Engine.IdleRpm                  = (int)idleRpmBox.Value;
            Engine.RpmLimit                 = (int)rpmLimitBox.Value;
            Engine.RpmLimitNeutral          = (int)neutralRpmBox.Value;
            Engine.BrakeStrength            = brakeStrengthBox.Value;
            Engine.BrakePositions           = (int)brakePositionsBox.Value;
            Engine.BrakeDownshift           = automaticDSCheckBox.Checked;
            Engine.MinRpmRange_LowGear      = (int)rpmRangeBox1.Value;
            Engine.MaxRpmRange_LowGear      = (int)rpmRangeBox2.Value;
            Engine.MinRpmRange_HighGear     = (int)rpmRangeBox3.Value;
            Engine.MaxRpmRange_HighGear     = (int)rpmRangeBox4.Value;
            Engine.LowRpmRange_PowerBoost   = (int)rpmRangeBox5.Value;
            Engine.HighRpmRange_PowerBoost  = (int)rpmRangeBox6.Value;
            Engine.ResistanceTorque         = (int)resistanceBox.Value;
            Engine.FuelConsumption          = Math.Round(consumptionBox.Value / 100, 2);
            Engine.NoAdbluePowerLimit       = adBlueNoPowerLimit.Value;
            Engine.AdblueConsumption        = adBlueConsumption.Value;
            Engine.LowRpmRange_EngineBrake  = (int)engineBrakeLow.Value;
            Engine.HighRpmRange_EngineBrake = (int)engineBrakeHigh.Value;
            Engine.Defaults                 = fileDefaultsTextBox.Lines;
            Engine.Overrides                = fileOverridesTextBox.Lines;
            Engine.Comment                  = fileCommentTextBox.Lines;
            Engine.Conflicts                = conflictsTextBox.Lines;

            // Torque metrics
            if (Program.Config.UnitSystem == UnitSystem.Imperial)
            {
                Engine.Torque = (int)torqueBox.Value;
            }
            else
            {
                Engine.NewtonMetres = (int)torqueBox.Value;
            }

            // Figure out the filename
            if (!String.IsNullOrWhiteSpace(filenameTextBox.Text))
            {
                Engine.FileName = filenameTextBox.Text.Trim();
            }

            // Validate and Save
            using (AppDatabase db = new AppDatabase())
                using (SQLiteTransaction trans = db.BeginTransaction())
                {
                    // Verify that the series.Id and engine.UnitName are unique
                    string query  = "SELECT * FROM `Engine` WHERE `SeriesId`=@P0 AND `UnitName`=@P1";
                    var    engine = db.Query <Engine>(query, Engine.SeriesId, Engine.UnitName).FirstOrDefault();
                    if (engine != null && (NewEngine || engine.Id != Engine.Id))
                    {
                        // Tell the user this isnt allowed
                        MessageBox.Show(
                            $"The selected Engine Series already contains an engine with the Sii Unit Name of \""
                            + Engine.UnitName + "\"! Please select a different Engine Series or change the Sii "
                            + "Unit Name to something unique.",
                            "Unique Constraint Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning
                            );
                        return;
                    }

                    // Wrap database changes in a try-catch block so we can Rollback on error
                    try
                    {
                        // Update or Add engine
                        db.Engines.AddOrUpdate(Engine);

                        // If pre-existing engine, delete all changed data
                        if (!NewEngine)
                        {
                            // Delete any and all TorueRatios from thed database
                            if (RatiosChanged)
                            {
                                foreach (TorqueRatio ratio in Engine.TorqueRatios)
                                {
                                    db.TorqueRatios.Remove(ratio);
                                }
                            }

                            // Set Conflicts
                            if (ConflictsChanged)
                            {
                                // Remove old
                                foreach (var conflict in Engine.TransmissionConflicts)
                                {
                                    db.AccessoryConflicts.Remove(conflict);
                                }
                            }

                            // Set Suitables
                            if (SuitablesChanged)
                            {
                                foreach (var item in Engine.SuitableTransmissions)
                                {
                                    db.SuitableAccessories.Remove(item);
                                }
                            }

                            // Set compatible trucks
                            if (TrucksChanged)
                            {
                                foreach (var item in Engine.ItemOf)
                                {
                                    db.TruckEngines.Remove(item);
                                }
                            }
                        }

                        // Add conflicts
                        if ((NewEngine || ConflictsChanged) && conflictListView.CheckedItems.Count > 0)
                        {
                            var ids = conflictListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.AccessoryConflicts.Add(new AccessoryConflict()
                                {
                                    EngineId       = Engine.Id,
                                    TransmissionId = item
                                });
                            }
                        }

                        // Add suitible fors
                        if ((NewEngine || SuitablesChanged) && suitsListView.CheckedItems.Count > 0)
                        {
                            var ids = suitsListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.SuitableAccessories.Add(new SuitableAccessory()
                                {
                                    EngineId       = Engine.Id,
                                    TransmissionId = item
                                });
                            }
                        }

                        // Add new truck engines
                        if ((NewEngine || TrucksChanged) && truckListView.CheckedItems.Count > 0)
                        {
                            var ids = truckListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.TruckEngines.Add(new TruckEngine()
                                {
                                    EngineId = Engine.Id,
                                    TruckId  = item
                                });
                            }
                        }

                        // Add the new torque ratios
                        if (NewEngine || RatiosChanged)
                        {
                            foreach (TorqueRatio ratio in Ratios.OrderBy(x => x.RpmLevel))
                            {
                                ratio.EngineId = Engine.Id;
                                db.TorqueRatios.AddOrUpdate(ratio);
                            }
                        }

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();

                        // Tell the user about the failed validation error
                        MessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

            this.DialogResult = DialogResult.OK;
        }
Beispiel #3
0
        /// <summary>
        /// Sound File compiler
        /// </summary>
        /// <param name="location"></param>
        /// <returns></returns>
        private static string CompileSoundFile(
            SoundLocation location,
            Truck truck,
            SoundPackageWrapper <EngineSoundPackage, EngineSound> enginePackage,
            SoundPackageWrapper <TruckSoundPackage, TruckSound> truckPackage,
            string unitName = null)
        {
            // Local variables
            var builder      = new SiiFileBuilder();
            var objectMap    = new Dictionary <string, Sound>();
            var engineSounds = enginePackage.GetSoundsByLocation(location);
            var truckSounds  = truckPackage.GetSoundsByLocation(location);

            // Figure out the accessory name
            var name = new StringBuilder(unitName ?? enginePackage.Package.UnitName);

            name.Append($".{truck.UnitName}.");
            name.AppendLineIf(location == SoundLocation.Exterior, "esound", "isound");

            // Write file intro
            builder.IndentStructs = false;
            builder.WriteStartDocument();

            // Write the accessory type
            builder.WriteStructStart("accessory_sound_data", name.ToString().TrimEnd());

            // Mark exterior or interior attribute
            builder.WriteAttribute("exterior_sound", location == SoundLocation.Exterior);
            builder.WriteLine();

            // ===
            // === Write Engine Attributes
            // ===
            foreach (var info in SoundInfo.Attributes.Values)
            {
                // Only engine sounds
                if (info.SoundType != SoundType.Engine)
                {
                    continue;
                }

                WriteAttribute(info, engineSounds, objectMap, builder);
            }

            // ===
            // === Write Truck Attributes
            // ===
            foreach (var info in SoundInfo.Attributes.Values)
            {
                // Only truck sounds
                if (info.SoundType != SoundType.Truck)
                {
                    continue;
                }

                WriteAttribute(info, truckSounds, objectMap, builder);
            }

            // Include directive.. Directives have no tabs at all!
            if (location == SoundLocation.Interior)
            {
                builder.WriteInclude("/def/vehicle/truck/common_sound_int.sui");
            }
            else
            {
                builder.WriteInclude("/def/vehicle/truck/common_sound_ext.sui");
            }

            // Close Accessory
            builder.WriteStructEnd();
            builder.WriteLine();

            // ===
            // === Append class objects
            // ===
            foreach (var item in objectMap)
            {
                // Get sound package
                SoundPackage package = (item.Value.SoundType == SoundType.Engine)
                    ? enginePackage.Package as SoundPackage
                    : truckPackage.Package as SoundPackage;

                // Add sound object
                item.Value.AppendTo(builder, item.Key, package);
            }

            // Write the include directive
            if (location == SoundLocation.Interior)
            {
                builder.WriteInclude("/def/vehicle/truck/common_sound_int_data.sui");
            }
            else
            {
                builder.WriteInclude("/def/vehicle/truck/common_sound_ext_data.sui");
            }

            // Close SiiNUnit
            builder.WriteEndDocument();
            return(builder.ToString());
        }
Beispiel #4
0
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            // Check UnitName
            // Check for a valid identifier string
            if (!SiiFileBuilder.IsValidUnitName(unitNameBox.Text))
            {
                // Tell the user this isnt allowed
                MessageBox.Show(
                    "Invalid Transmission Sii Unit Name. Tokens must be 1 to 12 characters in length, seperated by a dot, "
                    + "and contain alpha-numeric or underscores only",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning
                    );

                return;
            }

            // Check engine name
            if (transNameBox.Text.Length < 2 || transNameBox.Text.Contains('"'))
            {
                // Tell the user this isnt allowed
                MessageBox.Show(
                    "Invalid Transmission Name string! The name must be at least 2 characters long and contain no quotes",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning
                    );

                return;
            }

            // Set new attribute values
            Transmission.SeriesId          = ((TransmissionSeries)seriesModelBox.SelectedItem).Id;
            Transmission.UnitName          = unitNameBox.Text.Trim();
            Transmission.Name              = transNameBox.Text.Trim();
            Transmission.Price             = (int)priceBox.Value;
            Transmission.Unlock            = (int)unlockBox.Value;
            Transmission.DifferentialRatio = diffRatio.Value;
            Transmission.Defaults          = fileDefaultsTextBox.Lines;
            Transmission.Comment           = fileCommentTextBox.Lines;
            Transmission.Conflicts         = conflictsTextBox.Lines;
            Transmission.SuitableFor       = suitablesTextBox.Lines;
            Transmission.Retarder          = (hasRetarder.Checked) ? (int)retardPositions.Value : 0;
            Transmission.StallTorqueRatio  = (hasTorqueConverter.Checked) ? stallRatio.Value : 0.0m;

            // Figure out the filename
            if (!String.IsNullOrWhiteSpace(filenameTextBox.Text))
            {
                Transmission.FileName = filenameTextBox.Text.Trim();
            }

            // Validate and Save
            using (AppDatabase db = new AppDatabase())
                using (SQLiteTransaction trans = db.BeginTransaction())
                {
                    // Verify that the series.Id and engine.UnitName are unique
                    string query  = "SELECT * FROM `Transmission` WHERE `SeriesId`=@P0 AND `UnitName`=@P1";
                    var    eTrans = db.Query <Transmission>(query, Transmission.SeriesId, Transmission.UnitName).FirstOrDefault();
                    if (eTrans != null && (NewTransmission || eTrans.Id != Transmission.Id))
                    {
                        // Tell the user this isnt allowed
                        MessageBox.Show(
                            $"The selected Transmission Series already contains a transmission with the Sii Unit Name of \""
                            + Transmission.UnitName + "\"! Please select a different Transmission Series or change the Sii "
                            + "Unit Name to something unique.",
                            "Unique Constraint Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning
                            );
                        return;
                    }

                    // Wrap database changes in a try-catch block so we can Rollback on error
                    try
                    {
                        // Update the current engine
                        db.Transmissions.AddOrUpdate(Transmission);

                        // If pre-existing transmission, delete all changed data
                        if (!NewTransmission)
                        {
                            // Delete any and all TorueRatios from the database
                            if (GearsChanged)
                            {
                                foreach (var gear in Transmission.Gears)
                                {
                                    db.TransmissionGears.Remove(gear);
                                }
                            }

                            // Set Conflicts
                            if (ConflictsChanged)
                            {
                                foreach (var conflict in Transmission.EngineConflicts)
                                {
                                    db.AccessoryConflicts.Remove(conflict);
                                }
                            }

                            // Set Suitables
                            if (SuitablesChanged)
                            {
                                foreach (var item in Transmission.SuitableEngines)
                                {
                                    db.SuitableAccessories.Remove(item);
                                }
                            }

                            // Set Conflicts
                            if (TrucksChanged)
                            {
                                foreach (var item in Transmission.ItemOf)
                                {
                                    db.TruckTransmissions.Remove(item);
                                }
                            }
                        }

                        // Add conflicts if any
                        if ((NewTransmission || ConflictsChanged) && conflictListView.CheckedItems.Count > 0)
                        {
                            var ids = conflictListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.AccessoryConflicts.Add(new AccessoryConflict()
                                {
                                    EngineId       = item,
                                    TransmissionId = Transmission.Id
                                });
                            }
                        }

                        // Add suitible fors if any
                        if ((NewTransmission || SuitablesChanged) && suitsListView.CheckedItems.Count > 0)
                        {
                            var ids = suitsListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.SuitableAccessories.Add(new SuitableAccessory()
                                {
                                    EngineId       = item,
                                    TransmissionId = Transmission.Id
                                });
                            }
                        }

                        // Add trucks if any
                        if ((NewTransmission || TrucksChanged) && truckListView.CheckedItems.Count > 0)
                        {
                            var ids = truckListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.TruckTransmissions.Add(new TruckTransmission()
                                {
                                    TruckId        = item,
                                    TransmissionId = Transmission.Id
                                });
                            }
                        }

                        // Add the new torque ratios
                        if (NewTransmission || GearsChanged)
                        {
                            int i = 0;
                            foreach (var gear in ReverseGears.OrderBy(x => x.Ratio))
                            {
                                gear.TransmissionId = Transmission.Id;
                                gear.GearIndex      = i++;
                                db.TransmissionGears.Add(gear);
                            }
                            foreach (var gear in ForwardGears.OrderByDescending(x => x.Ratio))
                            {
                                gear.TransmissionId = Transmission.Id;
                                gear.GearIndex      = i++;
                                db.TransmissionGears.Add(gear);
                            }
                        }

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();

                        // Tell the user about the failed validation error
                        MessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

            this.DialogResult = DialogResult.OK;
        }