Exemplo n.º 1
0
 void Awake()
 {
     trainCar         = GameController.instance.activeCar;
     parentController = GetComponent <EnemyController>();
 }
Exemplo n.º 2
0
 public Blinker(TrainCar car)
 {
     CurrentValue = () => (float)car.Simulator.GameTime;
 }
        public static bool Prefix(TrainCar __instance, SpriteBatch b, Vector2 globalPosition, float wheelRotation)
        {
            TrainCar car = __instance;

            _monitor.Log($"Starting the draw proccess. Car Type: { car.carType.Value }, Resource Type: { car.resourceType.Value }");
            b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, globalPosition), new Rectangle(192 + car.carType.Value * 128, 512 - (car.alternateCar.Value ? 64 : 0), 128, 57), car.color.Value, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)((globalPosition.Y + 256.0) / 10000.0));
            b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, globalPosition + new Vector2(0.0f, 228f)), new Rectangle(192 + car.carType.Value * 128, 569, 128, 7), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)((globalPosition.Y + 256.0) / 10000.0));
            if (car.carType.Value == 1)
            {
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, globalPosition), new Rectangle(448 + car.resourceType.Value * 128 % 256, 576 + car.resourceType.Value / 2 * 32, 128, 32), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)((globalPosition.Y + 260.0) / 10000.0));
                if (car.loaded.Value > 0 && Game1.random.NextDouble() < 0.003 && (globalPosition.X > 256.0 && globalPosition.X < (double)(Game1.currentLocation.map.DisplayWidth - 256)))
                {
                    --car.loaded.Value;
                    int objectIndex = -1;
                    switch (car.resourceType.Value)
                    {
                    case 0:
                        objectIndex = 521;
                        break;

                    case 1:
                        objectIndex = car.color.R > car.color.G ? 378 : (car.color.G > car.color.B ? 522 : (car.color.B > car.color.R ? 523 : 524));
                        break;

                    case 2:
                        objectIndex = 525;
                        break;

                    case 6:
                        objectIndex = 526;
                        break;

                    case 7:
                        objectIndex = Game1.currentSeason.Equals("winter") ? 536 : (Game1.stats.DaysPlayed <= 120U || car.color.R <= car.color.G ? 535 : 537);
                        break;
                    }
                    if (objectIndex != -1)
                    {
                        Game1.createObjectDebris(objectIndex, (int)globalPosition.X / 64, (int)globalPosition.Y / 64, (int)(globalPosition.Y + 320.0));
                    }
                    _monitor.Log($"Objects created should have been {objectIndex}");
                }
            }
            if (car.carType.Value == 0)
            {
                for (int index = 0; index < car.topFeatures.Count; index += 64)
                {
                    if (car.topFeatures[index] != -1)
                    {
                        b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, globalPosition + new Vector2(64 + index, 20f)), new Rectangle(192, 608 + car.topFeatures[index] * 16, 16, 16), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)((globalPosition.Y + 260.0) / 10000.0));
                    }
                }
            }
            if (car.frontDecal.Value != -1 && (car.carType.Value == 0 || car.carType.Value == 1))
            {
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, globalPosition + new Vector2(192f, 92f)), new Rectangle(224 + car.frontDecal.Value * 32 % 224, 576 + car.frontDecal.Value * 32 / 224 * 32, 32, 32), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)((globalPosition.Y + 260.0) / 10000.0));
            }
            if (car.carType.Value != 3)
            {
                return(false);
            }
            Vector2 local1 = Game1.GlobalToLocal(Game1.viewport, globalPosition + new Vector2(72f, 208f));
            Vector2 local2 = Game1.GlobalToLocal(Game1.viewport, globalPosition + new Vector2(316f, 208f));

            b.Draw(Game1.mouseCursors, local1, new Rectangle(192, 576, 20, 20), Color.White, wheelRotation, new Vector2(10f, 10f), 4f, SpriteEffects.None, (float)((globalPosition.Y + 260.0) / 10000.0));
            b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, globalPosition + new Vector2(228f, 208f)), new Rectangle(192, 576, 20, 20), Color.White, wheelRotation, new Vector2(10f, 10f), 4f, SpriteEffects.None, (float)((globalPosition.Y + 260.0) / 10000.0));
            b.Draw(Game1.mouseCursors, local2, new Rectangle(192, 576, 20, 20), Color.White, wheelRotation, new Vector2(10f, 10f), 4f, SpriteEffects.None, (float)((globalPosition.Y + 260.0) / 10000.0));
            int x1 = (int)(local1.X + 4.0 + 24.0 * Math.Cos(wheelRotation));
            int y1 = (int)(local1.Y + 4.0 + 24.0 * Math.Sin(wheelRotation));
            int x2 = (int)(local2.X + 4.0 + 24.0 * Math.Cos(wheelRotation));
            int y2 = (int)(local2.Y + 4.0 + 24.0 * Math.Sin(wheelRotation));

            Utility.drawLineWithScreenCoordinates(x1, y1, x2, y2, b, new Color(112, 98, 92), (float)((globalPosition.Y + 264.0) / 10000.0));
            Utility.drawLineWithScreenCoordinates(x1, y1 + 2, x2, y2 + 2, b, new Color(112, 98, 92), (float)((globalPosition.Y + 264.0) / 10000.0));
            Utility.drawLineWithScreenCoordinates(x1, y1 + 4, x2, y2 + 4, b, new Color(53, 46, 43), (float)((globalPosition.Y + 264.0) / 10000.0));
            Utility.drawLineWithScreenCoordinates(x1, y1 + 6, x2, y2 + 6, b, new Color(53, 46, 43), (float)((globalPosition.Y + 264.0) / 10000.0));
            b.Draw(Game1.mouseCursors, new Vector2(x1 - 8, y1 - 8), new Rectangle(192, 640, 24, 24), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)((globalPosition.Y + 268.0) / 10000.0));
            b.Draw(Game1.mouseCursors, new Vector2(x2 - 8, y2 - 8), new Rectangle(192, 640, 24, 24), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)((globalPosition.Y + 268.0) / 10000.0));

            //Stop the original from running. This one will be so similar it wont matter.
            return(false);
        }
Exemplo n.º 4
0
        private void DrawTrains(Graphics g, PointF scaledA, PointF scaledB)
        {
            var margin  = 30 * F.xScale;  //margins to determine if we want to draw a train
            var margin2 = 5000 * F.xScale;

            //variable for drawing train path
            var mDist = 5000f; var pDist = 50; //segment length when drawing path

            F.selectedTrainList.Clear();

            if (F.simulator.TimetableMode)
            {
                // Add the player's train
                if (F.simulator.PlayerLocomotive.Train is Orts.Simulation.AIs.AITrain)
                {
                    F.selectedTrainList.Add(F.simulator.PlayerLocomotive.Train as Orts.Simulation.AIs.AITrain);
                }

                // and all the other trains
                foreach (var train in F.simulator.AI.AITrains)
                {
                    F.selectedTrainList.Add(train);
                }
            }
            else
            {
                foreach (var train in F.simulator.Trains)
                {
                    F.selectedTrainList.Add(train);
                }
            }

            foreach (var train in F.selectedTrainList)
            {
                string        trainName;
                WorldPosition worldPos;
                TrainCar      locoCar = null;
                if (train.LeadLocomotive != null)
                {
                    trainName = train.GetTrainName(train.LeadLocomotive.CarID);
                    locoCar   = train.LeadLocomotive;
                }
                else if (train.Cars != null && train.Cars.Count > 0)
                {
                    trainName = train.GetTrainName(train.Cars[0].CarID);
                    if (train.TrainType == Train.TRAINTYPE.AI)
                    {
                        trainName = train.Number.ToString() + ":" + train.Name;
                    }

                    locoCar = train.Cars.Where(r => r is MSTSLocomotive).FirstOrDefault();

                    // Skip trains with no loco
                    if (locoCar == null)
                    {
                        continue;
                    }
                }
                else
                {
                    continue;
                }

                // Draw the path, then each car of the train, then maybe the name
                var   loc = train.FrontTDBTraveller.WorldLocation;
                float x   = (loc.TileX * 2048 + loc.Location.X - F.subX) * F.xScale;
                float y   = F.pbCanvas.Height - (loc.TileZ * 2048 + loc.Location.Z - F.subY) * F.yScale;

                // If train out of view then skip it.
                if (x < -margin2 ||
                    y < -margin2)
                {
                    continue;
                }

                F.DrawTrainPath(train, F.subX, F.subY, F.pathPen, g, scaledA, scaledB, pDist, mDist);

                // If zoomed out, so train occupies less than 2 * minTrainPx pixels, then
                // draw the train as 2 squares of combined length minTrainPx.
                const int minTrainPx = 24;

                // pen | train | Values for a good presentation
                //  1		10
                //  2       12
                //  3       14
                //  4		16
                F.trainPen.Width = F.grayPen.Width * 6;

                var  minTrainLengthM = minTrainPx / F.xScale; // Calculate length equivalent to a set number of pixels
                bool drawEveryCar    = IsDrawEveryCar(train, minTrainLengthM);

                foreach (var car in train.Cars)
                {
                    DrawCar(g, train, car, locoCar, margin, minTrainPx, drawEveryCar);
                }

                worldPos = locoCar.WorldPosition;
                var scaledTrain = new PointF();
                scaledTrain.X = (worldPos.TileX * 2048 - F.subX + worldPos.Location.X) * F.xScale;
                scaledTrain.Y = -25 + F.pbCanvas.Height - (worldPos.TileZ * 2048 - F.subY + worldPos.Location.Z) * F.yScale;
                if (F.cbShowTrainLabels.Checked)
                {
                    DrawTrainLabels(g, train, trainName, locoCar, scaledTrain);
                }
            }
        }
