Initial commit

This commit is contained in:
Kurt 2020-03-27 17:54:17 -07:00
commit fb13723b01
477 changed files with 23660 additions and 0 deletions

22
.gitattributes vendored Normal file
View File

@ -0,0 +1,22 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

View File

@ -0,0 +1,22 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
Note: Requesting new editing features that *require research* are not Feature Requests. This is only for improving interactions and/or leveraging the current code in new/interesting ways.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -0,0 +1,11 @@
---
name: Fix
about: Provide a fix for this project
title: ''
labels: enhancement
assignees: ''
---
**Please describe your fix.**
A clear and concise description of what the pull request contains.

View File

@ -0,0 +1,11 @@
---
name: Improvement
about: Provide an improvement for this project
title: ''
labels: enhancement
assignees: ''
---
**Please describe your improvement.**
A clear and concise description of what the pull request contains.

353
.gitignore vendored Normal file
View File

@ -0,0 +1,353 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/

5
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,5 @@
# Contributor Code of Conduct
This project adheres to No Code of Conduct. We are all adults. We accept anyone's contributions. Nothing else matters.
For more information please visit the [No Code of Conduct](https://github.com/domgetter/NCoC) homepage.

25
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,25 @@
# Contributing
Thank you for taking the time to contribute to this project's development. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.
This is a community driven project based off of shared information and tools. Even if you can't write code, community documentation of in-game behaviors can go a long way to help implement new features.
This project is written in C#, and tries to keep up to date with the latest standard language style.
### Issues
When submitting an issue, please use an issue template and ensure you are filing things correctly. If you are unsure, you can always create a thread on our forums instead (we monitor both locations)!
Have a question? Please contact us on the associated forums (or IRC/Discord, wherever communication is) instead. Please be patient when expecting a response; this is free software and we aren't available at all times.
### Pull Requests
When submitting a pull request, please try to have everything ready for merging and passing all tests. Draft pull requests may be rejected as we value having a minimal amount of open issues/pull requests!
Please make sure your code is maintainable; provide comments and xmldoc when appropriate. If you are coding new GUI features, ensure any non-GUI logic is separate from the GUI specific logic; separating concerns is important for maintainability and portability!
If you are providing something that interacts with game data, try to model things to match the way the game interacts with the data. When done this way, it is easiest for others to replicate your research and expand upon your improvements.
### Formatting
Spaces instead of tabs. Please follow the standard C# formatting rules provided by Visual Studio.

596
LICENSE.md Normal file
View File

@ -0,0 +1,596 @@
GNU GENERAL PUBLIC LICENSE
==========================
Version 3, 29 June 2007
Copyright &copy; 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and other
kinds of works.
The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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 them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert
copyright on the software, and (2) offer you this License giving you legal permission
to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
## TERMS AND CONDITIONS
### 0. Definitions.
&ldquo;This License&rdquo; refers to version 3 of the GNU General Public License.
&ldquo;Copyright&rdquo; also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
&ldquo;The Program&rdquo; refers to any copyrightable work licensed under this
License. Each licensee is addressed as &ldquo;you&rdquo;. &ldquo;Licensees&rdquo; and
&ldquo;recipients&rdquo; may be individuals or organizations.
To &ldquo;modify&rdquo; a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact copy. The
resulting work is called a &ldquo;modified version&rdquo; of the earlier work or a
work &ldquo;based on&rdquo; the earlier work.
A &ldquo;covered work&rdquo; means either the unmodified Program or a work based on
the Program.
To &ldquo;propagate&rdquo; a work means to do anything with it that, without
permission, would make you directly or secondarily liable for infringement under
applicable copyright law, except executing it on a computer or modifying a private
copy. Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To &ldquo;convey&rdquo; a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays &ldquo;Appropriate Legal Notices&rdquo; to the
extent that it includes a convenient and prominently visible feature that (1)
displays an appropriate copyright notice, and (2) tells the user that there is no
warranty for the work (except to the extent that warranties are provided), that
licensees may convey the work under this License, and how to view a copy of this
License. If the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code.
The &ldquo;source code&rdquo; for a work means the preferred form of the work for
making modifications to it. &ldquo;Object code&rdquo; means any non-source form of a
work.
A &ldquo;Standard Interface&rdquo; means an interface that either is an official
standard defined by a recognized standards body, or, in the case of interfaces
specified for a particular programming language, one that is widely used among
developers working in that language.
The &ldquo;System Libraries&rdquo; of an executable work include anything, other than
the work as a whole, that (a) is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and (b) serves only to
enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code form.
A &ldquo;Major Component&rdquo;, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on which
the executable work runs, or a compiler used to produce the work, or an object code
interpreter used to run it.
The &ldquo;Corresponding Source&rdquo; for a work in object code form means all the
source code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities. However,
it does not include the work's System Libraries, or general-purpose tools or
generally available free programs which are used unmodified in performing those
activities but which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for the work, and
the source code for shared libraries and dynamically linked subprograms that the work
is specifically designed to require, such as by intimate data communication or
control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License
explicitly affirms your unlimited permission to run the unmodified Program. The
output from running a covered work is covered by this License only if the output,
given its content, constitutes a covered work. This License acknowledges your rights
of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do so
exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising
rights under this License with respect to the covered work, and you disclaim any
intention to limit operation or modification of the work as a means of enforcing,
against the work's users, your or third parties' legal rights to forbid circumvention
of technological measures.
### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and
any non-permissive terms added in accord with section 7 apply to the code; keep
intact all notices of the absence of any warranty; and give all recipients a copy of
this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.
### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified it, and giving a
relevant date.
* **b)** The work must carry prominent notices stating that it is released under this
License and any conditions added under section 7. This requirement modifies the
requirement in section 4 to &ldquo;keep intact all notices&rdquo;.
* **c)** You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license the
work in any other way, but it does not invalidate such permission if you have
separately received it.
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are
not by their nature extensions of the covered work, and which are not combined with
it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an &ldquo;aggregate&rdquo; if the compilation and its resulting
copyright are not used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work in an aggregate
does not cause this License to apply to the other parts of the aggregate.
### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under the
terms of this License, in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by a written offer, valid for at least
three years and valid for as long as you offer spare parts or customer support for
that product model, to give anyone who possesses the object code either (1) a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange, for
a price no more than your reasonable cost of physically performing this conveying of
source, or (2) access to copy the Corresponding Source from a network server at no
charge.
* **c)** Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally and
noncommercially, and only if you received the object code with such an offer, in
accord with subsection 6b.
* **d)** Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same way
through the same place at no further charge. You need not require recipients to copy
the Corresponding Source along with the object code. If the place to copy the object
code is a network server, the Corresponding Source may be on a different server
(operated by you or a third party) that supports equivalent copying facilities,
provided you maintain clear directions next to the object code saying where to find
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
you remain obligated to ensure that it is available for as long as needed to satisfy
these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are being
offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A &ldquo;User Product&rdquo; is either (1) a &ldquo;consumer product&rdquo;, which
means any tangible personal property which is normally used for personal, family, or
household purposes, or (2) anything designed or sold for incorporation into a
dwelling. In determining whether a product is a consumer product, doubtful cases
shall be resolved in favor of coverage. For a particular product received by a
particular user, &ldquo;normally used&rdquo; refers to a typical or common use of
that class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use, the
product. A product is a consumer product regardless of whether the product has
substantial commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
&ldquo;Installation Information&rdquo; for a User Product means any methods,
procedures, authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the continued
functioning of the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient
in perpetuity or for a fixed term (regardless of how the transaction is
characterized), the Corresponding Source conveyed under this section must be
accompanied by the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified object code
on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to
continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules
and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require no
special password or key for unpacking, reading or copying.
### 7. Additional Terms.
&ldquo;Additional permissions&rdquo; are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. Additional
permissions that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when you
modify the work.) You may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed by works
containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
modified versions of such material be marked in reasonable ways as different from the
original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
material; or
* **e)** Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that material by anyone
who conveys the material (or modified versions of it) with contractual assumptions of
liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.
All other non-permissive additional terms are considered &ldquo;further
restrictions&rdquo; within the meaning of section 10. If the Program as you received
it, or any part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or conveying
under this License, you may add to a covered work material governed by the terms of
that license document, provided that the further restriction does not survive such
relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in
the relevant source files, a statement of the additional terms that apply to those
files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements apply
either way.
### 8. Termination.
You may not propagate or modify a covered work except as expressly provided under
this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated (a) provisionally, unless and until the
copyright holder explicitly and finally terminates your license, and (b) permanently,
if the copyright holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means, this
is the first time you have received notice of violation of this License (for any
work) from that copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of
parties who have received copies or rights from you under this License. If your
rights have been terminated and not permanently reinstated, you do not qualify to
receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require
acceptance. However, nothing other than this License grants you permission to
propagate or modify any covered work. These actions infringe copyright if you do not
accept this License. Therefore, by modifying or propagating a covered work, you
indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.
An &ldquo;entity transaction&rdquo; is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or
merging organizations. If propagation of a covered work results from an entity
transaction, each party to that transaction who receives a copy of the work also
receives whatever licenses to the work the party's predecessor in interest had or
could give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty,
or other charge for exercise of rights granted under this License, and you may not
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
that any patent claim is infringed by making, using, selling, offering for sale, or
importing the Program or any portion of it.
### 11. Patents.
A &ldquo;contributor&rdquo; is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work thus
licensed is called the contributor's &ldquo;contributor version&rdquo;.
A contributor's &ldquo;essential patent claims&rdquo; are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired, that
would be infringed by some manner, permitted by this License, of making, using, or
selling its contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor version. For
purposes of this definition, &ldquo;control&rdquo; includes the right to grant patent
sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor's essential patent claims, to make, use, sell, offer for sale,
import and otherwise run, modify and propagate the contents of its contributor
version.
In the following three paragraphs, a &ldquo;patent license&rdquo; is any express
agreement or commitment, however denominated, not to enforce a patent (such as an
express permission to practice a patent or covenant not to sue for patent
infringement). To &ldquo;grant&rdquo; such a patent license to a party means to make
such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of charge
and under the terms of this License, through a publicly available network server or
other readily accessible means, then you must either (1) cause the Corresponding
Source to be so available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner consistent with
the requirements of this License, to extend the patent license to downstream
recipients. &ldquo;Knowingly relying&rdquo; means you have actual knowledge that, but
for the patent license, your conveying the covered work in a country, or your
recipient's use of the covered work in a country, would infringe one or more
identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
license to some of the parties receiving the covered work authorizing them to use,
propagate, modify or convey a specific copy of the covered work, then the patent
license you grant is automatically extended to all recipients of the covered work and
works based on it.
A patent license is &ldquo;discriminatory&rdquo; if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license (a) in connection with
copies of the covered work conveyed by you (or copies made from those copies), or (b)
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.
### 12. No Surrender of Others' Freedom.
If 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 convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.
### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.
### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU
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 Program specifies that
a certain numbered version of the GNU General Public License &ldquo;or any later
version&rdquo; applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.
### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM &ldquo;AS IS&rdquo; 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 PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM 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
PROGRAM (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 PROGRAM TO OPERATE
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be
given local legal effect according to their terms, reviewing courts shall apply local
law that most closely approximates an absolute waiver of all civil liability in
connection with the Program, unless a warranty or assumption of liability accompanies
a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to
the public, the best way to achieve this is to make it free software which everyone
can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them
to the start of each source file to most effectively state the exclusion of warranty;
and each file should have at least the &ldquo;copyright&rdquo; line and a pointer to
where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'show c' for details.
The hypothetical commands 'show w' and 'show c' should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an &ldquo;about box&rdquo;.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a &ldquo;copyright disclaimer&rdquo; for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
&lt;<http://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.

View File

@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace NHSE.Core
{
// The MIT License (MIT)
// Copyright (c) 2014 Hans Wolff
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public sealed class Aes128CounterMode : SymmetricAlgorithm
{
private readonly byte[] _counter;
private readonly AesManaged _aes;
public Aes128CounterMode(byte[] counter)
{
if (counter == null)
throw new ArgumentNullException(nameof(counter));
if (counter.Length != 16)
throw new ArgumentException($"Counter size must be same as block size (actual: {counter.Length}, expected: {16})");
_aes = new AesManaged
{
Mode = CipherMode.ECB,
Padding = PaddingMode.None
};
_counter = counter;
}
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] ignoredParameter)
{
return new CounterModeCryptoTransform(_aes, rgbKey, _counter);
}
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] ignoredParameter)
{
return new CounterModeCryptoTransform(_aes, rgbKey, _counter);
}
public override void GenerateKey()
{
_aes.GenerateKey();
}
public override void GenerateIV()
{
// IV not needed in Counter Mode
}
protected override void Dispose(bool disposing)
{
_aes.Dispose();
}
}
public sealed class CounterModeCryptoTransform : ICryptoTransform
{
private readonly byte[] _counter;
private readonly ICryptoTransform _counterEncryptor;
private readonly Queue<byte> _xorMask = new Queue<byte>();
private readonly SymmetricAlgorithm _symmetricAlgorithm;
public CounterModeCryptoTransform(SymmetricAlgorithm symmetricAlgorithm, byte[] key, byte[] counter)
{
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
if (key == null)
throw new ArgumentNullException(nameof(key));
if (counter == null)
throw new ArgumentNullException(nameof(counter));
if (counter.Length != symmetricAlgorithm.BlockSize / 8)
throw new ArgumentException($"Counter size must be same as block size (actual: {counter.Length}, expected: {symmetricAlgorithm.BlockSize / 8})");
_symmetricAlgorithm = symmetricAlgorithm;
_counter = counter;
var zeroIv = new byte[_symmetricAlgorithm.BlockSize / 8];
_counterEncryptor = symmetricAlgorithm.CreateEncryptor(key, zeroIv);
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
var output = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, output, 0);
return output;
}
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
for (var i = 0; i < inputCount; i++)
{
if (NeedMoreXorMaskBytes()) EncryptCounterThenIncrement();
var mask = _xorMask.Dequeue();
outputBuffer[outputOffset + i] = (byte)(inputBuffer[inputOffset + i] ^ mask);
}
return inputCount;
}
private bool NeedMoreXorMaskBytes()
{
return _xorMask.Count == 0;
}
private void EncryptCounterThenIncrement()
{
var counterModeBlock = new byte[_symmetricAlgorithm.BlockSize / 8];
_counterEncryptor.TransformBlock(_counter, 0, _counter.Length, counterModeBlock, 0);
IncrementCounter();
foreach (var b in counterModeBlock)
{
_xorMask.Enqueue(b);
}
}
private void IncrementCounter()
{
for (var i = _counter.Length - 1; i >= 0; i--)
{
if (++_counter[i] != 0)
break;
}
}
public int InputBlockSize => _symmetricAlgorithm.BlockSize / 8;
public int OutputBlockSize => _symmetricAlgorithm.BlockSize / 8;
public bool CanTransformMultipleBlocks => true;
public bool CanReuseTransform => false;
public void Dispose()
{
_counterEncryptor.Dispose();
}
}
}

