Merge branch 'refs/heads/master' into modifiers

# Conflicts:
#	MiraAPI.Example/Buttons/ExampleButton.cs
#	MiraAPI.Example/ExampleRole.cs
#	MiraAPI/GameOptions/OptionTypes/ModdedOption.cs
#	MiraAPI/Hud/CustomActionButton.cs
#	MiraAPI/MiraApiPlugin.cs
#	MiraAPI/Patches/Options/RoleSettingMenuPatches.cs
#	MiraAPI/Patches/PlayerControlPatches.cs
#	MiraAPI/PluginLoading/MiraPluginManager.cs
#	MiraAPI/Roles/ICustomRole.cs
#	MiraAPI/Utilities/Extensions.cs
This commit is contained in:
XtraCube committed 2024-08-27 14:43:05 -04:00
commit 625cd2ca4b
80 files changed
+2363 -586

No files matched your search

+504
View File
@@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
@@ -4,7 +4,7 @@ using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using UnityEngine;
namespace MiraAPI.Example;
namespace MiraAPI.Example.Buttons;
[RegisterButton]
public class ExampleButton : CustomActionButton
@@ -13,7 +13,8 @@ public class ExampleButton : CustomActionButton
public override float Cooldown => 5f;
public override float EffectDuration => 0f;
public override int MaxUses => 5;
public override LoadableAsset<Sprite> Sprite { get; } = new LoadableResourceAsset("MiraAPI.Resources.ExampleButton.png");
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
public override ButtonLocation Location => ButtonLocation.BottomRight;
protected override void OnClick()
{
@@ -0,0 +1,40 @@
using MiraAPI.Hud;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.Buttons;
public class ExampleTargetButton : CustomActionButton<PlayerControl>
{
public override string Name => "Shoot";
public override float Cooldown => 0f;
public override float EffectDuration => 0f;
public override int MaxUses => 0;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
protected override void OnClick()
{
PlayerControl.LocalPlayer.CmdCheckMurder(Target);
}
public override PlayerControl GetTarget()
{
return PlayerControl.LocalPlayer.Data.Role.FindClosestTarget();
}
public override void SetOutline(bool active)
{
Target?.cosmetics.SetOutline(active, new Il2CppSystem.Nullable<Color>(Color.red));
}
public override bool IsTargetValid(PlayerControl target)
{
return PlayerControl.LocalPlayer.Data.Role.IsValidTarget(target.Data);
}
public override bool Enabled(RoleBehaviour role)
{
return role.IsImpostor;
}
}
+9
View File
@@ -0,0 +1,9 @@
using MiraAPI.Utilities.Assets;
namespace MiraAPI.Example;
public static class ExampleAssets
{
public static LoadableResourceAsset ExampleButton { get; } = new("MiraAPI.Example.Resources.ExampleButton.png");
public static LoadableResourceAsset Banner { get; } = new("MiraAPI.Example.Resources.FortniteBanner.jpeg");
}
+2 -1
View File
@@ -9,7 +9,7 @@ using Reactor.Networking.Attributes;
namespace MiraAPI.Example;
[BepInAutoPlugin("mira.example", "MiraAPIExample")]
[BepInAutoPlugin("mira.example", "MiraExampleMod")]
[BepInProcess("Among Us.exe")]
[BepInDependency(ReactorPlugin.Id)]
[BepInDependency(MiraApiPlugin.Id)]
@@ -17,6 +17,7 @@ namespace MiraAPI.Example;
public partial class ExamplePlugin : BasePlugin, IMiraPlugin
{
public Harmony Harmony { get; } = new(Id);
public string OptionsTitleText => "Mira API\nExample Mod";
public ConfigFile GetConfigFile() => Config;
public override void Load()
{
-16
View File
@@ -1,16 +0,0 @@
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example;
[RegisterCustomRole]
public class ExampleRole : ImpostorRole, ICustomRole
{
public string RoleName => "fortnite killer";
public string RoleLongDescription => "ok so your objective is to eliminate everyone \nwith your fortnite tactical shotgun";
public string RoleDescription => RoleLongDescription;
public Color RoleColor => Palette.Orange;
public ModdedRoleTeams Team => ModdedRoleTeams.Impostor;
public LoadableAsset<Sprite> OptionsScreenshot => MiraAssets.Empty;
}
+11 -12
View File
@@ -6,20 +6,14 @@
<VersionPrefix>1.0.0</VersionPrefix>
<VersionSuffix>dev</VersionSuffix>
<Description>Simple and easy to use Among Us modding API.</Description>
<Description>Example mod for Mira API</Description>
<Authors>Angxl, XtraCube</Authors>
</PropertyGroup>
<PropertyGroup>
<GamePlatform Condition="'$(GamePlatform)' == ''">Steam</GamePlatform>
<GameVersion Condition="'$(GamePlatform)' == 'Steam'">2024.6.18</GameVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Reactor" Version="2.3.0" />
<PackageReference Include="Reactor" Version="2.3.1" />
<PackageReference Include="BepInEx.Unity.IL2CPP" Version="6.0.0-be.697" Private="false" ExcludeAssets="runtime;native" />
<PackageReference Include="Iced" Version="1.21.0" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="$(GameVersion)" PrivateAssets="all" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2024.8.13" PrivateAssets="all" />
<PackageReference Include="BepInEx.AutoPlugin" Version="1.1.0" PrivateAssets="all" />
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.1.0-rc.1" PrivateAssets="all" ExcludeAssets="runtime">
@@ -28,10 +22,15 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MiraAPI\MiraAPI.csproj" />
<ProjectReference Include="..\MiraAPI\MiraAPI.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\ExampleButton.png" />
<EmbeddedResource Include="Resources\FortniteBanner.jpeg" />
</ItemGroup>
<Target Name="Copy" AfterTargets="Build" Condition="'$(AmongUs)' != ''">
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(AmongUs)/BepInEx/plugins/" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(AmongUs)/BepInEx/plugins/" UseSymboliclinksIfPossible="true" />
</Target>
</Project>
+33
View File
@@ -0,0 +1,33 @@
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using UnityEngine;
namespace MiraAPI.Example.Options;
public class ExampleOptions : AbstractOptionGroup
{
public override string GroupName => "Example Options 1";
public override Color GroupColor => Color.green;
[ModdedToggleOption("Toggle Opt 1")]
public bool ToggleOpt { get; set; } = false;
[ModdedToggleOption("Toggle Opt 2")]
public bool ToggleOpt2 { get; set; } = true;
[ModdedNumberOption("Number Opt", min: 0, max: 10)]
public float NumberOpt { get; set; } = 4f;
[ModdedStringOption("String Opt", ["Hello", "Hey", "Bye"])]
public int StringOpt { get; set; } = 2;
[ModdedEnumOption("Enum Opt", typeof(TestEnum))]
public TestEnum EnumOpt { get; set; } = TestEnum.Mira;
}
public enum TestEnum
{
Welcome,
To,
Mira
}
@@ -0,0 +1,27 @@
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.Example.Options;
public class ExampleOptions2 : AbstractOptionGroup
{
public override string GroupName => "Example Options 2";
public ModdedToggleOption ToggleOpt1 { get; } = new("Toggle Option 1", false);
public ModdedToggleOption ToggleOpt2 { get; } = new("Toggle Option 2", false)
{
Visible = () => OptionGroupSingleton<ExampleOptions2>.Instance.ToggleOpt1.Value
};
public ModdedStringOption StringOpt { get; } = new("String Opt", 0, ["Choice 1", "Choice 2", "Choice 3"]);
public ModdedEnumOption EnumOpt { get; } = new("Enum Opt", 0, typeof(TestingEnum));
}
public enum TestingEnum
{
Happy,
Sad,
Neutral
}
@@ -0,0 +1,16 @@
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using System;
namespace MiraAPI.Example.Options.Roles;
public class CustomRole2Settings : AbstractOptionGroup
{
public override string GroupName => "Custom Role";
public override Type AdvancedRole => typeof(CustomRole2);
[ModdedToggleOption("Teleportation ability")] public bool Teleport { get; set; } = true;
}
@@ -0,0 +1,16 @@
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using System;
namespace MiraAPI.Example.Options.Roles;
public class CustomRoleSettings : AbstractOptionGroup
{
public override string GroupName => "Custom Role";
public override Type AdvancedRole => typeof(CustomRole);
[ModdedNumberOption("Number Opt", min: 3, max: 9)] public float NumberOpt { get; set; } = 4;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

+17
View File
@@ -0,0 +1,17 @@
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.Roles;
[RegisterCustomRole]
public class CustomRole : ImpostorRole, ICustomRole
{
public string RoleName => "Custom Role";
public string RoleLongDescription => "Eliminate everyone with your special ability!";
public string RoleDescription => RoleLongDescription;
public Color RoleColor => Palette.Black;
public ModdedRoleTeams Team => ModdedRoleTeams.Impostor;
public LoadableAsset<Sprite> OptionsScreenshot => ExampleAssets.Banner;
}
+17
View File
@@ -0,0 +1,17 @@
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.Roles;
[RegisterCustomRole]
public class CustomRole2 : CrewmateRole, ICustomRole
{
public string RoleName => "Custom Role 2";
public string RoleLongDescription => "Save everyone from dying!";
public string RoleDescription => RoleLongDescription;
public Color RoleColor => Palette.AcceptedGreen;
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
public LoadableAsset<Sprite> OptionsScreenshot => ExampleAssets.Banner;
}
+3 -3
View File
@@ -24,7 +24,7 @@ public static class CustomGameModeManager
/// <summary>
/// Current gamemode
/// </summary>
public static CustomGameMode? ActiveMode;
public static CustomGameMode? ActiveMode = new DefaultMode();
/// <summary>
/// Set current gamemode
@@ -45,11 +45,11 @@ public static class CustomGameModeManager
/// Register gamemode from type
/// </summary>
/// <param name="gameModeType">Type of gamemode class, should inherit from <see cref="CustomGameMode"/></param>
public static void RegisterGameMode(Type gameModeType)
internal static void RegisterGameMode(Type gameModeType)
{
if (!typeof(CustomGameMode).IsAssignableFrom(gameModeType))
{
Logger<MiraApiPlugin>.Warning($"{gameModeType?.Name} does not inherit CustomGameMode!");
Logger<MiraApiPlugin>.Warning($"{gameModeType.Name} does not inherit CustomGameMode!");
return;
}
@@ -9,9 +9,12 @@ public class RegisterGameModeAttribute : Attribute
{
private static readonly HashSet<Assembly> RegisteredAssemblies = [];
public static void Register(Assembly assembly)
internal static void Register(Assembly assembly)
{
if (!RegisteredAssemblies.Add(assembly)) return;
if (!RegisteredAssemblies.Add(assembly))
{
return;
}
foreach (var type in assembly.GetTypes())
{
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace MiraAPI.GameOptions;
public abstract class AbstractOptionGroup
{
public List<IModdedOption> Options { get; } = [];
/// <summary>
/// The name of the group. Visible in options menu.
/// </summary>
public abstract string GroupName { get; }
/// <summary>
/// A function that returns whether the group should be visible or not.
/// </summary>
public virtual Func<bool> GroupVisible => () => true;
/// <summary>
/// The group color. This is used to color the group in the options menu.
/// </summary>
public virtual Color GroupColor => Color.clear;
/// <summary>
/// The role the group is associated with. This is used for the advanced role options menu.
/// </summary>
public virtual Type AdvancedRole => null;
internal bool AllOptionsHidden = true;
internal CategoryHeaderMasked Header;
}
@@ -7,8 +7,7 @@ namespace MiraAPI.GameOptions.Attributes;
public class ModdedEnumOptionAttribute(string title, Type enumType, Type roleType = null)
: ModdedOptionAttribute(title, roleType)
{
public override IModdedOption CreateOption(object value, PropertyInfo property)
internal override IModdedOption CreateOption(object value, PropertyInfo property)
{
var opt = new ModdedEnumOption(Title, (int)value, enumType, RoleType);
return opt;
@@ -14,7 +14,7 @@ public class ModdedNumberOptionAttribute(
Type roleType = null)
: ModdedOptionAttribute(title, roleType)
{
public override IModdedOption CreateOption(object value, PropertyInfo property)
internal override IModdedOption CreateOption(object value, PropertyInfo property)
{
var toggleOpt = new ModdedNumberOption(Title, (float)value, min, max, increment, suffixType, zeroInfinity, RoleType);
return toggleOpt;
@@ -15,6 +15,6 @@ public abstract class ModdedOptionAttribute(string title, Type roleType = null)
public abstract void SetValue(object val);
public abstract object GetValue();
public abstract IModdedOption CreateOption(object value, PropertyInfo property);
internal abstract IModdedOption CreateOption(object value, PropertyInfo property);
}
@@ -7,7 +7,7 @@ namespace MiraAPI.GameOptions.Attributes;
public class ModdedStringOptionAttribute(string title, string[] values, Type roleType = null)
: ModdedOptionAttribute(title, roleType)
{
public override IModdedOption CreateOption(object value, PropertyInfo property)
internal override IModdedOption CreateOption(object value, PropertyInfo property)
{
var opt = new ModdedStringOption(Title, (int)value, values, RoleType);
return opt;
@@ -6,7 +6,7 @@ namespace MiraAPI.GameOptions.Attributes;
public class ModdedToggleOptionAttribute(string title, Type roleType = null) : ModdedOptionAttribute(title, roleType)
{
public override IModdedOption CreateOption(object value, PropertyInfo property)
internal override IModdedOption CreateOption(object value, PropertyInfo property)
{
var toggleOpt = new ModdedToggleOption(Title, (bool)value, RoleType);
return toggleOpt;
+3 -1
View File
@@ -1,5 +1,6 @@
using MiraAPI.PluginLoading;
using System;
using BepInEx.Configuration;
using MiraAPI.Networking;
using UnityEngine;
@@ -9,15 +10,16 @@ public interface IModdedOption
{
public uint Id { get; }
public BaseGameSetting Data { get; }
public IModdedOptionGroup Group { get; set; }
public IMiraPlugin ParentMod { get; set; }
public Type AdvancedRole { get; set; }
public OptionBehaviour OptionBehaviour { get; protected set; }
public string Title { get; }
public StringNames StringName { get; }
public Func<bool> Visible { get; set; }
public ConfigDefinition ConfigDefinition { get; }
public void ValueChanged(OptionBehaviour optionBehaviour);
public OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, Transform container);
public abstract float GetFloatData();
public NetData GetNetData();
public void HandleNetData(byte[] data);
}
-12
View File
@@ -1,12 +0,0 @@
using System;
using UnityEngine;
namespace MiraAPI.GameOptions;
public interface IModdedOptionGroup
{
public string GroupName { get; }
public Func<bool> GroupVisible => () => true;
public Color GroupColor => Color.clear;
public Type AdvancedRole => null;
}
+103 -70
View File
@@ -6,94 +6,129 @@ using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
using Reactor.Networking.Rpc;
namespace MiraAPI.GameOptions;
public static class ModdedOptionsManager
{
public static readonly Dictionary<uint, IModdedOption> ModdedOptions = new();
public static readonly List<IModdedOption> Options = [];
public static readonly List<IModdedOptionGroup> Groups = [];
private static readonly Dictionary<PropertyInfo, ModdedOptionAttribute> OptionAttributes = new();
public static readonly Dictionary<Type, IModdedOptionGroup> OriginalTypes = new();
public static uint NextId = 1;
private static readonly Dictionary<Type, AbstractOptionGroup> TypeToGroup = new();
public static IModdedOption RegisterOption(Type type, ModdedOptionAttribute attribute, PropertyInfo property)
public static readonly Dictionary<uint, IModdedOption> ModdedOptions = new();
public static readonly List<AbstractOptionGroup> Groups = [];
public static uint NextId => _nextId++;
private static uint _nextId = 1;
internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo)
{
if (OptionAttributes.ContainsKey(property)) return null;
object newObj = Activator.CreateInstance(type);
IModdedOption result;
try
{
result = attribute.CreateOption(property.GetValue(newObj), property);
}
catch (Exception e)
if (Activator.CreateInstance(type) is not AbstractOptionGroup group)
{
Logger<MiraApiPlugin>.Error(e);
return null;
Logger<MiraApiPlugin>.Error($"Failed to create group from {type.Name}");
return false;
}
if (result != null)
if (TypeToGroup.ContainsKey(type))
{
var setterOriginal = property.GetSetMethod();
var setterPatch = typeof(ModdedOptionsManager).GetMethod(nameof(PropertySetterPatch));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: new HarmonyMethod(setterPatch));
var getterOriginal = property.GetGetMethod();
var getterPatch = typeof(ModdedOptionsManager).GetMethod(nameof(PropertyGetterPatch));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: new HarmonyMethod(getterPatch));
attribute.HolderOption = result;
OptionAttributes.Add(property, attribute);
if (OriginalTypes.ContainsKey(type))
{
Logger<MiraApiPlugin>.Error($"Grouping {attribute.Title} with {OriginalTypes[type].GroupName}");
result.Group = OriginalTypes[type];
result.AdvancedRole = OriginalTypes[type].AdvancedRole;
}
Logger<MiraApiPlugin>.Error($"Group {type.Name} already exists.");
return false;
}
return result;
Groups.Add(group);
TypeToGroup.Add(type, group);
pluginInfo.OptionGroups.Add(group);
return true;
}
internal static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (!TypeToGroup.TryGetValue(type, out var group))
{
Logger<MiraApiPlugin>.Error($"Failed to get group for {type.Name}");
return;
}
if (property.GetValue(group) is not IModdedOption option)
{
Logger<MiraApiPlugin>.Error($"Failed to get option for {property.Name}");
return;
}
RegisterOption(option, group, pluginInfo);
}
internal static void RegisterAttributeOption(Type type, ModdedOptionAttribute attribute, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (OptionAttributes.ContainsKey(property))
{
Logger<MiraApiPlugin>.Error($"Property {property.Name} already has an attribute registered.");
return;
}
if (!TypeToGroup.TryGetValue(type, out var group))
{
Logger<MiraApiPlugin>.Error($"Failed to get group for {type.Name}");
return;
}
var option = attribute.CreateOption(property.GetValue(group), property);
if (option == null)
{
Logger<MiraApiPlugin>.Error($"Failed to get option for {property.Name}");
return;
}
var setterOriginal = property.GetSetMethod();
var setterPatch = typeof(ModdedOptionsManager).GetMethod(nameof(PropertySetterPatch));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: new HarmonyMethod(setterPatch));
var getterOriginal = property.GetGetMethod();
var getterPatch = typeof(ModdedOptionsManager).GetMethod(nameof(PropertyGetterPatch));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: new HarmonyMethod(getterPatch));
OptionAttributes.Add(property, attribute);
attribute.HolderOption = option;
RegisterOption(option, group, pluginInfo);
}
public static void SyncAllOptions(int targetId=-1)
private static void RegisterOption(IModdedOption option, AbstractOptionGroup group, MiraPluginInfo pluginInfo)
{
List<NetData> data = [];
int count = 0;
foreach (var option in ModdedOptions.Values)
option.ParentMod = pluginInfo.MiraPlugin;
option.AdvancedRole = group.AdvancedRole;
pluginInfo.Options.Add(option);
ModdedOptions.Add(option.Id, option);
group.Options.Add(option);
}
internal static void SyncAllOptions(int targetId=-1)
{
var chunks = ModdedOptions.Values.Select(option => option.GetNetData()).ChunkNetData(1000);
while (chunks.Count > 0)
{
var netData = option.GetNetData();
data.Add(netData);
count += netData.GetLength();
if (count > 1000)
{
Rpc<SyncOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, data.ToArray());
data.Clear();
count = 0;
}
}
if (data.Count > 0)
{
Rpc<SyncOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, data.ToArray());
Rpc<SyncOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, chunks.Dequeue());
}
}
public static void HandleSyncOptions(NetData[] data)
internal static void HandleSyncOptions(NetData[] data)
{
foreach (var netData in data)
{
if (ModdedOptions.TryGetValue(netData.Id, out var option))
if (!ModdedOptions.TryGetValue(netData.Id, out var option))
{
Logger<MiraApiPlugin>.Error("Handling option " + option.Title);
option.HandleNetData(netData.Data);
continue;
}
Logger<MiraApiPlugin>.Error("Handling option " + option.Title);
option.HandleNetData(netData.Data);
}
}
@@ -102,21 +137,19 @@ public static class ModdedOptionsManager
{
ModdedOptionAttribute attribute = OptionAttributes.First(pair => pair.Key.GetSetMethod().Equals(__originalMethod)).Value;
if (attribute != null)
{
attribute.SetValue(value);
}
attribute?.SetValue(value);
}
public static bool PropertyGetterPatch(MethodBase __originalMethod, ref object __result)
{
ModdedOptionAttribute attribute = OptionAttributes.First(pair => pair.Key.GetGetMethod().Equals(__originalMethod)).Value;
if (attribute != null)
if (attribute == null)
{
__result = attribute.GetValue();
return false;
return true;
}
return true;
__result = attribute.GetValue();
return false;
}
}
@@ -3,7 +3,7 @@ using System.Linq;
namespace MiraAPI.GameOptions;
public class ModdedGroupSingleton<T> where T : IModdedOptionGroup
public class OptionGroupSingleton<T> where T : AbstractOptionGroup
{
private static T _instance;
@@ -12,7 +12,11 @@ public class ModdedGroupSingleton<T> where T : IModdedOptionGroup
get => _instance ??= ModdedOptionsManager.Groups.OfType<T>().Single();
set
{
if (_instance != null) throw new InvalidOperationException($"Instance for {typeof(T)} is already set");
if (_instance != null)
{
throw new InvalidOperationException($"Instance for {typeof(T)} is already set");
}
_instance = value;
}
}
@@ -39,7 +39,12 @@ public class ModdedEnumOption : ModdedOption<int>
return stringOption;
}
public override float GetFloatData()
{
return Value;
}
public override NetData GetNetData()
{
return new NetData(Id, BitConverter.GetBytes(Value));
@@ -63,7 +68,10 @@ public class ModdedEnumOption : ModdedOption<int>
public override void OnValueChanged(int newValue)
{
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(newValue), false);
if (OptionBehaviour is null) return;
if (!OptionBehaviour)
{
return;
}
var opt = OptionBehaviour as StringOption;
if (opt)
@@ -37,7 +37,7 @@ public class ModdedNumberOption : ModdedOption<float>
data.Value = Value;
data.Increment = Increment;
data.ValidRange = new FloatRange(Min, Max);
data.FormatString = Increment % 1 == 0 ? "0" : "0.0";
data.FormatString = Increment % 1 == 0 && Value % 1 == 0 && Min % 1 == 0 && Max % 1 == 0 ? "0" : "0.0";
data.ZeroIsInfinity = ZeroInfinity;
data.SuffixType = SuffixType;
data.OptionName = FloatOptionNames.Invalid;
@@ -54,7 +54,7 @@ public class ModdedNumberOption : ModdedOption<float>
numberOption.Value = Value;
numberOption.Increment = Increment;
numberOption.ValidRange = new FloatRange(Min, Max);
numberOption.FormatString = "0";
numberOption.FormatString = ((FloatGameSetting)Data).FormatString;
numberOption.ZeroIsInfinity = ZeroInfinity;
numberOption.SuffixType = SuffixType;
numberOption.floatOptionName = FloatOptionNames.Invalid;
@@ -65,6 +65,11 @@ public class ModdedNumberOption : ModdedOption<float>
return numberOption;
}
public override float GetFloatData()
{
return Value;
}
public override NetData GetNetData()
{
return new NetData(Id, BitConverter.GetBytes(Value));
@@ -90,7 +95,10 @@ public class ModdedNumberOption : ModdedOption<float>
Value = Mathf.Clamp(newValue, Min, Max);
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(Value), false);
if (OptionBehaviour is null) return;
if (!OptionBehaviour)
{
return;
}
var opt = OptionBehaviour as NumberOption;
if (opt)
+28 -15
View File
@@ -1,17 +1,30 @@
using MiraAPI.PluginLoading;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using Reactor.Localization.Utilities;
using System;
using MiraAPI.Networking;
using Reactor.Networking.Rpc;
using System;
using UnityEngine;
namespace MiraAPI.GameOptions.OptionTypes;
public abstract class ModdedOption<T> : IModdedOption
{
private IMiraPlugin _parentMod;
public uint Id { get; }
public BaseGameSetting Data { get; protected init; }
public IMiraPlugin ParentMod
{
get => _parentMod;
set
{
_parentMod = value;
var entry = _parentMod.GetConfigFile().Bind(ConfigDefinition, DefaultValue);
Value = entry.Value;
}
}
public T Value { get; protected set; }
public T DefaultValue { get; init; }
public Action<T> ChangedEvent { get; set; }
@@ -20,11 +33,11 @@ public abstract class ModdedOption<T> : IModdedOption
public Func<bool> Visible { get; set; }
public Type AdvancedRole { get; set; }
public OptionBehaviour OptionBehaviour { get; set; }
public IModdedOptionGroup Group { get; set; } = null;
public IMiraPlugin ParentMod { get; set; } = null;
public ConfigDefinition ConfigDefinition => new("Options", Title);
protected ModdedOption(string title, T defaultValue, Type roleType) : this()
protected ModdedOption(string title, T defaultValue, Type roleType)
{
Id = ModdedOptionsManager.NextId;
Title = title;
DefaultValue = defaultValue;
Value = defaultValue;
@@ -37,13 +50,6 @@ public abstract class ModdedOption<T> : IModdedOption
}
}
private ModdedOption()
{
Id = ModdedOptionsManager.NextId++;
ModdedOptionsManager.Options.Add(this);
ModdedOptionsManager.ModdedOptions.Add(Id, this);
}
public void ValueChanged(OptionBehaviour optionBehaviour)
{
SetValue(GetValueFromOptionBehaviour(optionBehaviour));
@@ -62,12 +68,19 @@ public abstract class ModdedOption<T> : IModdedOption
{
Rpc<SyncOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, [GetNetData()], true);
}
if (ParentMod?.GetConfigFile().TryGetEntry<T>(ConfigDefinition, out var entry) == true)
{
entry.Value = Value;
}
OnValueChanged(newValue);
}
public abstract float GetFloatData();
public abstract NetData GetNetData();
public abstract void HandleNetData(byte[] data);
public abstract void OnValueChanged(T newValue);
@@ -40,6 +40,11 @@ public class ModdedStringOption : ModdedOption<int>
return stringOption;
}
public override float GetFloatData()
{
return Value;
}
public override NetData GetNetData()
{
return new NetData(Id, BitConverter.GetBytes(Value));
@@ -63,7 +68,10 @@ public class ModdedStringOption : ModdedOption<int>
public override void OnValueChanged(int newValue)
{
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(newValue), false);
if (OptionBehaviour is null) return;
if (!OptionBehaviour)
{
return;
}
var opt = OptionBehaviour as StringOption;
if (opt)
@@ -1,5 +1,5 @@
using System;
using MiraAPI.Networking;
using MiraAPI.Networking;
using System;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -7,7 +7,7 @@ namespace MiraAPI.GameOptions.OptionTypes;
public class ModdedToggleOption : ModdedOption<bool>
{
public ModdedToggleOption(string title, bool defaultValue, Type roleType=null) : base(title, defaultValue, roleType)
public ModdedToggleOption(string title, bool defaultValue, Type roleType = null) : base(title, defaultValue, roleType)
{
Data = ScriptableObject.CreateInstance<CheckboxGameSetting>();
@@ -32,6 +32,11 @@ public class ModdedToggleOption : ModdedOption<bool>
return toggleOption;
}
public override float GetFloatData()
{
return Value ? 1 : 0;
}
public override NetData GetNetData()
{
return new NetData(Id, BitConverter.GetBytes(Value));
@@ -55,7 +60,10 @@ public class ModdedToggleOption : ModdedOption<bool>
public override void OnValueChanged(bool newValue)
{
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(StringName, newValue ? "On" : "Off", false);
if (OptionBehaviour is null) return;
if (!OptionBehaviour)
{
return;
}
var toggleOpt = OptionBehaviour as ToggleOption;
if (toggleOpt)
+7
View File
@@ -0,0 +1,7 @@
namespace MiraAPI.Hud;
public enum ButtonLocation
{
BottomLeft,
BottomRight
}
+87 -15
View File
@@ -1,9 +1,14 @@
using MiraAPI.Utilities.Assets;
#nullable enable
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
using UnityEngine.Events;
namespace MiraAPI.Hud;
/// <summary>
/// Class for making custom action buttons. More customizable than the default Action/Ability buttons in the base game
/// </summary>
public abstract class CustomActionButton
{
/// <summary>
@@ -31,6 +36,11 @@ public abstract class CustomActionButton
/// </summary>
public abstract LoadableAsset<Sprite> Sprite { get; }
/// <summary>
/// The location of the button on the screen
/// </summary>
public virtual ButtonLocation Location => ButtonLocation.BottomLeft;
/// <summary>
/// Returns true if the button has an effect ability.
/// </summary>
@@ -59,8 +69,8 @@ public abstract class CustomActionButton
/// <summary>
/// The button object in game. This is created by Mira API automatically.
/// </summary>
protected ActionButton Button { get; private set; }
protected ActionButton? Button { get; private set; }
internal void CreateButton(Transform parent)
{
if (Button)
@@ -99,17 +109,20 @@ public abstract class CustomActionButton
{
OnEffectEnd();
}
EffectActive = false;
}
/// <summary>
/// A utility function to override the sprite of the button.
/// </summary>
/// <param name="sprite">The new sprite to override with</param>
public void OverrideSprite(Sprite sprite)
{
Button.graphic.sprite = sprite;
if (Button != null)
{
Button.graphic.sprite = sprite;
}
}
/// <summary>
@@ -118,7 +131,7 @@ public abstract class CustomActionButton
/// <param name="name">The new name to override with</param>
public void OverrideName(string name)
{
Button.OverrideText(name);
Button?.OverrideText(name);
}
/// <summary>
@@ -164,7 +177,7 @@ public abstract class CustomActionButton
/// <param name="role">Passed in from HudManager.SetHudActive, the current role of the player.</param>
public virtual void SetActive(bool visible, RoleBehaviour role)
{
Button.ToggleVisible(visible && Enabled(role));
Button?.ToggleVisible(visible && Enabled(role));
}
/// <summary>
@@ -172,7 +185,7 @@ public abstract class CustomActionButton
/// This method takes into account cooldowns, effects, and uses, before calling the <see cref="OnClick"/> method.
/// It can be overridden for custom behavior.
/// </summary>
public virtual void ClickHandler()
protected virtual void ClickHandler()
{
if (!CanUse())
{
@@ -182,11 +195,11 @@ public abstract class CustomActionButton
if (LimitedUses)
{
UsesLeft--;
Button.SetUsesRemaining(UsesLeft);
Button?.SetUsesRemaining(UsesLeft);
}
OnClick();
Button.SetDisabled();
Button?.SetDisabled();
if (HasEffect)
{
EffectActive = true;
@@ -219,15 +232,74 @@ public abstract class CustomActionButton
if (CanUse())
{
Button.SetEnabled();
Button?.SetEnabled();
}
else
{
Button.SetDisabled();
Button?.SetDisabled();
}
Button.SetCoolDown(Timer, EffectActive ? EffectDuration : Cooldown);
Button?.SetCoolDown(Timer, EffectActive ? EffectDuration : Cooldown);
FixedUpdate(playerControl);
}
}
/// <summary>
/// Custom action button that has a target object.
/// </summary>
/// <typeparam name="T">The type of the target object.</typeparam>
public abstract class CustomActionButton<T> : CustomActionButton where T : MonoBehaviour
{
/// <summary>
/// The target object of the button.
/// </summary>
public T? Target { get; private set; }
/// <summary>
/// The distance the player must be from the target object to use the button.
/// </summary>
public virtual float Distance => PlayerControl.LocalPlayer.Data.Role.GetAbilityDistance();
/// <summary>
/// An optional collider tag to filter the target object by.
/// </summary>
public virtual string? ColliderTag => null;
/// <summary>
/// Determines if the target object is valid.
/// </summary>
public virtual bool IsTargetValid(T target)
{
return target;
}
/// <summary>
/// The method used to get the target object.
/// </summary>
public virtual T? GetTarget()
{
return PlayerControl.LocalPlayer.GetNearestObjectOfType<T>(Distance, ColliderTag, IsTargetValid);
}
/// <summary>
/// Sets the outline of the target object.
/// </summary>
/// <param name="active">Should the outline be active</param>
public abstract void SetOutline(bool active);
public override bool CanUse()
{
var newTarget = GetTarget();
if (newTarget != Target)
{
SetOutline(false);
}
Target = newTarget;
SetOutline(true);
return base.CanUse() && Target;
}
}
+10 -3
View File
@@ -1,21 +1,28 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using Reactor.Utilities;
namespace MiraAPI.Hud;
public static class CustomButtonManager
{
public static readonly List<CustomActionButton> CustomButtons = [];
public static void RegisterButton(Type buttonType)
internal static void RegisterButton(Type buttonType)
{
if (!typeof(CustomActionButton).IsAssignableFrom(buttonType))
{
Logger<MiraApiPlugin>.Error($"{buttonType?.Name} does not inherit from CustomActionButton.");
return;
}
var button = (CustomActionButton)Activator.CreateInstance(buttonType);
if (Activator.CreateInstance(buttonType) is not CustomActionButton button)
{
Logger<MiraApiPlugin>.Error($"Failed to create button from {buttonType.Name}");
return;
}
CustomButtons.Add(button);
typeof(CustomButtonSingleton<>).MakeGenericType(buttonType)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
+10 -2
View File
@@ -17,8 +17,16 @@ public class CustomButtonSingleton<T> where T : CustomActionButton
get => _instance ??= CustomButtonManager.CustomButtons.OfType<T>().Single();
set
{
if (_instance == value) return;
if (_instance != null) throw new InvalidOperationException($"Instance for {typeof(T)} is already set");
if (_instance == value)
{
return;
}
if (_instance != null)
{
throw new InvalidOperationException($"Instance for {typeof(T)} is already set");
}
_instance = value;
}
}
+11 -11
View File
@@ -9,26 +9,26 @@
<Description>Simple and easy to use Among Us modding API.</Description>
<Authors>Angxl, XtraCube</Authors>
</PropertyGroup>
<PropertyGroup>
<GamePlatform Condition="'$(GamePlatform)' == ''">Steam</GamePlatform>
<GameVersion Condition="'$(GamePlatform)' == 'Steam'">2024.6.18</GameVersion>
</PropertyGroup>
<ItemGroup>
<None Remove="Resources\Buttons.png" />
<None Remove="Resources\Checkmark.png" />
<None Remove="Resources\CheckMarkBox.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\Checkmark.png" />
<EmbeddedResource Include="Resources\CheckMarkBox.png" />
<EmbeddedResource Include="Resources\Cog.png" />
<EmbeddedResource Include="Resources\CogActive.png" />
<EmbeddedResource Include="Resources\FortniteBanner.jpeg" />
<EmbeddedResource Include="Resources\NextButton.png" />
<EmbeddedResource Include="Resources\NextButtonActive.png" />
<EmbeddedResource Include="Resources\ExampleButton.png" />
<EmbeddedResource Include="Resources\Empty.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Reactor" Version="2.3.0" />
<PackageReference Include="Reactor" Version="2.3.1" />
<PackageReference Include="BepInEx.Unity.IL2CPP" Version="6.0.0-be.697" Private="false" ExcludeAssets="runtime;native" />
<PackageReference Include="Iced" Version="1.21.0" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="$(GameVersion)" PrivateAssets="all" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2024.8.13" PrivateAssets="all" />
<PackageReference Include="BepInEx.AutoPlugin" Version="1.1.0" PrivateAssets="all" />
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.1.0-rc.1" PrivateAssets="all" ExcludeAssets="runtime">
+6 -20
View File
@@ -2,12 +2,11 @@
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
using Reactor;
using Reactor.Networking;
using Reactor.Networking.Attributes;
using Reactor.Patches;
using System;
using System.Text;
using Reactor.Utilities;
using UnityEngine;
namespace MiraAPI;
@@ -19,30 +18,17 @@ namespace MiraAPI;
public partial class MiraApiPlugin : BasePlugin
{
public Harmony Harmony { get; } = new(Id);
public static MiraPluginManager PluginManager { get; private set; }
private static MiraPluginManager PluginManager { get; set; }
public static Color MiraColor = new Color32(238, 154, 112, 255);
public override void Load()
{
Harmony.PatchAll();
ReactorCredits.Register("Mira API", Version.Truncate(15, "") ?? Version, true, ReactorCredits.AlwaysShow);
PluginManager = new MiraPluginManager();
PluginManager.Initialize();
ReactorVersionShower.TextUpdated += text =>
{
text.text = new StringBuilder($"{MiraColor.ToTextColor()}Mira API</color> ")
.Append(GetShortHashVersion(Version))
.Append('\n')
.Append(text.text)
.ToString();
};
}
private static string GetShortHashVersion(string version)
{
var index = version.IndexOf("+", StringComparison.Ordinal);
return index < 0 ? version : version[..(index + 3)];
}
}
+2 -4
View File
@@ -1,10 +1,8 @@
using System;
namespace MiraAPI.Networking;
namespace MiraAPI.Networking;
public readonly struct NetData(uint id, byte[] data)
{
public uint Id { get; } = id;
public byte[] Data { get; } = data;
public int GetLength() => BitConverter.GetBytes(Id).Length + Data.Length;
public int GetLength() => 4 + Data.Length;
}
+3 -7
View File
@@ -1,9 +1,5 @@
using HarmonyLib;
using InnerNet;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
/*
[HarmonyPatch]
public static class ConsolePatches
{
@@ -73,4 +69,4 @@ public static class ConsolePatches
canUse = couldUse = true;
return true;
}
}
}*/
@@ -0,0 +1,13 @@
/*
[HarmonyPatch(typeof(DeadBody))]
public static class DeadBodyPatch
{
[HarmonyPrefix]
[HarmonyPatch(nameof(DeadBody.OnClick))]
public static bool OnClickPatch(DeadBody __instance)
{
return CustomGameModeManager.ActiveMode == null || CustomGameModeManager.ActiveMode.CanReport(__instance);
}
}*/
@@ -1,8 +1,6 @@
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
/*
[HarmonyPatch]
public static class GameLogicPatches
{
@@ -21,4 +19,4 @@ public static class GameLogicPatches
CustomGameModeManager.ActiveMode?.AssignRoles(out runOriginal, __instance);
return runOriginal;
}
}
}*/
@@ -1,8 +1,6 @@
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
/*
/// <summary>
/// Allow Impostors to kill each other if can kill is enabled in gamemode or friendly fire is toggled on
/// </summary>
@@ -25,4 +23,4 @@ public static class ImpostorTargetPatch
return false;
}
}
}*/
@@ -1,10 +1,8 @@
using HarmonyLib;
using MiraAPI.GameModes;
namespace MiraAPI.Patches.GameModes;
/*
[HarmonyPatch(typeof(MapBehaviour))]
public class MapBehaviourPatch
public static class MapBehaviourPatch
{
[HarmonyPrefix]
[HarmonyPatch(nameof(MapBehaviour.ShowSabotageMap))]
@@ -19,4 +17,4 @@ public class MapBehaviourPatch
return true;
}
}
}*/
+13
View File
@@ -0,0 +1,13 @@
/*
[HarmonyPatch(typeof(KillAnimation))]
public static class OnDeathPatch
{
[HarmonyPostfix]
[HarmonyPatch(nameof(KillAnimation.CoPerformKill))]
public static void OnDeathPostfix([HarmonyArgument(0)] PlayerControl source, [HarmonyArgument(1)] PlayerControl target)
{
CustomGameModeManager.ActiveMode?.OnDeath(target);
}
}*/
+51
View File
@@ -0,0 +1,51 @@
/*
[HarmonyPatch(typeof(Vent))]
public static class VentPatches
{
[HarmonyPrefix]
[HarmonyPatch(nameof(Vent.CanUse))]
public static bool CanUseVentPatch(Vent __instance, ref float __result, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] ref bool canUse, [HarmonyArgument(2)] ref bool couldUse)
{
if (CustomGameModeManager.ActiveMode?.CanVent(__instance, pc) == false)
{
return couldUse = canUse = false;
}
if (pc.Role is not ICustomRole role)
{
return couldUse = canUse = true;
}
var num = float.MaxValue;
var @object = pc.Object;
var customRoleUsable = role.CanUseVent;
canUse = couldUse = customRoleUsable && !pc.IsDead && (@object.CanMove || @object.inVent);
if (canUse)
{
var center = @object.Collider.bounds.center;
var position = __instance.transform.position;
num = Vector2.Distance(center, position);
canUse &= num <= __instance.UsableDistance && !PhysicsHelpers.AnythingBetween(@object.Collider, center, position, Constants.ShipOnlyMask, false);
}
__result = num;
return false;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(Vent.SetOutline))]
public static bool SetOutlinePatch(Vent __instance, [HarmonyArgument(0)] bool on, [HarmonyArgument(1)] bool mainTarget)
{
var color = PlayerControl.LocalPlayer.Data.Role is ICustomRole role
? role.RoleColor : PlayerControl.LocalPlayer.Data.Role.IsImpostor ? Palette.ImpostorRed : Palette.CrewmateBlue;
__instance.myRend.material.SetFloat(ShaderID.Outline, on ? 1 : 0);
__instance.myRend.material.SetColor(ShaderID.OutlineColor, color);
__instance.myRend.material.SetColor(ShaderID.AddColor, mainTarget ? color : Color.clear);
return false;
}
}*/
+27 -10
View File
@@ -1,10 +1,11 @@
using HarmonyLib;
using System;
using HarmonyLib;
using InnerNet;
using MiraAPI.GameModes;
using MiraAPI.Hud;
using MiraAPI.Roles;
using Reactor.Utilities.Extensions;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches;
@@ -27,9 +28,13 @@ public static class HudManagerPatches
{
return;
}
//CustomGameModeManager.ActiveMode?.HudUpdate(__instance);
//CustomGameModeManager.ActiveMode.HudUpdate(__instance);
if (local is null || local.Data is null || local.Data.Role is null) return;
if (local?.Data?.Role is null)
{
return;
}
if (local.Data.Role is ICustomRole customRole)
{
@@ -37,7 +42,7 @@ public static class HudManagerPatches
if (customRole.SetTabText() != null)
{
if (_roleTab == null)
if (!_roleTab)
{
_roleTab = CustomRoleManager.CreateRoleTab(customRole);
}
@@ -57,6 +62,7 @@ public static class HudManagerPatches
}
}
/*
/// <summary>
/// Trigger hudstart on current custom gamemode
/// </summary>
@@ -65,7 +71,7 @@ public static class HudManagerPatches
public static void GameStartPatch(HudManager __instance)
{
CustomGameModeManager.ActiveMode?.HudStart(__instance);
}
}*/
/// <summary>
/// Create custom buttons parent
@@ -74,10 +80,12 @@ public static class HudManagerPatches
[HarmonyPatch(nameof(HudManager.Start))]
public static void StartPostfix(HudManager __instance)
{
var buttons = __instance.transform.Find("Buttons");
var bottomRight = buttons.Find("BottomRight");
if (!_bottomLeft)
{
var buttons = __instance.transform.Find("Buttons");
_bottomLeft = Object.Instantiate(buttons.Find("BottomRight").gameObject, buttons);
_bottomLeft = Object.Instantiate(bottomRight.gameObject, buttons);
}
foreach (var t in _bottomLeft.GetComponentsInChildren<ActionButton>(true))
@@ -94,7 +102,14 @@ public static class HudManagerPatches
foreach (var button in CustomButtonManager.CustomButtons)
{
button.CreateButton(_bottomLeft.transform);
Transform location = button.Location switch
{
ButtonLocation.BottomLeft => _bottomLeft.transform,
ButtonLocation.BottomRight => bottomRight,
_ => throw new ArgumentOutOfRangeException()
};
button.CreateButton(location);
}
gridArrange.Start();
@@ -110,7 +125,7 @@ public static class HudManagerPatches
[HarmonyPatch(nameof(HudManager.SetHudActive), typeof(PlayerControl), typeof(RoleBehaviour), typeof(bool))]
public static void SetHudActivePostfix(HudManager __instance, [HarmonyArgument(0)] PlayerControl player, [HarmonyArgument(1)] RoleBehaviour roleBehaviour, [HarmonyArgument(2)] bool isActive)
{
if (player.Data == null)
if (!player.Data)
{
return;
}
@@ -121,7 +136,9 @@ public static class HudManagerPatches
}
foreach (var button in CustomButtonManager.CustomButtons)
{
button.SetActive(isActive, roleBehaviour);
}
if (roleBehaviour is ICustomRole role)
{
+4 -3
View File
@@ -1,5 +1,4 @@
using HarmonyLib;
using MiraAPI.GameModes;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using UnityEngine;
@@ -9,6 +8,7 @@ namespace MiraAPI.Patches;
[HarmonyPatch(typeof(IntroCutscene))]
public static class IntroCutscenePatches
{
/*
[HarmonyPostfix]
[HarmonyPatch(nameof(IntroCutscene.BeginImpostor))]
public static void BeginImpostorPatch(IntroCutscene __instance)
@@ -18,7 +18,7 @@ public static class IntroCutscenePatches
var mode = CustomGameModeManager.ActiveMode;
__instance.TeamTitle.text = $"<size=70%>{mode.Name}</size>\n<size=20%>{mode.Description}</size>";
}
}
}*/
[HarmonyPrefix]
[HarmonyPatch(nameof(IntroCutscene.BeginCrewmate))]
@@ -48,10 +48,11 @@ public static class IntroCutscenePatches
return true;
}
/*
[HarmonyPostfix]
[HarmonyPatch(nameof(IntroCutscene.OnDestroy))]
public static void GameBeginPatch()
{
CustomGameModeManager.ActiveMode?.Initialize();
}
}*/
}
+119 -46
View File
@@ -1,11 +1,14 @@
using HarmonyLib;
using Il2CppSystem.Collections.Generic;
using MiraAPI.GameOptions;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Localization.Utilities;
using Reactor.Utilities.Extensions;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
namespace MiraAPI.Patches.Options;
@@ -13,89 +16,156 @@ namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(GameOptionsMenu))]
public static class GameOptionsMenuPatch
{
[HarmonyPostfix]
[HarmonyPatch(nameof(GameOptionsMenu.Update))]
public static void UpdatePatch(GameOptionsMenu __instance)
{
if (GameSettingMenuPatches.CurrentSelectedMod == 0)
{
return;
}
float num = 2.1f;
var filteredGroups = GameSettingMenuPatches.SelectedMod.OptionGroups.Where(x => x.GroupVisible.Invoke() && x.AdvancedRole is null);
foreach (AbstractOptionGroup group in filteredGroups)
{
var filteredOpts = group.Options.Where(x => x.Visible.Invoke()).ToList();
if (filteredOpts.Count == 0)
{
continue;
}
group.Header.gameObject.SetActive(true);
group.Header.transform.localScale = Vector3.one * 0.63f;
group.Header.transform.localPosition = new Vector3(-0.903f, num, -2f);
num -= 0.58f;
foreach (var opt in group.Options)
{
OptionBehaviour newOpt = opt.OptionBehaviour;
if (opt.Visible.Invoke() == false)
{
newOpt.gameObject.SetActive(false);
continue;
}
if (!group.AllOptionsHidden)
{
newOpt.gameObject.SetActive(true);
newOpt.transform.localPosition = new Vector3(0.952f, num, -2f);
num -= 0.45f;
}
else
{
newOpt.gameObject.SetActive(false);
}
}
}
__instance.scrollBar.SetYBoundsMax(-num - 1.65f);
}
[HarmonyPrefix]
[HarmonyPatch(nameof(GameOptionsMenu.CreateSettings))]
public static bool SettingsPatch(GameOptionsMenu __instance)
{
if (GameSettingMenuPatches.CurrentSelectedMod == 0) return true;
if (GameSettingMenuPatches.CurrentSelectedMod == 0)
{
return true;
}
__instance.MapPicker.gameObject.SetActive(false);
float num = 2.1f;
foreach (IModdedOptionGroup group in GameSettingMenuPatches.SelectedMod.OptionGroups)
var filteredGroups = GameSettingMenuPatches.SelectedMod.OptionGroups.Where(x => x.AdvancedRole is null);
foreach (AbstractOptionGroup group in filteredGroups)
{
CategoryHeaderMasked categoryHeaderMasked = Object.Instantiate(__instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer);
categoryHeaderMasked.SetHeader(CustomStringName.CreateAndRegister(group.GroupName), 20);
if (group.GroupColor != Color.clear)
{
categoryHeaderMasked.Background.color = group.GroupColor;
categoryHeaderMasked.Title.color = group.GroupColor.DarkenColor();
categoryHeaderMasked.Divider.color = group.GroupColor;
categoryHeaderMasked.Title.color = group.GroupColor.GetAlternateColor();
}
categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f;
categoryHeaderMasked.transform.localPosition = new Vector3(-0.903f, num, -2f);
num -= 0.63f;
categoryHeaderMasked.Background.size = new Vector2(categoryHeaderMasked.Background.size.x + 1.5f, categoryHeaderMasked.Background.size.y);
categoryHeaderMasked.gameObject.SetActive(false);
group.Header = categoryHeaderMasked;
foreach (var opt in ModdedOptionsManager.Options.Where(opt => opt.Group is not null && opt.AdvancedRole is null && opt.Group.GroupName == group.GroupName))
TextMeshPro newText = Object.Instantiate(categoryHeaderMasked.Title, categoryHeaderMasked.transform);
newText.text = $"<size=70%>(Click to open)</size>";
newText.transform.localPosition = new Vector3(2.6249f, -0.165f, 0f);
newText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
List<OptionBehaviour> newOpts = [];
foreach (var opt in group.Options)
{
OptionBehaviour newOpt = opt.CreateOption(__instance.checkboxOrigin, __instance.numberOptionOrigin, __instance.stringOptionOrigin, __instance.settingsContainer);
newOpt.transform.localPosition = new Vector3(0.952f, num, -2f);
newOpt.SetClickMask(__instance.ButtonClickMask);
SpriteRenderer[] componentsInChildren = newOpt.GetComponentsInChildren<SpriteRenderer>(true);
for (int i = 0; i < componentsInChildren.Length; i++)
{
if (group.GroupColor != Color.clear) componentsInChildren[i].color = group.GroupColor;
if (group.GroupColor != Color.clear)
{
componentsInChildren[i].color = group.GroupColor.GetAlternateColor();
if (componentsInChildren[i].transform.parent.TryGetComponent<GameOptionButton>(out var btn))
{
btn.interactableColor = group.GroupColor.GetAlternateColor();
btn.interactableHoveredColor = Color.white;
}
}
componentsInChildren[i].material.SetInt(PlayerMaterial.MaskLayer, 20);
}
foreach (TextMeshPro textMeshPro in newOpt.GetComponentsInChildren<TextMeshPro>(true))
{
if (group.GroupColor != Color.clear) textMeshPro.color = group.GroupColor.DarkenColor();
if (group.GroupColor != Color.clear)
{
textMeshPro.color = group.GroupColor;
}
textMeshPro.fontMaterial.SetFloat(ShaderID.StencilComp, 3f);
textMeshPro.fontMaterial.SetFloat(ShaderID.Stencil, 20);
}
if (newOpt is ToggleOption toggle)
{
toggle.CheckMark.sprite = MiraAssets.Checkmark.LoadAsset();
SpriteRenderer rend = toggle.CheckMark.transform.parent.FindChild("ActiveSprite").GetComponent<SpriteRenderer>();
rend.sprite = MiraAssets.CheckmarkBox.LoadAsset();
rend.color = group.GroupColor;
}
__instance.Children.Add(newOpt);
num -= 0.45f;
newOpt.Initialize();
newOpts.Add(newOpt);
newOpt.gameObject.SetActive(false);
}
}
CategoryHeaderMasked ungroupedHeader = Object.Instantiate(__instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer);
ungroupedHeader.SetHeader(CustomStringName.CreateAndRegister("Ungrouped Options"), 20);
ungroupedHeader.transform.localScale = Vector3.one * 0.63f;
ungroupedHeader.transform.localPosition = new Vector3(-0.903f, num, -2f);
BoxCollider2D boxCol = categoryHeaderMasked.gameObject.AddComponent<BoxCollider2D>();
boxCol.size = new Vector2(7, 0.7f);
boxCol.offset = new Vector2(1.5f, -0.3f);
num -= 0.63f;
foreach (var opt in ModdedOptionsManager.Options.Where(opt => opt.Group is null && opt.AdvancedRole is null))
{
OptionBehaviour newOpt = opt.CreateOption(__instance.checkboxOrigin, __instance.numberOptionOrigin, __instance.stringOptionOrigin, __instance.settingsContainer);
newOpt.transform.localPosition = new Vector3(0.952f, num, -2f);
newOpt.SetClickMask(__instance.ButtonClickMask);
newOpt.SetUpFromData(newOpt.data, 20);
SpriteRenderer[] componentsInChildren = newOpt.GetComponentsInChildren<SpriteRenderer>(true);
for (int i = 0; i < componentsInChildren.Length; i++)
PassiveButton headerBtn = categoryHeaderMasked.gameObject.AddComponent<PassiveButton>();
headerBtn.ClickSound = __instance.BackButton.GetComponent<PassiveButton>().ClickSound;
headerBtn.OnMouseOver = new UnityEvent();
headerBtn.OnMouseOut = new UnityEvent();
headerBtn.OnClick.AddListener((UnityAction)(() =>
{
componentsInChildren[i].material.SetInt(PlayerMaterial.MaskLayer, 20);
}
foreach (TextMeshPro textMeshPro in newOpt.GetComponentsInChildren<TextMeshPro>(true))
{
textMeshPro.fontMaterial.SetFloat(ShaderID.StencilComp, 3f);
textMeshPro.fontMaterial.SetFloat(ShaderID.Stencil, 20);
}
__instance.Children.Add(newOpt);
num -= 0.45f;
newOpt.Initialize();
group.AllOptionsHidden = !group.AllOptionsHidden;
newText.text = group.AllOptionsHidden ? "<size=70%>(Click to open)</size>" : "<size=70%>(Click to close)</size>";
}));
headerBtn.SetButtonEnableState(true);
}
__instance.scrollBar.SetYBoundsMax(-num - 1.65f);
return false;
}
@@ -109,7 +179,7 @@ public static class GameOptionsMenuPatch
__instance.MapPicker.Initialize(20);
BaseGameSetting mapNameSetting = GameManager.Instance.GameSettingsList.MapNameSetting;
__instance.MapPicker.SetUpFromData(mapNameSetting, 20);
__instance.Children = new List<OptionBehaviour>();
__instance.Children = new Il2CppSystem.Collections.Generic.List<OptionBehaviour>();
__instance.Children.Add(__instance.MapPicker);
__instance.CreateSettings();
__instance.cachedData = GameOptionsManager.Instance.CurrentGameOptions;
@@ -120,7 +190,10 @@ public static class GameOptionsMenuPatch
optionBehaviour.SetAsPlayer();
}
if (optionBehaviour.IsCustom()) continue;
if (optionBehaviour.IsCustom())
{
continue;
}
optionBehaviour.OnValueChanged = new System.Action<OptionBehaviour>(__instance.ValueChanged);
}
@@ -16,15 +16,18 @@ namespace MiraAPI.Patches.Options;
public static class GameSettingMenuPatches
{
public static int CurrentSelectedMod { get; private set; }
public static MiraPluginInfo SelectedMod { get; private set; }
private static TextMeshPro _text;
private static Vector3 _roleBtnOgPos;
[HarmonyPrefix]
[HarmonyPatch(nameof(GameSettingMenu.Start))]
public static void StartPrefix(GameSettingMenu __instance)
{
_roleBtnOgPos = __instance.RoleSettingsButton.transform.localPosition;
__instance.transform.FindChild("GameSettingsLabel").gameObject.SetActive(false);
Transform helpThing = __instance.transform.FindChild("What Is This?");
@@ -36,7 +39,9 @@ public static class GameSettingMenuPatches
_text = tmpText.GetComponent<TextMeshPro>();
_text.fontSizeMax = 3.2f;
UpdateText(__instance.GameSettingsTab, __instance.RoleSettingsTab);
_text.overflowMode = TextOverflowModes.Overflow;
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
_text.alignment = TextAlignmentOptions.Center;
@@ -54,7 +59,7 @@ public static class GameSettingMenuPatches
if (CurrentSelectedMod != MiraPluginManager.Instance.RegisteredPlugins.Count)
{
CurrentSelectedMod += 1;
UpdateText(__instance.GameSettingsTab, __instance.RoleSettingsTab);
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
}
}));
@@ -68,12 +73,12 @@ public static class GameSettingMenuPatches
if (CurrentSelectedMod != 0)
{
CurrentSelectedMod -= 1;
UpdateText(__instance.GameSettingsTab, __instance.RoleSettingsTab);
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
}
}));
}
public static void UpdateText(GameOptionsMenu settings, RolesSettingsMenu roles)
private static void UpdateText(GameSettingMenu menu, GameOptionsMenu settings, RolesSettingsMenu roles)
{
if (CurrentSelectedMod == 0)
{
@@ -82,19 +87,41 @@ public static class GameSettingMenuPatches
}
else
{
_text.fontSizeMax = 2f;
_text.fontSizeMax = 2.3f;
SelectedMod = MiraPluginManager.Instance.RegisteredPlugins.ElementAt(CurrentSelectedMod - 1).Value;
if (SelectedMod == null)
{
CurrentSelectedMod = 0;
UpdateText(settings, roles);
UpdateText(menu, settings, roles);
}
string name = SelectedMod.PluginInfo.Metadata.Name;
_text.text = name.Substring(0, Math.Min(name.Length, 15));
var name = SelectedMod?.MiraPlugin.OptionsTitleText;
_text.text = name?[..Math.Min(name.Length, 25)];
}
if (roles is not null && roles.roleChances is not null)
menu.RoleSettingsButton.transform.localPosition = _roleBtnOgPos;
menu.GameSettingsButton.gameObject.SetActive(true);
menu.RoleSettingsButton.gameObject.SetActive(true);
if (CurrentSelectedMod != 0)
{
if (SelectedMod.Options.Where(x=>x.AdvancedRole==null).ToList().Count == 0)
{
menu.GameSettingsButton.gameObject.SetActive(false);
}
if (SelectedMod.CustomRoles.Count == 0)
{
menu.RoleSettingsButton.gameObject.SetActive(false);
}
if (!menu.GameSettingsButton.gameObject.active && menu.RoleSettingsButton.gameObject.active)
{
menu.RoleSettingsButton.transform.localPosition = menu.GameSettingsButton.transform.localPosition;
}
}
if (roles?.roleChances != null && SelectedMod != null && SelectedMod.CustomRoles.Count != 0)
{
if (roles.advancedSettingChildren is not null)
{
@@ -116,20 +143,29 @@ public static class GameSettingMenuPatches
roleChance.gameObject.DestroyImmediate();
}
roles.roleChances.Clear();
roles.roleChances = null;
roles.AdvancedRolesSettings.gameObject.SetActive(false);
roles.RoleChancesSettings.gameObject.SetActive(true);
roles.SetQuotaTab();
roles.scrollBar.CalculateAndSetYBounds(roles.roleChances.Count + 5, 1f, 6f, 0.43f);
roles.scrollBar.ScrollToTop();
}
if (settings is not null && settings.Children is not null)
if (settings?.Children != null && SelectedMod.OptionGroups.Count != 0)
{
foreach (var child in settings.Children)
{
if (child.TryCast<GameOptionsMapPicker>()) continue;
if (child.gameObject is null) continue;
if (child.TryCast<GameOptionsMapPicker>())
{
continue;
}
if (!child.gameObject)
{
continue;
}
child.gameObject.DestroyImmediate();
}
@@ -143,6 +179,7 @@ public static class GameSettingMenuPatches
settings.Children = null;
settings.Initialize();
settings.scrollBar.ScrollToTop();
}
}
}
+341 -11
View File
@@ -1,27 +1,38 @@
using HarmonyLib;
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(LobbyViewSettingsPane))]
public static class LobbyViewPanePatches
{
public static int CurrentSelectedMod { get; private set; }
public static MiraPluginInfo? SelectedMod => CurrentSelectedMod == 0 ? null : MiraPluginManager.Instance.RegisteredPlugins.ElementAt(CurrentSelectedMod-1).Value;
[HarmonyPostfix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.Awake))]
public static void AwakePatch(LobbyViewSettingsPane __instance)
{
__instance.gameModeText.transform.localPosition = new Vector3(-4.3f, 2.4f, -2);
__instance.gameModeText.horizontalAlignment = HorizontalAlignmentOptions.Center;
__instance.gameModeText.fontSizeMax = 10f;
__instance.gameModeText.margin = new Vector4(1,0,1,0);
__instance.gameModeText.transform.localPosition = new Vector3(-2.3f, 2.4f, -2);
// Create the next button
GameObject nextButton = Object.Instantiate(__instance.BackButton, __instance.BackButton.transform.parent).gameObject;
nextButton.transform.localPosition = new Vector3(-2.3f, 2.4f, -2f);
var nextButton = Object.Instantiate(__instance.BackButton, __instance.BackButton.transform.parent).gameObject;
nextButton.GetComponent<BoxCollider2D>().size = new Vector2(0.2f, 0.3f);
nextButton.transform.localPosition = new Vector3(-5.4f, 2.4f, -2f);
nextButton.transform.localScale = new Vector3(3, 3, 2);
nextButton.name = "RightArrowButton";
@@ -33,24 +44,343 @@ public static class LobbyViewPanePatches
hover.transform.localPosition = new Vector3(0, 0f, 0.3f);
hover.sprite = MiraAssets.NextButtonActive.LoadAsset();
PassiveButton passiveButton = nextButton.gameObject.GetComponent<PassiveButton>();
var passiveButton = nextButton.gameObject.GetComponent<PassiveButton>();
passiveButton.OnClick = new Button.ButtonClickedEvent();
passiveButton.OnClick.AddListener((UnityAction)(() =>
{
CurrentSelectedMod += 1;
if (CurrentSelectedMod > MiraPluginManager.Instance.RegisteredPlugins.Count)
{
CurrentSelectedMod = 0;
}
__instance.RefreshTab();
__instance.scrollBar.ScrollToTop();
}));
// Create the back button
GameObject backButton = Object.Instantiate(nextButton, __instance.BackButton.transform.parent).gameObject;
var backButton = Object.Instantiate(nextButton, __instance.BackButton.transform.parent).gameObject;
backButton.transform.localPosition = new Vector3(-6.3f, 2.4f, -2f);
backButton.name = "LeftArrowButton";
backButton.transform.FindChild("Normal").gameObject.GetComponentInChildren<SpriteRenderer>().flipX
= backButton.transform.FindChild("Hover").gameObject.GetComponentInChildren<SpriteRenderer>().flipX
= true;
PassiveButton passiveButton2 = backButton.gameObject.GetComponent<PassiveButton>();
var passiveButton2 = backButton.gameObject.GetComponent<PassiveButton>();
passiveButton2.OnClick = new Button.ButtonClickedEvent();
passiveButton2.OnClick.AddListener((UnityAction)(() =>
{
CurrentSelectedMod -= 1;
if (CurrentSelectedMod < 0)
{
CurrentSelectedMod = MiraPluginManager.Instance.RegisteredPlugins.Count;
}
__instance.RefreshTab();
__instance.scrollBar.ScrollToTop();
}));
}
[HarmonyPostfix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.Update))]
public static void UpdatePatch(LobbyViewSettingsPane __instance)
{
__instance.gameModeText.text = SelectedMod?.PluginInfo.Metadata.Name ?? "Default";
}
[HarmonyPrefix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.DrawNormalTab))]
public static bool DrawNormalTabPatch(LobbyViewSettingsPane __instance)
{
if (CurrentSelectedMod == 0)
{
return true;
}
DrawOptionsTab(__instance);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.DrawRolesTab))]
public static bool DrawRolesTabPatch(LobbyViewSettingsPane __instance)
{
if (CurrentSelectedMod == 0)
{
return true;
}
DrawRolesTab(__instance);
return false;
}
private static void DrawOptionsTab(LobbyViewSettingsPane instance)
{
if (SelectedMod == null)
{
return;
}
var num = 1.44f;
var filteredGroups = SelectedMod.OptionGroups.Where(x => x.GroupVisible.Invoke() && x.AdvancedRole is null);
foreach (var group in filteredGroups)
{
if (group.Options.Count == 0)
{
continue;
}
var categoryHeaderMasked = Object.Instantiate(instance.categoryHeaderOrigin, instance.settingsContainer, true);
categoryHeaderMasked.SetHeader(StringNames.Name, 61);
categoryHeaderMasked.Title.text = group.GroupName;
categoryHeaderMasked.transform.localScale = Vector3.one;
categoryHeaderMasked.transform.localPosition = new Vector3(-9.77f, num, -2f);
instance.settingsInfo.Add(categoryHeaderMasked.gameObject);
num -= 0.85f;
var i = 0;
foreach (var option in group.Options)
{
if (!option.Visible.Invoke())
{
continue;
}
var viewSettingsInfoPanel = Object.Instantiate(instance.infoPanelOrigin, instance.settingsContainer, true);
viewSettingsInfoPanel.transform.localScale = Vector3.one;
float num2;
if (i % 2 == 0)
{
num2 = -8.95f;
if (i > 0)
{
num -= 0.59f;
}
}
else
{
num2 = -3f;
}
viewSettingsInfoPanel.transform.localPosition = new Vector3(num2, num, -2f);
var data = option.Data;
if (data.Type == OptionTypes.Checkbox)
{
viewSettingsInfoPanel.SetInfoCheckbox(data.Title, 61, Mathf.Approximately(option.GetFloatData(), 1));
}
else
{
viewSettingsInfoPanel.SetInfo(data.Title, data.GetValueString(option.GetFloatData()), 61);
}
instance.settingsInfo.Add(viewSettingsInfoPanel.gameObject);
i++;
}
num -= 0.59f;
}
instance.scrollBar.CalculateAndSetYBounds(instance.settingsInfo.Count + 10, 2f, 6f, 0.59f);
}
private static void DrawRolesTab(LobbyViewSettingsPane instance)
{
if (SelectedMod == null)
{
return;
}
var num = 0.95f;
var num2 = -6.53f;
var categoryHeaderMasked =
Object.Instantiate(instance.categoryHeaderOrigin, instance.settingsContainer, true);
categoryHeaderMasked.SetHeader(StringNames.RoleQuotaLabel, 61);
categoryHeaderMasked.transform.localScale = Vector3.one;
categoryHeaderMasked.transform.localPosition = new Vector3(-9.77f, 1.26f, -2f);
instance.settingsInfo.Add(categoryHeaderMasked.gameObject);
var list = new List<Type>();
foreach (var team in Enum.GetValues<ModdedRoleTeams>())
{
var filteredRoles = SelectedMod.CustomRoles.Values
.OfType<ICustomRole>()
.Where(x => !x.HideSettings && x.Team == team).ToList();
if (filteredRoles.Count == 0)
{
continue;
}
var categoryHeaderRoleVariant =
Object.Instantiate(instance.categoryHeaderRoleOrigin, instance.settingsContainer, true);
switch (team)
{
case ModdedRoleTeams.Crewmate:
categoryHeaderRoleVariant.SetHeader(StringNames.CrewmateRolesHeader, 61);
break;
case ModdedRoleTeams.Impostor:
categoryHeaderRoleVariant.SetHeader(StringNames.ImpostorRolesHeader, 61);
break;
case ModdedRoleTeams.Neutral:
default:
categoryHeaderRoleVariant.SetHeader(StringNames.CrewmateRolesHeader, 61);
categoryHeaderRoleVariant.Title.text = team + " Roles";
categoryHeaderRoleVariant.Background.color = Color.gray;
categoryHeaderRoleVariant.Title.color = Color.white;
break;
}
categoryHeaderRoleVariant.transform.localScale = Vector3.one;
categoryHeaderRoleVariant.transform.localPosition = new Vector3(0.09f, num, -2f);
instance.settingsInfo.Add(categoryHeaderRoleVariant.gameObject);
num -= 0.696f;
foreach (var customRole in filteredRoles)
{
var roleBehaviour = customRole as RoleBehaviour;
if (roleBehaviour == null)
{
continue;
}
var chancePerGame =
GameOptionsManager.Instance.CurrentGameOptions.RoleOptions.GetChancePerGame(roleBehaviour.Role);
var numPerGame =
GameOptionsManager.Instance.CurrentGameOptions.RoleOptions.GetNumPerGame(roleBehaviour.Role);
var flag = numPerGame == 0;
var viewSettingsInfoPanelRoleVariant =
Object.Instantiate(
instance.infoPanelRoleOrigin, instance.settingsContainer, true);
viewSettingsInfoPanelRoleVariant.transform.localScale = Vector3.one;
viewSettingsInfoPanelRoleVariant.transform.localPosition = new Vector3(num2, num, -2f);
var advancedRoleOptions = SelectedMod.Options
.Where(x => x.AdvancedRole == customRole.GetType())
.ToList();
if (!flag && advancedRoleOptions.Count > 0)
{
list.Add(customRole.GetType());
}
viewSettingsInfoPanelRoleVariant.SetInfo(roleBehaviour.NiceName, numPerGame, chancePerGame,
61, customRole.RoleColor, customRole.Icon.LoadAsset(), true);
viewSettingsInfoPanelRoleVariant.titleText.color =
viewSettingsInfoPanelRoleVariant.chanceTitle.color =
viewSettingsInfoPanelRoleVariant.chanceBackground.color =
viewSettingsInfoPanelRoleVariant.background.color =
customRole.RoleColor.GetAlternateColor();
instance.settingsInfo.Add(viewSettingsInfoPanelRoleVariant.gameObject);
num -= 0.664f;
}
}
if (list.Count > 0)
{
var categoryHeaderMasked2 =
Object.Instantiate(instance.categoryHeaderOrigin, instance.settingsContainer, true);
categoryHeaderMasked2.SetHeader(StringNames.RoleSettingsLabel, 61);
categoryHeaderMasked2.transform.localScale = Vector3.one;
categoryHeaderMasked2.transform.localPosition = new Vector3(-9.77f, num, -2f);
instance.settingsInfo.Add(categoryHeaderMasked2.gameObject);
num -= 1.7f;
var num3 = 0f;
for (var k = 0; k < list.Count; k++)
{
float num4;
if (k % 2 == 0)
{
num4 = -5.8f;
if (k > 0)
{
num -= num3 + 0.59f;
num3 = 0f;
}
}
else
{
num4 = 0.14999962f;
}
var advancedRoleViewPanel =
Object.Instantiate(instance.advancedRolePanelOrigin, instance.settingsContainer, true);
advancedRoleViewPanel.transform.localScale = Vector3.one;
advancedRoleViewPanel.transform.localPosition = new Vector3(num4, num, -2f);
var num5 = SetUpAdvancedRoleViewPanel(advancedRoleViewPanel, list[k], 0.59f, 61);
if (num5 > num3)
{
num3 = num5;
}
instance.settingsInfo.Add(advancedRoleViewPanel.gameObject);
}
}
instance.scrollBar.SetYBoundsMax(-num);
}
private static float SetUpAdvancedRoleViewPanel(AdvancedRoleViewPanel viewPanel, Type roleType, float spacingY, int maskLayer)
{
if (SelectedMod == null)
{
return 0;
}
var role = SelectedMod.CustomRoles.Values.FirstOrDefault(x => x.GetType() == roleType);
if (role == null)
{
return 0;
}
if (role is not ICustomRole customRole)
{
return 0;
}
viewPanel.header.SetHeader(role.StringName, maskLayer, role.TeamType == RoleTeamTypes.Crewmate, customRole.Icon.LoadAsset());
viewPanel.divider.material.SetInt(PlayerMaterial.MaskLayer, maskLayer);
var num = viewPanel.yPosStart;
var num2 = 1.08f;
var filteredOptions = SelectedMod.Options
.Where(x => x.AdvancedRole == roleType)
.ToList();
for (var i = 0; i < filteredOptions.Count; i++)
{
var option = filteredOptions[i];
BaseGameSetting baseGameSetting = option.Data;
var viewSettingsInfoPanel = Object.Instantiate(viewPanel.infoPanelOrigin, viewPanel.transform, true);
viewSettingsInfoPanel.transform.localScale = Vector3.one;
viewSettingsInfoPanel.transform.localPosition = new Vector3(viewPanel.xPosStart, num, -2f);
var value = option.GetFloatData();
if (baseGameSetting.Type == OptionTypes.Checkbox)
{
viewSettingsInfoPanel.SetInfoCheckbox(baseGameSetting.Title, maskLayer, value > 0f);
}
else
{
viewSettingsInfoPanel.SetInfo(baseGameSetting.Title, baseGameSetting.GetValueString(value), maskLayer);
}
num -= spacingY;
if (i > 0)
{
num2 += 0.8f;
}
}
return num2;
}
}
+15 -3
View File
@@ -11,7 +11,11 @@ public static class OptionsPatches
[HarmonyPatch(typeof(ToggleOption), nameof(ToggleOption.Initialize))]
public static bool ToggleInit(ToggleOption __instance)
{
if (!__instance.IsCustom()) return true;
if (!__instance.IsCustom())
{
return true;
}
__instance.TitleText.text = DestroyableSingleton<TranslationController>.Instance.GetString(__instance.Title, Array.Empty<Object>());
return false;
@@ -28,7 +32,11 @@ public static class OptionsPatches
[HarmonyPatch(typeof(NumberOption), nameof(NumberOption.Initialize))]
public static bool NumberInit(NumberOption __instance)
{
if (!__instance.IsCustom()) return true;
if (!__instance.IsCustom())
{
return true;
}
__instance.TitleText.text = DestroyableSingleton<TranslationController>.Instance.GetString(__instance.Title, Array.Empty<Object>());
return false;
@@ -45,7 +53,11 @@ public static class OptionsPatches
[HarmonyPatch(typeof(StringOption), nameof(StringOption.Initialize))]
public static bool StringInit(StringOption __instance)
{
if (!__instance.IsCustom()) return true;
if (!__instance.IsCustom())
{
return true;
}
__instance.TitleText.text = DestroyableSingleton<TranslationController>.Instance.GetString(__instance.Title, Array.Empty<Object>());
__instance.ValueText.text = DestroyableSingleton<TranslationController>.Instance.GetString(__instance.Values[__instance.Value], Array.Empty<Object>());
+112 -44
View File
@@ -27,6 +27,7 @@ public static class RoleSettingMenuPatches
__instance.advancedSettingChildren = new Il2CppSystem.Collections.Generic.List<OptionBehaviour>();
var maskBg = __instance.scrollBar.transform.FindChild("MaskBg");
var hitbox = __instance.scrollBar.transform.FindChild("Hitbox");
if (GameSettingMenuPatches.CurrentSelectedMod == 0)
{
@@ -35,6 +36,8 @@ public static class RoleSettingMenuPatches
__instance.scrollBar.transform.localPosition = new Vector3(-1.4957f, 0.657f, -4);
maskBg.localPosition = new Vector3(1.5353f, -.5734f, -.1f);
maskBg.localScale = new Vector3(6.6811f, 3.3563f, 0.5598f);
hitbox.localPosition = new Vector3(0.3297f, -.2333f, 4f);
hitbox.localScale = new Vector3(1, 1, 1);
return true;
}
@@ -45,44 +48,75 @@ public static class RoleSettingMenuPatches
__instance.scrollBar.transform.localPosition = new Vector3(-1.4957f, 1.5261f, -4);
maskBg.localPosition = new Vector3(1.5353f, -1.0607f, -.1f);
maskBg.localScale = new Vector3(6.6811f, 4.1563f, 0.5598f);
hitbox.localPosition = new Vector3(0.3297f, -.6333f, 4f);
hitbox.localScale = new Vector3(1, 1.2f, 1);
CategoryHeaderEditRole categoryHeaderEditRole = Object.Instantiate(__instance.categoryHeaderEditRoleOrigin, Vector3.zero, Quaternion.identity, __instance.RoleChancesSettings.transform);
categoryHeaderEditRole.SetHeader(StringNames.CrewmateRolesHeader, 20);
categoryHeaderEditRole.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
int num3 = 0;
foreach (var role in GameSettingMenuPatches.SelectedMod.CustomRoles.Values.OfType<ICustomRole>().Where(role => role.Team == ModdedRoleTeams.Crewmate))
var crewRoles = GameSettingMenuPatches.SelectedMod.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role.Team == ModdedRoleTeams.Crewmate && !role.HideSettings)
.ToList();
if (crewRoles.Count > 0)
{
CreateQuotaOption(__instance, role as RoleBehaviour, ref num, num3);
num3++;
CategoryHeaderEditRole categoryHeaderEditRole = Object.Instantiate(__instance.categoryHeaderEditRoleOrigin, Vector3.zero, Quaternion.identity, __instance.RoleChancesSettings.transform);
categoryHeaderEditRole.SetHeader(StringNames.CrewmateRolesHeader, 20);
categoryHeaderEditRole.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
foreach (var role in crewRoles)
{
CreateQuotaOption(__instance, role as RoleBehaviour, ref num, num3);
num3++;
}
}
num -= 0.4f;
CategoryHeaderEditRole categoryHeaderEditRole2 = Object.Instantiate(__instance.categoryHeaderEditRoleOrigin, Vector3.zero, Quaternion.identity, __instance.RoleChancesSettings.transform);
categoryHeaderEditRole2.SetHeader(StringNames.ImpostorRolesHeader, 20);
categoryHeaderEditRole2.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
var impRoles = GameSettingMenuPatches.SelectedMod.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role.Team == ModdedRoleTeams.Impostor && !role.HideSettings)
.ToList();
foreach (var role in GameSettingMenuPatches.SelectedMod.CustomRoles.Values.OfType<ICustomRole>().Where(role => role.Team == ModdedRoleTeams.Impostor))
if (impRoles.Count > 0)
{
CreateQuotaOption(__instance, role as RoleBehaviour, ref num, num3);
num3++;
num -= 0.4f;
CategoryHeaderEditRole categoryHeaderEditRole2 = Object.Instantiate(__instance.categoryHeaderEditRoleOrigin,
Vector3.zero, Quaternion.identity, __instance.RoleChancesSettings.transform);
categoryHeaderEditRole2.SetHeader(StringNames.ImpostorRolesHeader, 20);
categoryHeaderEditRole2.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
foreach (var role in impRoles)
{
CreateQuotaOption(__instance, role as RoleBehaviour, ref num, num3);
num3++;
}
}
num -= 0.8f;
CategoryHeaderEditRole categoryHeaderEditRole3 = Object.Instantiate(__instance.categoryHeaderEditRoleOrigin, Vector3.zero, Quaternion.identity, __instance.RoleChancesSettings.transform);
categoryHeaderEditRole3.SetHeader(StringNames.None, 20);
categoryHeaderEditRole3.Title.text = "Neutral Roles";
categoryHeaderEditRole3.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
var neutRoles = GameSettingMenuPatches.SelectedMod.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role.Team == ModdedRoleTeams.Neutral && !role.HideSettings)
.ToList();
foreach (var role in GameSettingMenuPatches.SelectedMod.CustomRoles.Values.OfType<ICustomRole>().Where(role => role.Team == ModdedRoleTeams.Neutral))
if (neutRoles.Count > 0)
{
CreateQuotaOption(__instance, role as RoleBehaviour, ref num, num3);
num3++;
num -= 0.4f;
CategoryHeaderEditRole categoryHeaderEditRole3 = Object.Instantiate(__instance.categoryHeaderEditRoleOrigin,
Vector3.zero, Quaternion.identity, __instance.RoleChancesSettings.transform);
categoryHeaderEditRole3.SetHeader(StringNames.None, 20);
categoryHeaderEditRole3.Title.text = "Neutral Roles";
categoryHeaderEditRole3.Background.color = Color.gray;
categoryHeaderEditRole3.Title.color = Color.white;
categoryHeaderEditRole3.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
foreach (var role in neutRoles)
{
CreateQuotaOption(__instance, role as RoleBehaviour, ref num, num3);
num3++;
}
}
return false;
@@ -100,24 +134,42 @@ public static class RoleSettingMenuPatches
return false;
}
[HarmonyPostfix]
[HarmonyPatch(nameof(RolesSettingsMenu.OpenChancesTab))]
public static void OpenChancesTabPostfix(RolesSettingsMenu __instance)
{
__instance.scrollBar.CalculateAndSetYBounds(__instance.roleChances.Count + 5, 1f, 6f, 0.43f);
__instance.scrollBar.ScrollToTop();
}
private static void ValueChanged(OptionBehaviour obj)
{
var roleSetting = obj.Cast<RoleOptionSetting>();
var role = roleSetting.Role as ICustomRole;
if (role is null or { HideSettings: true }) return;
if (role is null or { HideSettings: true })
{
return;
}
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(role.NumConfigDefinition, out var numEntry);
numEntry.Value = roleSetting.RoleMaxCount;
try
{
role.ParentMod.PluginConfig.TryGetEntry<int>(role.NumConfigDefinition, out var numEntry);
numEntry.Value = roleSetting.RoleMaxCount;
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(role.ChanceConfigDefinition, out var chanceEntry);
chanceEntry.Value = roleSetting.RoleChance;
role.ParentMod.PluginConfig.TryGetEntry<int>(role.ChanceConfigDefinition, out var chanceEntry);
chanceEntry.Value = roleSetting.RoleChance;
}
catch (Exception e)
{
Logger<MiraApiPlugin>.Warning(e);
}
roleSetting.UpdateValuesAndText(GameOptionsManager.Instance.CurrentGameOptions.RoleOptions);
DestroyableSingleton<HudManager>.Instance.Notifier.AddRoleSettingsChangeMessage(roleSetting.Role.StringName, roleSetting.RoleMaxCount, roleSetting.RoleChance, roleSetting.Role.TeamType, false);
if (AmongUsClient.Instance.AmHost)
{
Rpc<SyncRoleOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, [role.GetNetData(roleSetting.Role)], true);
Rpc<SyncRoleOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, [role.GetNetData()], true);
}
GameOptionsManager.Instance.GameHostOptions = GameOptionsManager.Instance.CurrentGameOptions;
}
@@ -132,8 +184,16 @@ public static class RoleSettingMenuPatches
__instance.advancedSettingChildren.Clear();
float num = -0.872f;
foreach (var option in GameSettingMenuPatches.SelectedMod.Options.Where(option => option.AdvancedRole != null && option.AdvancedRole == role.GetType()))
var filteredOptions = GameSettingMenuPatches.SelectedMod.Options.Where(x => x.AdvancedRole == role.GetType());
foreach (var option in filteredOptions)
{
if (option.AdvancedRole is not null && option.AdvancedRole != role.GetType())
{
continue;
}
OptionBehaviour newOpt = option.CreateOption(__instance.checkboxOrigin, __instance.numberOptionOrigin, __instance.stringOptionOrigin, __instance.AdvancedRolesSettings.transform);
newOpt.transform.localPosition = new Vector3(2.17f, num, -2f);
newOpt.SetClickMask(__instance.ButtonClickMask);
@@ -156,17 +216,18 @@ public static class RoleSettingMenuPatches
newOpt.Initialize();
}
__instance.scrollBar.CalculateAndSetYBounds((float)(__instance.advancedSettingChildren.Count + 3), 1f, 6f, 0.45f);
__instance.scrollBar.CalculateAndSetYBounds(__instance.advancedSettingChildren.Count + 3, 1f, 6f, 0.45f);
__instance.scrollBar.ScrollToTop();
}
private static void ChangeTab(RoleBehaviour role, RolesSettingsMenu __instance)
{
ICustomRole customRole = role as ICustomRole;
__instance.roleDescriptionText.text = customRole.RoleLongDescription;
__instance.roleTitleText.text = DestroyableSingleton<TranslationController>.Instance.GetString(role.StringName, []);
__instance.roleScreenshot.sprite = Sprite.Create(role.RoleScreenshot.texture, new Rect(0, 0, 370, 230), Vector2.one / 2, 100);
__instance.roleTitleText.text = DestroyableSingleton<TranslationController>.Instance.GetString(role.StringName, Array.Empty<Il2CppSystem.Object>());
__instance.roleScreenshot.sprite = Sprite.Create(customRole.OptionsScreenshot.LoadAsset().texture, new Rect(0, 0, 370, 230), Vector2.one / 2, 100);
__instance.roleScreenshot.drawMode = SpriteDrawMode.Sliced;
__instance.roleHeaderSprite.color = customRole.RoleColor;
__instance.roleHeaderText.color = customRole.RoleColor.DarkenColor();
__instance.roleHeaderText.color = customRole.RoleColor.GetAlternateColor();
CreateAdvancedSettings(__instance, role);
@@ -190,21 +251,28 @@ public static class RoleSettingMenuPatches
roleOptionSetting.transform.localPosition = new Vector3(-0.15f, yPos, -2f);
roleOptionSetting.SetRole(GameOptionsManager.Instance.CurrentGameOptions.RoleOptions, role, 20);
roleOptionSetting.labelSprite.color = customRole.RoleColor;
roleOptionSetting.titleText.color = customRole.RoleColor.DarkenColor();
roleOptionSetting.OnValueChanged = new Action<OptionBehaviour>(ValueChanged);
roleOptionSetting.titleText.horizontalAlignment = HorizontalAlignmentOptions.Left;
roleOptionSetting.SetClickMask(__instance.ButtonClickMask);
__instance.roleChances.Add(roleOptionSetting);
roleOptionSetting.titleText.transform.localPosition = new Vector3(-0.5376f, -0.2923f, 0f);
roleOptionSetting.titleText.color = customRole.RoleColor.GetAlternateColor();
roleOptionSetting.titleText.horizontalAlignment = HorizontalAlignmentOptions.Left;
PassiveButton newButton = Object.Instantiate(roleOptionSetting.buttons[0], roleOptionSetting.transform);
newButton.name = "ConfigButton";
newButton.transform.localPosition = new Vector3(0.2419f, -0.2582f, -2f);
newButton.transform.FindChild("Plus_TMP").gameObject.DestroyImmediate();
newButton.transform.FindChild("InactiveSprite").GetComponent<SpriteRenderer>().sprite = MiraAssets.Cog.LoadAsset();
newButton.transform.FindChild("ActiveSprite").GetComponent<SpriteRenderer>().sprite = MiraAssets.CogActive.LoadAsset();
newButton.transform.localPosition = new Vector3(0.4473f, -0.3f, -2f);
newButton.transform.FindChild("Text_TMP").gameObject.DestroyImmediate();
newButton.activeSprites.Destroy();
PassiveButton passiveButton = newButton.GetComponent<PassiveButton>();
SpriteRenderer btnRend = newButton.transform.FindChild("ButtonSprite").GetComponent<SpriteRenderer>();
btnRend.sprite = MiraAssets.Cog.LoadAsset();
GameOptionButton passiveButton = newButton.GetComponent<GameOptionButton>();
passiveButton.OnClick = new ButtonClickedEvent();
passiveButton.interactableColor = btnRend.color = customRole.RoleColor.GetAlternateColor();
passiveButton.interactableHoveredColor = Color.white;
passiveButton.OnClick.AddListener((UnityAction)(() =>
{
ChangeTab(role, __instance);
+13 -4
View File
@@ -1,5 +1,6 @@
using HarmonyLib;
using MiraAPI.Hud;
using MiraAPI.Roles;
using MiraAPI.Modifiers;
using Reactor.Utilities.Extensions;
@@ -21,17 +22,25 @@ public static class PlayerControlPatches
[HarmonyPatch(nameof(PlayerControl.FixedUpdate))]
public static void PlayerControlFixedUpdatePostfix(PlayerControl __instance)
{
if (!__instance.AmOwner) return;
if (__instance.Data?.Role is ICustomRole customRole)
{
customRole.PlayerControlFixedUpdate(__instance);
}
if (!__instance.AmOwner)
{
return;
}
foreach (var button in CustomButtonManager.CustomButtons)
{
if (!button.Enabled(__instance.Data?.Role))
{
continue;
}
button.FixedUpdateHandler(__instance);
}
}
}
+26
View File
@@ -0,0 +1,26 @@
using HarmonyLib;
using MiraAPI.Roles;
namespace MiraAPI.Patches.Roles;
[HarmonyPatch(typeof(ExileController))]
public static class EjectionPatches
{
[HarmonyPostfix]
[HarmonyPatch(nameof(ExileController.Begin))]
public static void Begin(ExileController __instance)
{
if (!__instance.initData.networkedPlayer || !__instance.initData.networkedPlayer.Role || __instance.initData.networkedPlayer.Role is not ICustomRole role)
{
return;
}
if (role.GetCustomEjectionMessage(__instance.initData.networkedPlayer) == null)
{
return;
}
__instance.completeString = role.GetCustomEjectionMessage(__instance.initData.networkedPlayer);
}
}
@@ -1,5 +1,6 @@
using HarmonyLib;
using MiraAPI.Roles;
using MiraAPI.Utilities.Colors;
namespace MiraAPI.Patches.Roles;
@@ -22,5 +23,6 @@ public static class GameStartupPatch
_runOnce = true;
CustomRoleManager.RegisterInRoleManager();
PaletteManager.RegisterAllColors();
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ public static class NameTagPatch
return true;
}
if (PlayerControl.LocalPlayer == null || PlayerControl.LocalPlayer.Data == null || PlayerControl.LocalPlayer.Data.Role == null || otherPlayerRole == null)
if (!PlayerControl.LocalPlayer || !PlayerControl.LocalPlayer.Data || !PlayerControl.LocalPlayer.Data.Role || !otherPlayerRole)
{
__result = Color.white;
}
+1 -1
View File
@@ -23,7 +23,7 @@ public static class RoleManagerPatches
[HarmonyPatch(nameof(RoleManager.AssignRoleOnDeath))]
public static bool AssignRoleOnDeath(RoleManager __instance, [HarmonyArgument(0)] PlayerControl plr)
{
if (plr == null || !plr.Data.IsDead)
if (!plr || !plr.Data.IsDead)
{
return false;
}
@@ -1,7 +1,6 @@
using AmongUs.GameOptions;
using HarmonyLib;
using MiraAPI.Roles;
using Reactor.Utilities;
namespace MiraAPI.Patches.Roles;
@@ -22,7 +21,7 @@ public static class RoleOptionsCollectionPatch
return false;
}
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(customRole.ChanceConfigDefinition, out var entry);
customRole.ParentMod.PluginConfig.TryGetEntry<int>(customRole.ChanceConfigDefinition, out var entry);
__result = entry.Value;
return false;
}
@@ -44,7 +43,7 @@ public static class RoleOptionsCollectionPatch
return false;
}
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(customRole.NumConfigDefinition, out var entry);
customRole.ParentMod.PluginConfig.TryGetEntry<int>(customRole.NumConfigDefinition, out var entry);
__result = entry.Value;
return false;
}
+4 -4
View File
@@ -160,23 +160,23 @@ public static class TaskAdderPatch
RoleBehaviour roleBehaviour = DestroyableSingleton<RoleManager>.Instance.AllRoles[m];
if (roleBehaviour.Role != RoleTypes.ImpostorGhost && roleBehaviour.Role != RoleTypes.CrewmateGhost && !CustomRoleManager.CustomRoles.ContainsKey((ushort)roleBehaviour.Role))
{
TaskAddButton taskAddButton2 = Object.Instantiate<TaskAddButton>(__instance.RoleButton);
TaskAddButton taskAddButton2 = Object.Instantiate(__instance.RoleButton);
taskAddButton2.SafePositionWorld = __instance.SafePositionWorld;
taskAddButton2.Text.text = "Be_" + roleBehaviour.NiceName + ".exe";
__instance.AddFileAsChild(RolesFolder, taskAddButton2, ref num, ref num2, ref num3);
taskAddButton2.Role = roleBehaviour;
if (taskAddButton2 != null && taskAddButton2.Button != null)
{
ControllerManager.Instance.AddSelectableUiElement(taskAddButton2.Button, false);
ControllerManager.Instance.AddSelectableUiElement(taskAddButton2.Button);
if (m == 0 && __instance.restorePreviousSelectionFound != null)
{
ControllerManager.Instance.SetDefaultSelection(__instance.restorePreviousSelectionFound, null);
ControllerManager.Instance.SetDefaultSelection(__instance.restorePreviousSelectionFound);
__instance.restorePreviousSelectionByFolderName = string.Empty;
__instance.restorePreviousSelectionFound = null;
}
else if (m == 0)
{
ControllerManager.Instance.SetDefaultSelection(taskAddButton2.Button, null);
ControllerManager.Instance.SetDefaultSelection(taskAddButton2.Button);
}
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ public static class TaskPanelPatch
vector2.x += vector.x * 2f;
__instance.tab.transform.localPosition = vector2;
if (GameManager.Instance == null)
if (!GameManager.Instance)
{
return false;
}
+1
View File
@@ -4,5 +4,6 @@ namespace MiraAPI.PluginLoading;
public interface IMiraPlugin
{
string OptionsTitleText { get; }
public ConfigFile GetConfigFile();
}
+3 -3
View File
@@ -6,14 +6,14 @@ using System.Collections.Generic;
namespace MiraAPI.PluginLoading;
public class MiraPluginInfo(string id, IMiraPlugin miraPlugin, PluginInfo info)
public class MiraPluginInfo(IMiraPlugin miraPlugin, PluginInfo info)
{
public string PluginId { get; set; } = id;
public string PluginId { get; set; } = info.Metadata.GUID;
public IMiraPlugin MiraPlugin { get; set; } = miraPlugin;
public PluginInfo PluginInfo { get; set; } = info;
public ConfigFile PluginConfig { get; set; } = miraPlugin.GetConfigFile();
public readonly List<IModdedOptionGroup> OptionGroups = [];
public readonly List<AbstractOptionGroup> OptionGroups = [];
public readonly List<IModdedOption> Options = [];
public readonly Dictionary<ushort, RoleBehaviour> CustomRoles = [];
+86 -56
View File
@@ -1,20 +1,23 @@
using BepInEx;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP;
using Il2CppInterop.Runtime.Injection;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.Hud;
using MiraAPI.Hud;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using MiraAPI.Utilities.Colors;
using Reactor.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MiraAPI.Utilities;
using Reactor.Networking;
namespace MiraAPI.PluginLoading;
public class MiraPluginManager
internal class MiraPluginManager
{
public readonly Dictionary<Assembly, MiraPluginInfo> RegisteredPlugins = [];
@@ -26,25 +29,29 @@ public class MiraPluginManager
private set => _instance = value;
}
public void Initialize()
internal void Initialize()
{
Instance = this;
IL2CPPChainloader.Instance.PluginLoad += (_, assembly, plugin) =>
IL2CPPChainloader.Instance.PluginLoad += (pluginInfo, assembly, plugin) =>
{
if (!plugin.GetType().GetInterfaces().Contains(typeof(IMiraPlugin))) return;
if (!plugin.GetType().GetInterfaces().Contains(typeof(IMiraPlugin)))
{
return;
}
var id = MetadataHelper.GetMetadata(plugin.GetType()).GUID;
var info = new MiraPluginInfo(id, plugin as IMiraPlugin, IL2CPPChainloader.Instance.Plugins[id]);
var info = new MiraPluginInfo(plugin as IMiraPlugin, pluginInfo);
RegisterModifierAttribute(assembly);
RegisterOptionsGroups(assembly, info);
RegisterOptionsAttributes(assembly, info);
RegisterAllOptions(assembly, info);
RegisterRoleAttribute(assembly, info);
RegisterButtonAttribute(assembly);
RegisterColorClasses(assembly);
RegisteredPlugins.Add(assembly, info);
Logger<MiraApiPlugin>.Info($"Registering mod {id} with Mira API.");
Logger<MiraApiPlugin>.Info($"Registering mod {pluginInfo.Metadata.GUID} with Mira API.");
};
}
@@ -53,73 +60,95 @@ public class MiraPluginManager
return RegisteredPlugins.Values.First(plugin => plugin.PluginId == guid);
}
private static void RegisterOptionsAttributes(Assembly assembly, MiraPluginInfo pluginInfo)
private static void RegisterAllOptions(Assembly assembly, MiraPluginInfo pluginInfo)
{
foreach (var type in assembly.GetTypes())
var filteredTypes = assembly.GetTypes().Where(type => type.IsAssignableTo(typeof(AbstractOptionGroup)));
foreach (var type in filteredTypes)
{
foreach (PropertyInfo property in type.GetProperties())
if (!ModdedOptionsManager.RegisterGroup(type, pluginInfo))
{
foreach (var attribute in property.GetCustomAttributes())
{
if (attribute.GetType().BaseType == typeof(ModdedOptionAttribute))
{
pluginInfo.Options.Add(ModdedOptionsManager.RegisterOption(type, (ModdedOptionAttribute)attribute, property));
}
}
continue;
}
}
}
private static void RegisterOptionsGroups(Assembly assembly, MiraPluginInfo pluginInfo)
{
foreach (var type in assembly.GetTypes())
{
if (typeof(IModdedOptionGroup).IsAssignableFrom(type))
foreach (var property in type.GetProperties())
{
IModdedOptionGroup group = (IModdedOptionGroup)Activator.CreateInstance(type);
ModdedOptionsManager.Groups.Add(group);
ModdedOptionsManager.OriginalTypes.Add(type, group);
pluginInfo.OptionGroups.Add(group);
foreach (var property in type.GetProperties())
if (property.PropertyType.IsAssignableTo(typeof(IModdedOption)))
{
if (typeof(IModdedOption).IsAssignableFrom(property.PropertyType))
{
IModdedOption option = (IModdedOption)property.GetValue(group);
option.Group = group;
option.AdvancedRole = group.AdvancedRole;
}
ModdedOptionsManager.RegisterPropertyOption(type, property, pluginInfo);
continue;
}
var attribute = property.GetCustomAttribute<ModdedOptionAttribute>();
if (attribute == null)
{
continue;
}
ModdedOptionsManager.RegisterAttributeOption(type, attribute, property, pluginInfo);
}
}
}
private static void RegisterRoleAttribute(Assembly assembly, MiraPluginInfo pluginInfo)
{
List<Type> roles = [];
foreach (var type in assembly.GetTypes())
{
var attribute = type.GetCustomAttribute<RegisterCustomRoleAttribute>();
if (attribute == null) continue;
ClassInjector.RegisterTypeInIl2Cpp(type);
var role = CustomRoleManager.RegisterRole(type, attribute.RoleId);
try
if (attribute == null)
{
pluginInfo.CustomRoles.Add((ushort)role.Role, role);
continue;
}
catch (Exception e)
if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type)))
{
Logger<MiraApiPlugin>.Error("Failed to register role: " + type.Name);
Logger<MiraApiPlugin>.Error($"{type.Name} does not inherit from RoleBehaviour or ICustomRole.");
continue;
}
if (!ModList.GetById(pluginInfo.PluginId).IsRequiredOnAllClients)
{
Logger<MiraApiPlugin>.Error("Custom roles are only supported on all clients.");
return;
}
roles.Add(type);
}
CustomRoleManager.RegisterRoleTypes(roles, pluginInfo);
}
foreach (var (k, v) in pluginInfo.CustomRoles)
private static void RegisterColorClasses(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
{
if (type.GetCustomAttribute<RegisterCustomColorsAttribute>() == null)
{
continue;
}
if (!type.IsStatic())
{
Logger<MiraApiPlugin>.Error($"Color class {type.Name} must be static.");
continue;
}
foreach (var property in type.GetProperties())
{
if (property.PropertyType != typeof(CustomColor))
{
Logger<MiraApiPlugin>.Error($"{k}: {v}");
continue;
}
Logger<MiraApiPlugin>.Error(e);
var color = (CustomColor)property.GetValue(null);
if (color == null)
{
Logger<MiraApiPlugin>.Error($"Color property {property.Name} in {type.Name} is null.");
continue;
}
PaletteManager.CustomColors.Add(color);
}
}
}
@@ -136,6 +165,7 @@ public class MiraPluginManager
}
}
private static void RegisterButtonAttribute(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
Binary file not shown.

After

Width:  |  Height:  |  Size: 347 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

+74 -62
View File
@@ -9,7 +9,8 @@ using Reactor.Utilities.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using MiraAPI.Utilities;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -19,24 +20,40 @@ namespace MiraAPI.Roles;
public static class CustomRoleManager
{
public static readonly Dictionary<ushort, RoleBehaviour> CustomRoles = new();
private static int GetNextRoleId(ushort requestedId)
public static readonly Dictionary<Type, ushort> RoleIds = new();
private static ushort _roleId = 100;
private static ushort GetNextRoleId()
{
while (CustomRoles.ContainsKey(requestedId) || requestedId <= Enum.GetNames<RoleTypes>().Length)
{
Logger<MiraApiPlugin>.Error(requestedId + ", " + (requestedId+1));
requestedId++;
}
return requestedId;
return _roleId++;
}
public static void RegisterInRoleManager()
internal static void RegisterInRoleManager()
{
RoleManager.Instance.AllRoles = RoleManager.Instance.AllRoles.Concat(CustomRoles.Values).ToArray();
}
internal static RoleBehaviour RegisterRole(Type roleType, ushort roleId)
public static void RegisterRoleTypes(List<Type> roles, MiraPluginInfo pluginInfo)
{
roles.ForEach(x=>RoleIds.Add(x, GetNextRoleId()));
foreach (var roleType in roles)
{
ClassInjector.RegisterTypeInIl2Cpp(roleType);
var role = RegisterRole(roleType, pluginInfo);
if (role is null)
{
continue;
}
pluginInfo.CustomRoles.Add((ushort)role.Role, role);
}
}
private static RoleBehaviour RegisterRole(Type roleType, MiraPluginInfo parentMod)
{
if (!(typeof(RoleBehaviour).IsAssignableFrom(roleType) && typeof(ICustomRole).IsAssignableFrom(roleType)))
{
@@ -51,8 +68,10 @@ public static class CustomRoleManager
roleBehaviour.gameObject.Destroy();
return null;
}
var roleId = RoleIds[roleType];
roleBehaviour.Role = (RoleTypes)GetNextRoleId(roleId);
roleBehaviour.Role = (RoleTypes)roleId;
roleBehaviour.TeamType = customRole.Team == ModdedRoleTeams.Neutral ? RoleTeamTypes.Crewmate : (RoleTeamTypes)customRole.Team;
roleBehaviour.NameColor = customRole.RoleColor;
roleBehaviour.StringName = CustomStringName.CreateAndRegister(customRole.RoleName);
@@ -79,22 +98,22 @@ public static class CustomRoleManager
return roleBehaviour;
}
var config = PluginSingleton<MiraApiPlugin>.Instance.Config;
var config = parentMod.PluginConfig;
config.Bind(customRole.NumConfigDefinition, 1);
config.Bind(customRole.ChanceConfigDefinition, 100);
return roleBehaviour;
}
public static MiraPluginInfo FindParentMod(ICustomRole role)
{
return MiraPluginManager.Instance.RegisteredPlugins.First(plugin => plugin.Value.CustomRoles.Values.Contains(role as RoleBehaviour)).Value;
return MiraPluginManager.Instance.RegisteredPlugins.First(plugin => plugin.Value.CustomRoles.ContainsValue(role as RoleBehaviour)).Value;
}
public static bool GetCustomRoleBehaviour(RoleTypes roleType, out ICustomRole result)
{
CustomRoles.TryGetValue((ushort)roleType, out var temp);
if (temp != null)
if (temp)
{
result = temp as ICustomRole;
return true;
@@ -104,7 +123,7 @@ public static class CustomRoleManager
return false;
}
public static TaskPanelBehaviour CreateRoleTab(ICustomRole role)
internal static TaskPanelBehaviour CreateRoleTab(ICustomRole role)
{
var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").gameObject.GetComponent<TaskPanelBehaviour>();
var clonePanel = Object.Instantiate(ogPanel.gameObject, ogPanel.transform.parent);
@@ -122,7 +141,7 @@ public static class CustomRoleManager
return newPanel;
}
public static void UpdateRoleTab(TaskPanelBehaviour panel, ICustomRole role)
internal static void UpdateRoleTab(TaskPanelBehaviour panel, ICustomRole role)
{
var tabText = panel.tab.gameObject.GetComponentInChildren<TextMeshPro>();
var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").gameObject.GetComponent<TaskPanelBehaviour>();
@@ -138,60 +157,53 @@ public static class CustomRoleManager
panel.SetTaskText(role.SetTabText().ToString());
}
public static void SyncAllRoleSettings(int targetId=-1)
internal static void SyncAllRoleSettings(int targetId=-1)
{
List<NetData> data = [];
int count = 0;
foreach (var role in CustomRoles.Values)
var data = CustomRoles.Values
.Where(x => x is ICustomRole { HideSettings: false })
.Select(x => ((ICustomRole)x).GetNetData())
.ChunkNetData(1000);
while (data.Count > 0)
{
ICustomRole customRole = role as ICustomRole;
Rpc<SyncRoleOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, data.Dequeue());
}
}
internal static void HandleSyncRoleOptions(NetData[] data)
{
foreach (var netData in data)
{
if (!CustomRoles.TryGetValue((ushort)netData.Id, out var role))
{
continue;
}
var customRole = role as ICustomRole;
if (customRole is null or { HideSettings: true })
{
continue;
}
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(customRole.NumConfigDefinition, out var numEntry);
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(customRole.ChanceConfigDefinition, out var chanceEntry);
var netData = new NetData((uint)role.Role, BitConverter.GetBytes(numEntry.Value).AddRangeToArray(BitConverter.GetBytes(chanceEntry.Value)));
data.Add(netData);
count += netData.GetLength();
if (count > 1000)
{
Rpc<SyncRoleOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, data.ToArray());
data.Clear();
count = 0;
}
}
if (data.Count > 0)
{
Rpc<SyncRoleOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, data.ToArray());
}
}
public static void HandleSyncRoleOptions(NetData[] data)
{
foreach (var netData in data)
{
if (CustomRoles.TryGetValue((ushort)netData.Id, out var role))
var num = BitConverter.ToInt32(netData.Data, 0);
var chance = BitConverter.ToInt32(netData.Data, 4);
DestroyableSingleton<HudManager>.Instance.Notifier.AddRoleSettingsChangeMessage(role.StringName, num, chance, role.TeamType, false);
try
{
var customRole = role as ICustomRole;
if (customRole is null or { HideSettings: true })
{
continue;
}
var num = BitConverter.ToInt32(netData.Data, 0);
var chance = BitConverter.ToInt32(netData.Data, 4);
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(customRole.NumConfigDefinition, out var numEntry);
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(customRole.ChanceConfigDefinition, out var chanceEntry);
customRole.ParentMod.PluginConfig.TryGetEntry<int>(customRole.NumConfigDefinition,
out var numEntry);
customRole.ParentMod.PluginConfig.TryGetEntry<int>(customRole.ChanceConfigDefinition,
out var chanceEntry);
numEntry.Value = num;
chanceEntry.Value = chance;
}
catch (Exception e)
{
Logger<MiraApiPlugin>.Error(e);
}
}
}
}
+18 -11
View File
@@ -8,6 +8,7 @@ using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using System;
using System.Text;
using MiraAPI.PluginLoading;
using UnityEngine;
namespace MiraAPI.Roles;
@@ -24,7 +25,7 @@ public interface ICustomRole
ModdedRoleTeams Team { get; }
LoadableAsset<Sprite> OptionsScreenshot { get; }
LoadableAsset<Sprite> OptionsScreenshot => MiraAssets.Empty;
LoadableAsset<Sprite> Icon => MiraAssets.Empty;
@@ -46,18 +47,24 @@ public interface ICustomRole
bool IsGhostRole => false;
bool TargetsBodies => false;
bool CreateCustomTab => true;
bool HideSettings => IsGhostRole;
RoleTypes GhostRole => Team == ModdedRoleTeams.Crewmate ? RoleTypes.CrewmateGhost : RoleTypes.ImpostorGhost;
void CreateOptions() { }
MiraPluginInfo ParentMod => CustomRoleManager.FindParentMod(this);
/// <summary>
/// Runs on the PlayerControl FixedUpdate method for any player with this role
/// </summary>
/// <param name="playerControl">The PlayerControl that has this role</param>
void PlayerControlFixedUpdate(PlayerControl playerControl) { }
/// <summary>
/// Only runs for local player on HudManager Update method
/// </summary>
/// <param name="hudManager">Reference to HudManager instance</param>
void HudUpdate(HudManager hudManager) { }
string GetCustomEjectionMessage(NetworkedPlayerInfo player)
@@ -70,17 +77,17 @@ public interface ICustomRole
var taskStringBuilder = Helpers.CreateForRole(this);
return taskStringBuilder;
}
bool IsModifierApplicable(BaseModifier modifier)
{
return true;
}
NetData GetNetData(RoleBehaviour roleBehaviour)
NetData GetNetData()
{
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(NumConfigDefinition, out var numEntry);
PluginSingleton<MiraApiPlugin>.Instance.Config.TryGetEntry<int>(ChanceConfigDefinition, out var chanceEntry);
return new NetData((uint)roleBehaviour.Role, BitConverter.GetBytes(numEntry.Value).AddRangeToArray(BitConverter.GetBytes(chanceEntry.Value)));
ParentMod.PluginConfig.TryGetEntry<int>(NumConfigDefinition, out var numEntry);
ParentMod.PluginConfig.TryGetEntry<int>(ChanceConfigDefinition, out var chanceEntry);
return new NetData(RoleId.Get(GetType()), BitConverter.GetBytes(numEntry.Value).AddRangeToArray(BitConverter.GetBytes(chanceEntry.Value)));
}
}
+1 -13
View File
@@ -3,16 +3,4 @@
namespace MiraAPI.Roles;
[AttributeUsage(AttributeTargets.Class)]
public class RegisterCustomRoleAttribute : Attribute
{
public ushort RoleId { get; }
public RegisterCustomRoleAttribute()
{
RoleId = (ushort)(20 + CustomRoleManager.CustomRoles.Count);
}
public RegisterCustomRoleAttribute(ushort roleId)
{
RoleId = roleId;
}
}
public class RegisterCustomRoleAttribute : Attribute;
+27
View File
@@ -0,0 +1,27 @@
using System;
using System.Linq;
namespace MiraAPI.Roles;
public class RoleId
{
public static ushort Get<T>() where T : RoleBehaviour
{
if (!CustomRoleManager.RoleIds.TryGetValue(typeof(T), out var roleId))
{
throw new InvalidOperationException($"Role {typeof(T)} is not registered");
}
return roleId;
}
public static ushort Get(Type type)
{
if (!CustomRoleManager.RoleIds.TryGetValue(type, out var roleId))
{
throw new InvalidOperationException($"Role {type} is not registered");
}
return roleId;
}
}
@@ -1,9 +1,12 @@
using UnityEngine;
using System.Reflection;
using UnityEngine;
namespace MiraAPI.Utilities.Assets;
public class LoadableResourceAsset(string path) : LoadableAsset<Sprite>
{
private readonly Assembly _assembly = Assembly.GetCallingAssembly();
public override Sprite LoadAsset()
{
if (LoadedAsset != null)
@@ -13,7 +16,7 @@ public class LoadableResourceAsset(string path) : LoadableAsset<Sprite>
try
{
return LoadedAsset = SpriteTools.LoadSpriteFromPath(path);
return LoadedAsset = SpriteTools.LoadSpriteFromPath(path, _assembly);
}
catch
{
+3 -3
View File
@@ -2,11 +2,11 @@
public static class MiraAssets
{
public static readonly LoadableResourceAsset Empty = new("");
public static readonly LoadableResourceAsset Empty = new("MiraAPI.Resources.Empty.png");
public static readonly LoadableResourceAsset NextButton = new("MiraAPI.Resources.NextButton.png");
public static readonly LoadableResourceAsset NextButtonActive = new("MiraAPI.Resources.NextButtonActive.png");
public static readonly LoadableResourceAsset Cog = new("MiraAPI.Resources.Cog.png");
public static readonly LoadableResourceAsset CogActive = new("MiraAPI.Resources.CogActive.png");
public static readonly LoadableResourceAsset Banner = new("MiraAPI.Resources.FortniteBanner.jpeg");
public static readonly LoadableResourceAsset Checkmark = new("MiraAPI.Resources.Checkmark.png");
public static readonly LoadableResourceAsset CheckmarkBox = new("MiraAPI.Resources.CheckMarkBox.png");
}
+1 -2
View File
@@ -32,10 +32,9 @@ public static class SpriteTools
/// <param name="resourcePath">The path to the resource.</param>
/// <returns>A sprite made from the resource</returns>
/// <exception cref="Exception">The resource cannot be found.</exception>
public static Sprite LoadSpriteFromPath(string resourcePath)
public static Sprite LoadSpriteFromPath(string resourcePath, Assembly assembly)
{
var tex = new Texture2D(1, 1, TextureFormat.ARGB32, false);
var assembly = Assembly.GetExecutingAssembly();
var myStream = assembly.GetManifestResourceStream(resourcePath);
if (myStream != null)
{
+22
View File
@@ -0,0 +1,22 @@
using Reactor.Localization.Utilities;
using UnityEngine;
namespace MiraAPI.Utilities.Colors;
public sealed class CustomColor(Color32 mainColor, Color32 shadowColor, StringNames name)
{
public Color32 MainColor { get; } = mainColor;
public Color32 ShadowColor { get; } = shadowColor;
public StringNames Name { get; } = name;
public CustomColor(Color32 mainColor, StringNames name) : this(mainColor, mainColor.GetShadowColor(60), name)
{
}
public CustomColor(Color32 mainColor, string name) : this(mainColor, mainColor.GetShadowColor(60), name)
{
}
public CustomColor(Color32 mainColor, Color32 shadowColor, string name) : this(mainColor, shadowColor, CustomStringName.CreateAndRegister(name))
{
}
}
@@ -0,0 +1,21 @@
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
namespace MiraAPI.Utilities.Colors;
internal static class PaletteManager
{
public static readonly List<CustomColor> CustomColors = [];
public static void RegisterAllColors()
{
var colors = CustomColors.Select(x => x.MainColor);
var shadowColors = CustomColors.Select(x => x.ShadowColor);
var stringNames = CustomColors.Select(x => x.Name);
Palette.PlayerColors = Palette.PlayerColors.ToArray().AddRangeToArray(colors.ToArray());
Palette.ShadowColors = Palette.ShadowColors.ToArray().AddRangeToArray(shadowColors.ToArray());
Palette.ColorNames = Palette.ColorNames.ToArray().AddRangeToArray(stringNames.ToArray());
}
}
@@ -0,0 +1,6 @@
using System;
namespace MiraAPI.Utilities.Colors;
[AttributeUsage(AttributeTargets.Class)]
public class RegisterCustomColorsAttribute : Attribute;
+93 -38
View File
@@ -1,10 +1,15 @@
using MiraAPI.GameOptions;
#nullable enable
using System;
using System.Collections.Generic;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Networking;
using Reactor.Utilities;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -12,9 +17,63 @@ namespace MiraAPI.Utilities;
public static class Extensions
{
public static bool IsStatic(this Type type)
{
return type is { IsClass: true, IsAbstract: true, IsSealed: true };
}
public static Color32 GetShadowColor(this Color32 color, byte darknessAmount)
{
return
new Color32((byte)Mathf.Clamp(color.r - darknessAmount, 0, 255), (byte)Mathf.Clamp(color.g - darknessAmount, 0, 255),
(byte)Mathf.Clamp(color.b - darknessAmount, 0, 255), byte.MaxValue);
}
public static string? Truncate(this string? value, int maxLength, string truncationSuffix = "…")
{
return value?.Length > maxLength
? value[..maxLength] + truncationSuffix
: value;
}
public static Queue<NetData[]> ChunkNetData(this IEnumerable<NetData> dataCollection, int chunkSize)
{
Queue<NetData[]> chunks = [];
List<NetData> current = [];
var count = 0;
foreach (var netData in dataCollection)
{
var length = netData.GetLength();
if (length > chunkSize)
{
Logger<MiraApiPlugin>.Error($"NetData length is greater than chunk size: {length} > {chunkSize}");
continue;
}
if (count + length > chunkSize)
{
chunks.Enqueue(current.ToArray());
current.Clear();
count = 0;
}
current.Add(netData);
}
if (current.Count > 0)
{
chunks.Enqueue(current.ToArray());
}
return chunks;
}
public static bool IsCustom(this OptionBehaviour optionBehaviour)
{
return ModdedOptionsManager.Options.Any(opt => opt.OptionBehaviour && opt.OptionBehaviour.Equals(optionBehaviour));
return ModdedOptionsManager.ModdedOptions.Values.Any(opt => opt.OptionBehaviour && opt.OptionBehaviour.Equals(optionBehaviour));
}
public static ModifierComponent GetModifierComponent(this PlayerControl player)
@@ -68,48 +127,46 @@ public static class Extensions
public static Color DarkenColor(this Color color)
{
return new Color(color.r - 0.3f, color.g - 0.3f, color.b - 0.3f);
return new Color(color.r - 0.45f, color.g - 0.45f, color.b - 0.45f);
}
public static void UpdateBodies(this PlayerControl playerControl, Color outlineColor, ref DeadBody target)
public static Color GetAlternateColor(this Color color)
{
foreach (var body in Object.FindObjectsOfType<DeadBody>())
{
foreach (var bodyRenderer in body.bodyRenderers)
{
bodyRenderer.SetOutline(null);
}
}
if (playerControl.Data.Role is not ICustomRole { TargetsBodies: true })
{
return;
}
target = playerControl.NearestDeadBody();
if (!target)
{
return;
}
foreach (var renderer in target.bodyRenderers)
{
renderer.SetOutline(outlineColor);
}
return color.IsColorDark() ? LightenColor(color) : DarkenColor(color);
}
public static DeadBody NearestDeadBody(this PlayerControl playerControl)
public static Color LightenColor(this Color color)
{
return new Color(color.r + 0.45f, color.g + 0.45f, color.b + 0.45f);
}
public static bool IsColorDark(this Color color)
{
return color.r < 0.5f && color is { g: < 0.5f, b: < 0.5f };
}
public static DeadBody? NearestDeadBody(this PlayerControl playerControl, float radius)
{
var results = new Il2CppSystem.Collections.Generic.List<Collider2D>();
Physics2D.OverlapCircle(playerControl.GetTruePosition(), playerControl.MaxReportDistance / 4f, Helpers.Filter, results);
Physics2D.OverlapCircle(playerControl.GetTruePosition(), radius, Helpers.Filter, results);
return results.ToArray()
.Where(collider2D => collider2D.CompareTag("DeadBody"))
.Select(collider2D => collider2D.GetComponent<DeadBody>())
.FirstOrDefault(component => component && !component.Reported);
}
public static PlayerControl GetClosestPlayer(this PlayerControl playerControl, bool includeImpostors, float distance)
public static T? GetNearestObjectOfType<T>(this PlayerControl playerControl, float radius, string? colliderTag=null, Func<T, bool>? predicate=null) where T : Component
{
PlayerControl result = null;
var results = new Il2CppSystem.Collections.Generic.List<Collider2D>();
Physics2D.OverlapCircle(playerControl.GetTruePosition(), radius, Helpers.Filter, results);
return results.ToArray()
.Where(collider2D => colliderTag == null || collider2D.CompareTag(colliderTag))
.Select(collider2D => collider2D.GetComponent<T>())
.FirstOrDefault(predicate ?? (component => component));
}
public static PlayerControl? GetClosestPlayer(this PlayerControl playerControl, bool includeImpostors, float distance)
{
PlayerControl? result = null;
if (!ShipStatus.Instance)
{
return null;
@@ -117,14 +174,12 @@ public static class Extensions
var truePosition = playerControl.GetTruePosition();
foreach (var playerInfo in GameData.Instance.AllPlayers)
var filteredPlayers = GameData.Instance.AllPlayers.ToArray()
.Where(playerInfo => !playerInfo.Disconnected && playerInfo.PlayerId != playerControl.PlayerId && !playerInfo.IsDead &&
(includeImpostors || !playerInfo.Role.IsImpostor));
foreach (var playerInfo in filteredPlayers)
{
if (playerInfo.Disconnected || playerInfo.PlayerId == playerControl.PlayerId ||
playerInfo.IsDead || !includeImpostors && playerInfo.Role.IsImpostor)
{
continue;
}
var @object = playerInfo.Object;
if (!@object)
{
+136 -20
View File
@@ -2,16 +2,19 @@
# Mira API
A thorough, but simple, Among Us modding API that covers:
A thorough, but simple, Among Us modding API and utility library that covers:
- Roles
- Options
- Gamemodes
- Buttons
- Assets
- HUD Elements
- Compatibility
- ~~Modifiers~~ (coming soon)
- ~~Game Modes~~ (coming soon)
Mira API strives to be simple and easy to use, while also using as many base game elements as possible. The result is a less intrusive, better modding API that covers general use cases.
**Join the [Discord](https://discord.gg/all-of-us-launchpad-794950428756410429) for support and to stay updated on the latest releases**
# Usage
To start using Mira API, you need to:
@@ -21,39 +24,143 @@ To start using Mira API, you need to:
For a full example, see [this file](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/ExamplePlugin.cs).
## Recommended Project Structure
It is highly recommended to follow this project structure when using Mira API in order to keep your code clean and organized. You can also view the Example Mod in this repository for some guidance.
```
MyMiraMod/
├── Buttons/
│ └── MyCoolButton.cs
├── Options/
│ ├── Roles/
│ │ └── CoolCustomRoleOptions.cs
│ └── MainOptionGroup.cs
├── Patches/
│ ├── Roles/
│ │ └── CoolCustomRole/
│ │ ├── PlayerControlPatches.cs
│ │ └── ExileControllerPatches.cs
│ └── General/
│ └── HudManagerPatches.cs
├── Resources/
│ ├── CoolButton.png
│ └── myAssets-win-x86.bundle
├── Roles/
│ └── CoolCustomRole.cs
├── MyMiraModPlugin.cs
└── MyModAssets.cs
```
## Roles
Roles are very simple in Mira API. There are 3 things you need to do to create a custom role:
1. Create a class that inherits from a base game role (like `RoleBehaviour`, `CrewmateRole`, `ImpostorRole`, etc).
1. Create a class that inherits from a base game role (like `CrewmateRole`, `ImpostorRole`, etc)
2. Implement the `ICustomRole` interface from Mira API.
3. Add the `[RegisterCustomRole]` attribute to the class.
See [this file](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/CustomRole.cs) for a code example.
Note: For step 1, if you are making neutral roles, choose either `CrewmateRole` or `ImpostorRole` as the base depending on if it can kill or not!
Mira API handles everything else, from adding the proper options to the settings menu, to managing the role assignment at the start of the game. There are no extra steps on the developer's part.
See [this file](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/Roles/CustomRole.cs) for a code example.
## Options
Options are also very simple in Mira API. Options are split up into Groups and Options. Every Option needs to be in a Group.
Options are also very simple in Mira API. Mira API handles all the hard work behind the scenes, so developers only have to follow a few steps to create their custom options. The Options API is split up into Groups and Options. Every Option needs to be in a Group.
To create a group, you need to create a class that implements the `IModdedOptionGroup` interface. Groups contain two properties, the `GroupName` and `GroupColor`.
To create a group, you need to create a class that inherits from the `AbstractOptionGroup` abstract class. Groups contain 4 properties, `GroupName`, `GroupColor`, `GroupVisible`, and `AdvancedRole`. Only the `GroupName` is required.
The easiest way to create an option within this group is to make a property within a class and assign one of the various Options Attributes listed below:
Here is an example of a group class:
```csharp
public class MyOptionsGroup : AbstractOptionGroup
{
public override string GroupName => "My Options"; // this is required
[ModdedNumberOption("My Number Option", min: 0, max: 10)]
public float MyNumberOption { get; set; } = 5f;
}
```
You can access any group class using the `OptionGroupSingleton` class like this:
```csharp
// MyOptionsGroup is a class that inherits from AbstractOptionGroup
var myGroup = OptionGroupSingleton<MyOptionsGroup>.Instance; // gets the instance of the group
Logger<MyPlugin>.Info(myGroup.MyNumberOption); // prints the value of the option to the console
```
Once you have an options group, there are two ways to make the actual options:
- Use an Option Attribute with a property.
- Create a ModdedOption property.
### Option Attributes
This is an example of using an Option Attribute on a property:
```csharp
// The first parameter is always the name of the option. The rest are dependent on the type of option.
[ModdedNumberOption("Sussy level", min: 0, max: 10)]
public float SussyLevel { get; set; } = 4f; // You can set a default value here.
```
Here are the available Option Attributes and their signatures:
```csharp
ModdedEnumOption(string name, Type enumType, Type roleType = null)
ModdedNumberOption(
string name,
float min,
float max,
float increment=1
NumberSuffixes suffixType = NumberSuffixes.None,
bool zeroInfinity = false,
Type roleType = null)
ModdedStringOption(string title, string[] values, Type roleType = null)
ModdedToggleOption(string name, Type roleType = null)
```
### ModdedOption Properties
And this is an example of a ModdedOption property:
```csharp
public ModdedToggleOption YeezusAbility { get; } = new ModdedToggleOption("Yeezus Ability", false);
```
Here is a full list of ModdedOption classes you can use:
- `ModdedEnumOption`
- `ModdedNumberOption`
- `ModdedStringOption`
- `ModdedToggleOption`
They are used like this:
```csharp
// The first parameter is always the name of the option. The rest are dependent on the type of option.
[ModdedNumberOption("Sussy level", min: 0, max: 10)]
public float sussyLevel { get; set; } = 4f; // You can set a default value here.
```
To see a full example, see [this file](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/ExampleOptions.cs).
To see a full example of an options class, see [this file](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/Options/ExampleOptions.cs).
### Role Options
Options can also be used within a Role class to show up in that Role's settings. To do this, simply add your option property to the Role class and specify the `roleType` parameter in the Option attribute.
You can also specify a role type for an option or option group.
An example can be found [here](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/CustomRole2.cs).
To set the role type for an entire group, set the `AdvancedRole` property on that group like this:
```csharp
public class MyOptionsGroup : AbstractOptionGroup
{
public override string GroupName => "My Options";
public override Type AdvancedRole => typeof(MyRole); // this is the role that will have these options
[ModdedNumberOption("Ability Uses", min: 0, max: 10)]
public float AbilityUses { get; set; } = 5f;
}
```
To set the role type for individual options, specify the `roleType` parameter in the option like this:
```csharp
// this group doesnt specify a role, so it will show up in the global settings
public class MyOptionsGroup : AbstractOptionGroup
{
public override string GroupName => "My Options";
// this option will only show up in the settings for MyRole
[ModdedNumberOption("Ability Uses", min: 0, max: 10, roleType: typeof(MyRole))]
public float AbilityUses { get; set; } = 5f;
}
```
An example can be found [here](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/Options/Roles/CustomRoleSettings.cs).
## Buttons
@@ -61,9 +168,16 @@ Mira API provides a simple interface for adding ability buttons to the game. The
1. Create a class that inherits from the `CustomActionButton` class and implement the properties and methods.
2. Add the `[RegisterCustomButton]` attribute to the class.
All other tasks and logic required to add the button to the game are handled by Mira API.
In case you need to access your `CustomActionButton` instance from another class, you can use the `CustomButtonSingleton` class like this:
```csharp
var myButton = CustomButtonSingleton<MyCoolButton>.Instance;
```
The button API is simple, but provides a lot of flexibility. There are various methods you can override to customize the behaviour of your button. See [this file](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI/Hud/CustomActionButton.cs) for a full list of methods you can override.
An example button can be found [here](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/ExampleButton.cs).
An example button can be found [here](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/Buttons/ExampleButton.cs).
## Assets
@@ -86,6 +200,8 @@ LoadableAsset<Sprite> buttonAsset = new LoadableResourceAsset("ExampleMod.Resour
Sprite button = buttonSpriteAsset.LoadAsset();
```
You can view an example file [here](https://github.com/All-Of-Us-Mods/MiraAPI/blob/master/MiraAPI.Example/ExampleAssets.cs).
You can create your own asset loaders by inheriting from `LoadableAsset<T>` and implementing the `LoadAsset` method.
# Disclaimer