Exemplo n.º 5
0
 private static void Prefix(TrainCar __instance)
 {
     DoDestroy(__instance);
 }
Exemplo n.º 6
0
        /// <summary>
        /// Retrieve a formatted list <see cref="ListLabel"/>s to be displayed as an in-browser Track Monitor.
        /// </summary>
        /// <param name="viewer">The Viewer to read train data from.</param>
        /// <returns>A list of <see cref="ListLabel"/>s, one per row of the popup.</returns>
        public static IEnumerable <ListLabel> TrainDrivingDisplayList(this Viewer viewer, bool normalTextMode = true)
        {
            bool useMetric = viewer.MilepostUnitsMetric;
            var  labels    = new List <ListLabel>();

            void AddLabel(ListLabel label)
            {
                CheckLabel(ref label, normalTextMode);
                labels.Add(label);
            }

            void AddSeparator() => AddLabel(new ListLabel
            {
                FirstCol = Viewer.Catalog.GetString("Sprtr"),
            });

            TrainCar       trainCar            = viewer.PlayerLocomotive;
            Train          train               = trainCar.Train;
            string         trainBrakeStatus    = trainCar.GetTrainBrakeStatus();
            string         dynamicBrakeStatus  = trainCar.GetDynamicBrakeStatus();
            string         engineBrakeStatus   = trainCar.GetEngineBrakeStatus();
            MSTSLocomotive locomotive          = (MSTSLocomotive)trainCar;
            string         locomotiveStatus    = locomotive.GetStatus();
            bool           combinedControlType = locomotive.CombinedControlType == MSTSLocomotive.CombinedControl.ThrottleDynamic;
            bool           showMUReverser      = Math.Abs(train.MUReverserPercent) != 100f;
            bool           showRetainers       = train.RetainerSetting != RetainerSetting.Exhaust;
            bool           stretched           = train.Cars.Count > 1 && train.CouplersPulled == train.Cars.Count - 1;
            bool           bunched             = !stretched && train.Cars.Count > 1 && train.CouplersPushed == train.Cars.Count - 1;

            Orts.Simulation.Physics.TrainInfo trainInfo = train.GetTrainInfo();

            // First Block
            // Client and server may have a time difference.
            AddLabel(new ListLabel
            {
                FirstCol = Viewer.Catalog.GetString("Time"),
                LastCol  = FormatStrings.FormatTime(viewer.Simulator.ClockTime + (MultiPlayer.MPManager.IsClient() ? MultiPlayer.MPManager.Instance().serverTimeDifference : 0)),
            });
            if (viewer.Simulator.IsReplaying)
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Replay"),
                    LastCol  = FormatStrings.FormatTime(viewer.Log.ReplayEndsAt - viewer.Simulator.ClockTime),
                });
            }

            Color speedColor;

            if (locomotive.SpeedMpS < trainInfo.AllowedSpeed - 1f)
            {
                speedColor = Color.White;
            }
            else if (locomotive.SpeedMpS < trainInfo.AllowedSpeed)
            {
                speedColor = Color.PaleGreen;
            }
            else if (locomotive.SpeedMpS < trainInfo.AllowedSpeed + 5f)
            {
                speedColor = Color.Orange;
            }
            else
            {
                speedColor = Color.OrangeRed;
            }
            AddLabel(new ListLabel
            {
                FirstCol = Viewer.Catalog.GetString("Speed"),
                LastCol  = $"{FormatStrings.FormatSpeedDisplay(locomotive.SpeedMpS, useMetric)}{ColorCode[speedColor]}",
            });

            // Gradient info
            if (normalTextMode)
            {
                float       gradient = -trainInfo.Gradient;
                const float minSlope = 0.00015f;
                string      gradientIndicator;
                if (gradient < -minSlope)
                {
                    gradientIndicator = $"{gradient:F1}%{Symbols.GradientDown}{ColorCode[Color.LightSkyBlue]}";
                }
                else if (gradient > minSlope)
                {
                    gradientIndicator = $"{gradient:F1}%{Symbols.GradientUp}{ColorCode[Color.Yellow]}";
                }
                else
                {
                    gradientIndicator = $"{gradient:F1}%";
                }
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Gradient"),
                    LastCol  = gradientIndicator,
                });
            }
            // Separator
            AddSeparator();

            // Second block
            // Direction
            {
                string reverserKey;
                bool   moving      = Math.Abs(trainCar.SpeedMpS) > 1;
                bool   nonSteamEnd = trainCar.EngineType != TrainCar.EngineTypes.Steam && trainCar.Direction == MidpointDirection.N && (trainCar.ThrottlePercent >= 1 || moving);
                bool   steamEnd    = locomotive is MSTSSteamLocomotive steamLocomotive2 && steamLocomotive2.CutoffController.MaximumValue == Math.Abs(train.MUReverserPercent / 100);
                if (reverserForwardDown)
                {
                    if (nonSteamEnd || steamEnd)
                    {
                        reverserKey = Symbols.End + ColorCode[Color.Yellow];
                    }
                    else
                    {
                        reverserKey = Symbols.ArrowUp + ColorCode[Color.Yellow];
                    }
                    reverserForwardDown = false;
                }
                else if (reverserBackwardDown)
                {
                    if (nonSteamEnd || steamEnd)
                    {
                        reverserKey = Symbols.End + ColorCode[Color.Yellow];
                    }
                    else
                    {
                        reverserKey = Symbols.ArrowDown + ColorCode[Color.Yellow];
                    }
                    reverserBackwardDown = false;
                }
                else
                {
                    reverserKey = "";
                }

                string reverserIndicator = showMUReverser ? $"{Round(Math.Abs(train.MUReverserPercent))}% " : "";
                AddLabel(new ListLabel
                {
                    FirstCol   = Viewer.Catalog.GetString(locomotive.EngineType == TrainCar.EngineTypes.Steam ? "Reverser" : "Direction"),
                    LastCol    = $"{reverserIndicator}{FormatStrings.Catalog.GetParticularString("Reverser", locomotive.Direction.GetDescription())}",
                    KeyPressed = reverserKey,
                    SymbolCol  = reverserKey,
                });
            }

            // Throttle
            {
                string throttleKey;
                if (locomotive.DynamicBrakePercent > -1)
                {
                    throttleKey = Symbols.EndLower + ColorCode[Color.Yellow];
                }
                else if (throttleIncrease)
                {
                    if (locomotive.DynamicBrakePercent < 1 && locomotive.ThrottleController.MaximumValue == trainCar.ThrottlePercent / 100)
                    {
                        throttleKey = Symbols.End + ColorCode[Color.Yellow];
                    }
                    else
                    {
                        throttleKey = Symbols.ArrowUp + ColorCode[Color.Yellow];
                    }
                    throttleIncrease = false;
                }
                else if (throttleDecrease)
                {
                    if (locomotive.DynamicBrakePercent < 1 && trainCar.ThrottlePercent == 0)
                    {
                        throttleKey = Symbols.End + ColorCode[Color.Yellow];
                    }
                    else
                    {
                        throttleKey = Symbols.ArrowDown + ColorCode[Color.Yellow];
                    }
                    throttleDecrease = false;
                }
                else
                {
                    throttleKey = "";
                }

                AddLabel(new ListLabel
                {
                    FirstCol   = Viewer.Catalog.GetString(locomotive is MSTSSteamLocomotive ? "Regulator" : "Throttle"),
                    LastCol    = $"{Round(locomotive.ThrottlePercent)}%",
                    KeyPressed = throttleKey,
                    SymbolCol  = throttleKey,
                });
            }

            // Cylinder Cocks
            if (locomotive is MSTSSteamLocomotive steamLocomotive)
            {
                string cocksIndicator, cocksKey;
                if (steamLocomotive.CylinderCocksAreOpen)
                {
                    cocksIndicator = Viewer.Catalog.GetString("Open") + ColorCode[Color.Orange];
                    cocksKey       = Symbols.ArrowToRight + ColorCode[Color.Yellow];
                }
                else
                {
                    cocksIndicator = Viewer.Catalog.GetString("Closed") + ColorCode[Color.White];
                    cocksKey       = "";
                }
                AddLabel(new ListLabel
                {
                    FirstCol   = Viewer.Catalog.GetString("Cylinder cocks"),
                    LastCol    = cocksIndicator,
                    KeyPressed = cocksKey,
                    SymbolCol  = cocksKey,
                });
            }

            // Sander
            if (locomotive.GetSanderOn())
            {
                bool   sanderBlocked = locomotive.AbsSpeedMpS > locomotive.SanderSpeedOfMpS;
                string sanderKey     = Symbols.ArrowToRight + ColorCode[Color.Yellow];
                AddLabel(new ListLabel
                {
                    FirstCol   = Viewer.Catalog.GetString("Sander"),
                    LastCol    = sanderBlocked ? Viewer.Catalog.GetString("Blocked") + ColorCode[Color.OrangeRed] : Viewer.Catalog.GetString("On") + ColorCode[Color.Orange],
                    KeyPressed = sanderKey,
                    SymbolCol  = sanderKey,
                });
            }
            else
            {
                AddLabel(new ListLabel
                {
                    FirstCol   = Viewer.Catalog.GetString("Sander"),
                    LastCol    = Viewer.Catalog.GetString("Off"),
                    KeyPressed = "",
                    SymbolCol  = "",
                });
            }

            AddSeparator();

            // Train Brake multi-lines
            // TODO: A better algorithm
            //var brakeStatus = Owner.Viewer.PlayerLocomotive.GetTrainBrakeStatus();
            //steam loco
            string brakeInfoValue = "";
            int    index          = 0;

            if (trainBrakeStatus.Contains(Viewer.Catalog.GetString("EQ")))
            {
                string brakeKey;
                if (trainBrakeIncrease)
                {
                    brakeKey           = Symbols.ArrowUp + ColorCode[Color.Yellow];
                    trainBrakeIncrease = false;
                }
                else if (trainBrakeDecrease)
                {
                    brakeKey           = Symbols.ArrowDown + ColorCode[Color.Yellow];
                    trainBrakeDecrease = false;
                }
                else
                {
                    brakeKey = "";
                }

                brakeInfoValue = trainBrakeStatus.Substring(0, trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("EQ"))).TrimEnd();
                AddLabel(new ListLabel
                {
                    FirstCol   = Viewer.Catalog.GetString("Train brake"),
                    LastCol    = $"{brakeInfoValue}{ColorCode[Color.Cyan]}",
                    KeyPressed = brakeKey,
                    SymbolCol  = brakeKey,
                });

                index          = trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("EQ"));
                brakeInfoValue = trainBrakeStatus.Substring(index, trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("BC")) - index).TrimEnd();

                AddLabel(new ListLabel
                {
                    LastCol = brakeInfoValue,
                });
                if (trainBrakeStatus.Contains(Viewer.Catalog.GetString("EOT")))
                {
                    int indexOffset = Viewer.Catalog.GetString("EOT").Length + 1;
                    index          = trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("BC"));
                    brakeInfoValue = trainBrakeStatus.Substring(index, trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("EOT")) - index).TrimEnd();
                    AddLabel(new ListLabel
                    {
                        LastCol = brakeInfoValue,
                    });
                    index          = trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("EOT")) + indexOffset;
                    brakeInfoValue = trainBrakeStatus.Substring(index, trainBrakeStatus.Length - index).TrimStart();
                    AddLabel(new ListLabel
                    {
                        LastCol = brakeInfoValue,
                    });
                }
                else
                {
                    index          = trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("BC"));
                    brakeInfoValue = trainBrakeStatus.Substring(index, trainBrakeStatus.Length - index).TrimEnd();
                    AddLabel(new ListLabel
                    {
                        LastCol = brakeInfoValue,
                    });
                }
            }
            else if (trainBrakeStatus.Contains(Viewer.Catalog.GetString("Lead")))
            {
                int indexOffset = Viewer.Catalog.GetString("Lead").Length + 1;
                brakeInfoValue = trainBrakeStatus.Substring(0, trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("Lead"))).TrimEnd();
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Train brake"),
                    LastCol  = $"{brakeInfoValue}{ColorCode[Color.Cyan]}",
                });

                index = trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("Lead")) + indexOffset;
                if (trainBrakeStatus.Contains(Viewer.Catalog.GetString("EOT")))
                {
                    brakeInfoValue = trainBrakeStatus.Substring(index, trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("EOT")) - index).TrimEnd();
                    AddLabel(new ListLabel
                    {
                        LastCol = brakeInfoValue,
                    });

                    index          = trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("EOT")) + indexOffset;
                    brakeInfoValue = trainBrakeStatus.Substring(index, trainBrakeStatus.Length - index).TrimEnd();
                    AddLabel(new ListLabel
                    {
                        LastCol = brakeInfoValue,
                    });
                }
                else
                {
                    brakeInfoValue = trainBrakeStatus.Substring(index, trainBrakeStatus.Length - index).TrimEnd();
                    AddLabel(new ListLabel
                    {
                        LastCol = brakeInfoValue,
                    });
                }
            }
            else if (trainBrakeStatus.Contains(Viewer.Catalog.GetString("BC")))
            {
                brakeInfoValue = trainBrakeStatus.Substring(0, trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("BC"))).TrimEnd();
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Train brake"),
                    LastCol  = $"{brakeInfoValue}{ColorCode[Color.Cyan]}",
                });

                index          = trainBrakeStatus.IndexOf(Viewer.Catalog.GetString("BC"));
                brakeInfoValue = trainBrakeStatus.Substring(index, trainBrakeStatus.Length - index).TrimEnd();

                AddLabel(new ListLabel
                {
                    LastCol = brakeInfoValue,
                });
            }

            if (showRetainers)
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Retainers"),
                    LastCol  = $"{train.RetainerPercent} {Viewer.Catalog.GetString(train.RetainerSetting.GetDescription())}",
                });
            }

            if (engineBrakeStatus.Contains(Viewer.Catalog.GetString("BC")))
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Engine brake"),
                    LastCol  = engineBrakeStatus.Substring(0, engineBrakeStatus.IndexOf("BC")) + ColorCode[Color.Cyan],
                });
                index          = engineBrakeStatus.IndexOf(Viewer.Catalog.GetString("BC"));
                brakeInfoValue = engineBrakeStatus.Substring(index, engineBrakeStatus.Length - index).TrimEnd();
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString(""),
                    LastCol  = $"{brakeInfoValue}{ColorCode[Color.White]}",
                });
            }
            else
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Engine brake"),
                    LastCol  = $"{engineBrakeStatus}{ColorCode[Color.Cyan]}",
                });
            }

            if (dynamicBrakeStatus != null && locomotive.IsLeadLocomotive())
            {
                if (locomotive.DynamicBrakePercent >= 0)
                {
                    AddLabel(new ListLabel
                    {
                        FirstCol = Viewer.Catalog.GetString("Dynamic brake"),
                        LastCol  = locomotive.DynamicBrake ? dynamicBrakeStatus : Viewer.Catalog.GetString("Setup") + ColorCode[Color.Cyan],
                    });
                }
                else
                {
                    AddLabel(new ListLabel
                    {
                        FirstCol = Viewer.Catalog.GetString("Dynamic brake"),
                        LastCol  = Viewer.Catalog.GetString("Off"),
                    });
                }
            }

            AddSeparator();

            if (locomotiveStatus != null)
            {
                foreach (string data in locomotiveStatus.Split('\n').Where((string d) => d.Length > 0))
                {
                    string[] parts     = data.Split(new string[] { " = " }, 2, StringSplitOptions.None);
                    string   keyPart   = parts[0];
                    string   valuePart = parts?[1];
                    if (Viewer.Catalog.GetString(keyPart).StartsWith(Viewer.Catalog.GetString("Boiler pressure")))
                    {
                        MSTSSteamLocomotive steamLocomotive2 = (MSTSSteamLocomotive)locomotive;
                        float bandUpper = steamLocomotive2.PreviousBoilerHeatOutBTUpS * 1.025f; // find upper bandwidth point
                        float bandLower = steamLocomotive2.PreviousBoilerHeatOutBTUpS * 0.975f; // find lower bandwidth point - gives a total 5% bandwidth

                        string heatIndicator;
                        if (steamLocomotive2.BoilerHeatInBTUpS > bandLower && steamLocomotive2.BoilerHeatInBTUpS < bandUpper)
                        {
                            heatIndicator = $"{Symbols.SmallDiamond}{ColorCode[Color.White]}";
                        }
                        else if (steamLocomotive2.BoilerHeatInBTUpS < bandLower)
                        {
                            heatIndicator = $"{Symbols.SmallArrowDown}{ColorCode[Color.Cyan]}";
                        }
                        else if (steamLocomotive2.BoilerHeatInBTUpS > bandUpper)
                        {
                            heatIndicator = $"{Symbols.SmallArrowUp}{ColorCode[Color.Orange]}";
                        }
                        else
                        {
                            heatIndicator = ColorCode[Color.White];
                        }

                        AddLabel(new ListLabel
                        {
                            FirstCol  = Viewer.Catalog.GetString("Boiler pressure"),
                            LastCol   = Viewer.Catalog.GetString(valuePart),
                            SymbolCol = heatIndicator,
                        });
                    }
                    else if (!normalTextMode && Viewer.Catalog.GetString(parts[0]).StartsWith(Viewer.Catalog.GetString("Fuel levels")))
                    {
                        AddLabel(new ListLabel
                        {
                            FirstCol = keyPart.EndsWith("?") || keyPart.EndsWith("!") ? Viewer.Catalog.GetString(keyPart.Substring(0, keyPart.Length - 3)) : Viewer.Catalog.GetString(keyPart),
                            LastCol  = valuePart.Length > 1 ? Viewer.Catalog.GetString(valuePart.Replace(" ", string.Empty)) : "",
                        });
                    }
                    else if (keyPart.StartsWith(Viewer.Catalog.GetString("Gear")))
                    {
                        string gearKey;
                        if (gearUp)
                        {
                            gearKey = Symbols.ArrowUp + ColorCode[Color.Yellow];
                            gearUp  = false;
                        }
                        else if (gearDown)
                        {
                            gearKey  = Symbols.ArrowDown + ColorCode[Color.Yellow];
                            gearDown = false;
                        }
                        else
                        {
                            gearKey = "";
                        }

                        AddLabel(new ListLabel
                        {
                            FirstCol   = Viewer.Catalog.GetString(keyPart),
                            LastCol    = valuePart != null ? Viewer.Catalog.GetString(valuePart) : "",
                            KeyPressed = gearKey,
                            SymbolCol  = gearKey,
                        });
                    }
                    else if (parts.Contains(Viewer.Catalog.GetString("Pantographs")))
                    {
                        string pantoKey;
                        if (pantographKey)
                        {
                            string arrow = parts[1].StartsWith(Viewer.Catalog.GetString("Up")) ? Symbols.ArrowUp : Symbols.ArrowDown;
                            pantoKey      = arrow + ColorCode[Color.Yellow];
                            pantographKey = false;
                        }
                        else
                        {
                            pantoKey = "";
                        }

                        AddLabel(new ListLabel
                        {
                            FirstCol   = Viewer.Catalog.GetString(keyPart),
                            LastCol    = valuePart != null ? Viewer.Catalog.GetString(valuePart) : "",
                            KeyPressed = pantoKey,
                            SymbolCol  = pantoKey,
                        });
                    }
                    else if (parts.Contains(Viewer.Catalog.GetString("Engine")))
                    {
                        AddLabel(new ListLabel
                        {
                            FirstCol = Viewer.Catalog.GetString(keyPart),
                            LastCol  = valuePart != null ? $"{Viewer.Catalog.GetString(valuePart)}{ColorCode[Color.White]}" : "",
                        });
                    }
                    else
                    {
                        AddLabel(new ListLabel
                        {
                            FirstCol = keyPart.EndsWith("?") || keyPart.EndsWith("!") ? Viewer.Catalog.GetString(keyPart.Substring(0, keyPart.Length - 3)) : Viewer.Catalog.GetString(keyPart),
                            LastCol  = valuePart != null ? Viewer.Catalog.GetString(valuePart) : "",
                        });
                    }
                }
            }

            AddSeparator();

            if (normalTextMode)
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("FPS"),
                    LastCol  = $"{Math.Floor(viewer.RenderProcess.FrameRate.SmoothedValue)}",
                });
            }

            // Messages
            // Autopilot
            bool autopilot = locomotive.Train.TrainType == TrainType.AiPlayerHosting;

            AddLabel(new ListLabel
            {
                FirstCol = Viewer.Catalog.GetString("Autopilot"),
                LastCol  = autopilot ? Viewer.Catalog.GetString("On") + ColorCode[Color.Yellow] : Viewer.Catalog.GetString("Off"),
            });

            // Grate limit
            if (locomotive is MSTSSteamLocomotive steamLocomotive1)
            {
                if (steamLocomotive1.IsGrateLimit && steamLocomotive1.GrateCombustionRateLBpFt2 > steamLocomotive1.GrateLimitLBpFt2)
                {
                    AddLabel(new ListLabel
                    {
                        FirstCol = Viewer.Catalog.GetString("Grate limit"),
                        LastCol  = Viewer.Catalog.GetString("Exceeded") + ColorCode[Color.OrangeRed],
                    });
                }
                else
                {
                    AddLabel(new ListLabel
                    {
                        FirstCol = Viewer.Catalog.GetString("Grate limit") + ColorCode[Color.Black],
                        LastCol  = Viewer.Catalog.GetString("Normal") + ColorCode[Color.Black],
                    });
                }
            }
            else
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Grate limit") + ColorCode[Color.Black],
                    LastCol  = Viewer.Catalog.GetString("-") + ColorCode[Color.Black],
                });
            }

            // Wheel
            if (train.IsWheelSlip)
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Wheel"),
                    LastCol  = Viewer.Catalog.GetString("slip") + ColorCode[Color.OrangeRed],
                });
            }
            else if (train.IsWheelSlipWarninq)
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Wheel"),
                    LastCol  = Viewer.Catalog.GetString("slip warning") + ColorCode[Color.Yellow],
                });
            }
            else if (train.IsBrakeSkid)
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Wheel"),
                    LastCol  = Viewer.Catalog.GetString("skid") + ColorCode[Color.OrangeRed],
                });
            }
            else
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Wheel") + ColorCode[Color.Black],
                    LastCol  = Viewer.Catalog.GetString("Normal") + ColorCode[Color.Black],
                });
            }

            // Doors
            var wagon = (MSTSWagon)locomotive;

            if (wagon.DoorLeftOpen || wagon.DoorRightOpen)
            {
                var  status  = new List <string>();
                bool flipped = locomotive.GetCabFlipped();
                if (wagon.DoorLeftOpen)
                {
                    status.Add(Viewer.Catalog.GetString(Viewer.Catalog.GetString(flipped ? "Right" : "Left")));
                }
                if (wagon.DoorRightOpen)
                {
                    status.Add(Viewer.Catalog.GetString(Viewer.Catalog.GetString(flipped ? "Left" : "Right")));
                }

                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Doors open"),
                    LastCol  = string.Join(" ", status) + ColorCode[locomotive.AbsSpeedMpS > 0.1f ? Color.OrangeRed : Color.Yellow],
                });
            }
            else
            {
                AddLabel(new ListLabel
                {
                    FirstCol = Viewer.Catalog.GetString("Doors open") + ColorCode[Color.Black],
                    LastCol  = Viewer.Catalog.GetString("Closed") + ColorCode[Color.Black],
                });
            }

            AddLabel(new ListLabel());
            return(labels);
        }
