commit 017174ac53d6f2852914d9ce7e7f17cdb78887b2 Author: zznty <94796179+zznty@users.noreply.github.com> Date: Wed Nov 16 22:56:13 2022 +0700 first diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7f25aed --- /dev/null +++ b/.gitignore @@ -0,0 +1,365 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +TorchBinaries \ No newline at end of file diff --git a/AreaJumpDepleter.sln b/AreaJumpDepleter.sln new file mode 100644 index 0000000..37a480f --- /dev/null +++ b/AreaJumpDepleter.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AreaJumpDepleter", "AreaJumpDepleter\AreaJumpDepleter.csproj", "{CA91AC84-36AD-4C1D-92C0-7388DC872CEF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CA91AC84-36AD-4C1D-92C0-7388DC872CEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CA91AC84-36AD-4C1D-92C0-7388DC872CEF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CA91AC84-36AD-4C1D-92C0-7388DC872CEF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CA91AC84-36AD-4C1D-92C0-7388DC872CEF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/AreaJumpDepleter/AreaJumpDepleter.csproj b/AreaJumpDepleter/AreaJumpDepleter.csproj new file mode 100644 index 0000000..3a7e376 --- /dev/null +++ b/AreaJumpDepleter/AreaJumpDepleter.csproj @@ -0,0 +1,27 @@ + + + + net48 + enable + enable + x64 + 11 + true + + + + none + + + + + + + + + + PreserveNewest + + + + diff --git a/AreaJumpDepleter/Commands.cs b/AreaJumpDepleter/Commands.cs new file mode 100644 index 0000000..aa74ae2 --- /dev/null +++ b/AreaJumpDepleter/Commands.cs @@ -0,0 +1,59 @@ +using System.Text; +using AreaJumpDepleter.Managers; +using Torch.API.Managers; +using Torch.Commands; + +namespace AreaJumpDepleter; + +[Category("jp")] +public class Commands : CommandModule +{ + private Config Config => ((Plugin)Context.Plugin).Cfg; + private AreaManager Manager => Context.Torch.CurrentSession.Managers.GetManager(); + + [Command("area list", "Lists all deplete areas")] + public void List() + { + var sb = new StringBuilder("Areas:\n"); + foreach (var area in Config.Areas) + { + sb.AppendLine($"{area.Name}: pos {area.Position} radius {area.Radius}"); + } + Context.Respond(sb.ToString()); + } + + [Command("area delete", "Delete deplete area by name")] + public void Delete(string name) + { + if (Config.Areas.FirstOrDefault( + b => b.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) is not { } area) return; + Manager.RemoveArea(area); + Config.Areas.Remove(area); + Config.RefreshModel(); + Context.Respond($"Successfully deleted {name}"); + } + + [Command("area create", "Create area from character position")] + public void Create(string name, float radius) + { + if (Context.Player is null) + { + Context.Respond("From console, please use !jp area create "); + return; + } + + var area = new DepleteArea + { + Name = name, + Radius = radius, + Position = Context.Player.GetPosition() + }; + + Config.Areas.Add(area); + Config.RefreshModel(); + + Manager.AddArea(area); + Context.Respond($"Successfully created {name}"); + Context.Respond($"GPS:{name}:{area.Position.X}:{area.Position.Y}:{area.Position.Z}"); + } +} \ No newline at end of file diff --git a/AreaJumpDepleter/Config.cs b/AreaJumpDepleter/Config.cs new file mode 100644 index 0000000..9ac61ed --- /dev/null +++ b/AreaJumpDepleter/Config.cs @@ -0,0 +1,43 @@ +using System.Collections.ObjectModel; +using Torch; +using Torch.Views; +using VRageMath; + +#nullable disable +namespace AreaJumpDepleter; + +public class Config : ViewModel +{ + public ObservableCollection Areas { get; set; } = new(); + [Display(Name = "Over Time Multiplier", Description = "stores percents - minutes spent in zone * multiplier * discharge rate")] + public double OverTimeMultiplier { get; set; } = 0; + [Display(Name = "Discharge Rate", Description = "stores percents - minutes spent in zone * multiplier * discharge rate")] + public double DischargeRate { get; set; } = 0.0006944444444444444; +} + +public class DepleteArea : ViewModel, IEquatable +{ + public Vector3D Position { get; set; } + public float Radius { get; set; } + public string Name { get; set; } + + public bool Equals(DepleteArea other) + { + if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(this, other)) return true; + return Name == other.Name; + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != this.GetType()) return false; + return Equals((DepleteArea)obj); + } + + public override int GetHashCode() + { + return (Name != null ? Name.GetHashCode() : 0); + } +} \ No newline at end of file diff --git a/AreaJumpDepleter/FodyWeavers.xml b/AreaJumpDepleter/FodyWeavers.xml new file mode 100644 index 0000000..d5abfed --- /dev/null +++ b/AreaJumpDepleter/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/AreaJumpDepleter/Managers/AreaManager.cs b/AreaJumpDepleter/Managers/AreaManager.cs new file mode 100644 index 0000000..d1cf16b --- /dev/null +++ b/AreaJumpDepleter/Managers/AreaManager.cs @@ -0,0 +1,134 @@ +using System.Runtime.CompilerServices; +using AreaJumpDepleter.Patches; +using AreaJumpDepleter.Utils; +using Sandbox.Game.Entities; +using Torch.API; +using Torch.Managers; +using Torch.Mod; +using Torch.Mod.Messages; +using VRage.Game; +using VRage.Game.Entity; + +namespace AreaJumpDepleter.Managers; + +public class AreaManager : Manager +{ + private readonly Config _config; + private readonly Dictionary _areas = new(); + + private readonly ConditionalWeakTable _states = new(); + + public AreaManager(ITorchBase torchInstance, Config config) : base(torchInstance) + { + _config = config; + } + + public void AddArea(DepleteArea area) + { + if (_areas.ContainsKey(area)) + throw new InvalidOperationException($"Area with name {area.Name} already exists"); + + var triggerArea = new TriggerArea(new(area.Position, area.Radius)); + _areas.Add(area, triggerArea); + + triggerArea.Create(); + triggerArea.EntityEntered += (sender, entity) => + { + if (entity is not MyCubeGrid grid) return; + + foreach (var drive in grid.GridSystems.TerminalSystem.Blocks.OfType()) + { + _states.GetOrCreateValue(drive).Area = area; + } + + /*foreach (var cockpit in grid.GridSystems.TerminalSystem.Blocks.OfType()) + { + if (cockpit.Pilot is { ControlSteamId: { } steamId }) + ModCommunication.SendMessageTo(new NotificationMessage($"Entering {area.Name}", 15000, MyFontEnum.Red), steamId); + }*/ + }; + triggerArea.EntityLeft += TriggerAreaOnEntityLeft; + } + + private void TriggerAreaOnEntityLeft(object sender, MyEntity e) + { + if (e is not MyCubeGrid grid) return; + + foreach (var drive in grid.GridSystems.TerminalSystem.Blocks.OfType()) + { + if (_states.TryGetValue(drive, out var state)) + state.Area = null; + } + } + + public void RemoveArea(DepleteArea area) + { + if (!_areas.TryGetValue(area, out var trigger)) + throw new KeyNotFoundException($"Area with name {area.Name} not found"); + + trigger.Dispose(); + _areas.Remove(area); + } + + public override void Attach() + { + foreach (var area in _config.Areas) + { + AddArea(area); + } + JumpDriveUpdatePatch.Deplete += JumpDriveUpdatePatchOnDeplete; + } + + private float? JumpDriveUpdatePatchOnDeplete(MyJumpDrive drive, float storedPower) + { + if (!_states.TryGetValue(drive, out var state)) + return null; + + state.Update(); + + if (_config.OverTimeMultiplier == 0) + return (float)(storedPower - _config.DischargeRate); + + return (float)(storedPower - state.Duration.TotalMinutes * _config.OverTimeMultiplier * _config.DischargeRate); + } + + public override void Detach() + { + foreach (var triggerArea in _areas.Values) + { + triggerArea.Dispose(); + } + } + + private class State + { + private DepleteArea? _area; + + public DepleteArea? Area + { + get => _area; + set + { + _area = value; + if (_area is not null) + LastEnterTime = DateTime.Now; + } + } + + public DateTime? LastEnterTime { get; set; } + public TimeSpan Duration { get; set; } + public bool IsInside => Area is not null; + + public void Update() + { + if (LastEnterTime is not null && IsInside) + Duration = DateTime.Now - LastEnterTime.Value; + else if (Duration > TimeSpan.Zero) + { + Duration -= TimeSpan.FromSeconds(10); + if (Duration < TimeSpan.Zero) + Duration = TimeSpan.Zero; + } + } + } +} \ No newline at end of file diff --git a/AreaJumpDepleter/Patches/JumpDriveUpdatePatch.cs b/AreaJumpDepleter/Patches/JumpDriveUpdatePatch.cs new file mode 100644 index 0000000..d764d7c --- /dev/null +++ b/AreaJumpDepleter/Patches/JumpDriveUpdatePatch.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using Sandbox.Game.Entities; +using Torch.Managers.PatchManager; +using Torch.Utils; +using VRage.Sync; + +namespace AreaJumpDepleter.Patches; + +[PatchShim] +public static class JumpDriveUpdatePatch +{ + [ReflectedMethodInfo(typeof(MyJumpDrive), nameof(MyJumpDrive.UpdateAfterSimulation100))] + private static readonly MethodInfo UpdateMethod = null!; + + [ReflectedMethodInfo(typeof(JumpDriveUpdatePatch), nameof(Suffix))] + private static readonly MethodInfo SuffixMethod = null!; + + public static event Func? Deplete; + + public static void Patch(PatchContext context) + { + context.GetPattern(UpdateMethod).Suffixes.Add(SuffixMethod); + } + + private static void Suffix(MyJumpDrive __instance, Sync __field_m_storedPower) + { + var value = Deplete?.Invoke(__instance, __field_m_storedPower.Value); + if (value is null) + return; + + __field_m_storedPower.Value = value.Value < 0 ? 0 : value.Value; + } +} \ No newline at end of file diff --git a/AreaJumpDepleter/Plugin.cs b/AreaJumpDepleter/Plugin.cs new file mode 100644 index 0000000..5a492b9 --- /dev/null +++ b/AreaJumpDepleter/Plugin.cs @@ -0,0 +1,32 @@ +using System.IO; +using System.Windows.Controls; +using AreaJumpDepleter.Managers; +using Torch; +using Torch.API; +using Torch.API.Managers; +using Torch.API.Plugins; +using Torch.API.Session; +using Torch.Views; + +namespace AreaJumpDepleter; + +public class Plugin : TorchPluginBase, IWpfPlugin +{ + private Persistent _config = null!; + + public Config Cfg => _config.Data; + + public override void Init(ITorchBase torch) + { + base.Init(torch); + _config = Persistent.Load(Path.Combine(StoragePath, "AreaJumpDepleter.cfg")); + + Torch.Managers.GetManager().AddFactory(s => new AreaManager(s.Torch, Cfg)); + } + + public UserControl GetControl() => new PropertyGrid + { + Margin = new(3), + DataContext = _config.Data + }; +} \ No newline at end of file diff --git a/AreaJumpDepleter/Utils/TriggerArea.cs b/AreaJumpDepleter/Utils/TriggerArea.cs new file mode 100644 index 0000000..1c4724c --- /dev/null +++ b/AreaJumpDepleter/Utils/TriggerArea.cs @@ -0,0 +1,116 @@ +using Havok; +using Sandbox.Engine.Physics; +using Sandbox.Game.Entities; +using VRage; +using VRage.Game.Components; +using VRage.Game.Entity; +using VRage.ObjectBuilders; +using VRageMath; + +namespace AreaJumpDepleter.Utils; + +public class TriggerArea : IDisposable, IEquatable +{ + private Dummy? _entity; + public BoundingSphere Sphere { get; } + + public event EventHandler? EntityEntered; + public event EventHandler? EntityLeft; + + public TriggerArea(BoundingSphere sphere) + { + Sphere = sphere; + } + + public void Create() + { + _entity = new Dummy(Sphere, EnterHandler, ExitHandler); + _entity.Init(null); + MyEntities.Add(_entity); + } + + private void ExitHandler(MyEntity entity) + { + EntityEntered?.Invoke(this, entity); + } + + private void EnterHandler(MyEntity entity) + { + EntityLeft?.Invoke(this, entity); + } + + public void Dispose() + { + if (_entity != null) + MyEntities.Close(_entity); + } + + public bool Equals(TriggerArea? other) + { + if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(this, other)) return true; + return Sphere.Equals(other.Sphere); + } + + public override bool Equals(object? obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != this.GetType()) return false; + return Equals((TriggerArea)obj); + } + + public override int GetHashCode() + { + return Sphere.GetHashCode(); + } + + private class Dummy : MyEntity + { + private readonly BoundingSphere _sphere; + private readonly Action _enterHandler; + private readonly Action _exitHandler; + + public Dummy(BoundingSphere sphere, Action enterHandler, Action exitHandler) + { + _sphere = sphere; + _enterHandler = enterHandler; + _exitHandler = exitHandler; + } + + public override void Init(MyObjectBuilder_EntityBase? objectBuilder) + { + base.Init(objectBuilder); + PositionComp.LocalAABB = BoundingBox.CreateFromSphere(_sphere); + + Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_STATIC); + Physics.IsPhantom = true; + + var phantom = new HkPhantomCallbackShape(EnterCallback, LeaveCallback); + var shape = new HkBvShape(new HkSphereShape(_sphere.Radius), phantom, HkReferencePolicy.TakeOwnership); + + ((MyPhysicsBody)Physics).CreateFromCollisionObject(shape, _sphere.Center, MatrixD.Identity); + shape.Base.RemoveReference(); + + Physics.Enabled = true; + + BoundingSphereD sphere = _sphere; + foreach (var entity in MyEntities.GetTopMostEntitiesInSphere(ref sphere)) + { + _enterHandler(entity); + } + } + + private void LeaveCallback(HkPhantomCallbackShape shape, HkRigidBody body) + { + if (body.GetSingleEntity() is MyEntity entity) + _exitHandler(entity); + } + + private void EnterCallback(HkPhantomCallbackShape shape, HkRigidBody body) + { + if (body.GetSingleEntity() is MyEntity entity) + _enterHandler(entity); + } + } +} \ No newline at end of file diff --git a/AreaJumpDepleter/manifest.xml b/AreaJumpDepleter/manifest.xml new file mode 100644 index 0000000..de69f05 --- /dev/null +++ b/AreaJumpDepleter/manifest.xml @@ -0,0 +1,6 @@ + + + AreaJumpDepleter + 208FCD32-71CB-4184-86C3-11C557E7AC35 + v1.0.0 + \ No newline at end of file