Compare commits

...

32 Commits

Author SHA1 Message Date
80f0847587 reverting updated context menu visualizations, and allowing the even spacing of items vs quadrant concept. Pesky double circle context menu borders still remain, but I'm working on it. 2025-03-02 12:43:08 -06:00
7552422b6e disabling context menu dividers and expanding the context menu radius to 200f to help spread things out. 2025-02-22 23:43:00 -06:00
58dc7efac0 adjusting CarIdsInRect -> CarIdsInRadius 2025-02-16 09:41:58 -06:00
7ebd14db2a adjusting railroader usage of namespace Model.OpsNew -> Model.Ops and some adjustments to the version files. 2024-12-24 22:11:22 -06:00
ca0e78b971 hotfix for car inspector rebuild 2024-08-03 00:55:43 -05:00
9f210b0b8a increasing version number. 2024-08-01 15:55:29 -05:00
840f35cf62 Merge pull request #38 from rmroc451/37-passenger-stops-not-filling-crew-hours-on-cabeese
#37 refactored caboose crew hours load refill logic, condensing and a…
2024-07-28 12:11:16 -05:00
786db49b68 #37 refactored caboose crew hours load refill logic, condensing and also allowing passenger stops to work as they were expected to. 2024-07-28 08:13:21 -05:00
108900b026 Merge pull request #36 from rmroc451/33-double-click-to-follow-car
#33 double primary click any car/loco to follow
2024-07-27 22:33:18 -05:00
9e8c38e6f4 Merge pull request #35 from rmroc451/26-caboose-auto-heal-hotbox-when-fully-oiled
#26 auto heal hotbox when found if caboose use is enabled and caboose…
2024-07-27 22:32:49 -05:00
89f2490f14 Merge pull request #34 from rmroc451/32-buttons-dont-adjust-when-decoupling-as-expected
#32 swap from integration set that was giving inconsistent results, a…
2024-07-27 22:32:20 -05:00
fbd08b007c #33 double primary click any car/loco to follow 2024-07-27 22:31:33 -05:00
27d3432cbf #26 auto heal hotbox when found if caboose use is enabled and caboose is present in consist. 2024-07-27 22:30:40 -05:00
cf1d5e32e5 #32 swap from integration set that was giving inconsistent results, and adding in a panel.reubuildOnInterval when an observed value changes. 2024-07-27 22:25:23 -05:00
92317b29b2 Merge pull request #31 from rmroc451/v1.0.0-prep
Closes #27 fix issue with last car end gear issue detection
Closes #28 add hotbox icon to tag update info
Closes #25 adding follow to car context menu
Closes #24 adding consist info to non motive power cars, that have a caboose when Caboose Use mod setting is enabled.
Closes #29, #30 Allow caboose setting to require that a caboose is present in the consist to use the AI Engineer's AutoOiler & - AutoHotboxSpotter.
2024-07-26 12:40:38 -05:00
1f48bf04aa increment version number 2024-07-26 12:35:52 -05:00
5774c7f04c #29 #30 Allow caboose setting to require that a caboose is present in the consist to use the AI Engineer's AutoOiler & AutoHotboxSpotter. 2024-07-26 12:25:03 -05:00
5eed492b47 #24 adding consist info to non motive power cars, that have a caboose, when Caboose Use mod setting is enabled. 2024-07-26 12:20:52 -05:00
d4d18d8c92 #25 adding follow to car context menu 2024-07-26 10:17:09 -05:00
d7e35828b8 #28 add hotbox icon to tag update info 2024-07-26 10:15:09 -05:00
0b444d6364 #27 fix issue with last car end gear issue detection 2024-07-26 10:13:35 -05:00
d197ff8d8a Merge pull request #23 from rmroc451/misc-fixes-and-caboose-additions
Misc fixes and caboose additions
2024-07-24 00:09:54 -05:00
89894890b4 build version increment 2024-07-24 00:07:59 -05:00
a13701c3d2 AutoHotboxSpotter Patch for caboose consist presence, making checks happen between every 15-30 seconds vs 60-300 (default) 2024-07-24 00:07:48 -05:00
b5be17703f Adding AutoOiler Patch that halves times to oil consists and the start delay, if a caboose is presentin the consist that the ai engineer is in. 2024-07-24 00:06:37 -05:00
35afa4520d log context adjustments for CarInspector patch class 2024-07-24 00:04:49 -05:00
80d064c950 remove SetActive call, which seems to be a performance gain when tags are displayed. 2024-07-24 00:03:11 -05:00
ec21effd30 Adding consist buttons from inspector to new context menu, and squashing bug that would occur if inspector open but tags weren't active, breaking the ui panel builder reload detection for handbrake/couple/air changes.
final change of Version 0.1.7
2024-07-13 13:09:42 -05:00
2242aaacde Merge pull request #22 from rmroc451/1.6.1
Fix issue with cars that are missing tagcallouts from throwing errors.
2024-07-13 11:12:24 -05:00
e26713688b Fix issue with cars that are missing tagcallouts from throwing errors. 2024-07-13 11:11:22 -05:00
8a228be5a8 Merge pull request #21 from rmroc451/20-webhook-settings-adds-a-new-blank-entry-every-time-the-settings-window-opens
misc refactor and fixes
2024-07-05 20:22:52 -05:00
2ed33465d9 reduce cyclomatic complexity of the cabeese hunting algorithm, and fix issue with webhook settings adding an empty row each time settings screen opens. 2024-07-05 20:21:41 -05:00
24 changed files with 876 additions and 271 deletions

7
Assembly.version Normal file
View File

@@ -0,0 +1,7 @@
<Project>
<PropertyGroup>
<MajorVersion>1</MajorVersion>
<MinorVersion>2</MinorVersion>
<PatchVersion>4</PatchVersion>
</PropertyGroup>
</Project>

View File

@@ -1,5 +1,6 @@
<Project>
<Import Project="Paths.user" Condition="Exists('Paths.user')" />
<Import Project="Assembly.version" Condition="Exists('Assembly.version')" />
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<LangVersion>latest</LangVersion>

View File

@@ -6,13 +6,14 @@
<!-- Copy the mod to the game directory -->
<GameModDir Condition="'$(GameModDir)' == ''">$(GameDir)/Mods/$(AssemblyName)</GameModDir>
<OutDir Condition="'$(Configuration)' == 'Debug'">$(GameModDir)/</OutDir>
<VersionTimestamp>$([System.DateTime]::UtcNow.ToString(`o`))</VersionTimestamp>
</PropertyGroup>
<!-- Replace the default version if something was set for it -->
<PropertyGroup Condition="'$(AssemblyVersion)' == '' OR '$(MajorVersion)' != '' OR '$(MinorVersion)' != ''">
<MajorVersion Condition="'$(MajorVersion)' == ''">0</MajorVersion>
<MajorVersion Condition="'$(MajorVersion)' == ''">1</MajorVersion>
<MinorVersion Condition="'$(MinorVersion)' == ''">1</MinorVersion>
<PatchVersion Condition="'$(PatchVersion)' == ''">6</PatchVersion>
<PatchVersion Condition="'$(PatchVersion)' == ''">1</PatchVersion>
<AssemblyVersion>$(MajorVersion).$(MinorVersion).$(PatchVersion)</AssemblyVersion>
<FileVersion>$(AssemblyVersion)</FileVersion>
<ProductVersion>$(AssemblyVersion)</ProductVersion>
@@ -30,7 +31,7 @@
<!-- Publish the mod as a neat zip file -->
<Target Name="PrepareForPublishing" AfterTargets="AfterBuild" Condition="'$(Configuration)' == 'Release'">
<!-- Replace $(AssemblyVersion) with the actual version -->
<Exec Command="powershell -Command &quot;(Get-Content '$(OutputPath)Definition.json') -replace '\$\(AssemblyVersion\)', '$(AssemblyVersion)' | Set-Content '$(OutputPath)Definition.json'&quot;" />
<Exec Command="powershell -Command &quot;(Get-Content '$(OutputPath)Definition.json') -replace '\$\(AssemblyVersion\)', '$(AssemblyVersion)_$(VersionTimestamp)' | Set-Content '$(OutputPath)Definition.json'&quot;" />
<PropertyGroup>
<ModsDirectory>$(OutputPath)/Mods</ModsDirectory>
@@ -38,7 +39,7 @@
<!-- Folder we'll put the published zips into -->
<PublishPath>../bin</PublishPath>
<ZipName>$(PublishPath)/$(AssemblyName)_$(AssemblyVersion).zip</ZipName>
<ZipName>$(PublishPath)/$(AssemblyName)_$(AssemblyVersion)_Experimental.zip</ZipName>
</PropertyGroup>
<!-- Assure the output path exists -->