Exemplo n.º 7
0
 static void Postfix(TrainCar __instance)
 {
     Main.ReplaceInteriorTexture(__instance);
 }
Exemplo n.º 8
0
 public int AddTrainCar(TrainCar tc)
 {
     return(dal.AddTrainCar(tc));
 }
Exemplo n.º 9
0
        public static void ReplaceInteriorTexture(TrainCar trainCar)
        {
            var skin = FindTrainCarSkin(trainCar);

            if (skin == null)
            {
                return;
            }

            var cmps = trainCar.interior.GetComponentsInChildren <MeshRenderer>();

            foreach (var cmp in cmps)
            {
                if (!cmp.material)
                {
                    continue;
                }

                var diffuse   = GetMaterialTexture(cmp, "_MainTex");
                var normal    = GetMaterialTexture(cmp, "_BumpMap");
                var specular  = GetMaterialTexture(cmp, "_MetallicGlossMap");
                var emission  = GetMaterialTexture(cmp, "_EmissionMap");
                var occlusion = GetMaterialTexture(cmp, "_OcclusionMap");

                if (!defaultSkins.TryGetValue(trainCar.carType, out Skin defSkin))
                {
                    defSkin = null;
                }

                if (diffuse != null)
                {
                    if (skin.ContainsTexture(diffuse.name))
                    {
                        var skinTexture = skin.GetTexture(diffuse.name);

                        cmp.material.SetTexture("_MainTex", skinTexture.textureData);
                    }
                    else if ((defSkin != null) && defSkin.ContainsTexture(diffuse.name))
                    {
                        var skinTexture = defSkin.GetTexture(diffuse.name);
                        cmp.material.SetTexture("_MainTex", skinTexture.textureData);
                    }
                }

                if (normal != null)
                {
                    if (skin.ContainsTexture(normal.name))
                    {
                        var skinTexture = skin.GetTexture(normal.name);

                        cmp.material.SetTexture("_BumpMap", skinTexture.textureData);
                    }
                    else if ((defSkin != null) && defSkin.ContainsTexture(normal.name))
                    {
                        var skinTexture = defSkin.GetTexture(normal.name);
                        cmp.material.SetTexture("_BumpMap", skinTexture.textureData);
                    }
                }

                if (specular != null)
                {
                    if (skin.ContainsTexture(specular.name))
                    {
                        var skinTexture = skin.GetTexture(specular.name);

                        cmp.material.SetTexture("_MetallicGlossMap", skinTexture.textureData);

                        if (occlusion != null)
                        {
                            // occlusion is in green channel of specular map
                            cmp.material.SetTexture("_OcclusionMap", skinTexture.textureData);
                        }
                    }
                    else if ((defSkin != null) && defSkin.ContainsTexture(specular.name))
                    {
                        var skinTexture = defSkin.GetTexture(specular.name);
                        cmp.material.SetTexture("_MetallicGlossMap", skinTexture.textureData);

                        if (occlusion != null)
                        {
                            // occlusion is in green channel of specular map
                            cmp.material.SetTexture("_OcclusionMap", skinTexture.textureData);
                        }
                    }
                }

                if (emission != null)
                {
                    if (skin.ContainsTexture(emission.name))
                    {
                        var skinTexture = skin.GetTexture(emission.name);

                        cmp.material.SetTexture("_EmissionMap", skinTexture.textureData);
                    }
                    else if ((defSkin != null) && defSkin.ContainsTexture(emission.name))
                    {
                        var skinTexture = defSkin.GetTexture(emission.name);
                        cmp.material.SetTexture("_EmissionMap", skinTexture.textureData);
                    }
                }
            }
        }