View File

@ -0,0 +1,23 @@
namespace NHSE.Core
{
public readonly struct CryptoFile
{
public readonly byte[] Data;
public readonly byte[] Key;
public readonly byte[] Ctr;
public CryptoFile(byte[] data, byte[] key, byte[] ctr)
{
Data = data;
Key = key;
Ctr = ctr;
}
#region Equality Comparison
public override bool Equals(object obj) => obj is CryptoFile r && r == this;
public override int GetHashCode() => Data.GetHashCode();
public static bool operator !=(CryptoFile left, CryptoFile right) => !(left == right);
public static bool operator ==(CryptoFile left, CryptoFile right) => left.Data == right.Data;
#endregion
}
}

View File

@ -0,0 +1,92 @@
using System;
namespace NHSE.Core
{
public sealed class EncryptedInt32
{
// Encryption constant used to encrypt the int.
private const uint ENCRYPTION_CONSTANT = 0x80E32B11;
// Base shift count used in the encryption.
private const byte SHIFT_BASE = 3;
public uint Value;
public ushort Adjust;
public byte Shift;
public byte Checksum;
public override string ToString() => Value.ToString();
public EncryptedInt32(uint encryptedValue, ushort adjust = 0, byte shift = 0, byte checksum = 0)
{
Adjust = adjust;
Shift = shift;
Checksum = checksum;
Value = Decrypt(encryptedValue, shift, adjust);
}
public EncryptedInt32(uint value)
{
Adjust = (ushort)RandUtil.Rand.Next();
Shift = (byte)RandUtil.Rand.Next();
var enc = Encrypt(value, Shift, Adjust);
Checksum = CalculateChecksum(enc);
Value = value;
}
public void Write(byte[] data, int offset) => Write(this, data, offset);
// Calculates a checksum for a given encrypted value
// Checksum calculation is every byte of the encrypted in added together minus 0x2D.
public static byte CalculateChecksum(uint value)
{
var byteSum = value + (value >> 16) + (value >> 24) + (value >> 8);
return (byte)(byteSum - 0x2D);
}
public static uint Decrypt(uint encrypted, byte shift, ushort adjust)
{
// Decrypt the encrypted int using the given params.
ulong val = ((ulong) encrypted) << ((32 - SHIFT_BASE - shift) & 0x3F);
int valConcat = (int) val + (int) (val >> 32);
return (uint) ((ENCRYPTION_CONSTANT - adjust) + valConcat);
}
public static uint Encrypt(uint value)
{
var adjust = (ushort)RandUtil.Rand.Next();
var shift = (byte)RandUtil.Rand.Next();
return Encrypt(value, shift, adjust);
}
private static uint Encrypt(uint value, byte shift, ushort adjust)
{
ulong val = (ulong) (value + (adjust - ENCRYPTION_CONSTANT)) << (shift + SHIFT_BASE);
return (uint) ((val >> 32) + val);
}
public static EncryptedInt32 Read(byte[] data, int offset)
{
var enc = BitConverter.ToUInt32(data, offset + 0);
var adjust = BitConverter.ToUInt16(data, offset + 4);
var shift = data[offset + 6];
var chk = data[offset + 7];
return new EncryptedInt32(enc, adjust, shift, chk);
}
public static void Write(EncryptedInt32 value, byte[] data, int offset)
{
uint enc = Encrypt(value.Value, value.Shift, value.Adjust);
byte chk = CalculateChecksum(enc);
BitConverter.GetBytes(enc).CopyTo(data, offset + 0);
BitConverter.GetBytes(value.Adjust).CopyTo(data, offset + 4);
data[offset + 6] = value.Shift;
data[offset + 7] = chk;
}
public static void Write(uint value, byte[] data, int offset)
{
var fake = new EncryptedInt32(value);
Write(fake, data, offset);
}
}
}

View File

@ -0,0 +1,21 @@
namespace NHSE.Core
{
public readonly struct EncryptedSaveFile
{
public readonly byte[] Data;
public readonly byte[] Header;
public EncryptedSaveFile(byte[] data, byte[] header)
{
Data = data;
Header = header;
}
#region Equality Comparison
public override bool Equals(object obj) => obj is EncryptedSaveFile r && r == this;
public override int GetHashCode() => Data.GetHashCode();
public static bool operator !=(EncryptedSaveFile left, EncryptedSaveFile right) => !(left == right);
public static bool operator ==(EncryptedSaveFile left, EncryptedSaveFile right) => left.Data == right.Data && left.Header == right.Header;
#endregion
}
}

View File