6
Paths.user.example Normal file
View File

@@ -0,0 +1,6 @@
<Project>
<PropertyGroup>
<!-- Directory that the game (Railroader.exe) is in -->
<GameDir></GameDir>
</PropertyGroup>
</Project>

View File

@@ -6,6 +6,7 @@ MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{452A23A6-81C8-49C6-A7EE-95FD9377F896}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
Assembly.version = Assembly.version
Directory.Build.props = Directory.Build.props
Directory.Build.targets = Directory.Build.targets
Paths.user = Paths.user

View File

@@ -1,6 +1,6 @@
using Game.State;
using Helpers;
using Model.OpsNew;
using Model.Ops;
using Network;
using RMROC451.TweaksAndThings.Extensions;
using System.Linq;

View File

@@ -5,10 +5,17 @@
"version": "$(AssemblyVersion)",
"requires": [
{
"id": "railloader",
"notBefore": "1.8.1"
"id": "railroader",
"notBefore": "2024.6"
},
"Zamu.StrangeCustoms"
{
"id": "railloader",
"notBefore": "1.9.6.14"
},
{
"id": "Zamu.StrangeCustoms",
"notBefore": "1.10.25017.313"
}
],
"assemblies": [ "RMROC451.TweaksAndThings" ],
"mixintos": {

View File

@@ -0,0 +1,118 @@
using Model.AI;
using System.Collections;
using UnityEngine;
namespace RMROC451.TweaksAndThings.Extensions
{
internal static class AutoEngineer_Extensions
{
private static float CabooseHalvedFloat(this float input, Model.Car? hasCaboose) =>
hasCaboose ? input / 2 : input;
private static float CabooseAutoOilerLimit(this Model.Car? caboose) =>
caboose ? 0.99f : AutoOiler.OilIfBelow;
public static IEnumerator MrocAutoOilerLoop(this AutoOiler oiler, Serilog.ILogger _log, bool cabooseRequired)
{
int originIndex = oiler.FindOriginIndex();
Model.Car? foundCaboose = oiler._cars.CabooseInConsist();
if (originIndex < 0)
{
_log.Error("Couldn't find origin car {car}", oiler._originCar);
oiler._coroutine = null;
yield break;
} else if (CabooseRequirementChecker(string.Format("{0} {1}", oiler.GetType().Name, oiler.name), cabooseRequired, foundCaboose, _log))
{
yield break;
}
oiler._reverse = originIndex > oiler._cars.Count - originIndex;
_log.Information(
"AutoOiler {name} starting, rev = {reverse}, caboose required = {req}, caboose halving adjustment = {hasCaboose}, oil limit = {limit}",
oiler.name,
oiler._reverse,
cabooseRequired,
foundCaboose,
foundCaboose.CabooseAutoOilerLimit()
);
while (true)
{
yield return new WaitForSeconds(AutoOiler.StartDelay.CabooseHalvedFloat(foundCaboose));
int carIndex = originIndex;
float adjustedTimeToWalk = AutoOiler.TimeToWalkCar.CabooseHalvedFloat(foundCaboose);
do
{
if (oiler.TryGetCar(carIndex, out var car))
{
float num = 0f;
float origOil = car.Oiled;
if (car.NeedsOiling && car.Oiled < foundCaboose.CabooseAutoOilerLimit())
{
float num2 = 1f - car.Oiled;
car.OffsetOiled(num2);
float num3 = num2 * AutoOiler.TimeToFullyOil.CabooseHalvedFloat(foundCaboose);
num += num3;
oiler._pendingRunDuration += num3;
oiler._oiledCount++;
_log.Information("AutoOiler {name}: oiled {car} from {orig} => {new}", oiler.name, car, origOil, car.Oiled);
}
if (car.HasHotbox && car.Oiled == 1f && cabooseRequired && foundCaboose)
{
_log.Information("AutoOiler {name}: {foundCaboose} repaired hotbox {car}", oiler.name, foundCaboose, car);
car.AdjustHotboxValue(0f);
}
num += adjustedTimeToWalk;
oiler._pendingRunDuration += adjustedTimeToWalk;
yield return new WaitForSeconds(num);
}
carIndex = oiler.NextIndex(carIndex);
}
while (oiler.InBounds(carIndex));
oiler._reverse = !oiler._reverse;
oiler.PayWages();
}
}
public static IEnumerator MrocAutoHotboxSpotterLoop(this AutoHotboxSpotter spotter, Serilog.ILogger _log, bool cabooseRequired)
{
while (true)
{
Model.Car? foundCaboose = spotter._cars.CabooseInConsist();
if (!spotter.HasCars)
{
yield return new WaitForSeconds(1f);
continue;
}
_log.Information("AutoHotboxSpotter {name}: Hotbox Spotter Running, Found Caboose => {hasCaboose}; Has Cars {hasCars}; Requires Caboose {requiresCaboose}",
spotter.name, foundCaboose, spotter.HasCars, cabooseRequired);
foundCaboose = spotter._cars.CabooseInConsist();
if (CabooseRequirementChecker(string.Format("{0} {1}", spotter.GetType().Name, spotter.name), cabooseRequired, foundCaboose, _log))
{
yield break;
}
spotter.CheckForHotbox();
while (spotter.HasCars)
{
int num = Random.Range(60, 300);
foundCaboose = spotter._cars.CabooseInConsist();
if (foundCaboose)
{
var numOrig = num;
num = Random.Range(15, 30);
_log.Information("AutoHotboxSpotter {name}: Next check went from num(60,300) => {numOrig}; to num(15,30) => {hasCaboose}; Requires Caboose {requiresCaboose}", spotter.name, numOrig, num, foundCaboose, cabooseRequired);
}
yield return new WaitForSeconds(num);
spotter.CheckForHotbox();
}
}
}
private static bool CabooseRequirementChecker(string name, bool cabooseRequired, Model.Car? foundCaboose, Serilog.ILogger _log)
{
bool error = cabooseRequired && foundCaboose == null;
if (error) {
_log.Debug("{name}: Couldn't find required caboose!", name);
}
return error;
}
}
}

View File

@@ -1,7 +1,9 @@
using Helpers;
using Game.Messages;
using Game.State;
using Helpers;
using Model;
using Model.Definition.Data;
using Model.OpsNew;
using Model.Ops;
using Serilog;
using System;
using System.Collections.Generic;
@@ -12,10 +14,14 @@ namespace RMROC451.TweaksAndThings.Extensions;
public static class Car_Extensions
{
private static bool EndGearIssue(this Car car, Car.LogicalEnd end) =>
(!car[end].IsCoupled && car[end].IsAnglecockOpen) ||
(car[end].IsCoupled && !car[end].IsAirConnectedAndOpen);
public static bool EndAirSystemIssue(this Car car)
{
bool AEndAirSystemIssue = car[Car.LogicalEnd.A].IsCoupled && !car[Car.LogicalEnd.A].IsAirConnectedAndOpen;
bool BEndAirSystemIssue = car[Car.LogicalEnd.B].IsCoupled && !car[Car.LogicalEnd.B].IsAirConnectedAndOpen;
bool AEndAirSystemIssue = car.EndGearIssue(Car.LogicalEnd.A);
bool BEndAirSystemIssue = car.EndGearIssue(Car.LogicalEnd.B);
bool EndAirSystemIssue = AEndAirSystemIssue || BEndAirSystemIssue;
return EndAirSystemIssue;
}
@@ -56,12 +62,14 @@ public static class Car_Extensions
public static bool IsCaboose(this Car car) => car.Archetype == Model.Definition.CarArchetype.Caboose;
public static bool CabooseInConsist(this IEnumerable<Car> input) => input.FirstOrDefault(c => c.IsCaboose());
public static bool IsCabooseAndStoppedForLoadRefresh(this Car car) => car.IsCaboose() && car.IsStopped(30f);
public static Car? CabooseWithSufficientCrewHours(this Car car, float timeNeeded, bool decrement = false)
public static Car? CabooseInConsist(this IEnumerable<Car> input) => input.FirstOrDefault(c => c.IsCaboose());
public static Car? CabooseWithSufficientCrewHours(this Car car, float timeNeeded, HashSet<string> carIdsCheckedAlready, bool decrement = false)
{
Car? output = null;
if (!car.IsCaboose()) return null;
if (carIdsCheckedAlready.Contains(car.id) || !car.IsCaboose()) return null;
List<LoadSlot> loadSlots = car.Definition.LoadSlots;
for (int i = 0; i < loadSlots.Count; i++)
@@ -78,33 +86,51 @@ public static class Car_Extensions
return output;
}
public static Car? HuntingForCabeeseNearCar(this Car car, float timeNeeded, TrainController tc, bool decrement = false)
public static Car? HuntingForCabeeseNearCar(this Car car, float timeNeeded, TrainController tc, HashSet<string> carIdsCheckedAlready, bool decrement = false)
{
Vector3 position = car.GetMotionSnapshot().Position;
Vector3 center = WorldTransformer.WorldToGame(position);
Rect rect = new Rect(new Vector2(center.x - 30f, center.z - 30f), Vector2.one * 30f * 2f);
var cars = tc.CarIdsInRect(rect);
Log.Information($"{nameof(HuntingForCabeeseNearCar)} => {cars.Count()}");
bool decrementedAlready = false;
List<(string carId, float distance)> source = cars.Select(carId =>
{
Car car = tc.CarForId(carId);
if (car == null || !car.CabooseWithSufficientCrewHours(timeNeeded, decrement && !decrementedAlready))
{
return (carId: carId, distance: 1000f);
}
decrementedAlready = true;
Vector3 a = WorldTransformer.WorldToGame(car.GetMotionSnapshot().Position);
return (carId: carId, distance: Vector3.Distance(a, center));
}).ToList();
List<(string carId, float distance)> source =
CarsNearCurrentCar(car, timeNeeded, tc, carIdsCheckedAlready, decrement);
Car? output =
(from t in source
where t.distance < 21f
Car output = FindNearestCabooseFromNearbyCars(tc, source);
if (output != null) output.CabooseWithSufficientCrewHours(timeNeeded, carIdsCheckedAlready, decrement);
return output;
}
private static Car FindNearestCabooseFromNearbyCars(TrainController tc, List<(string carId, float distance)> source) =>
(
from t in source
where t.distance < 21f //todo: add setting slider for catchment
orderby t.distance ascending
select tc.CarForId(t.carId)
).FirstOrDefault();
return output;
private static List<(string carId, float distance)> CarsNearCurrentCar(Car car, float timeNeeded, TrainController tc, HashSet<string> carIdsCheckedAlready, bool decrement)
{
Vector3 position = car.GetMotionSnapshot().Position;
Vector3 center = WorldTransformer.WorldToGame(position);
var cars = tc.CarIdsInRadius(center, 60f);
Log.Information($"{nameof(HuntingForCabeeseNearCar)} => {cars.Count()}");
List<(string carId, float distance)> source =
cars
.Select(carId =>
{
Car car = tc.CarForId(carId);
if (car == null || !car.CabooseWithSufficientCrewHours(timeNeeded, carIdsCheckedAlready))
{
return (carId: carId, distance: 1000f);
}
Vector3 a = WorldTransformer.WorldToGame(car.GetMotionSnapshot().Position);
return (carId: carId, distance: Vector3.Distance(a, center));
}).ToList();
return source;
}
public static void AdjustHotboxValue(this Car car, float hotboxValue) =>
StateManager.ApplyLocal(
new PropertyChange(
car.id, PropertyChange.KeyForControl(PropertyChange.Control.Hotbox),
new FloatPropertyValue(hotboxValue)
)
);
}

View File

@@ -0,0 +1,27 @@
using HarmonyLib;
using Model.AI;
using Railloader;
using RMROC451.TweaksAndThings.Extensions;
using Serilog;
using System.Collections;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(AutoHotboxSpotter))]
[HarmonyPatch(nameof(AutoHotboxSpotter.SpotterLoop))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class AutoHotboxSpotter_SpotterLoop_Patch
{
private static ILogger _log => Log.ForContext<AutoHotboxSpotter_SpotterLoop_Patch>();
public static bool Prefix(AutoHotboxSpotter __instance, ref IEnumerator __result)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return true;
bool buttonsHaveCost = tweaksAndThings.EndGearHelpersRequirePayment();
bool cabooseRequired = tweaksAndThings.RequireConsistCabooseForOilerAndHotboxSpotter();
if (buttonsHaveCost) __result = __instance.MrocAutoHotboxSpotterLoop(_log, cabooseRequired);
return !buttonsHaveCost; //only hit this if !buttonsHaveCost, since Loop is a coroutine
}
}