Exemplo n.º 10
0
 static void Postfix(TrainCar __result)
 {
     Main.ReplaceTexture(__result);
 }
Exemplo n.º 11
0
        public static Skin FindTrainCarSkin(TrainCar trainCar, string findSkinName = "")
        {
            if (!skinGroups.ContainsKey(trainCar.carType))
            {
                return(null);
            }

            var skinGroup = skinGroups[trainCar.carType];

            if (skinGroup.skins.Count == 0)
            {
                return(null);
            }

            Skin skin;

            if (trainCarState.ContainsKey(trainCar.logicCar.carGuid))
            {
                string skinName = trainCarState[trainCar.logicCar.carGuid];

                if (skinName == "__default")
                {
                    return(null);
                }

                skin = skinGroup.GetSkin(skinName);

                if (skin == null)
                {
                    return(null);
                }
            }
            else
            {
                string selectedSkin = Main.selectedSkin[trainCar.carType];

                if (findSkinName != "")
                {
                    selectedSkin = findSkinName;
                }

                if (selectedSkin == "Random" && skinGroup.skins.Count > 0)
                {
                    var range = UnityEngine.Random.Range(0, skinGroup.skins.Count);

                    // default skin if it hits out of index
                    if (range == skinGroup.skins.Count)
                    {
                        SetCarState(trainCar.logicCar.carGuid, "__default");

                        return(null);
                    }

                    skin = skinGroup.skins[range];

                    SetCarState(trainCar.logicCar.carGuid, skin.name);
                }
                else if (selectedSkin == "Default")
                {
                    SetCarState(trainCar.logicCar.carGuid, "__default");

                    return(null);
                }
                else
                {
                    skin = skinGroup.GetSkin(selectedSkin);

                    if (skin != null)
                    {
                        SetCarState(trainCar.logicCar.carGuid, skin.name);
                    }
                }
            }

            return(skin);
        }