@ -0,0 +1,85 @@
using System;
namespace NHSE.Core
{
public static class Encryption
{
private static byte[] GetParam(uint[] data, in int index)
{
var sead = new SEADRandom(data[data[index] & 0x7F]);
var prms = data[data[index + 1] & 0x7F] & 0x7F;
var rndRollCount = (prms & 0xF) + 1;
for (var i = 0; i < rndRollCount; i++)
sead.GetU64();
var result = new byte[0x10];
for (var i = 0; i < result.Length; i++)
result[i] = (byte)(sead.GetU32() >> 24);
return result;
}
/// <summary>
/// Decrypts the <see cref="encData"/> using the <see cref="headerData"/>.
/// </summary>
/// <param name="headerData">Header Data</param>
/// <param name="encData">Encrypted SaveData</param>
/// <returns>Decrypted SaveData</returns>
public static byte[] Decrypt(byte[] headerData, byte[] encData)
{
// First 256 bytes go unused
var importantData = new uint[0x80];
Buffer.BlockCopy(headerData, 0x100, importantData, 0, 0x200);
// Set up Key
var key = GetParam(importantData, 0);
// Set up counter
var counter = GetParam(importantData, 2);
// Do the AES
using var aesCtr = new Aes128CounterMode(counter);
var transform = aesCtr.CreateDecryptor(key, counter);
var decData = new byte[encData.Length];
transform.TransformBlock(encData, 0, encData.Length, decData, 0);
return decData;
}
private static CryptoFile GenerateHeaderFile(uint seed, byte[] versionData)
{
// Generate 128 Random uints which will be used for params
var random = new SEADRandom(seed);
var encryptData = new uint[128];
for (var i = 0; i < encryptData.Length; i++)
encryptData[i] = random.GetU32();
var headerData = new byte[0x300];
Buffer.BlockCopy(versionData, 0, headerData, 0, 0x100);
Buffer.BlockCopy(encryptData, 0, headerData, 0x100, 0x200);
return new CryptoFile(headerData, GetParam(encryptData, 0), GetParam(encryptData, 2));
}
/// <summary>
/// Encrypts the <see cref="data"/> (savedata) using the provided <see cref="seed"/>.
/// </summary>
/// <param name="data">SaveData to encrypt</param>
/// <param name="seed">Seed to encrypt with</param>
/// <param name="versionData">Version data to encrypt with</param>
/// <returns>Encrypted SaveData, and associated headerData</returns>
public static EncryptedSaveFile Encrypt(byte[] data, uint seed, byte[] versionData)
{
// Generate header file and get key and counter
var header = GenerateHeaderFile(seed, versionData);
// Encrypt file
using var aesCtr = new Aes128CounterMode(header.Ctr);
var transform = aesCtr.CreateEncryptor(header.Key, header.Ctr);
var encData = new byte[data.Length];
transform.TransformBlock(data, 0, data.Length, encData, 0);
return new EncryptedSaveFile(encData, header.Data);
}
}
}

View File