View File

@@ -0,0 +1,27 @@
using HarmonyLib;
using Model.AI;
using Railloader;
using RMROC451.TweaksAndThings.Extensions;
using Serilog;
using System.Collections;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(AutoOiler))]
[HarmonyPatch(nameof(AutoOiler.Loop))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class AutoOiler_Loop_Patch
{
private static ILogger _log => Log.ForContext<AutoOiler_Loop_Patch>();
public static bool Prefix(AutoOiler __instance, ref IEnumerator __result)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return true;
bool buttonsHaveCost = tweaksAndThings.EndGearHelpersRequirePayment();
bool cabooseRequired = tweaksAndThings.RequireConsistCabooseForOilerAndHotboxSpotter();
if (buttonsHaveCost) __result = __instance.MrocAutoOilerLoop(_log, cabooseRequired);
return !buttonsHaveCost; //only hit this if !buttonsHaveCost, since Loop is a coroutine
}
}

View File

@@ -1,19 +1,22 @@
using Game.Messages;
using Core;
using Game.Messages;
using Game.State;
using HarmonyLib;
using KeyValue.Runtime;
using Model;
using Model.OpsNew;
using Network;
using Railloader;
using RMROC451.TweaksAndThings.Enums;
using RMROC451.TweaksAndThings.Extensions;
using RollingStock;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using UI;
using UI.Builder;
using UI.CarInspector;
using UI.ContextMenu;
using UI.Tags;
using static Model.Car;
@@ -24,6 +27,7 @@ namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class CarInspector_PopulateCarPanel_Patch
{
private static ILogger _log => Log.ForContext<CarInspector_PopulateCarPanel_Patch>();
private static IEnumerable<LogicalEnd> ends = Enum.GetValues(typeof(LogicalEnd)).Cast<LogicalEnd>();
/// <summary>
@@ -37,40 +41,65 @@ internal class CarInspector_PopulateCarPanel_Patch
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return true;
bool buttonsHaveCost = tweaksAndThings?.settings?.EndGearHelpersRequirePayment ?? false;
bool buttonsHaveCost = tweaksAndThings.EndGearHelpersRequirePayment();
var consist = __instance._car.EnumerateCoupled(LogicalEnd.A);
builder = AddCarConsistRebuildObservers(builder, consist);
var consist = __instance._car.EnumerateCoupled();
builder.HStack(delegate (UIPanelBuilder hstack)
{
hstack = AddCarConsistRebuildObservers(hstack, consist);
var buttonName = $"{(consist.Any(c => c.HandbrakeApplied()) ? "Release " : "Set ")} {TextSprites.HandbrakeWheel}";
hstack.AddButtonCompact(buttonName, delegate {
hstack.AddButtonCompact(buttonName, delegate
{
MrocConsistHelper(__instance._car, MrocHelperType.Handbrake, buttonsHaveCost);
hstack.Rebuild();
}).Tooltip(buttonName, $"Iterates over cars in this consist and {(consist.Any(c => c.HandbrakeApplied()) ? "releases" : "sets")} {TextSprites.HandbrakeWheel}.");
if (consist.Any(c => c.EndAirSystemIssue()))
{
hstack.AddButtonCompact("Connect Air", delegate {
hstack.AddButtonCompact("Connect Air", delegate
{
MrocConsistHelper(__instance._car, MrocHelperType.GladhandAndAnglecock, buttonsHaveCost);
hstack.Rebuild();
}).Tooltip("Connect Consist Air", "Iterates over each car in this consist and connects gladhands and opens anglecocks.");
}
hstack.AddButtonCompact("Bleed Consist", delegate {
hstack.AddButtonCompact("Bleed Consist", delegate
{
MrocConsistHelper(__instance._car, MrocHelperType.BleedAirSystem, buttonsHaveCost);
hstack.Rebuild();
}).Tooltip("Bleed Air Lines", "Iterates over each car in this consist and bleeds the air out of the lines.");
});
CabooseUiEnhancer(__instance, builder, consist, tweaksAndThings);
return true;
}
private static void CabooseUiEnhancer(CarInspector __instance, UIPanelBuilder builder, IEnumerable<Car> consist, TweaksAndThingsPlugin plugin)
{
if (plugin.CabooseNonMotiveAllowedSetting(__instance._car))
{
builder.HStack(delegate (UIPanelBuilder hstack)
{
hstack.AddField("Consist Info", hstack.HStack(delegate (UIPanelBuilder field)
{
int consistLength = consist.Count();
int tonnage = LocomotiveControlsHoverArea.CalculateTonnage(consist);
int lengthInMeters = UnityEngine.Mathf.CeilToInt(LocomotiveControlsHoverArea.CalculateLengthInMeters(consist.ToList()) * 3.28084f);
var newSubTitle = () => string.Format("{0}, {1:N0}T, {2:N0}ft, {3:0.0} mph", consistLength.Pluralize("car"), tonnage, lengthInMeters, __instance._car.VelocityMphAbs);
field.AddLabel(() => newSubTitle(), UIPanelBuilder.Frequency.Fast)
.Tooltip("Consist Info", "Reflects info about consist.").FlexibleWidth();
}));
});
}
}
private static UIPanelBuilder AddCarConsistRebuildObservers(UIPanelBuilder builder, IEnumerable<Model.Car> consist)
{
TagController tagController = UnityEngine.Object.FindFirstObjectByType<TagController>();
foreach (Model.Car car in consist)
foreach (Model.Car car in consist.Where(c => c.Archetype != Model.Definition.CarArchetype.Tender))
{
builder = AddObserver(builder, car, PropertyChange.KeyForControl(PropertyChange.Control.Handbrake), tagController);
foreach (LogicalEnd logicalEnd in ends)
@@ -93,12 +122,13 @@ internal class CarInspector_PopulateCarPanel_Patch
{
try
{
tagController.UpdateTag(car, car.TagCallout, OpsController.Shared);
builder.Rebuild();
if (car.TagCallout != null) tagController.UpdateTags(CameraSelector.shared._currentCamera.GroundPosition, true);
if (ContextMenu.IsShown && ContextMenu.Shared.centerLabel.text == car.DisplayName) CarPickable.HandleShowContextMenu(car);
}
catch(Exception ex)
catch (Exception ex)
{
Log.Warning(ex, $"{nameof(AddObserver)} {car} Exception logged for {key}");
_log.ForContext("car", car).Warning(ex, $"{nameof(AddObserver)} {car} Exception logged for {key}");
}
},
false
@@ -121,8 +151,8 @@ internal class CarInspector_PopulateCarPanel_Patch
public static void MrocConsistHelper(Model.Car car, MrocHelperType mrocHelperType, bool buttonsHaveCost)
{
TrainController tc = UnityEngine.Object.FindObjectOfType<TrainController>();
IEnumerable<Model.Car> consist = car.EnumerateCoupled(LogicalEnd.A);
//Log.Information($"{car} => {mrocHelperType} => {string.Join("/", consist.Select(c => c.ToString()))}");
IEnumerable<Model.Car> consist = car.EnumerateCoupled();
_log.ForContext("car", car).Verbose($"{car} => {mrocHelperType} => {string.Join("/", consist.Select(c => c.ToString()))}");
CalculateCostIfEnabled(car, mrocHelperType, buttonsHaveCost, consist);
@@ -136,7 +166,6 @@ internal class CarInspector_PopulateCarPanel_Patch
else
{
consist = consist.Where(c => c is not BaseLocomotive && c.Archetype != Model.Definition.CarArchetype.Tender);
Log.Information($"{car} => {mrocHelperType} => {string.Join("/", consist.Select(c => c.ToString()))}");
//when ApplyHandbrakesAsNeeded is called, and the consist contains an engine, it stops applying brakes.
tc.ApplyHandbrakesAsNeeded(consist.ToList(), PlaceTrainHandbrakes.Automatic);
}
@@ -163,7 +192,7 @@ internal class CarInspector_PopulateCarPanel_Patch
case MrocHelperType.BleedAirSystem:
consist = consist.Where(c => c.NotMotivePower());
Log.Information($"{car} => {mrocHelperType} => {string.Join("/", consist.Select(c => c.ToString()))}");
_log.ForContext("car", car).Information($"{car} => {mrocHelperType} => {string.Join("/", consist.Select(c => c.ToString()))}");
foreach (Model.Car bleed in consist)
{
StateManager.ApplyLocal(new PropertyChange(bleed.id, PropertyChange.Control.Bleed, 1));
@@ -179,36 +208,40 @@ internal class CarInspector_PopulateCarPanel_Patch
float originalTimeCost = consist.CalculateCostForAutoEngineerEndGearSetting();
float timeCost = originalTimeCost;
float crewCost = timeCost / 3600; //hours of time deducted from caboose.
var tsString = crewCost.FormatCrewHours(IndustryComponent_Service_Patch.CrewHoursLoad().description);
var tsString = crewCost.FormatCrewHours(OpsController_AnnounceCoalescedPayments_Patch.CrewHoursLoad().description);
Car? cabooseWithAvailCrew = NearbyCabooseWithAvailableCrew(car, crewCost, buttonsHaveCost);
if (cabooseWithAvailCrew == null) timeCost *= 1.5f;
var cabooseFoundDisplay = cabooseWithAvailCrew?.DisplayName ?? "No caboose";
Log.Information($"{nameof(MrocConsistHelper)} {mrocHelperType} : [VACINITY CABEESE FOUND:{cabooseWithAvailCrew?.ToString() ?? "NONE"}] => Consist Length {consist.Count()} => costs {timeCost / 60} minutes of AI Engineer time, $5 per hour = ~${Math.Ceiling((decimal)(timeCost / 3600) * 5)} (*2 if no caboose nearby)");
_log.ForContext("car", car).Information($"{nameof(MrocConsistHelper)} {mrocHelperType} : [VACINITY CABEESE FOUND:{cabooseWithAvailCrew?.ToString() ?? "NONE"}] => Consist Length {consist.Count()} => costs {timeCost / 60} minutes of AI Engineer time, $5 per hour = ~${Math.Ceiling((decimal)(timeCost / 3600) * 5)} (*2 if no caboose nearby)");
Multiplayer.SendError(StateManager.Shared._playersManager.LocalPlayer, $"{(cabooseWithAvailCrew != null ? $"{cabooseWithAvailCrew.DisplayName} Hours Adjusted: ({tsString})\n" : string.Empty)}Wages: ~(${Math.Ceiling((decimal)(timeCost / 3600) * 5)})");
if (buttonsHaveCost) StateManager_OnDayDidChange_Patch.UnbilledAutoBrakeCrewRunDuration += timeCost;
StateManager_OnDayDidChange_Patch.UnbilledAutoBrakeCrewRunDuration += timeCost;
}
}
public static Car? NearbyCabooseWithAvailableCrew(Car car, float timeNeeded, bool decrement = false)
{
HashSet<string> carIdsCheckedAlready = new();
//check current car.
Car? output = car.CabooseWithSufficientCrewHours(timeNeeded, decrement);
Car? output = car.CabooseWithSufficientCrewHours(timeNeeded, carIdsCheckedAlready, decrement);
if (output != null) return output; //short out if we are good
carIdsCheckedAlready.Add(car.id);
//check consist, for cabeese
IEnumerable<Car> consist = car.EnumerateCoupled(LogicalEnd.A);
output = consist.FirstOrDefault(c => c.CabooseWithSufficientCrewHours(timeNeeded, decrement));
IEnumerable<Car> consist = car.EnumerateCoupled();
output = consist.FirstOrDefault(c => c.CabooseWithSufficientCrewHours(timeNeeded, carIdsCheckedAlready, decrement));
if (output != null) return output; //short out if we are good
carIdsCheckedAlready.UnionWith(consist.Select(c => c.id));
//then check near consist cars for cabeese
TrainController tc = UnityEngine.Object.FindObjectOfType<TrainController>();
foreach (var c in consist)
{
output = c.HuntingForCabeeseNearCar(timeNeeded, tc, decrement);
output = c.HuntingForCabeeseNearCar(timeNeeded, tc, carIdsCheckedAlready, decrement);
if (output != null) return output; //short out if we are good
}

View File

@@ -0,0 +1,52 @@
using HarmonyLib;
using Railloader;
using RollingStock;
using UnityEngine;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(CarPickable))]
[HarmonyPatch(nameof(CarPickable.Activate), typeof(PickableActivateEvent))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class CarPickable_Activate_Patch
{
static float clicked = 0;
static float clicktime = 0;
static float clickdelay = 0.5f;
private static bool Prefix(CarPickable __instance, PickableActivateEvent evt)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return true;
if (OnPointerDown(evt))
{
CameraSelector.shared.FollowCar(__instance.car);
return false;
}
return true;
}
public static bool OnPointerDown(PickableActivateEvent evt)
{
bool output = false;
if (evt.Activation == PickableActivation.Primary)
{
clicked++;
if (clicked == 1) clicktime = Time.time;
if (clicked > 1 && Time.time - clicktime < clickdelay)
{
clicked = 0;
clicktime = 0;
output = true;
}
else if (clicked > 2 || Time.time - clicktime > 1) clicked = 0;
}
return output;
}
}

View File

@@ -0,0 +1,53 @@
using HarmonyLib;
using Model;
using Railloader;
using RMROC451.TweaksAndThings.Enums;
using RMROC451.TweaksAndThings.Extensions;
using RollingStock;
using System.Linq;
using UI;
using UI.ContextMenu;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(CarPickable))]
[HarmonyPatch(nameof(CarPickable.HandleShowContextMenu), typeof(Car))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class CarPickable_HandleShowContextMenu_Patch
{
private static void Postfix(Car car)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return;
bool buttonsHaveCost = tweaksAndThings.EndGearHelpersRequirePayment();
ContextMenu shared = ContextMenu.Shared;
shared.AddButton(ContextMenuQuadrant.Unused1, $"{(car.EnumerateCoupled().Any(c => c.HandbrakeApplied()) ? "Release " : "Set ")} Consist", SpriteName.Handbrake, delegate
{
CarInspector_PopulateCarPanel_Patch.MrocConsistHelper(car, MrocHelperType.Handbrake, buttonsHaveCost);
});
if (car.EnumerateCoupled().Any(c => c.EndAirSystemIssue()))
{
shared.AddButton(ContextMenuQuadrant.Unused1, $"Air Up Consist", SpriteName.Select, delegate
{
CarInspector_PopulateCarPanel_Patch.MrocConsistHelper(car, MrocHelperType.GladhandAndAnglecock, buttonsHaveCost);
});
}
if (!car.EnumerateCoupled().Any(c => !c.SupportsBleed()))
{
shared.AddButton(ContextMenuQuadrant.Unused2, $"Bleed Consist", SpriteName.Bleed, delegate
{
CarInspector_PopulateCarPanel_Patch.MrocConsistHelper(car, MrocHelperType.BleedAirSystem, buttonsHaveCost);
});
}
shared.AddButton(ContextMenuQuadrant.Unused2, $"Follow", SpriteName.Inspect, delegate
{
CameraSelector.shared.FollowCar(car);
});
shared.BuildItemAngles();
shared.StartCoroutine(shared.AnimateButtonsShown());
}
}

View File

@@ -0,0 +1,25 @@
using HarmonyLib;
using Railloader;
using System;
using UI.ContextMenu;
using UnityEngine;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(UI.ContextMenu.ContextMenu))]
//ContextMenuQuadrant quadrant, int index, float normalizedRadius = 1f
[HarmonyPatch(nameof(UI.ContextMenu.ContextMenu.PositionForItem), typeof(ContextMenuQuadrant), typeof(int), typeof(float))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class ContextMenu_PositionForItem_Patch
{
static void Postfix(UI.ContextMenu.ContextMenu __instance, ref Vector2 __result, ContextMenuQuadrant quadrant, int index, float normalizedRadius = 1f)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return;
float num = __instance._itemAngles[(quadrant, index)] * ((float)Math.PI / 180f);
float num2 = __instance.radius * normalizedRadius;
__result = new Vector2(1.3f * Mathf.Sin(num) * num2, Mathf.Cos(num) * num2);
}
}

View File

@@ -0,0 +1,127 @@
using HarmonyLib;
using Helpers;
using Railloader;
using Serilog;
using System;
using System.Collections.Generic;
using UI;
using UI.ContextMenu;
using UnityEngine;
using UnityEngine.UI;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(UI.ContextMenu.ContextMenu))]
[HarmonyPatch(nameof(UI.ContextMenu.ContextMenu.Show), typeof(string))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class ContextMenu_Show_Patch
{
static bool Prefix(UI.ContextMenu.ContextMenu __instance, string centerText)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return true;
if (!__instance.GetRootCanvas(out var rootCanvas))
{
Log.Warning("Couldn't get root canvas");
return true;
}
__instance.CancelHideCoroutine();
__instance.SetupTemplate(rootCanvas);
__instance.centerLabel.text = centerText;
Canvas componentInParent = ((Component)__instance.contentRectTransform).GetComponentInParent<Canvas>();
Vector3 mousePosition = Input.mousePosition;
Vector2 val = componentInParent.ScreenToCanvasPosition(mousePosition).XY();
Vector2 renderingDisplaySize = rootCanvas.renderingDisplaySize;
float num = __instance.radius + 50f;
if (val.x < num)
{
val.x = num;
}
if (val.x > renderingDisplaySize.x - num)
{
val.x = renderingDisplaySize.x - num;
}
if (val.y < num)
{
val.y = num;
}
if (val.y > renderingDisplaySize.y - num)
{
val.y = renderingDisplaySize.y - num;
}
__instance.contentRectTransform.anchoredPosition = val;
__instance.BuildItemAngles();
((MonoBehaviour)__instance).StartCoroutine(__instance.AnimateButtonsShown());
((Component)__instance.contentRectTransform).gameObject.SetActive(true);
UI.ContextMenu.ContextMenu.IsShown = true;
__instance._blocker = __instance.CreateBlocker(rootCanvas);
GameInput.RegisterEscapeHandler(GameInput.EscapeHandler.Transient, delegate
{
__instance.Hide();
return true;
});
return false;
}
}
[HarmonyPatch(typeof(UI.ContextMenu.ContextMenu))]
[HarmonyPatch(nameof(UI.ContextMenu.ContextMenu.DefaultAngleForItem), typeof(ContextMenuQuadrant), typeof(int), typeof(int))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class ContextMenu_DefaultAngleForItem_Patch
{
static bool Prefix(UI.ContextMenu.ContextMenu __instance, ref float __result, ContextMenuQuadrant quadrant, int index, int quadrantItemCount)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return true;
int num = quadrant switch
{
ContextMenuQuadrant.General => 0,
ContextMenuQuadrant.Unused1 => 90,
ContextMenuQuadrant.Brakes => 180,
ContextMenuQuadrant.Unused2 => -90,
_ => throw new ArgumentOutOfRangeException("quadrant", quadrant, null),
};
if (quadrantItemCount <= 1)
{
__result = num;
return false;
}
int num2 = ((quadrantItemCount <= 3) ? 30 : (90 / (quadrantItemCount - 1)));
__result = (float)num + -0.5f * (float)((quadrantItemCount - 1) * num2) + (float)(num2 * index);
return false;
}
}
[HarmonyPatch(typeof(UI.ContextMenu.ContextMenu))]
[HarmonyPatch(nameof(UI.ContextMenu.ContextMenu.AddButton), typeof(ContextMenuQuadrant), typeof(string), typeof(Sprite), typeof(Action))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class ContextMenu_AddButton_Patch
{
static bool Prefix(UI.ContextMenu.ContextMenu __instance, ContextMenuQuadrant quadrant, string title, Sprite sprite, Action action)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return true;
List<ContextMenuItem> list = __instance._quadrants[(int)quadrant];
int index = list.Count;
ContextMenuItem contextMenuItem = UnityEngine.Object.Instantiate<ContextMenuItem>(__instance.itemPrefab, (Transform)(object)__instance.contentRectTransform);
contextMenuItem.image.sprite = sprite;
contextMenuItem.label.text = title;
contextMenuItem.OnClick = delegate
{
action();
__instance.Hide((quadrant, index));
};
((Component)contextMenuItem).gameObject.AddComponent<LayoutElement>().preferredHeight = 30f;
list.Add(contextMenuItem);
return false;
}
}

View File

@@ -1,7 +1,7 @@
using HarmonyLib;
using Model;
using Model.Definition.Data;
using Model.OpsNew;
using Model.Ops;
using Railloader;
using RMROC451.TweaksAndThings.Extensions;
using Serilog;

View File

@@ -1,139 +0,0 @@
using Game.State;
using HarmonyLib;
using Model;
using Model.Definition.Data;
using Model.Ops.Definition;
using Model.OpsNew;
using Railloader;
using RMROC451.TweaksAndThings.Extensions;
using Serilog;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(CarExtensions))]
[HarmonyPatch(nameof(CarExtensions.LoadString), typeof(CarLoadInfo), typeof(Load))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class CarExtensions_LoadString_Patch
{
public static bool Prefix(CarLoadInfo info, Load load, ref string __result)
{
bool output = load.id == IndustryComponent_Service_Patch.CrewHoursLoad().id;
if (output) __result = info.Quantity.FormatCrewHours(load.description);
return !output;
}
}
[HarmonyPatch(typeof(CarPrototypeLibrary))]
[HarmonyPatch(nameof(CarPrototypeLibrary.LoadForId), typeof(string))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class CarPrototypeLibrary_LoadForId_Patch
{
public static bool Prefix(string loadId, ref Load __result)
{
Load load = IndustryComponent_Service_Patch.CrewHoursLoad();
if (loadId == load.id) __result = load;
return __result == null;
}
}
[HarmonyPatch(typeof(TeamTrack))]
[HarmonyPatch(nameof(TeamTrack.Service), typeof(IIndustryContext))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class TeamTrack_Service_Patch
{
public static bool Prefix(IndustryComponent __instance, IIndustryContext ctx)
{
//Log.Information($"{nameof(SimplePassengerStop_Service_Patch)} => {((IndustryContext)ctx)._industry.name}");
return IndustryComponent_Service_Patch.Prefix(__instance, ctx);
}
}
[HarmonyPatch(typeof(RepairTrack))]
[HarmonyPatch(nameof(RepairTrack.Service), typeof(IIndustryContext))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class RepairTrack_Service_Patch
{
public static bool Prefix(IndustryComponent __instance, IIndustryContext ctx)
{
//Log.Information($"{nameof(SimplePassengerStop_Service_Patch)} => {((IndustryContext)ctx)._industry.name}");
return IndustryComponent_Service_Patch.Prefix(__instance, ctx);
}
}
[HarmonyPatch(typeof(SimplePassengerStop))]
[HarmonyPatch(nameof(SimplePassengerStop.Service), typeof(IIndustryContext))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class SimplePassengerStop_Service_Patch
{
public static bool Prefix(IndustryComponent __instance, IIndustryContext ctx)
{
Log.Information($"{nameof(SimplePassengerStop_Service_Patch)} => {((IndustryContext)ctx)._industry.name}");
return IndustryComponent_Service_Patch.Prefix(__instance, ctx);
}
}
internal static class IndustryComponent_Service_Patch
{
public static Load CrewHoursLoad()
{
Load load = (Load)ScriptableObject.CreateInstance(typeof(Load));
load.name = "crew-hours";
load.description = "Crew";
load.units = LoadUnits.Quantity;
return load;
}
public static bool Prefix(IndustryComponent __instance, IIndustryContext ctx)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!StateManager.IsHost || !tweaksAndThings.IsEnabled || !(tweaksAndThings?.settings?.EndGearHelpersRequirePayment ?? false)) return true;
Load load = CrewHoursLoad();
float rate2 = 24 * 2 * 8;// carLoadRate = 8 crew hours in 30 min loading; (24h * 2 to get half hour chunks * 8 hours to load in those chunks)
float num2 = 99999999; //QuantityInStorage for crew-hours (infinite where crew can be shuffling about)
float quantityToLoad = Mathf.Min(num2, IndustryComponent.RateToValue(rate2, ctx.DeltaTime));
var carsAtPosition = ctx.CarsAtPosition();
var cabeese = from car in carsAtPosition.Where(c => c.CarType == "NE")
where car.IsEmptyOrContains(load)
orderby car.QuantityOfLoad(load).quantity descending
select car;
foreach (IOpsCar item in cabeese)
{
TrainController tc = UnityEngine.Object.FindAnyObjectByType<TrainController>();
if (tc.TryGetCarForId(item.Id, out Car car))
{
List<LoadSlot> loadSlots = car.Definition.LoadSlots;
float quantity = 0f;
float max = 0f;
for (int i = 0; i < loadSlots.Count; i++)
{
LoadSlot loadSlot = loadSlots[i];
if (loadSlot.LoadRequirementsMatch(load) && loadSlot.LoadUnits == load.units)
{
CarLoadInfo? loadInfo = car.GetLoadInfo(i);
quantity = loadInfo.HasValue ? loadInfo.Value.Quantity : 0f;
max = loadSlots[i].MaximumCapacity;
break;
}
}
//Log.Information($"{nameof(IndustryComponent_Service_Patch)} {car} => {car.StoppedDuration} => {quantityToLoad} => {quantity}/{max}");
if (car.StoppedDuration > 30) item.Load(load, quantityToLoad);
}
//todo:crew refresh message?
}
return true;
}
}

View File

@@ -0,0 +1,140 @@
using Game;
using Game.State;
using HarmonyLib;
using Model;
using Model.Definition.Data;
using Model.Ops.Definition;
using Model.Ops;
using Network;
using Railloader;
using RMROC451.TweaksAndThings.Extensions;
using RollingStock;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(CarExtensions))]
[HarmonyPatch(nameof(CarExtensions.LoadString), typeof(CarLoadInfo), typeof(Load))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class CarExtensions_LoadString_Patch
{
public static bool Prefix(CarLoadInfo info, Load load, ref string __result)
{
bool output = load.id == OpsController_AnnounceCoalescedPayments_Patch.CrewHoursLoad().id;
if (output) __result = info.Quantity.FormatCrewHours(load.description);
return !output;
}
}
[HarmonyPatch(typeof(CarPrototypeLibrary))]
[HarmonyPatch(nameof(CarPrototypeLibrary.LoadForId), typeof(string))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class CarPrototypeLibrary_LoadForId_Patch
{
public static bool Prefix(string loadId, ref Load __result)
{
Load load = OpsController_AnnounceCoalescedPayments_Patch.CrewHoursLoad();
if (loadId == load.id) __result = load;
return __result == null;
}
}
[HarmonyPatch(typeof(OpsController))]
[HarmonyPatch(nameof(OpsController.AnnounceCoalescedPayments))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class OpsController_AnnounceCoalescedPayments_Patch
{
static Dictionary<string, (bool spotted, bool filling)> CrewCarDict = new();
public static (bool spotted, bool filling) CrewCarStatus(Car car)
{
bool found = CrewCarDict.TryGetValue(car.id, out (bool spotted, bool filling) val);
if (!found) CrewCarDict.Add(car.id, (false, false));
return val;
}
static GameDateTime dateTime = TimeWeather.Now;
static readonly IEnumerable<Type> refillLocations =
new List<Type>() {
typeof(PassengerStop),
typeof(SimplePassengerStop),
typeof(TeamTrack),
typeof(RepairTrack)
};
public static Load CrewHoursLoad()
{
Load load = (Load)ScriptableObject.CreateInstance(typeof(Load));
load.name = "crew-hours";
load.description = "Crew";
load.units = LoadUnits.Quantity;
return load;
}
private static void CarLoadCrewHelper(Car car, float deltaTime)
{
float rate2 = 24 * 2 * 8;// carLoadRate = 8 crew hours in 30 min loading; (24h * 2 to get half hour chunks * 8 hours to load in those chunks)
float num2 = 99999999; //QuantityInStorage for crew-hours (infinite where crew can be shuffling about)
float quantityToLoad = Mathf.Min(num2, IndustryComponent.RateToValue(rate2, deltaTime));
if (car.IsCaboose() && !CrewCarStatus(car).spotted)
{
CrewCarDict[car.id] = (true, CrewCarDict[car.id].filling);
}
if (car.IsCabooseAndStoppedForLoadRefresh())
{
if (!CrewCarDict[car.id].filling) Multiplayer.Broadcast($"{Hyperlink.To(car)}: \"Topping off caboose crew.\"");
CrewCarDict[car.id] = (CrewCarDict[car.id].spotted, true);
var data = car.QuantityCapacityOfLoad(CrewHoursLoad());
if ((data.quantity + quantityToLoad > data.capacity) && data.quantity < data.capacity)
{
Multiplayer.Broadcast($"{Hyperlink.To(car)}: \"Caboose crew topped off.\"");
CrewCarDict[car.id] = (CrewCarDict[car.id].spotted, false);
}
new OpsCarAdapter(car, OpsController.Shared).Load(CrewHoursLoad(), quantityToLoad);
}
}
public static bool Prefix(IndustryComponent __instance)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!StateManager.IsHost || !tweaksAndThings.IsEnabled || !(tweaksAndThings?.settings?.EndGearHelpersRequirePayment ?? false)) return true;
TrainController tc = UnityEngine.Object.FindAnyObjectByType<TrainController>();
try {
var passengerStops = OpsController.Shared.AllIndustries
.SelectMany(i => i.TrackDisplayables.Where(t => refillLocations.Contains(t.GetType())));
//Log.Information($"{nameof(OpsController_AnnounceCoalescedPayments_Patch)} => Caboose Helper => PassengerStops => {string.Join(",", passengerStops)}");
var cabeese = passengerStops
.SelectMany(t => t.TrackSpans?.Select(s => (tc.CarsOnSpan(s) ?? Enumerable.Empty<Car>()).Where(c => c.IsCaboose()))?.SelectMany(c => c?.Select(c2 => (t, c2))));
//Log.Information($"{nameof(OpsController_AnnounceCoalescedPayments_Patch)} => Caboose Helper => PassengerStops Cabeese => {string.Join(",", cabeese?.Select(c => $"{c.t} : {c.c2}") ?? [])}");
CrewCarDict = CrewCarDict.Where(kvp => cabeese.Select(c => c.c2.id).Contains(kvp.Key)).ToDictionary(k => k.Key, v => v.Value);
var deltaTime = (float)(TimeWeather.Now.TotalSeconds - dateTime.TotalSeconds);
foreach (var caboose in cabeese)
{
//Log.Information($"{nameof(OpsController_AnnounceCoalescedPayments_Patch)} => Caboose Helper ({deltaTime}) => {caboose.t} : {caboose.c2}");
CarLoadCrewHelper(caboose.c2, deltaTime);
}
dateTime = TimeWeather.Now;
} catch (System.Exception ex)
{
Log.Error(ex, "error with announce caboose helper");
}
return true;
}
}

View File

@@ -1,11 +1,11 @@
using HarmonyLib;
using Model;
using Model.OpsNew;
using Model.Ops;
using Railloader;
using RMROC451.TweaksAndThings.Extensions;
using UI;
using System.Collections.Generic;
using System.Linq;
using UI.Tags;
using UnityEngine;
namespace RMROC451.TweaksAndThings.Patches;
@@ -19,7 +19,6 @@ internal class TagController_UpdateTag_Patch
private static void Postfix(Car car, TagCallout tagCallout)
{
TagController tagController = UnityEngine.Object.FindObjectOfType<TagController>();
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled || !tweaksAndThings.settings.HandBrakeAndAirTagModifiers)
@@ -27,31 +26,25 @@ internal class TagController_UpdateTag_Patch
return;
}
ProceedWithPostFix(car, tagCallout, tagController);
ProceedWithPostFix(car, tagCallout);
return;
}
private static void ProceedWithPostFix(Car car, TagCallout tagCallout, TagController tagController)
private static void ProceedWithPostFix(Car car, TagCallout tagCallout)
{
bool isAltDownWithCarIssue = GameInput.IsAltDown && car.CarOrEndGearIssue();
tagCallout.callout.Title = string.Format(tagTitleFormat, "{0}", car.DisplayName);
tagCallout.gameObject.SetActive(
tagCallout.gameObject.activeSelf &&
(!GameInput.IsAltDown || isAltDownWithCarIssue)
);
List<string> tags = new();
if (tagCallout.gameObject.activeSelf && isAltDownWithCarIssue)
{
tagController.ApplyImageColor(tagCallout, Color.black);
}
if (OpsController_AnnounceCoalescedPayments_Patch.CrewCarStatus(car).spotted) tags.Add("+");
if (car.HasHotbox) tags.Add(TextSprites.Hotbox);
if (car.EndAirSystemIssue()) tags.Add(TextSprites.CycleWaybills);
if (car.HandbrakeApplied()) tags.Add(TextSprites.HandbrakeWheel);
tagCallout.callout.Title =
(car.CarAndEndGearIssue(), car.EndAirSystemIssue(), car.HandbrakeApplied()) switch
tags.Any() switch
{
(true, _, _) => $"{tagCallout.callout.Title}{tagTitleAndIconDelimeter}{TextSprites.CycleWaybills}{TextSprites.HandbrakeWheel}".Replace("{0}", "2"),
(_, true, _) => $"{tagCallout.callout.Title}{tagTitleAndIconDelimeter}{TextSprites.CycleWaybills}".Replace("{0}", "1"),
(_, _, true) => $"{tagCallout.callout.Title}{tagTitleAndIconDelimeter}{TextSprites.HandbrakeWheel}".Replace("{0}", "1"),
true => $"{tagCallout.callout.Title}{tagTitleAndIconDelimeter}{string.Join("", tags)}".Replace("{0}", tags.Count().ToString()),
_ => car.DisplayName
};
}