Exemplo n.º 12
0
        public static void DrawModUI()
        {
            if (!isEnabled)
            {
                showDropdown = false;
                return;
            }

            Cursor.lockState = CursorLockMode.None;
            Cursor.visible   = true;

            GameObject   carToSpawn = SingletonBehaviour <CarSpawner> .Instance.carToSpawn;
            TrainCar     trainCar   = carToSpawn.GetComponent <TrainCar>();
            TrainCarType carType    = trainCar.carType;

            SkinGroup skinGroup  = Main.skinGroups[carType];
            string    selectSkin = Main.selectedSkin[carType];

            float menuHeight = 60f;

            float menuWidth   = 270f;
            float buttonWidth = 240f;
            bool  isMaxHeight = false;
            float maxHeight   = Screen.height - 200f;

            if (showDropdown)
            {
                float totalItemHeight = skinGroup.skins.Count * 23f;

                if (totalItemHeight > maxHeight)
                {
                    totalItemHeight = maxHeight;
                    isMaxHeight     = true;
                }

                menuHeight += totalItemHeight + 46f;
            }

            if (isMaxHeight)
            {
                buttonWidth -= 20f;
            }

            GUI.skin = DVGUI.skin;
            GUI.skin.label.fontSize  = 11;
            GUI.skin.button.fontSize = 10;
            GUI.color = new Color32(0, 0, 0, 200);
            GUI.Box(new Rect(20f, 20f, menuWidth, menuHeight), "");
            GUILayout.BeginArea(new Rect(30f, 20f, menuWidth, menuHeight));
            GUI.color = Color.yellow;
            GUILayout.Label("Skin Manager Menu :: " + carToSpawn.name);
            GUI.color = Color.white;
            GUILayout.Space(5f);

            if (showDropdown)
            {
                if (GUILayout.Button("=== " + selectSkin + " ===", GUILayout.Width(240f)))
                {
                    showDropdown = false;
                }

                if (isMaxHeight)
                {
                    scrollViewVector = GUILayout.BeginScrollView(scrollViewVector, GUILayout.Width(245f), GUILayout.Height(menuHeight - 55f));
                }

                if (GUILayout.Button("Random", GUILayout.Width(buttonWidth)))
                {
                    showDropdown = false;
                    Main.selectedSkin[carType] = "Random";
                }

                if (GUILayout.Button("Default", GUILayout.Width(buttonWidth)))
                {
                    showDropdown = false;
                    Main.selectedSkin[carType] = "Default";
                }

                foreach (Skin skin in skinGroup.skins)
                {
                    if (GUILayout.Button(skin.name, GUILayout.Width(buttonWidth)))
                    {
                        showDropdown = false;
                        Main.selectedSkin[carType] = skin.name;
                    }
                }

                if (isMaxHeight)
                {
                    GUILayout.EndScrollView();
                }
            }
            else
            {
                if (GUILayout.Button("=== " + selectSkin + " ===", GUILayout.Width(240f)))
                {
                    showDropdown = true;
                }
            }

            GUILayout.EndArea();
        }