@ -0,0 +1,32 @@
using System.Collections.Generic;
namespace NHSE.Core
{
/// <summary>
/// Contains the <see cref="HashRegions"/> for a <see cref="FileName"/>.
/// </summary>
public sealed class FileHashDetails
{
/// <summary>
/// Name of the File that these <see cref="HashRegions"/> apply to.
/// </summary>
public readonly string FileName;
/// <summary>
/// Expected file size of the <see cref="FileName"/>.
/// </summary>
public readonly uint FileSize;
/// <summary>
/// Hash specs that are done in this file.
/// </summary>
public readonly IReadOnlyList<FileHashRegion> HashRegions;
public FileHashDetails(string fileName, uint fileSize, IReadOnlyList<FileHashRegion> regions)
{
FileName = fileName;
FileSize = fileSize;
HashRegions = regions;
}
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace NHSE.Core
{
#pragma warning disable CA2237 // Mark ISerializable types with serializable
public sealed class FileHashInfo : Dictionary<uint, FileHashDetails>
#pragma warning restore CA2237 // Mark ISerializable types with serializable
{
public readonly uint RevisionId; // Custom to us
public FileHashInfo(uint revisionId, FileHashDetails[] hashSets)
{
RevisionId = revisionId;
foreach (var hashSet in hashSets)
this[hashSet.FileSize] = hashSet;
}
public FileHashDetails? GetFile(string nameData)
{
return this.FirstOrDefault(z => z.Value.FileName == nameData).Value;
}
}
}

View File

@ -0,0 +1,53 @@
namespace NHSE.Core
{
/// <summary>
/// Specifies the region that a validation hash is calculated over.
/// </summary>
public readonly struct FileHashRegion
{
/// <summary>
/// Offset of the calculated hash.
/// </summary>
public readonly int HashOffset;
/// <summary>
/// Offset where the data to be hashed starts at.
/// </summary>
public readonly int BeginOffset;
/// <summary>
/// Length of the hashed data.
/// </summary>
public readonly int Size;
/// <summary>
/// Offset where the data to be hashed ends at (calculated).
/// </summary>
public int EndOffset => BeginOffset + Size;
public FileHashRegion(int hashOfs, int begOfs, int size)
{
HashOffset = hashOfs;
BeginOffset = begOfs;
Size = size;
}
#region Equality Comparison
public override bool Equals(object obj) => obj is FileHashRegion r && r == this;
public override int GetHashCode() => BeginOffset.GetHashCode();
public static bool operator !=(FileHashRegion left, FileHashRegion right) => !(left == right);
public static bool operator ==(FileHashRegion left, FileHashRegion right)
{
if (left.HashOffset != right.HashOffset)
return false;
if (left.BeginOffset != right.BeginOffset)
return false;
if (left.Size != right.Size)
return false;
return true;
}
#endregion
}
}

View File

@ -0,0 +1,116 @@
namespace NHSE.Core
{
/// <summary>
/// Provides information for hashing different revisions of the game's savedata.
/// </summary>
public static class FileHashRevision
{
#region REVISION 1.0.0
private const uint REVISION_100_ID = 0;
private const int MAIN_SAVE_SIZE = 0xAC0938;
private const int PERSONAL_SAVE_SIZE = 0x6BC50;
private const int POSTBOX_SAVE_SIZE = 0xB44580;
private const int PHOTO_STUDIO_ISLAND_SIZE = 0x263B4;
private const int PROFILE_SIZE = 0x69508;
public static readonly FileHashInfo REV_100 = new FileHashInfo(REVISION_100_ID, new[]
{
new FileHashDetails("main.dat", MAIN_SAVE_SIZE, new[]
{
new FileHashRegion(0x000108, 0x00010C, 0x1D6D4C),
new FileHashRegion(0x1D6E58, 0x1D6E5C, 0x323384),
new FileHashRegion(0x4FA2E8, 0x4FA2EC, 0x035AC4),
new FileHashRegion(0x52FDB0, 0x52FDB4, 0x03607C),
new FileHashRegion(0x565F38, 0x565F3C, 0x035AC4),
new FileHashRegion(0x59BA00, 0x59BA04, 0x03607C),
new FileHashRegion(0x5D1B88, 0x5D1B8C, 0x035AC4),
new FileHashRegion(0x607650, 0x607654, 0x03607C),
new FileHashRegion(0x63D7D8, 0x63D7DC, 0x035AC4),
new FileHashRegion(0x6732A0, 0x6732A4, 0x03607C),
new FileHashRegion(0x6A9428, 0x6A942C, 0x035AC4),
new FileHashRegion(0x6DEEF0, 0x6DEEF4, 0x03607C),
new FileHashRegion(0x715078, 0x71507C, 0x035AC4),
new FileHashRegion(0x74AB40, 0x74AB44, 0x03607C),
new FileHashRegion(0x780CC8, 0x780CCC, 0x035AC4),
new FileHashRegion(0x7B6790, 0x7B6794, 0x03607C),
new FileHashRegion(0x7EC918, 0x7EC91C, 0x035AC4),
new FileHashRegion(0x8223E0, 0x8223E4, 0x03607C),
new FileHashRegion(0x858460, 0x858464, 0x2684D4)
}),
new FileHashDetails("personal.dat", PERSONAL_SAVE_SIZE, new[]
{
new FileHashRegion(0x00108, 0x0010C, 0x35AC4),
new FileHashRegion(0x35BD0, 0x35BD4, 0x3607C)
}),
new FileHashDetails("postbox.dat", POSTBOX_SAVE_SIZE, new[]
{
new FileHashRegion(0x000100, 0x00104, 0xB4447C)
}),
new FileHashDetails("photo_studio_island.dat", PHOTO_STUDIO_ISLAND_SIZE, new[]
{
new FileHashRegion(0x000100, 0x00104, 0x262B0)
}),
new FileHashDetails("profile.dat", PROFILE_SIZE, new[]
{
new FileHashRegion(0x000100, 0x00104, 0x69404)
}),
});
#endregion
#region REVISION 1.1.0
private const uint REVISION_110_ID = 1;
private const int REV_110_MAIN_SAVE_SIZE = 0xAC2AA0;
private const int REV_110_PERSONAL_SAVE_SIZE = 0x6BED0;
private const int REV_110_POSTBOX_SAVE_SIZE = 0xB44590;
private const int REV_110_PHOTO_STUDIO_ISLAND_SIZE = 0x263C0;
private const int REV_110_PROFILE_SIZE = 0x69560;
public static readonly FileHashInfo REV_110 = new FileHashInfo(REVISION_110_ID, new[]
{
new FileHashDetails("main.dat", REV_110_MAIN_SAVE_SIZE, new[]
{
new FileHashRegion(0x000110, 0x000114, 0x1D6D5C),
new FileHashRegion(0x1D6E70, 0x1D6E74, 0x323C0C),
new FileHashRegion(0x4FAB90, 0x4FAB94, 0x035AFC),
new FileHashRegion(0x530690, 0x530694, 0x0362BC),
new FileHashRegion(0x566A60, 0x566A64, 0x035AFC),
new FileHashRegion(0x59C560, 0x59C564, 0x0362BC),
new FileHashRegion(0x5D2930, 0x5D2934, 0x035AFC),
new FileHashRegion(0x608430, 0x608434, 0x0362BC),
new FileHashRegion(0x63E800, 0x63E804, 0x035AFC),
new FileHashRegion(0x674300, 0x674304, 0x0362BC),
new FileHashRegion(0x6AA6D0, 0x6AA6D4, 0x035AFC),
new FileHashRegion(0x6E01D0, 0x6E01D4, 0x0362BC),
new FileHashRegion(0x7165A0, 0x7165A4, 0x035AFC),
new FileHashRegion(0x74C0A0, 0x74C0A4, 0x0362BC),
new FileHashRegion(0x782470, 0x782474, 0x035AFC),
new FileHashRegion(0x7B7F70, 0x7B7F74, 0x0362BC),
new FileHashRegion(0x7EE340, 0x7EE344, 0x035AFC),
new FileHashRegion(0x823E40, 0x823E44, 0x0362BC),
new FileHashRegion(0x85A100, 0x85A104, 0x26899C)
}),
new FileHashDetails("personal.dat", REV_110_PERSONAL_SAVE_SIZE, new[]
{
new FileHashRegion(0x00110, 0x00114, 0x35AFC),
new FileHashRegion(0x35C10, 0x35C14, 0x362BC)
}),
new FileHashDetails("postbox.dat", REV_110_POSTBOX_SAVE_SIZE, new[]
{
new FileHashRegion(0x000100, 0x00104, 0xB4448C)
}),
new FileHashDetails("photo_studio_island.dat", REV_110_PHOTO_STUDIO_ISLAND_SIZE, new[]
{
new FileHashRegion(0x000100, 0x00104, 0x262BC)
}),
new FileHashDetails("profile.dat", REV_110_PROFILE_SIZE, new[]
{
new FileHashRegion(0x000100, 0x00104, 0x6945C)
}),
});
#endregion
}
}

View File

@ -0,0 +1,84 @@
using System;
namespace NHSE.Core
{
/// <summary>
/// MurmurHash implementation used by Animal Crossing New Horizons
/// </summary>
public static class Murmur3
{
private static uint Murmur32_Scramble(uint k)
{
k = (k * 0x16A88000) | ((k * 0xCC9E2D51) >> 17);
k *= 0x1B873593;
return k;
}
/// <summary>
/// Updates the hash at the specified offset, using the input parameters.
/// </summary>
/// <param name="data">Data to hash</param>
/// <param name="offset">Where the data-to-be-hashed starts</param>
/// <param name="size">Amount of data to hash</param>
/// <param name="seed">Initial Murmur seed (optional)</param>
/// <returns>Calculated hash.</returns>
public static uint GetMurmur3Hash(byte[] data, int offset, uint size, uint seed = 0)
{
uint checksum = seed;
if (size > 3)
{
for (var i = 0; i < (size / sizeof(uint)); i++)
{
var val = BitConverter.ToUInt32(data, offset);
checksum ^= Murmur32_Scramble(val);
checksum = (checksum >> 19) | (checksum << 13);
checksum = (checksum * 5) + 0xE6546B64;
offset += 4;
}
}
var remainder = size % sizeof(uint);
if (remainder != 0)
{
uint val = BitConverter.ToUInt32(data, (int)((offset + size) - remainder));
for (var i = 0; i < (sizeof(uint) - remainder); i++)
val >>= 8;
checksum ^= Murmur32_Scramble(val);
}
checksum ^= size;
checksum ^= checksum >> 16;
checksum *= 0x85EBCA6B;
checksum ^= checksum >> 13;
checksum *= 0xC2B2AE35;
checksum ^= checksum >> 16;
return checksum;
}
/// <summary>
/// Updates the hash at the specified offset, using the input parameters.
/// </summary>
/// <param name="data">Data to hash</param>
/// <param name="hashOffset">Offset to write the hash</param>
/// <param name="readOffset">Where the data-to-be-hashed starts</param>
/// <param name="readSize">Amount of data to hash</param>
/// <returns>Calculated hash that was written back to the data.</returns>
public static uint UpdateMurmur32(byte[] data, int hashOffset, int readOffset, uint readSize)
{
var newHash = GetMurmur3Hash(data, readOffset, readSize);
Array.Copy(BitConverter.GetBytes(newHash), 0, data, hashOffset, 4);
return newHash;
}
/// <summary>
/// Checks the hash at the specified offset to see if the stored value matches the calculated value.
/// </summary>
/// <param name="data">Data to hash</param>
/// <param name="hashOffset">Offset to write the hash</param>
/// <param name="readOffset">Where the data-to-be-hashed starts</param>
/// <param name="readSize">Amount of data to hash</param>
/// <returns>Calculated hash matches the currently stored hash.</returns>
public static bool VerifyMurmur32(byte[] data, int hashOffset, int readOffset, uint readSize)
=> BitConverter.ToUInt32(data, hashOffset) == GetMurmur3Hash(data, readOffset, readSize);
}
}

View File

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46;netstandard2.0</TargetFrameworks>
<LangVersion>8</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Remove="Resources\text\en\text_villager_en.txt" />
<None Remove="Resources\text\en\text_item_en.txt" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\text\en\text_villager_en.txt" />
<EmbeddedResource Include="Resources\text\en\text_item_en.txt" />
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,397 @@
ant00 Cyrano
ant01 Antonio
ant02 Pango
ant03 Anabelle
ant06 Snooty
ant08 Annalisa
ant09 Olaf
bea00 Teddy
bea01 Pinky
bea02 Curt
bea03 Chow
bea05 Nate
bea06 Groucho
bea07 Tutu
bea08 Ursala
bea09 Grizzly
bea10 Paula
bea11 Ike
bea12 Charlise
bea13 Beardo
bea14 Klaus
bea15 Megan
brd00 Jay
brd01 Robin
brd02 Anchovy
brd03 Twiggy
brd04 Jitters
brd05 Piper
brd06 Admiral
brd08 Midge
brd11 Jakey
brd15 Lucha
brd16 Jacques
brd17 Peck
brd18 Sparro
bul00 Angus
bul01 Rodeo
bul03 Stu
bul05 T-Bone
bul07 Coach
bul08 Vic
cat00 Bob
cat01 Mitzi
cat02 Rosie
cat03 Olivia
cat04 Kiki
cat05 Tangy
cat06 Punchy
cat07 Purrl
cat08 Moe
cat09 Kabuki
cat10 Kid Cat
cat11 Monique
cat12 Tabby
cat13 Stinky
cat14 Kitty
cat15 Tom
cat16 Merry
cat17 Felicity
cat18 Lolly
cat19 Ankha
cat20 Rudy
cat21 Katt
cat23 Raymond
cbr00 Bluebear
cbr01 Maple
cbr02 Poncho
cbr03 Pudge
cbr04 Kody
cbr05 Stitches
cbr06 Vladimir
cbr07 Murphy
cbr09 Olive
cbr10 Cheri
cbr13 June
cbr14 Pekoe
cbr15 Chester
cbr16 Barold
cbr17 Tammy
cbr18 Marty
cbr19 Judy
chn00 Goose
chn01 Benedict
chn02 Egbert
chn05 Ava
chn09 Becky
chn10 Plucky
chn11 Knox
chn12 Broffina
chn13 Ken
cow00 Patty
cow01 Tipper
cow06 Norma
cow07 Naomi
crd00 Alfonso
crd01 Alli
crd02 Boots
crd04 Del
crd06 Sly
crd07 Gayle
crd08 Drago
der00 Fauna
der01 Bam
der02 Zell
der03 Bruce
der04 Deirdre
der05 Lopez
der06 Fuchsia
der07 Beau
der08 Diana
der09 Erik
der10 Chelsea
dog00 Goldie
dog01 Butch
dog02 Lucky
dog03 Biskit
dog04 Bones
dog05 Portia
dog06 Walker
dog07 Daisy
dog08 Cookie
dog09 Maddie
dog10 Bea
dog14 Mac
dog15 Marcel
dog16 Benjamin
dog17 Cherry
dog18 Shep
duk00 Bill
duk01 Joey
duk02 Pate
duk03 Maelle
duk04 Deena
duk05 Pompom
duk06 Mallary
duk07 Freckles
duk08 Derwin
duk09 Drake
duk10 Scoot
duk11 Weber
duk12 Miranda
duk13 Ketchup
duk15 Gloria
duk16 Molly
duk17 Quillson
elp00 Opal
elp01 Dizzy
elp02 Big Top
elp03 Eloise
elp04 Margie
elp05 Paolo
elp06 Axel
elp07 Ellie
elp09 Tucker
elp10 Tia
elp11 Chai
elp12 Cyd
flg00 Lily
flg01 Ribbot
flg02 Frobert
flg03 Camofrog
flg04 Drift
flg05 Wart Jr
flg06 Puddles
flg07 Jeremiah
flg09 Tad
flg10 Cousteau
flg11 Huck
flg12 Prince
flg13 Jambette
flg15 Raddle
flg16 Gigi
flg17 Croque
flg18 Diva
flg19 Henry
goa00 Chevre
goa01 Nan
goa02 Billy
goa04 Gruff
goa06 Velma
goa07 Kidd
goa08 Pashmina
goa09 Sherb
gor00 Cesar
gor01 Peewee
gor02 Boone
gor04 Louie
gor05 Boyd
gor07 Violet
gor08 Al
gor09 Rocket
gor10 Hans
gor11 Rilla
ham00 Hamlet
ham01 Apple
ham02 Graham
ham03 Rodney
ham04 Soleil
ham05 Clay
ham06 Flurry
ham07 Hamphrey
hip00 Rocco
hip02 Bubbles
hip03 Bertha
hip04 Biff
hip05 Bitty
hip08 Harry
hip09 Hippeux
hrs00 Buck
hrs01 Victoria
hrs02 Savannah
hrs03 Elmer
hrs04 Roscoe
hrs05 Winnie
hrs06 Ed
hrs07 Cleo
hrs08 Peaches
hrs09 Annalise
hrs10 Clyde
hrs11 Colton
hrs12 Papi
hrs13 Julian
hrs16 Reneigh
kal00 Yuka
kal01 Alice
kal02 Melba
kal03 Sydney
kal04 Gonzo
kal05 Ozzie
kal08 Canberra
kal09 Lyman
kal10 Eugene
kgr00 Kitt
kgr01 Mathilda
kgr02 Carrie
kgr05 Astrid
kgr06 Sylvia
kgr08 Walt
kgr09 Rooney
kgr10 Marcie
lon00 Bud
lon01 Elvis
lon02 Rex
lon04 Leopold
lon06 Mott
lon07 Rory
lon08 Lionel
mnk01 Nana
mnk02 Simon
mnk03 Tammi
mnk04 Monty
mnk05 Elise
mnk06 Flip
mnk07 Shari
mnk08 Deli
mus00 Dora
mus01 Limberg
mus02 Bella
mus03 Bree
mus04 Samson
mus05 Rod
mus08 Candi
mus09 Rizzo
mus10 Anicotti
mus12 Broccolo
mus14 Moose
mus15 Bettina
mus16 Greta
mus17 Penelope
mus18 Chadder
ocp00 Octavian
ocp01 Marina
ocp02 Zucker
ost00 Queenie
ost01 Gladys
ost02 Sandy
ost03 Sprocket
ost05 Julia
ost06 Cranston
ost07 Phil
ost08 Blanche
ost09 Flora
ost10 Phoebe
pbr00 Apollo
pbr01 Amelia
pbr02 Pierce
pbr03 Buzz
pbr05 Avery
pbr06 Frank
pbr07 Sterling
pbr08 Keaton
pbr09 Celia
pgn00 Aurora
pgn01 Roald
pgn02 Cube
pgn03 Hopper
pgn04 Friga
pgn05 Gwen
pgn06 Puck
pgn09 Wade
pgn10 Boomer
pgn11 Iggly
pgn12 Tex
pgn13 Flo
pgn14 Sprinkle
pig00 Curly
pig01 Truffles
pig02 Rasher
pig03 Hugh
pig04 Lucy
pig05 Crackle
pig08 Cobb
pig09 Boris
pig10 Maggie
pig11 Peggy
pig13 Gala
pig14 Chops
pig15 Kevin
pig16 Pancetti
pig17 Agnes
rbt00 Bunnie
rbt01 Dotty
rbt02 Coco
rbt03 Snake
rbt04 Gaston
rbt05 Gabi
rbt06 Pippy
rbt07 Tiffany
rbt08 Genji
rbt09 Ruby
rbt10 Doc
rbt11 Claude
rbt12 Francine
rbt13 Chrissy
rbt14 Hopkins
rbt15 O'Hare
rbt16 Carmen
rbt17 Bonbon
rbt18 Cole
rbt19 Mira
rbt20 Toby
rhn00 Tank
rhn01 Rhonda
rhn02 Spike
rhn04 Hornsby
rhn07 Merengue
rhn08 Renée
shp00 Vesta
shp01 Baabara
shp02 Eunice
shp03 Stella
shp04 Cashmere
shp07 Willow
shp08 Curlos
shp09 Wendy
shp10 Timbra
shp11 Frita
shp12 Muffy
shp13 Pietro
shp14 Étoile
shp15 Dom
squ00 Peanut
squ01 Blaire
squ02 Filbert
squ03 Pecan
squ04 Nibbles
squ05 Agent S
squ06 Caroline
squ07 Sally
squ08 Static
squ09 Mint
squ10 Ricky
squ11 Cally
squ13 Tasha
squ14 Sylvana
squ15 Poppy
squ16 Sheldon
squ17 Marshal
squ18 Hazel
tig00 Rolf
tig01 Rowan
tig02 Tybalt
tig03 Bangle
tig04 Leonardo
tig05 Claudia
tig06 Bianca
wol00 Chief
wol01 Lobo
wol02 Wolfgang
wol03 Whitney
wol04 Dobie
wol05 Freya
wol06 Fang
wol08 Vivian
wol09 Skye
wol10 Kyle
wol12 Audie

View File

@ -0,0 +1,10 @@
using System;
namespace NHSE.Core
{
public sealed class MainSave : EncryptedFilePair
{
public readonly MainSaveOffsets Offsets;
public MainSave(string folder) : base(folder, "main") => Offsets = MainSaveOffsets.GetOffsets(Info);
}
}

View File

@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
namespace NHSE.Core
{
public sealed class Personal : EncryptedFilePair
{
public readonly PersonalOffsets Offsets;
public Personal(string folder) : base(folder, "personal") => Offsets = PersonalOffsets.GetOffsets(Info);
public override string ToString() => Name;
public uint TownID
{
get => BitConverter.ToUInt32(Data, Offsets.PersonalId + 0x00);
set => BitConverter.GetBytes(value).CopyTo(Data, Offsets.PersonalId + 0x00);
}
public string TownName
{
get => GetString(Offsets.PersonalId + 0x04, 10);
set => GetBytes(value, 10).CopyTo(Data, Offsets.PersonalId + 0x04);
}
public uint PlayerID
{
get => BitConverter.ToUInt32(Data, Offsets.PersonalId + 0x1C);
set => BitConverter.GetBytes(value).CopyTo(Data, Offsets.PersonalId + 0x1C);
}
public string Name
{
get => GetString(Offsets.PersonalId + 0x20, 10);
set => GetBytes(value, 10).CopyTo(Data, Offsets.PersonalId + 0x20);
}
public EncryptedInt32 Wallet
{
get => EncryptedInt32.Read(Data, Offsets.Wallet);
set => value.Write(Data, Offsets.Wallet);
}
public EncryptedInt32 Bank
{
get => EncryptedInt32.Read(Data, Offsets.Bank);
set => value.Write(Data, Offsets.Bank);
}
public EncryptedInt32 NookMiles
{
get => EncryptedInt32.Read(Data, Offsets.NookMiles);
set => value.Write(Data, Offsets.NookMiles);
}
public IReadOnlyList<Item> Pocket1
{
get => Item.GetArray(Data.Slice(Offsets.Pockets1, Offsets.Pockets1Count * Item.SIZE));
set => Item.SetArray(value).CopyTo(Data, Offsets.Pockets1);
}
public IReadOnlyList<Item> Pocket2
{
get => Item.GetArray(Data.Slice(Offsets.Pockets2, Offsets.Pockets2Count * Item.SIZE));
set => Item.SetArray(value).CopyTo(Data, Offsets.Pockets2);
}
public IReadOnlyList<Item> Storage
{
get => Item.GetArray(Data.Slice(Offsets.Storage, Offsets.StorageCount * Item.SIZE));
set => Item.SetArray(value).CopyTo(Data, Offsets.Storage);
}
public byte[] GetPhotoData()
{
var offset = Offsets.Photo;
// Expect jpeg marker
if (BitConverter.ToUInt16(Data, offset) != 0xD8FF)
return Array.Empty<byte>();
var len = BitConverter.ToInt32(Data, offset - 4);
return Data.Slice(offset, len);
}
}
}

View File

@ -0,0 +1,7 @@
namespace NHSE.Core
{
public sealed class PhotoStudioIsland : EncryptedFilePair
{
public PhotoStudioIsland(string folder) : base(folder, "photo_studio_island") { }
}
}

View File

@ -0,0 +1,7 @@
namespace NHSE.Core
{
public sealed class PostBox : EncryptedFilePair
{
public PostBox(string folder) : base(folder, "postbox") { }
}
}

View File

@ -0,0 +1,7 @@
namespace NHSE.Core
{
public sealed class Profile : EncryptedFilePair
{
public Profile(string folder) : base(folder, "profile") { }
}
}

View File

@ -0,0 +1,72 @@
using System;
using System.IO;
using System.Text;
namespace NHSE.Core
{
public abstract class EncryptedFilePair
{
public readonly byte[] Data;
public readonly byte[] Header;
public readonly FileHeaderInfo Info;
public readonly string DataPath;
public readonly string HeaderPath;
public readonly string NameData;
public readonly string NameHeader;
protected EncryptedFilePair(string folder, string name)
{
NameData = $"{name}.dat";
NameHeader = $"{name}Header.dat";
var hdr = Path.Combine(folder, NameHeader);
var dat = Path.Combine(folder, NameData);
var hd = File.ReadAllBytes(hdr);
var md = File.ReadAllBytes(dat);
var decrypted = Encryption.Decrypt(hd, md);
Header = hd;
Data = decrypted;
DataPath = dat;
HeaderPath = hdr;
Info = Header.Slice(0, FileHeaderInfo.SIZE).ToClass<FileHeaderInfo>();
}
public void Save(uint seed)
{
var encrypt = Encryption.Encrypt(Data, seed, Header);
File.WriteAllBytes(DataPath, encrypt.Data);
File.WriteAllBytes(HeaderPath, encrypt.Header);
}
public void Hash()
{
var ver = Info.GetKnownRevisionIndex();
var hash = RevisionChecker.HashInfo[ver];
var details = hash.GetFile(NameData);
if (details == null)
throw new ArgumentNullException(nameof(NameData));
foreach (var h in details.HashRegions)
Murmur3.UpdateMurmur32(Data, h.HashOffset, h.BeginOffset, (uint)h.Size);
}
public string GetString(int offset, int maxLength)
{
var str = Encoding.Unicode.GetString(Data, offset, maxLength * 2);
return StringUtil.TrimFromZero(str);
}
public static byte[] GetBytes(string value, int maxLength)
{
if (value.Length > maxLength)
value = value.Substring(0, maxLength);
else if (value.Length < maxLength)
value = value.PadRight(maxLength, '\0');
return Encoding.Unicode.GetBytes(value);
}
}
}

View File

@ -0,0 +1,66 @@
using System;
using System.Runtime.InteropServices;
// ReSharper disable NonReadonlyMemberInGetHashCode
namespace NHSE.Core
{
[StructLayout(LayoutKind.Sequential)]
public class FileHeaderInfo : IEquatable<FileHeaderInfo>
{
public const int SIZE = 0x40;
/* 0x00 */ public uint Major;
/* 0x04 */ public uint Minor;
/* 0x08 */ public ushort Unk1;
/* 0x0A */ public ushort HeaderRevision;
/* 0x0C */ public ushort Unk2;
/* 0x0E */ public ushort SaveRevision;
public bool Equals(FileHeaderInfo? other)
{
if (other is null)
return false;
if (ReferenceEquals(this, other))
return true;
if (Major != other.Major)
return false;
if (Minor != other.Minor)
return false;
if (Unk1 != other.Unk1)
return false;
if (HeaderRevision != other.HeaderRevision)
return false;
if (Unk2 != other.Unk2)
return false;
if (SaveRevision != other.SaveRevision)
return false;
return true;
}
public override bool Equals(object? obj)
{
if (obj is null)
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != GetType())
return false;
return Equals((FileHeaderInfo) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (int) Major;
hashCode = (hashCode * 397) ^ (int) Minor;
hashCode = (hashCode * 397) ^ Unk1.GetHashCode();
hashCode = (hashCode * 397) ^ HeaderRevision.GetHashCode();
hashCode = (hashCode * 397) ^ Unk2.GetHashCode();
hashCode = (hashCode * 397) ^ SaveRevision.GetHashCode();
return hashCode;
}
}
}
}

View File

@ -0,0 +1,26 @@
namespace NHSE.Core
{
public class HorizonSave
{
public readonly MainSave Main;
public readonly Player[] Players;
public override string ToString() => $"{Players[0].Personal.TownName} - {Players[0]}";
public HorizonSave(string folder)
{
Main = new MainSave(folder);
Players = Player.ReadMany(folder);
}
public void Save(uint seed)
{
Main.Hash();
Main.Save(seed);
foreach (var player in Players)
{
player.Hash();
player.Save(seed);
}
}
}
}

View File

@ -0,0 +1,53 @@
using System.IO;
namespace NHSE.Core
{
/// <summary>
/// Stores references for all files in the Villager (<see cref="DirectoryName"/>) folder.
/// </summary>
public sealed class Player
{
public readonly Personal Personal;
public readonly PhotoStudioIsland Photo;
public readonly PostBox PostBox;
public readonly Profile Profile;
public readonly string DirectoryName;
public override string ToString() => Personal.Name;
public static Player[] ReadMany(string folder)
{
var dirs = Directory.GetDirectories(folder, "Villager*", SearchOption.TopDirectoryOnly);
var result = new Player[dirs.Length];
for (int i = 0; i <result.Length; i++)
result[i] = new Player(dirs[i]);
return result;
}
private Player(string folder)
{
DirectoryName = new DirectoryInfo(folder).Name;
Personal = new Personal(folder);
Photo = new PhotoStudioIsland(folder);
PostBox = new PostBox(folder);
Profile = new Profile(folder);
}
public void Save(uint seed)
{
Personal.Save(seed);
Photo.Save(seed);
PostBox.Save(seed);
Profile.Save(seed);
}
public void Hash()
{
Personal.Hash();
Photo.Hash();
PostBox.Hash();
Profile.Hash();
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
namespace NHSE.Core
{
public static class RevisionChecker
{
// Patches where the sizes of individual files changed
private static readonly SaveFileSizes[] SizesByRevision =
{
new SaveFileSizes(0xAC0938, 0x6BC50, 0x263B4, 0xB44580, 0x69508), // 1.0.0
new SaveFileSizes(0xAC2AA0, 0x6BED0, 0x263C0, 0xB44590, 0x69560), // 1.1.0
};
private static readonly FileHeaderInfo[] RevisionInfo =
{
new FileHeaderInfo { Major = 0x67, Minor = 0x6F, HeaderRevision = 0, Unk1 = 2, SaveRevision = 0, Unk2 = 2 }, // 1.0.0
new FileHeaderInfo { Major = 0x6D, Minor = 0x78, HeaderRevision = 0, Unk1 = 2, SaveRevision = 1, Unk2 = 2 }, // 1.1.0
new FileHeaderInfo { Major = 0x6D, Minor = 0x78, HeaderRevision = 0, Unk1 = 2, SaveRevision = 2, Unk2 = 2 }, // 1.1.1
};
public static readonly IReadOnlyList<SaveFileSizes> SizeInfo = new[]
{
SizesByRevision[0], // 1.0.0
SizesByRevision[1], // 1.1.0
SizesByRevision[1], // 1.1.1
};
public static readonly IReadOnlyList<FileHashInfo> HashInfo = new[]
{
FileHashRevision.REV_100, // 1.0.0
FileHashRevision.REV_110, // 1.1.0
FileHashRevision.REV_110, // 1.1.1
};
public static bool IsRevisionKnown(this FileHeaderInfo info) => info.GetKnownRevisionIndex() >= 0;
public static int GetKnownRevisionIndex(this FileHeaderInfo info) => Array.FindIndex(RevisionInfo, z => z.Equals(info));
}
}

View File

@ -0,0 +1,20 @@
namespace NHSE.Core
{
public class SaveFileSizes
{
public readonly uint Main;
public readonly uint Personal;
public readonly uint PhotoStudioIsland;
public readonly uint PostBox;
public readonly uint Profile;
public SaveFileSizes(uint main, uint personal, uint photo, uint postbox, uint profile)
{
Main = main;
Personal = personal;
PhotoStudioIsland = photo;
PostBox = postbox;
Profile = profile;
}
}
}

View File

@ -0,0 +1,28 @@
using System;
namespace NHSE.Core
{
public abstract class MainSaveOffsets
{
public abstract int Villager { get; }
public const int VillagerSize = 0x12AB0;
public static MainSaveOffsets GetOffsets(FileHeaderInfo Info)
{
var rev = Info.GetKnownRevisionIndex();
return rev switch
{
0 => new MainSaveOffsets10(),
1 => new MainSaveOffsets11(),
2 => new MainSaveOffsets11(),
_ => throw new IndexOutOfRangeException("Unknown revision!"),
};
}
public abstract Villager ReadVillager(byte[] data, int index);
public void WriteVillager(Villager v, byte[] data, int index)
{
v.Data.CopyTo(data, Villager + (index * VillagerSize));
}
}
}

View File

@ -0,0 +1,13 @@
namespace NHSE.Core
{
public class MainSaveOffsets10 : MainSaveOffsets
{
public override int Villager => 0x110;
public override Villager ReadVillager(byte[] data, int index)
{
var v = data.Slice(Villager + (index * VillagerSize), VillagerSize);
return new Villager(v);
}
}
}

View File

@ -0,0 +1,13 @@
namespace NHSE.Core
{
public class MainSaveOffsets11 : MainSaveOffsets
{
public override int Villager => 0x120;
public override Villager ReadVillager(byte[] data, int index)
{
var v = data.Slice(Villager + (index * VillagerSize), VillagerSize);
return new Villager(v);
}
}
}

View File

@ -0,0 +1,33 @@
using System;
namespace NHSE.Core
{
public abstract class PersonalOffsets
{
public abstract int PersonalId { get; }
public abstract int Wallet { get; }
public abstract int Bank { get; }
public abstract int NookMiles { get; }
public abstract int Photo { get; }
public abstract int Pockets1 { get; }
public abstract int Pockets2 { get; }
public abstract int Storage { get; }
public virtual int Pockets1Count { get; } = 20;
public virtual int Pockets2Count { get; } = 20;
public virtual int StorageCount { get; } = 5000;
public static PersonalOffsets GetOffsets(FileHeaderInfo Info)
{
var rev = Info.GetKnownRevisionIndex();
return rev switch
{
0 => new PersonalOffsets10(),
1 => new PersonalOffsets11(),
2 => new PersonalOffsets11(),
_ => throw new IndexOutOfRangeException("Unknown revision!"),
};
}
}
}

View File

@ -0,0 +1,15 @@
namespace NHSE.Core
{
public sealed class PersonalOffsets10 : PersonalOffsets
{
public override int PersonalId => 0xB0A0;
public override int Wallet => 0x11578;
public override int Bank => 0x68BE4;
public override int NookMiles => 0x11570;
public override int Photo => 0x11598;
public override int Pockets1 => 0x35BD4;
public override int Pockets2 => Pockets1 + (8 * Pockets1Count) + 0x18;
public override int Storage => Pockets2 + (8 * Pockets2Count) + 0x24;
}
}

View File

@ -0,0 +1,15 @@
namespace NHSE.Core
{
public sealed class PersonalOffsets11 : PersonalOffsets
{
public override int PersonalId => 0xB0B8;
public override int Wallet => 0x11590;
public override int Bank => 0x68C34;
public override int NookMiles => 0x11588;
public override int Photo => 0x115C4;
public override int Pockets1 => 0x35C20;
public override int Pockets2 => Pockets1 + (8 * Pockets1Count) + 0x18;
public override int Storage => Pockets2 + (8 * Pockets2Count) + 0x24;
}
}

View File

@ -0,0 +1,25 @@
using System.Collections.Generic;
namespace NHSE.Core
{
public static class GameInfo
{
private static readonly GameStrings[] Languages = new GameStrings[GameLanguage.LanguageCount];
public static string CurrentLanguage { get; set; } = GameLanguage.DefaultLanguage;
public static readonly IReadOnlyList<string> GenderSymbolUnicode = new[] { "♂", "♀", "-" };
public static readonly IReadOnlyList<string> GenderSymbolASCII = new[] { "M", "F", "-" };
public static GameStrings Strings { get; set; } = GetStrings(CurrentLanguage);
public static GameStrings GetStrings(string lang)
{
int index = GameLanguage.GetLanguageIndex(lang);
return GetStrings(index);
}
public static GameStrings GetStrings(int index)
{
return Languages[index] ??= new GameStrings(GameLanguage.Language2Char(index));
}
}
}

View File

@ -0,0 +1,33 @@
using System;
namespace NHSE.Core
{
public static class GameLanguage
{
public const string DefaultLanguage = "en"; // English
public static int DefaultLanguageIndex => Array.IndexOf(LanguageCodes, DefaultLanguage);
public static string Language2Char(int lang) => lang > LanguageCodes.Length ? DefaultLanguage : LanguageCodes[lang];
public static int LanguageCount => LanguageCodes.Length;
public static int GetLanguageIndex(string lang)
{
int l = Array.IndexOf(LanguageCodes, lang);
return l < 0 ? DefaultLanguageIndex : l;
}
/// <summary>
/// Language codes supported for loading string resources
/// </summary>
private static readonly string[] LanguageCodes = { "en" };
public static string[] GetStrings(string ident, string lang, string type = "text")
{
string[] data = ResourceUtil.GetStringList(ident, lang, type);
if (data == null || data.Length == 0)
data = ResourceUtil.GetStringList(ident, DefaultLanguage, type);
return data;
}
}
}

View File

@ -0,0 +1,37 @@
using System.IO;
namespace NHSE.Core
{
public static class GameFileDumper
{
public static void Dump(this HorizonSave sav, string path)
{
sav.Main.Dump(path);
foreach (var p in sav.Players)
{
var dir = Path.Combine(path, p.DirectoryName);
p.Dump(dir);
}
}
public static void Dump(this Player pair, string path)
{
pair.Profile.Dump(path);
pair.Personal.Dump(path);
pair.Photo.Dump(path);
pair.PostBox.Dump(path);
}
public static void Dump(this EncryptedFilePair pair, string path)
{
Dump(path, pair.Data, pair.NameData);
}
public static void Dump(string path, byte[] data, string name)
{
Directory.CreateDirectory(path);
var file = Path.Combine(path, name);
File.WriteAllBytes(file, data);
}
}
}

View File

@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace NHSE.Core
{
public class InventorySet
{
public readonly InventoryType Type;
public readonly IReadOnlyList<Item> Items;
public InventorySet(InventoryType type, IReadOnlyList<Item> items)
{
Type = type;
Items = items;
}
}
}

View File

@ -0,0 +1,9 @@
namespace NHSE.Core
{
public enum InventoryType
{
Pocket1,
Pocket2,
Storage,
}
}

View File

@ -0,0 +1,71 @@
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace NHSE.Core
{
[StructLayout(LayoutKind.Sequential)]
public sealed class Item
{
public static readonly Item NO_ITEM = new Item();
public const ushort NONE = 0xFFFE;
public const int SIZE = 8;
private static readonly ushort[] resolvedItemIdArray =
{
0x1E13, 0x1E14, 0x1E15, 0x1E16, 0x1E17, 0x1E18, 0x1E19, 0x1E1A,
0x1E1B, 0x1E1C, 0x1E1D, 0x1E1E, 0x1E1F, 0x1E20, 0x1E21, 0x1E22
};
public ushort ItemId;
public byte Flags0;
public byte Flags1;
public byte Count;
public byte Flags2;
public ushort UseCount;
public ItemType Type => (ItemType) (Flags1 & 3);
public int ReservedIndex => (Flags1 >> 2) & 0xF;
public Item() { } // marshalling
public Item(ushort itemId = NONE, byte flags0 = 0, byte flags1 = 0, byte count = 0, byte flags2 = 0, ushort useCount = 0)
{
ItemId = itemId;
Flags0 = flags0;
Flags1 = flags1;
Flags2 = flags2;
Count = count;
UseCount = useCount;
}
public static Item[] GetArray(byte[] data)
{
var result = new Item[data.Length / SIZE];
for (int i = 0; i < result.Length; i++)
result[i] = data.Slice(i * SIZE, SIZE).ToClass<Item>();
return result;
}
public static byte[] SetArray(IReadOnlyList<Item> data)
{
var result = new byte[data.Count * SIZE];
for (int i = 0; i < data.Count; i++)
data[i].ToBytesClass().CopyTo(result, i * SIZE);
return result;
}
public ushort GetInventoryNameFromFlags()
{
if (ItemId == 0x16A1 || ItemId == 0x3100)
return ItemId;
return Type switch
{
ItemType.Reserved => resolvedItemIdArray[ReservedIndex],
ItemType.Present => 0x1180,
ItemType.Delivery => 0x1225,
_ => ItemId,
};
}
}
}

View File

@ -0,0 +1,10 @@
namespace NHSE.Core
{
public enum ItemType
{
Nothing = 0,
Reserved = 1,
Present = 2,
Delivery = 3
};
}

View File

@ -0,0 +1,50 @@
namespace NHSE.Core
{
/// <summary>
/// SEAD likely stands for Software Entertainment Analysis & Development
/// </summary>
internal sealed class SEADRandom
{
private readonly uint[] state = new uint[4];
public SEADRandom(uint seedOne, uint seedTwo, uint seedThree, uint seedFour)
{
state[0] = seedOne;
state[1] = seedTwo;
state[2] = seedThree;
state[3] = seedFour;
}
public SEADRandom(uint seed)
{
for (int i = 0; i < 4; i++)
{
state[i] = (uint)((0x6C078965 * (seed ^ (seed >> 30))) + i + 1);
seed = state[i];
}
}
public uint GetU32()
{
uint v1 = state[0] ^ (state[0] << 11);
state[0] = state[1];
state[1] = state[2];
state[2] = state[3];
return state[3] = v1 ^ (v1 >> 8) ^ state[3] ^ (state[3] >> 19);
}
public ulong GetU64()
{
uint v1 = state[0] ^ (state[0] << 11);
uint v2 = state[1];
uint v3 = v1 ^ (v1 >> 8) ^ state[3];
state[0] = state[2];
state[1] = state[3];
state[2] = v3 ^ (state[3] >> 19);
state[3] = v2 ^ (v2 << 11) ^ ((v2 ^ (v2 << 11)) >> 8) ^ state[2] ^ (v3 >> 19);
return ((ulong)state[2] << 32) | state[3];
}
}
}

View File

@ -0,0 +1,53 @@
using System.Text;
namespace NHSE.Core
{
public class Villager
{
public readonly byte[] Data;
public Villager(byte[] data) => Data = data;
public byte Species
{
get => Data[0];
set => Data[0] = value;
}
public byte Variant
{
get => Data[1];
set => Data[1] = value;
}
public VillagerPersonality Personality
{
get => (VillagerPersonality)Data[2];
set => Data[2] = (byte)value;
}
public string CatchPhrase
{
get => GetString(0x10014, 2 * 12);
set => GetBytes(value, 2 * 12).CopyTo(Data, 0x10014);
}
public override string ToString() => InternalName;
public string InternalName => VillagerUtil.GetInternalVillagerName((VillagerSpecies) Species, Variant);
public int Gender => ((int)Personality / 4) & 1; // 0 = M, 1 = F
public string GetString(int offset, int maxLength)
{
var str = Encoding.Unicode.GetString(Data, offset, maxLength * 2);
return StringUtil.TrimFromZero(str);
}
public static byte[] GetBytes(string value, int maxLength)
{
if (value.Length > maxLength)
value = value.Substring(0, maxLength);
else if (value.Length < maxLength)
value = value.PadRight(maxLength, '\0');
return Encoding.Unicode.GetBytes(value);
}
}
}

View File

@ -0,0 +1,15 @@
namespace NHSE.Core
{
public enum VillagerPersonality : byte
{
Lazy,
Jock,
Cranky,
Smug,
Normal,
Peppy,
Snooty,
Uchi,
None,
}
}

View File

@ -0,0 +1,47 @@
namespace NHSE.Core
{
public static class VillagerUtil
{
public static string GetInternalVillagerName(VillagerSpecies species, int variant) => $"{species}{variant:00}";
}
public enum VillagerSpecies
{
ant = 0,
bea = 1,
brd = 2,
bul = 3,
cat = 4,
cbr = 5,
chn = 6,
cow = 7,
crd = 8,
der = 9,
dog = 10,
duk = 11,
elp = 12,
flg = 13,
goa = 14,
gor = 15,
ham = 16,
hip = 17,
hrs = 18,
kal = 19,
kgr = 20,
lon = 21,
mnk = 22,
mus = 23,
ocp = 24,
ost = 25,
pbr = 26,
pgn = 27,
pig = 28,
rbt = 29,
rhn = 30,
shp = 31,
squ = 32,
tig = 33,
wol = 34,
non = 35,
}
}

182
NHSE.Core/Util/ArrayUtil.cs Normal file
View File

@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
namespace NHSE.Core
{
/// <summary>
/// Array reusable logic
/// </summary>
public static class ArrayUtil
{
public static bool IsRangeAll<T>(this T[] data, T value, int offset, int length) where T : IEquatable<T>
{
int start = offset + length - 1;
int end = offset;
for (int i = start; i >= end; i--)
{
if (!data[i].Equals(value))
return false;
}
return true;
}
public static byte[] Slice(this byte[] src, int offset, int length)
{
byte[] data = new byte[length];
Buffer.BlockCopy(src, offset, data, 0, data.Length);
return data;
}
public static byte[] SliceEnd(this byte[] src, int offset)
{
int length = src.Length - offset;
byte[] data = new byte[length];
Buffer.BlockCopy(src, offset, data, 0, data.Length);
return data;
}
public static T[] Slice<T>(this T[] src, int offset, int length)
{
var data = new T[length];
Array.Copy(src, offset, data, 0, data.Length);
return data;
}
public static T[] SliceEnd<T>(this T[] src, int offset)
{
int length = src.Length - offset;
var data = new T[length];
Array.Copy(src, offset, data, 0, data.Length);
return data;
}
public static bool WithinRange(int value, int min, int max) => min <= value && value < max;
public static T[][] Split<T>(this T[] data, int size)
{
var result = new T[data.Length / size][];
for (int i = 0; i < data.Length; i += size)
result[i / size] = data.Slice(i, size);
return result;
}
public static IEnumerable<T[]> EnumerateSplit<T>(T[] bin, int size, int start = 0)
{
for (int i = start; i < bin.Length; i += size)
yield return bin.Slice(i, size);
}
public static IEnumerable<T[]> EnumerateSplit<T>(T[] bin, int size, int start, int end)
{
if (end < 0)
end = bin.Length;
for (int i = start; i < end; i += size)
yield return bin.Slice(i, size);
}
public static bool[] GitBitFlagArray(byte[] data, int offset, int count)
{
bool[] result = new bool[count];
for (int i = 0; i < result.Length; i++)
result[i] = (data[offset + (i >> 3)] >> (i & 7) & 0x1) == 1;
return result;
}
public static void SetBitFlagArray(byte[] data, int offset, bool[] value)
{
for (int i = 0; i < value.Length; i++)
{
var ofs = offset + (i >> 3);
var mask = (1 << (i & 7));
if (value[i])
data[ofs] |= (byte)mask;
else
data[ofs] &= (byte)~mask;
}
}
public static byte[] SetBitFlagArray(bool[] value)
{
byte[] data = new byte[value.Length / 8];
SetBitFlagArray(data, 0, value);
return data;
}
/// <summary>
/// Copies a <see cref="T"/> list to the destination list, with an option to copy to a starting point.
/// </summary>
/// <param name="list">Source list to copy from</param>
/// <param name="dest">Destination list/array</param>
/// <param name="skip">Criteria for skipping a slot</param>
/// <param name="start">Starting point to copy to</param>
/// <returns>Count of <see cref="T"/> copied.</returns>
public static int CopyTo<T>(this IEnumerable<T> list, IList<T> dest, Func<T, bool> skip, int start = 0)
{
int ctr = start;
int skipped = 0;
foreach (var z in list)
{
// seek forward to next open slot
int next = FindNextValidIndex(dest, skip, ctr);
if (next == -1)
break;
skipped += next - ctr;
ctr = next;
dest[ctr++] = z;
}
return ctr - start - skipped;
}
public static int FindNextValidIndex<T>(IList<T> dest, Func<T, bool> skip, int ctr)
{
while (true)
{
if ((uint)ctr >= dest.Count)
return -1;
var exist = dest[ctr];
if (exist == null || !skip(exist))
return ctr;
ctr++;
}
}
/// <summary>
/// Copies an <see cref="IEnumerable{T}"/> list to the destination list, with an option to copy to a starting point.
/// </summary>
/// <typeparam name="T">Typed object to copy</typeparam>
/// <param name="list">Source list to copy from</param>
/// <param name="dest">Destination list/array</param>
/// <param name="start">Starting point to copy to</param>
/// <returns>Count of <see cref="T"/> copied.</returns>
public static int CopyTo<T>(this IEnumerable<T> list, IList<T> dest, int start = 0)
{
int ctr = start;
foreach (var z in list)
{
if ((uint)ctr >= dest.Count)
break;
dest[ctr++] = z;
}
return ctr - start;
}
internal static T[] ConcatAll<T>(params T[][] arr)
{
int len = 0;
foreach (var a in arr)
len += a.Length;
var result = new T[len];
int ctr = 0;
foreach (var a in arr)
{
a.CopyTo(result, ctr);
ctr += a.Length;
}
return result;
}
}
}

View File

@ -0,0 +1,39 @@
using System.Collections.Generic;
namespace NHSE.Core
{
public sealed class GameStrings
{
private readonly string lang;
public readonly string[] villagers;
public readonly string[] itemlist;
public readonly Dictionary<string, string> VillagerMap;
private string[] Get(string ident) => GameLanguage.GetStrings(ident, lang);
public GameStrings(string l)
{
lang = l;
villagers = Get("villager");
VillagerMap = GetMap(villagers);
itemlist = Get("item");
}
private static Dictionary<string, string> GetMap(IReadOnlyCollection<string> arr)
{
var map = new Dictionary<string, string>(arr.Count);
foreach (var kvp in arr)
{
var split = kvp.Split('\t');
map.Add(split[0], split[1]);
}
return map;
}
public string GetVillager(string name)
{
return VillagerMap.TryGetValue(name, out var result) ? result : "???";
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace NHSE.Core
{
public static partial class RandUtil
{
// Multithread safe rand, ha
public static Random Rand => _local.Value;
private static readonly ThreadLocal<Random> _local = new ThreadLocal<Random>(() => new Random());
public static uint Rand32() => Rand32(Rand);
public static uint Rand32(Random rnd) => (uint)rnd.Next(1 << 30) << 2 | (uint)rnd.Next(1 << 2);
/// <summary>
/// Shuffles the order of items within a collection of items.
/// </summary>
/// <typeparam name="T">Item type</typeparam>
/// <param name="items">Item collection</param>
public static void Shuffle<T>(IList<T> items) => Shuffle(items, 0, items.Count, Rand);
/// <summary>
/// Shuffles the order of items within a collection of items.
/// </summary>
/// <typeparam name="T">Item type</typeparam>
/// <param name="items">Item collection</param>
/// <param name="start">Starting position</param>
/// <param name="end">Ending position</param>
/// <param name="rnd">RNG object to use</param>
public static void Shuffle<T>(IList<T> items, int start, int end, Random rnd)
{
for (int i = start; i < end; i++)
{
int index = i + rnd.Next(end - i);
T t = items[index];
items[index] = items[i];
items[i] = t;
}
}
}
}

View File

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace NHSE.Core
{
public static class ResourceUtil
{
private static readonly Assembly thisAssembly = typeof(ResourceUtil).GetTypeInfo().Assembly;
private static readonly string[] manifestResourceNames = thisAssembly.GetManifestResourceNames();
private static readonly Dictionary<string, string> resourceNameMap = new Dictionary<string, string>();
private static readonly Dictionary<string, string[]> stringListCache = new Dictionary<string, string[]>();
private static readonly object getStringListLoadLock = new object();
public static string[] GetStringList(string fileName)
{
if (IsStringListCached(fileName, out var result))
return result;
var txt = GetStringResource(fileName); // Fetch File, \n to list.
return LoadStringList(fileName, txt);
}
public static bool IsStringListCached(string fileName, out string[] result)
{
lock (getStringListLoadLock) // Make sure only one thread can read the cache
return stringListCache.TryGetValue(fileName, out result);
}
public static string[] LoadStringList(string file, string? txt)
{
if (txt == null)
return Array.Empty<string>();
string[] rawlist = txt.Split('\n');
for (int i = 0; i < rawlist.Length; i++)
rawlist[i] = rawlist[i].TrimEnd('\r');
lock (getStringListLoadLock) // Make sure only one thread can write to the cache
{
if (!stringListCache.ContainsKey(file)) // Check cache again in case of race condition
stringListCache.Add(file, rawlist);
}
return (string[])rawlist.Clone();
}
public static string[] GetStringList(string fileName, string lang2char, string type = "text") => GetStringList($"{type}_{fileName}_{lang2char}");
public static byte[] GetBinaryResource(string name)
{
using var resource = thisAssembly.GetManifestResourceStream($"NHSE.Core.Resources.byte.{name}");
var buffer = new byte[resource.Length];
resource.Read(buffer, 0, (int)resource.Length);
return buffer;
}
public static string? GetStringResource(string name)
{
if (!resourceNameMap.TryGetValue(name, out var resname))
{
bool Match(string x) => x.StartsWith("NHSE.Core.Resources.text.") && x.EndsWith($"{name}.txt", StringComparison.OrdinalIgnoreCase);
resname = Array.Find(manifestResourceNames, Match);
if (resname == null)
return null;
resourceNameMap.Add(name, resname);
}
using var resource = thisAssembly.GetManifestResourceStream(resname);
if (resource == null)
return null;
using var reader = new StreamReader(resource);
return reader.ReadToEnd();
}
}
}

View File

@ -0,0 +1,21 @@
using System.Runtime.CompilerServices;
namespace NHSE.Core
{
public static partial class StringUtil
{
/// <summary>
/// Trims a string at the first instance of a 0x0000 terminator.
/// </summary>
/// <param name="input">String to trim.</param>
/// <returns>Trimmed string.</returns>
public static string TrimFromZero(string input) => TrimFromFirst(input, '\0');
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static string TrimFromFirst(string input, char c)
{
int index = input.IndexOf(c);
return index < 0 ? input : input.Substring(0, index);
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Runtime.InteropServices;
namespace NHSE.Core
{
internal static class StructConverter
{
public static T ToStructure<T>(this byte[] bytes) where T : struct
{
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try { return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); }
finally { handle.Free(); }
}
public static T ToClass<T>(this byte[] bytes) where T : class
{
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try { return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); }
finally { handle.Free(); }
}
public static byte[] ToBytesClass<T>(this T obj) where T : class
{
int size = Marshal.SizeOf(obj);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
public static byte[] ToBytes<T>(this T obj) where T : struct
{
int size = Marshal.SizeOf(obj);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
}
}

View File

@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,40 @@
using System.IO;
using System.Linq;
namespace NHSE.Parsing
{
public static class ParseConverter
{
public static void ConvertItemStrings(string input, string output)
{
var result = ConvertItemList(input);
File.WriteAllLines(output, result);
}
private static string[] ConvertItemList(string path)
{
var lines = File.ReadAllLines(path);
var items = lines.Select(z => new ParseItem(z)).ToArray();
var max = items.Max(z => z.Index);
var result = new string[max + 1];
foreach (var item in items)
{
result[item.Index] = item.Name;
}
return result;
}
}
public class ParseItem
{
public int Index;
public string Name;
public ParseItem(string line)
{
var split = line.Split(new[] { ", " }, 0);
Index = int.Parse(split[0], System.Globalization.NumberStyles.HexNumber);
Name = split[1];
}
}
}

View File

@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46;netcoreapp3.1</TargetFrameworks>
<LangVersion>8</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Folder Include="Villagers\" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="System.Drawing.Common" Version="4.7.0" />
<PackageReference Include="System.Resources.Extensions" Version="4.7.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NHSE.Core\NHSE.Core.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
using System.Drawing;
using NHSE.Core;
using NHSE.Sprites.Properties;
namespace NHSE.Sprites
{
public static class VillagerSprite
{
public static Image? GetVillagerSprite(VillagerSpecies species, int variant)
{
var asset = VillagerUtil.GetInternalVillagerName(species, variant);
return GetVillagerSprite(asset);
}
public static Image? GetVillagerSprite(string asset)
{
return (Image?)Resources.ResourceManager.GetObject(asset);
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Some files were not shown because too many files have changed in this diff Show More