View File

@@ -0,0 +1,20 @@
using HarmonyLib;
using Railloader;
using UI.ContextMenu;
using UnityEngine.UI;
namespace RMROC451.TweaksAndThings.Patches;
[HarmonyPatch(typeof(WedgeImage))]
[HarmonyPatch(nameof(WedgeImage.OnPopulateMesh), typeof(VertexHelper))]
[HarmonyPatchCategory("RMROC451TweaksAndThings")]
internal class WedgeImage_OnPopulateMesh_Patch
{
private static void Postfix(VertexHelper vh)
{
TweaksAndThingsPlugin tweaksAndThings = SingletonPluginBase<TweaksAndThingsPlugin>.Shared;
if (!tweaksAndThings.IsEnabled) return;
vh.Clear(); //clear the image backgrounds for now.
}
}

View File

@@ -2,6 +2,9 @@
using System.Collections.Generic;
using System.Linq;
using RMROC451.TweaksAndThings.Enums;
using UI.Builder;
using Model;
using RMROC451.TweaksAndThings.Extensions;
namespace RMROC451.TweaksAndThings;
@@ -18,23 +21,30 @@ public class Settings
List<WebhookSettings> webhookSettingsList,
bool handBrakeAndAirTagModifiers,
RosterFuelColumnSettings engineRosterFuelColumnSettings,
bool endGearHelpersRequirePayment
bool endGearHelpersRequirePayment,
bool requireConsistCabooseForOilerAndHotboxSpotter,
bool cabooseAllowsConsistInfo
)
{
WebhookSettingsList = webhookSettingsList;
HandBrakeAndAirTagModifiers = handBrakeAndAirTagModifiers;
EngineRosterFuelColumnSettings = engineRosterFuelColumnSettings;
EndGearHelpersRequirePayment = endGearHelpersRequirePayment;
RequireConsistCabooseForOilerAndHotboxSpotter = requireConsistCabooseForOilerAndHotboxSpotter;
CabooseAllowsConsistInfo = cabooseAllowsConsistInfo;
}
public readonly UIState<string> _selectedTabState = new UIState<string>(null);
public List<WebhookSettings>? WebhookSettingsList;
public bool HandBrakeAndAirTagModifiers;
public RosterFuelColumnSettings? EngineRosterFuelColumnSettings;
public bool EndGearHelpersRequirePayment;
public bool RequireConsistCabooseForOilerAndHotboxSpotter;
public bool CabooseAllowsConsistInfo;
internal void AddAnotherRow()
{
WebhookSettingsList = !WebhookSettingsList?.Any() ?? false ? new[] { new WebhookSettings() }.ToList() : new List<WebhookSettings>();
WebhookSettingsList ??= new[] { new WebhookSettings() }.ToList();
if (!string.IsNullOrEmpty(WebhookSettingsList.OrderByDescending(wsl => wsl.WebhookUrl).Last().WebhookUrl))
{
WebhookSettingsList.Add(new());
@@ -77,3 +87,27 @@ public class RosterFuelColumnSettings
public bool EngineRosterShowsFuelStatusAlways;
public EngineRosterFuelDisplayColumn EngineRosterFuelStatusColumn;
}
public static class SettingsExtensions
{
public static List<WebhookSettings> SanitizeEmptySettings(this IEnumerable<WebhookSettings>? settings)
{
List<WebhookSettings> output =
settings?.Where(s => !string.IsNullOrEmpty(s.WebhookUrl))?.ToList() ??
new();
output.Add(new());
return output;
}
public static bool CabooseAllowsConsistInfo(this TweaksAndThingsPlugin input) =>
input?.settings?.CabooseAllowsConsistInfo ?? false;
public static bool EndGearHelpersRequirePayment(this TweaksAndThingsPlugin input) =>
input?.settings?.EndGearHelpersRequirePayment ?? false;
public static bool RequireConsistCabooseForOilerAndHotboxSpotter(this TweaksAndThingsPlugin input) =>
input?.settings?.RequireConsistCabooseForOilerAndHotboxSpotter ?? false;
public static bool CabooseNonMotiveAllowedSetting(this TweaksAndThingsPlugin input, Car car) =>
input.EndGearHelpersRequirePayment() && car.set.Cars.CabooseInConsist() && car.NotMotivePower();
}

View File

@@ -78,16 +78,82 @@ public class TweaksAndThingsPlugin : SingletonPluginBase<TweaksAndThingsPlugin>,
if (!settings?.WebhookSettingsList?.Any() ?? true) settings.WebhookSettingsList = new[] { new WebhookSettings() }.ToList();
if (settings?.EngineRosterFuelColumnSettings == null) settings.EngineRosterFuelColumnSettings = new();
//WebhookUISection(ref builder);
//builder.AddExpandingVerticalSpacer();
WebhooksListUISection(ref builder);
builder.AddExpandingVerticalSpacer();
HandbrakesAndAnglecocksUISection(ref builder);
builder.AddExpandingVerticalSpacer();
EnginRosterShowsFuelStatusUISection(ref builder);
settings.WebhookSettingsList =
settings?.WebhookSettingsList.SanitizeEmptySettings();
builder.AddTabbedPanels(settings._selectedTabState, delegate (UITabbedPanelBuilder tabBuilder)
{
tabBuilder.AddTab("Caboose Mods", "cabooseUpdates", CabooseMods);
tabBuilder.AddTab("UI", "rosterUi", UiUpdates);
tabBuilder.AddTab("Webhooks", "webhooks", WebhooksListUISection);
});
}
private void EnginRosterShowsFuelStatusUISection(ref UIPanelBuilder builder)
private static string cabooseUse => "Caboose Use";
private static string autoAiRequirment => "AutoAI\nRequirement";
private void CabooseMods(UIPanelBuilder builder)
{
builder.AddField(
cabooseUse,
builder.AddToggle(
() => settings?.EndGearHelpersRequirePayment ?? false,
delegate (bool enabled)
{
if (settings == null) settings = new();
settings.EndGearHelpersRequirePayment = enabled;
builder.Rebuild();
}
)
).Tooltip("Enable End Gear Helper Cost", @$"Will cost 1 minute of AI Brake Crew & Caboose Crew time per car in the consist when the new inspector buttons are utilized.
1.5x multiplier penalty to AI Brake Crew cost if no sufficiently crewed caboose nearby.
Caboose starts reloading `Crew Hours` at any Team or Repair track (no waybill), after being stationary for 30 seconds.
AutoOiler Update: Increases limit that crew will oiling a car from 75% -> 99%, also halves the time it takes (simulating crew from lead end and caboose handling half the train).
AutoOiler Update: if `{cabooseUse}` & `{autoAiRequirment.Replace("\n", " ")}` checked, then when a caboose is present, the AutoOiler will repair hotboxes afer oiling them to 100%.
AutoHotboxSpotter Update: decrease the random wait from 30 - 300 seconds to 15 - 30 seconds (Safety Is Everyone's Job)");
builder.AddField(
autoAiRequirment,
builder.AddToggle(
() => settings?.RequireConsistCabooseForOilerAndHotboxSpotter ?? false,
delegate (bool enabled)
{
if (settings == null) settings = new();
settings.RequireConsistCabooseForOilerAndHotboxSpotter = enabled;
builder.Rebuild();
}
)
).Tooltip("AI Engineer Requires Caboose", $@"A caboose is required in the consist to check for Hotboxes and perform Auto Oiler, if checked.");
}
private void UiUpdates(UIPanelBuilder builder)
{
builder.AddField(
"Enable Tag Updates",
builder.AddToggle(
() => settings?.HandBrakeAndAirTagModifiers ?? false,
delegate (bool enabled)
{
if (settings == null) settings = new();
settings.HandBrakeAndAirTagModifiers = enabled;
builder.Rebuild();
}
)
).Tooltip("Enable Tag Updates", $@"Will suffix tag title with:
{TextSprites.CycleWaybills} if Air System issue.
{TextSprites.HandbrakeWheel} if there is a handbrake set.
{TextSprites.Hotbox} if a hotbox.");
EngineRosterShowsFuelStatusUISection(builder);
}
private void EngineRosterShowsFuelStatusUISection(UIPanelBuilder builder)
{
var columns = Enum.GetValues(typeof(EngineRosterFuelDisplayColumn)).Cast<EngineRosterFuelDisplayColumn>().Select(i => i.ToString()).ToList();
builder.AddSection("Fuel Display in Engine Roster", delegate (UIPanelBuilder builder)
@@ -119,39 +185,7 @@ public class TweaksAndThingsPlugin : SingletonPluginBase<TweaksAndThingsPlugin>,
});
}
private void HandbrakesAndAnglecocksUISection(ref UIPanelBuilder builder)
{
builder.AddSection("Tag Callout Handbrake and Air System Helper", delegate (UIPanelBuilder builder)
{
builder.AddField(
"Enable Tag Updates",
builder.AddToggle(
() => settings?.HandBrakeAndAirTagModifiers ?? false,
delegate (bool enabled)
{
if (settings == null) settings = new();
settings.HandBrakeAndAirTagModifiers = enabled;
builder.Rebuild();
}
)
).Tooltip("Enable Tag Updates", $"Will add {TextSprites.CycleWaybills} to the car tag title having Air System issues. Also prepends {TextSprites.HandbrakeWheel} if there is a handbrake set.\n\nHolding Left Alt while tags are displayed only shows tag titles that have issues.");
builder.AddField(
"Caboose Use",
builder.AddToggle(
() => settings?.EndGearHelpersRequirePayment ?? false,
delegate (bool enabled)
{
if (settings == null) settings = new();
settings.EndGearHelpersRequirePayment = enabled;
builder.Rebuild();
}
)
).Tooltip("Enable End Gear Helper Cost", $"Will cost 1 minute of AI Brake Crew & Caboose Crew time per car in the consist when the new inspector buttons are utilized.\n\n1.5x multiplier penalty to AI Brake Crew cost if no sufficiently crewed caboose nearby.\n\nCaboose starts reloading `Crew Hours` at any Team or Repair track (no waybill), after being stationary for 30 seconds.");
});
}
private void WebhooksListUISection(ref UIPanelBuilder builder)
private void WebhooksListUISection(UIPanelBuilder builder)
{
builder.AddSection("Webhooks List", delegate (UIPanelBuilder builder)
{

12
updates.json Normal file
View File

@@ -0,0 +1,12 @@
{
"RMROC451.TweaksAndThings": {
"version": "1.0.0",
"changelog": [
{
"version": "*",
"date": "2024-07-26T14:31:49.0948925Z",
"desc": "https://github.com/rmroc451/TweaksAndThings/releases"
}
]
}
}