Exemplo n.º 13
0
        protected static void PropagateBrakeLinePressures(float elapsedClockSeconds, TrainCar trainCar, bool twoPipes)
        {
            var   train = trainCar.Train;
            var   lead  = trainCar as MSTSLocomotive;
            var   brakePipeTimeFactorS = lead == null ? 0.003f : lead.BrakePipeTimeFactorS;
            int   nSteps = (int)(elapsedClockSeconds * 2 / brakePipeTimeFactorS + 1);
            float dt     = elapsedClockSeconds / nSteps;

            // Propagate brake line (1) data
            if (lead != null && lead.BrakePipeChargingRatePSIpS >= 1000)
            {   // pressure gradient disabled
                if (lead.BrakeSystem.BrakeLine1PressurePSI < train.BrakeLine1PressurePSIorInHg)
                {
                    var dp1 = train.BrakeLine1PressurePSIorInHg - lead.BrakeSystem.BrakeLine1PressurePSI;
                    lead.MainResPressurePSI -= dp1 * lead.BrakeSystem.BrakePipeVolumeM3 / lead.MainResVolumeM3;
                }
                foreach (TrainCar car in train.Cars)
                {
                    if (car.BrakeSystem.BrakeLine1PressurePSI >= 0)
                    {
                        car.BrakeSystem.BrakeLine1PressurePSI = train.BrakeLine1PressurePSIorInHg;
                    }
                }
            }
            else
            {   // approximate pressure gradient in line1
                float serviceTimeFactor = lead != null ? lead.TrainBrakeController != null && lead.TrainBrakeController.EmergencyBraking ? lead.BrakeEmergencyTimeFactorS : lead.BrakeServiceTimeFactorS : 0;
                for (int i = 0; i < nSteps; i++)
                {
//                    Trace.TraceWarning("lead.BrakeLine1PressurePSI {0} car1.BrakeLine1PressurePSI {1} car2.BrakeLine1PressurePSI {2} lead.MainResPressurePSI {3} car1.AuxResPressure {4} i {5}",
//                        lead.BrakeSystem.BrakeLine1PressurePSI, train.Cars[1].BrakeSystem.BrakeLine1PressurePSI, train.Cars[2].BrakeSystem.BrakeLine1PressurePSI,  lead.MainResPressurePSI, (train.Cars[1].BrakeSystem as AirSinglePipe).AuxResPressurePSI, i);
                    if (lead != null)
                    {
                        if (lead.BrakeSystem.BrakeLine1PressurePSI < train.BrakeLine1PressurePSIorInHg)
                        {
                            float dp = dt * lead.BrakePipeChargingRatePSIpS;
                            if (lead.BrakeSystem.BrakeLine1PressurePSI + dp > train.BrakeLine1PressurePSIorInHg)
                            {
                                dp = train.BrakeLine1PressurePSIorInHg - lead.BrakeSystem.BrakeLine1PressurePSI;
                            }
                            if (lead.BrakeSystem.BrakeLine1PressurePSI + dp > lead.MainResPressurePSI)
                            {
                                dp = lead.MainResPressurePSI - lead.BrakeSystem.BrakeLine1PressurePSI;
                            }
                            if (dp < 0)
                            {
                                dp = 0;
                            }
                            lead.BrakeSystem.BrakeLine1PressurePSI += dp;
                            lead.MainResPressurePSI -= dp * lead.BrakeSystem.BrakePipeVolumeM3 / lead.MainResVolumeM3;
                        }
                        else if (lead.BrakeSystem.BrakeLine1PressurePSI > train.BrakeLine1PressurePSIorInHg)
                        {
                            lead.BrakeSystem.BrakeLine1PressurePSI *= (1 - dt / serviceTimeFactor);
                        }
                    }
                    TrainCar car0 = train.Cars[0];
                    float    p0   = car0.BrakeSystem.BrakeLine1PressurePSI;
                    float    brakePipeVolumeM30 = car0.BrakeSystem.BrakePipeVolumeM3;
                    foreach (TrainCar car in train.Cars)
                    {
                        float p1 = car.BrakeSystem.BrakeLine1PressurePSI;
                        if (car == train.Cars[0] || car.BrakeSystem.FrontBrakeHoseConnected && car.BrakeSystem.AngleCockAOpen && car0.BrakeSystem.AngleCockBOpen)
                        {
                            float dp = Math.Min(dt * (p1 - p0) / brakePipeTimeFactorS * 2, p1 - p0);
                            car.BrakeSystem.BrakeLine1PressurePSI  -= dp * brakePipeVolumeM30 / (brakePipeVolumeM30 + car.BrakeSystem.BrakePipeVolumeM3);
                            car0.BrakeSystem.BrakeLine1PressurePSI += dp * car.BrakeSystem.BrakePipeVolumeM3 / (brakePipeVolumeM30 + car.BrakeSystem.BrakePipeVolumeM3);
                        }
                        if (!car.BrakeSystem.FrontBrakeHoseConnected)
                        {
                            if (car.BrakeSystem.AngleCockAOpen)
                            {
                                car.BrakeSystem.BrakeLine1PressurePSI -= dt * p1 / brakePipeTimeFactorS;
                            }
                            if (car0.BrakeSystem.AngleCockBOpen && car != car0)
                            {
                                car0.BrakeSystem.BrakeLine1PressurePSI -= dt * p0 / brakePipeTimeFactorS;
                            }
                        }
                        if (car == train.Cars[train.Cars.Count - 1] && car.BrakeSystem.AngleCockBOpen)
                        {
                            car.BrakeSystem.BrakeLine1PressurePSI -= dt * p1 / brakePipeTimeFactorS;
                        }
                        p0   = car.BrakeSystem.BrakeLine1PressurePSI;
                        car0 = car;
                        brakePipeVolumeM30 = car0.BrakeSystem.BrakePipeVolumeM3;
                    }
                }
            }

            // Propagate main reservoir pipe (2) and engine brake pipe (3) data
            int first = -1;
            int last  = -1;

            train.FindLeadLocomotives(ref first, ref last);
            float sumpv = 0;
            float sumv  = 0;
            int   continuousFromInclusive = 0;
            int   continuousToExclusive   = train.Cars.Count;

            for (int i = 0; i < train.Cars.Count; i++)
            {
                BrakeSystem brakeSystem = train.Cars[i].BrakeSystem;
                if (i < first && (!train.Cars[i + 1].BrakeSystem.FrontBrakeHoseConnected || !brakeSystem.AngleCockBOpen || !train.Cars[i + 1].BrakeSystem.AngleCockAOpen || !train.Cars[i].BrakeSystem.TwoPipes))
                {
                    if (continuousFromInclusive < i + 1)
                    {
                        sumv = sumpv = 0;
                        continuousFromInclusive = i + 1;
                    }
                    continue;
                }
                if (i > last && i > 0 && (!brakeSystem.FrontBrakeHoseConnected || !brakeSystem.AngleCockAOpen || !train.Cars[i - 1].BrakeSystem.AngleCockBOpen || !train.Cars[i].BrakeSystem.TwoPipes))
                {
                    if (continuousToExclusive > i)
                    {
                        continuousToExclusive = i;
                    }
                    continue;
                }

                // Collect main reservoir pipe (2) data
                if (first <= i && i <= last || twoPipes && continuousFromInclusive <= i && i < continuousToExclusive)
                {
                    sumv  += brakeSystem.BrakePipeVolumeM3;
                    sumpv += brakeSystem.BrakePipeVolumeM3 * brakeSystem.BrakeLine2PressurePSI;
                    var eng = train.Cars[i] as MSTSLocomotive;
                    if (eng != null)
                    {
                        sumv  += eng.MainResVolumeM3;
                        sumpv += eng.MainResVolumeM3 * eng.MainResPressurePSI;
                    }
                }

                // Collect and propagate engine brake pipe (3) data
                if (i < first || i > last)
                {
                    brakeSystem.BrakeLine3PressurePSI = 0;
                }
                else
                {
                    if (lead != null)
                    {
                        float p = brakeSystem.BrakeLine3PressurePSI;
                        if (p > 1000)
                        {
                            p -= 1000;
                        }
                        var prevState = lead.EngineBrakeState;
                        if (p < train.BrakeLine3PressurePSI && p < lead.MainResPressurePSI)
                        {
                            float dp = elapsedClockSeconds * lead.EngineBrakeApplyRatePSIpS / (last - first + 1);
                            if (p + dp > train.BrakeLine3PressurePSI)
                            {
                                dp = train.BrakeLine3PressurePSI - p;
                            }
                            p += dp;
                            lead.EngineBrakeState = ValveState.Apply;
                            sumpv -= dp * brakeSystem.GetCylVolumeM3() / lead.MainResVolumeM3;
                        }
                        else if (p > train.BrakeLine3PressurePSI)
                        {
                            float dp = elapsedClockSeconds * lead.EngineBrakeReleaseRatePSIpS / (last - first + 1);
                            if (p - dp < train.BrakeLine3PressurePSI)
                            {
                                dp = p - train.BrakeLine3PressurePSI;
                            }
                            p -= dp;
                            lead.EngineBrakeState = ValveState.Release;
                        }
                        else
                        {
                            lead.EngineBrakeState = ValveState.Lap;
                        }
                        if (lead.EngineBrakeState != prevState)
                        {
                            switch (lead.EngineBrakeState)
                            {
                            case ValveState.Release: lead.SignalEvent(Event.EngineBrakePressureIncrease); break;

                            case ValveState.Apply: lead.SignalEvent(Event.EngineBrakePressureDecrease); break;

                            case ValveState.Lap: lead.SignalEvent(Event.EngineBrakePressureStoppedChanging); break;
                            }
                        }
                        if (lead.BailOff || (lead.DynamicBrakeAutoBailOff && train.MUDynamicBrakePercent > 0))
                        {
                            p += 1000;
                        }
                        brakeSystem.BrakeLine3PressurePSI = p;
                    }
                }
            }
            if (sumv > 0)
            {
                sumpv /= sumv;
            }

            if (!train.Cars[continuousFromInclusive].BrakeSystem.FrontBrakeHoseConnected && train.Cars[continuousFromInclusive].BrakeSystem.AngleCockAOpen ||
                (continuousToExclusive == train.Cars.Count || !train.Cars[continuousToExclusive].BrakeSystem.FrontBrakeHoseConnected) && train.Cars[continuousToExclusive - 1].BrakeSystem.AngleCockBOpen)
            {
                sumpv = 0;
            }

            // Propagate main reservoir pipe (2) data
            train.BrakeLine2PressurePSI = sumpv;
            for (int i = 0; i < train.Cars.Count; i++)
            {
                if (first <= i && i <= last || twoPipes && continuousFromInclusive <= i && i < continuousToExclusive)
                {
                    train.Cars[i].BrakeSystem.BrakeLine2PressurePSI = sumpv;
                    if (sumpv != 0 && train.Cars[i] is MSTSLocomotive)
                    {
                        (train.Cars[i] as MSTSLocomotive).MainResPressurePSI = sumpv;
                    }
                }
                else
                {
                    train.Cars[i].BrakeSystem.BrakeLine2PressurePSI = train.Cars[i] is MSTSLocomotive ? (train.Cars[i] as MSTSLocomotive).MainResPressurePSI : 0;
                }
            }
        }
Exemplo n.º 14
0
 public static TrainCar CarAtEnd(TrainCar loco, bool atFront) => atFront?FirstCar(loco) : LastCar(loco);
Exemplo n.º 15
0
 public abstract bool TryGetFormatted(TrainCar car, out string s);
Exemplo n.º 16
0
        public void Spawn(TrainCar trainCar)
        {
            #region Spawn Car

            var NewCar = Object.Instantiate(CarPrefab, trainCar.transform.root, true);
            NewCar.SetActive(true);
            NewCar.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
            NewCar.transform.localRotation = Quaternion.identity;

            //Deactivate underlying train car model
            switch (TrainCarType)
            {
            case TrainCarType.NotSet:
                throw new ArgumentOutOfRangeException();

            case TrainCarType.LocoShunter:
                Debug.LogError("Not supported.");
                break;

            case TrainCarType.LocoSteamHeavy:
                Debug.LogError("Not supported.");
                break;

            case TrainCarType.Tender:
                Debug.LogError("Not supported.");
                break;

            case TrainCarType.LocoSteamHeavyBlue:
                Debug.LogError("Not supported.");
                break;

            case TrainCarType.TenderBlue:
                Debug.LogError("Not supported.");
                break;

            case TrainCarType.LocoRailbus:
                Debug.LogError("Not supported.");
                break;

            case TrainCarType.LocoDiesel:
                Debug.LogError("Not supported.");
                break;

            case TrainCarType.FlatbedEmpty:
            case TrainCarType.FlatbedStakes:
            case TrainCarType.FlatbedMilitary:
                trainCar.transform.Find("car_flatcar_lod").gameObject.SetActive(false);
                break;

            case TrainCarType.AutorackRed:
            case TrainCarType.AutorackBlue:
            case TrainCarType.AutorackGreen:
            case TrainCarType.AutorackYellow:
                trainCar.transform.Find("car_autorack_lod").gameObject.SetActive(false);
                break;

            case TrainCarType.TankOrange:
            case TrainCarType.TankWhite:
            case TrainCarType.TankYellow:
            case TrainCarType.TankBlue:
            case TrainCarType.TankChrome:
            case TrainCarType.TankBlack:
                trainCar.transform.Find("car_tanker_lod").gameObject.SetActive(false);
                break;

            case TrainCarType.BoxcarBrown:
            case TrainCarType.BoxcarGreen:
            case TrainCarType.BoxcarPink:
            case TrainCarType.BoxcarRed:
                trainCar.transform.Find("car_boxcar_lod").gameObject.SetActive(false);
                break;

            case TrainCarType.BoxcarMilitary:
                trainCar.transform.Find("CarMilitaryBoxcar_lod").gameObject.SetActive(false);
                break;

            case TrainCarType.RefrigeratorWhite:
                trainCar.transform.Find("car_refrigerated_boxcar_lod").gameObject.SetActive(false);
                break;

            case TrainCarType.HopperBrown:
            case TrainCarType.HopperTeal:
            case TrainCarType.HopperYellow:
                trainCar.transform.Find("car_hopper_lod").gameObject.SetActive(false);
                break;

            case TrainCarType.PassengerRed:
            case TrainCarType.PassengerGreen:
            case TrainCarType.PassengerBlue:
                trainCar.transform.Find("car_passenger_lod").gameObject.SetActive(false);
                break;

            case TrainCarType.HandCar:
                Debug.LogError("Not supported.");
                break;

            case TrainCarType.NuclearFlask:
                trainCar.transform.Find("CarNuclearFlask").gameObject.SetActive(false);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            #endregion

            #region Bogies

            var bogey1 = trainCar.Bogies[0];
            var bogey2 = trainCar.Bogies[1];

            if (FrontBogiePosition != Vector3.zero)
            {
                bogey1.gameObject.SetActive(false);
                bogey1.transform.localPosition = FrontBogiePosition;
                bogey1.gameObject.SetActive(true);
            }

            if (RearBogiePosition != Vector3.zero)
            {
                bogey2.gameObject.SetActive(false);
                bogey2.transform.localPosition = RearBogiePosition;
                bogey2.gameObject.SetActive(true);
            }

            #endregion

            #region Couplers

            var frontCoupler = trainCar.frontCoupler;
            var rearCoupler  = trainCar.rearCoupler;

            if (FrontCouplerPosition != Vector3.zero)
            {
                frontCoupler.transform.localPosition = FrontCouplerPosition;
            }

            if (RearCouplerPosition != Vector3.zero)
            {
                rearCoupler.transform.localPosition = RearCouplerPosition;
            }

            #endregion

            #region Chains

            var frontChain = frontCoupler.visualCoupler.chain;
            var rearChain  = rearCoupler.visualCoupler.chain;

            if (FrontChainPosition != Vector3.zero)
            {
                frontChain.transform.localPosition = FrontChainPosition;
            }

            if (RearChainPosition != Vector3.zero)
            {
                rearChain.transform.localPosition = RearChainPosition;
            }

            #endregion

            #region Hoses

            var frontHose = frontCoupler.visualCoupler.hoses;
            var rearHose  = rearCoupler.visualCoupler.hoses;

            if (FrontHosePosition != Vector3.zero)
            {
                frontHose.localPosition = FrontHosePosition;
            }

            if (RearHosePosition != Vector3.zero)
            {
                rearHose.localPosition = RearHosePosition;
            }

            #endregion

            #region Buffers

            if (FrontBufferPosition != Vector3.zero)
            {
                frontCoupler.visualCoupler.transform.localPosition = FrontBufferPosition;
            }

            if (RearBufferPosition != Vector3.zero)
            {
                rearCoupler.visualCoupler.transform.localPosition = RearBufferPosition;
            }

            #endregion

            #region Name Plates

            var plate1 = trainCar.transform.Find("[car plate anchor1]");
            var plate2 = trainCar.transform.Find("[car plate anchor2]");

            if (SidePlate1Position != Vector3.zero && plate1)
            {
                plate1.localPosition = SidePlate1Position;
            }

            if (SidePlate2Position != Vector3.zero && plate2)
            {
                plate2.localPosition = SidePlate2Position;
            }

            #endregion
        }
Exemplo n.º 17
0
 public abstract bool TryGetValue(TrainCar car, out T v);
Exemplo n.º 18
0
 private static void Postfix(TrainCar __instance)
 {
     DoCreate(__instance);
 }
Exemplo n.º 19
0
 static bool?IsFrontCoupler(TrainCar car, TrainCar attached) =>
 car.frontCoupler.springyCJ && car.frontCoupler.coupledTo.train == attached ? (bool?)true
     : car.rearCoupler.springyCJ && car.rearCoupler.coupledTo.train == attached ? (bool?)false
     : null;
Exemplo n.º 20
0
 public TrainCarTouched(TrainCar car)
 {
     base.Car = car;
 }
Exemplo n.º 21
0
 public EPBrakeSystem(TrainCar car)
     : base(car)
 {
     DebugType = "EP";
 }
Exemplo n.º 22
0
 public TrainCarPassed(TrainCar car)
 {
     base.Car = car;
 }
Exemplo n.º 23
0
 protected TrainCarEvent(TrainCar car)
 {
     Car = car;
 }
Exemplo n.º 24
0
 public ManualBraking(TrainCar car)
 {
     Car = car;
 }
Exemplo n.º 25
0
 static void Postfix(TrainCar car, LocoAudioShunter __instance)
 {
     __instance.gameObject.AddComponent <LocoAudioShunterCustom>();
 }
Exemplo n.º 26
0
        private void DrawCar(Graphics g, Train train, TrainCar car, TrainCar locoCar, float margin, int minTrainPx, bool drawEveryCar)
        {
            if (drawEveryCar == false)
            {
                // Skip the intermediate cars
                if (car != train.Cars.First() && car != train.Cars.Last())
                {
                    return;
                }
            }

            var t        = new Traveller(train.RearTDBTraveller);
            var worldPos = car.WorldPosition;
            var dist     = t.DistanceTo(worldPos.WorldLocation.TileX, worldPos.WorldLocation.TileZ, worldPos.WorldLocation.Location.X, worldPos.WorldLocation.Location.Y, worldPos.WorldLocation.Location.Z);

            if (dist > -1)
            {
                var   scaledTrain = new PointF();
                float x;
                float y;
                if (drawEveryCar)
                {
                    t.Move(dist + car.CarLengthM / 2); // Move along from centre of car to front of car
                    x = (t.TileX * 2048 + t.Location.X - F.subX) * F.xScale;
                    y = F.pbCanvas.Height - (t.TileZ * 2048 + t.Location.Z - F.subY) * F.yScale;

                    // If car out of view then skip it.
                    if (x < -margin || y < -margin)
                    {
                        return;
                    }

                    t.Move(-car.CarLengthM + (1 / F.xScale)); // Move from front of car to rear less 1 pixel to create a visible gap
                    scaledTrain.X = x; scaledTrain.Y = y;
                }
                else    // Draw the train as 2 boxes of fixed size
                {
                    F.trainPen.Width = minTrainPx / 2;
                    if (car == train.Cars.First())
                    {
                        // Draw first half a train back from the front of the first car as abox
                        t.Move(dist + car.CarLengthM / 2);
                        x = (t.TileX * 2048 + t.Location.X - F.subX) * F.xScale;
                        y = F.pbCanvas.Height - (t.TileZ * 2048 + t.Location.Z - F.subY) * F.yScale;

                        // If car out of view then skip it.
                        if (x < -margin || y < -margin)
                        {
                            return;
                        }

                        t.Move(-(minTrainPx - 2) / F.xScale / 2); // Move from front of car to rear less 1 pixel to create a visible gap
                    }
                    else // car == t.Cars.Last()
                    {
                        // Draw half a train back from the rear of the first box
                        worldPos = train.Cars.First().WorldPosition;
                        dist     = t.DistanceTo(worldPos.WorldLocation.TileX, worldPos.WorldLocation.TileZ, worldPos.WorldLocation.Location.X, worldPos.WorldLocation.Location.Y, worldPos.WorldLocation.Location.Z);
                        t.Move(dist + train.Cars.First().CarLengthM / 2 - minTrainPx / F.xScale / 2);
                        x = (t.TileX * 2048 + t.Location.X - F.subX) * F.xScale;
                        y = F.pbCanvas.Height - (t.TileZ * 2048 + t.Location.Z - F.subY) * F.yScale;
                        if (x < -margin || y < -margin)
                        {
                            return;
                        }
                        t.Move(-minTrainPx / F.xScale / 2);
                    }
                    scaledTrain.X = x; scaledTrain.Y = y;
                }
                x = (t.TileX * 2048 + t.Location.X - F.subX) * F.xScale;
                y = F.pbCanvas.Height - (t.TileZ * 2048 + t.Location.Z - F.subY) * F.yScale;

                // If car out of view then skip it.
                if (x < -margin || y < -margin)
                {
                    return;
                }

                SetTrainColor(train, locoCar, car);
                g.DrawLine(F.trainPen, new PointF(x, y), scaledTrain);
            }
        }
Exemplo n.º 27
0
 public override void Init(TrainCar car, LocoLightData[] exterior, LocoLightData[] interior)
 {
     base.Init(car, exterior, interior);
     Direction = 0f;
 }
Exemplo n.º 28
0
 public OdoMeter(TrainCar car)
 {
     CurrentValue = () => (float)car.DistanceM;
 }
Exemplo n.º 29
0
        public void AddPlayers(MSGPlayer player, OnlinePlayer p)
        {
            if (Players.ContainsKey(player.user))
            {
                return;
            }
            if (MPManager.Client != null && player.user == MPManager.Client.UserName)
            {
                return;                                                                       //do not add self//WARNING: may need to worry about train number here
            }
            if (p == null)
            {
                p = new OnlinePlayer(null, null);
            }
            p.url = player.url;
            p.LeadingLocomotiveID = player.leadingID;
            p.con  = MPManager.Simulator.BasePath + "\\TRAINS\\CONSISTS\\" + player.con;
            p.path = MPManager.Simulator.RoutePath + "\\PATHS\\" + player.path;
            Train train = new Train(MPManager.Simulator);

            train.TrainType = Train.TRAINTYPE.REMOTE;
            if (MPManager.IsServer()) //server needs to worry about correct train number
            {
            }
            else
            {
                train.Number = player.num;
            }
            if (player.con.Contains("tilted"))
            {
                train.IsTilting = true;
            }
            int direction = player.dir;

            train.travelled        = player.Travelled;
            train.TrainMaxSpeedMpS = player.trainmaxspeed;

            if (MPManager.IsServer())
            {
                try
                {
#if ACTIVITY_EDITOR
                    AIPath aiPath = new AIPath(MPManager.Simulator.TDB, MPManager.Simulator.TSectionDat, p.path, MPManager.Simulator.TimetableMode, MPManager.Simulator.orRouteConfig);
#else
                    AIPath aiPath = new AIPath(MPManager.Simulator.TDB, MPManager.Simulator.TSectionDat, p.path);
#endif
                }
                catch (Exception) { MPManager.BroadCast((new MSGMessage(player.user, "Warning", "Server does not have path file provided, signals may always be red for you.")).ToString()); }
            }

            try
            {
                train.RearTDBTraveller = new Traveller(MPManager.Simulator.TSectionDat, MPManager.Simulator.TDB.TrackDB.TrackNodes, player.TileX, player.TileZ, player.X, player.Z, direction == 1 ? Traveller.TravellerDirection.Forward : Traveller.TravellerDirection.Backward);
            }
            catch (Exception e)
            {
                if (MPManager.IsServer())
                {
                    MPManager.BroadCast((new MSGMessage(player.user, "Error", "MultiPlayer Error:" + e.Message)).ToString());
                }
                else
                {
                    throw new Exception();
                }
            }
            for (var i = 0; i < player.cars.Length; i++)// cars.Length-1; i >= 0; i--) {
            {
                string   wagonFilePath = MPManager.Simulator.BasePath + @"\trains\trainset\" + player.cars[i];
                TrainCar car           = null;
                try
                {
                    car            = RollingStock.Load(MPManager.Simulator, wagonFilePath);
                    car.CarLengthM = player.lengths[i] / 100.0f;
                }
                catch (Exception error)
                {
                    System.Console.WriteLine(error.Message);
                    car = MPManager.Instance().SubCar(wagonFilePath, player.lengths[i]);
                }
                if (car == null)
                {
                    continue;
                }
                bool flip = true;
                if (player.flipped[i] == 0)
                {
                    flip = false;
                }
                car.Flipped = flip;
                car.CarID   = player.ids[i];
                train.Cars.Add(car);
                car.Train = train;
                MSTSWagon w = (MSTSWagon)car;
                if (w != null)
                {
                    w.SignalEvent((player.pantofirst == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 1);
                    w.SignalEvent((player.pantosecond == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 2);
                    w.SignalEvent((player.pantothird == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 3);
                    w.SignalEvent((player.pantofourth == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 4);
                }
            }// for each rail car

            if (train.Cars.Count == 0)
            {
                throw (new Exception("The train of player " + player.user + " is empty from "));
            }

            p.Username        = player.user;
            train.ControlMode = Train.TRAIN_CONTROL.EXPLORER;
            train.CheckFreight();
            train.InitializeBrakes();
            bool canPlace = true;
            Train.TCSubpathRoute tempRoute = train.CalculateInitialTrainPosition(ref canPlace);
            if (tempRoute.Count == 0 || !canPlace)
            {
                MPManager.BroadCast((new MSGMessage(p.Username, "Error", "Cannot be placed into the game")).ToString());//server will broadcast this error
                throw new InvalidDataException("Remote train original position not clear");
            }

            train.SetInitialTrainRoute(tempRoute);
            train.CalculatePositionOfCars();
            train.ResetInitialTrainRoute(tempRoute);

            train.CalculatePositionOfCars();
            train.AITrainBrakePercent = 100;

            //if (MPManager.Instance().AllowedManualSwitch) train.InitializeSignals(false);
            for (int iCar = 0; iCar < train.Cars.Count; iCar++)
            {
                var car = train.Cars[iCar];
                if (car.CarID == p.LeadingLocomotiveID)
                {
                    train.LeadLocomotive = car;
                    (train.LeadLocomotive as MSTSLocomotive).Headlight    = player.headlight;
                    (train.LeadLocomotive as MSTSLocomotive).UsingRearCab = player.frontorrearcab == "R" ? true : false;
                }
                if (car is MSTSLocomotive && MPManager.IsServer())
                {
                    MPManager.Instance().AddOrRemoveLocomotive(player.user, train.Number, iCar, true);
                }
            }
            if (train.LeadLocomotive == null)
            {
                train.LeadNextLocomotive();
                if (train.LeadLocomotive != null)
                {
                    p.LeadingLocomotiveID = train.LeadLocomotive.CarID;
                }
                else
                {
                    p.LeadingLocomotiveID = "NA";
                }
            }

            if (train.LeadLocomotive != null)
            {
                train.Name = train.GetTrainName(train.LeadLocomotive.CarID);
            }
            else if (train.Cars != null && train.Cars.Count > 0)
            {
                train.Name = train.GetTrainName(train.Cars[0].CarID);
            }
            else if (player != null && player.user != null)
            {
                train.Name = player.user;
            }

            if (MPManager.IsServer())
            {
                train.InitializeSignals(false);
            }
            p.Train = train;

            Players.Add(player.user, p);
            MPManager.Instance().AddOrRemoveTrain(train, true);
        }
Exemplo n.º 30
0
 public StraightVacuumSinglePipe(TrainCar car)
     : base(car)
 {
 }
Exemplo n.º 31
0
 public SingleTransferPipe(TrainCar car)
     : base(car)
 {
     DebugType = "-";
 }
Exemplo n.º 32
0
 public static TrainCar FirstCar(TrainCar loco) => IsFacingFrontOfTrainset(loco) ? loco.trainset.firstCar : loco.trainset.lastCar;
Exemplo n.º 33
0
 protected TrainCarEvent(TrainCar car)
 {
     Car = car;
 }