feat: rhm

This commit is contained in:
2026-07-23 22:19:33 -04:00
parent 569cdbd14a
commit c92b395a3e
21 changed files with 1090 additions and 7 deletions
+8 -7
View File
@@ -2,8 +2,6 @@
A .NET 10 C# library for reading and writing Rhythia replay and map files. A .NET 10 C# library for reading and writing Rhythia replay and map files.
Currently only `.rhr` replay files are supported, but `.rhm` map files are easy to implement and will be implemented in the coming days.
This library is designed for the Steam version of Rhythia, but it may work with the open-source one as well if they end up using the same formats. As of now (July 2026) the open-source version supports `.rhm` maps. This library is designed for the Steam version of Rhythia, but it may work with the open-source one as well if they end up using the same formats. As of now (July 2026) the open-source version supports `.rhm` maps.
## Installation ## Installation
@@ -22,15 +20,17 @@ dotnet add reference path/to/RhythiaLib/RhythiaLib/RhythiaLib.csproj
## Supported Formats ## Supported Formats
| Extension | Status | Description | | Extension | Status | Description |
| --------- | --------- | --------------------------- | | --------- | --------- | ------------------------ |
| .rhr | Supported | Rhythia replay file | | .rhr | Supported | Rhythia replay file |
| .rhm | Planned | Rhythia map file/archive | | .rhm | Supported | Rhythia map file/archive |
| .sspm | Possibly | Legacy/SoundSpace+ map file | | .sspm | Possibly | SoundSpace+ map file |
| .ssre | Possibly | SoundSpace+ replay file |
## Usage ## Usage
- [RHR Files](./RhythiaLib/Rhr/USAGE.MD) - [RHR Files](./RhythiaLib/Rhr/USAGE.MD)
- [RHM Files](./RhythiaLib/Rhm/USAGE.MD)
## Testing ## Testing
@@ -43,6 +43,7 @@ dotnet test
## Credits ## Credits
- [yoru](https://github.com/yo-ru) - Their [rhrParse](https://github.com/yo-ru/rhrParse) repo was used as reference for unknown fields and backwards compatibility. - [yoru](https://github.com/yo-ru) - Their [rhrParse](https://github.com/yo-ru/rhrParse) repo was used as reference for unknown fields and backwards compatibility.
- [FOSS Rhythia](https://github.com/Rhythia/Client) - Their map [parser](https://github.com/Rhythia/Client/blob/d931b419853387ef6d2ecd1b378e409f6de6f630/scripts/map/MapParser.cs)/[model](https://github.com/Rhythia/Client/blob/d931b419853387ef6d2ecd1b378e409f6de6f630/scripts/map/Map.cs) was used as reference.
## License ## License
Binary file not shown.
Binary file not shown.
+165
View File
@@ -0,0 +1,165 @@
using System.Text.Json;
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
namespace RhythiaLib.Tests.Rhm
{
public sealed class RhmCorruptionTests
{
[Fact]
public void Decode_NonZip_Throws()
{
Assert.Throws<InvalidRhmFormatException>(() => RhmFile.Decode("not a zip"u8));
}
[Fact]
public void Decode_MissingMap_Throws()
{
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(RhmFixtureData.CreateArchive("", includeMap: false))
);
}
[Fact]
public void Decode_InvalidMapJson_Throws()
{
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(RhmFixtureData.CreateArchive("{"))
);
}
[Fact]
public void Decode_MissingAudio_Throws()
{
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(
RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson, includeAudio: false)
)
);
}
[Fact]
public void Decode_MissingCover_Throws()
{
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(
RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson, includeCover: false)
)
);
}
[Fact]
public void Decode_MapOverLimit_Throws()
{
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(
RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson),
new RhmReadOptions { MaximumMapSize = 1 }
)
);
}
[Theory]
[InlineData(0)]
[InlineData(6)]
public void Decode_InvalidDifficulty_Throws(int difficulty)
{
string json = Replace("Difficulty", difficulty);
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(RhmFixtureData.CreateArchive(json))
);
}
[Fact]
public void Decode_NegativeDuration_Throws()
{
string json = Replace("Duration", -1);
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(RhmFixtureData.CreateArchive(json))
);
}
[Fact]
public void Decode_ExcessiveNoteCount_Throws()
{
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(
RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson),
new RhmReadOptions { MaximumNoteCount = 0 }
)
);
}
[Fact]
public void Decode_NegativeNoteTime_Throws()
{
string json = RhmFixtureData.ValidMapJson.Replace(
"\"Time\":10",
"\"Time\":-1",
StringComparison.Ordinal
);
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(RhmFixtureData.CreateArchive(json))
);
}
[Fact]
public void Decode_NonFiniteNoteCoordinate_Throws()
{
string json = RhmFixtureData.ValidMapJson.Replace(
"\"X\":1",
"\"X\":1e100",
StringComparison.Ordinal
);
Assert.Throws<InvalidRhmFormatException>(() =>
RhmFile.Decode(RhmFixtureData.CreateArchive(json))
);
}
[Fact]
public void Read_UnreadableStream_Throws()
{
using var stream = new UnreadableStream();
Assert.Throws<ArgumentException>(() => RhmFile.Read(stream));
}
[Fact]
public void Write_UnwritableStream_Throws()
{
using var stream = new MemoryStream([], writable: false);
Assert.Throws<ArgumentException>(() =>
RhmFile.Write(stream, RhmFixtureData.CreateMap())
);
}
[Fact]
public void Encode_MissingRequiredMedia_Throws()
{
RhythiaMap map = RhmFixtureData.CreateMap();
map.Audio = null;
Assert.Throws<ArgumentException>(() => RhmFile.Encode(map));
map.Audio = [];
map.Cover = null;
Assert.Throws<ArgumentException>(() => RhmFile.Encode(map));
}
private static string Replace(string propertyName, int value)
{
using JsonDocument document = JsonDocument.Parse(RhmFixtureData.ValidMapJson);
var values = new Dictionary<string, object?>();
foreach (JsonProperty property in document.RootElement.EnumerateObject())
{
values[property.Name] =
property.Name == propertyName ? value : property.Value.Clone();
}
return JsonSerializer.Serialize(values);
}
private sealed class UnreadableStream : MemoryStream
{
public override bool CanRead => false;
}
}
}
+59
View File
@@ -0,0 +1,59 @@
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
namespace RhythiaLib.Tests.Rhm
{
public sealed class RhmFileReadTests
{
[Theory]
[MemberData(nameof(RhmFixtureData.FixturePaths), MemberType = typeof(RhmFixtureData))]
public void Read_GameFixture_ReturnsValidMap(string path)
{
RhythiaMap map = RhmFile.Read(path);
Assert.False(string.IsNullOrWhiteSpace(map.Title));
Assert.InRange(map.Difficulty, 1, 5);
Assert.NotEmpty(map.Notes);
Assert.NotNull(map.Audio);
Assert.NotEmpty(map.Audio);
Assert.NotNull(map.Cover);
Assert.NotEmpty(map.Cover);
for (int index = 0; index < map.Notes.Count; index++)
{
RhythiaNote note = map.Notes[index];
Assert.Equal(index, note.Index);
Assert.True(float.IsFinite(note.X));
Assert.True(float.IsFinite(note.Y));
if (index > 0)
Assert.True(map.Notes[index - 1].TimeMilliseconds <= note.TimeMilliseconds);
}
}
[Fact]
public void Read_KnownFixture_ReturnsKnownMetadata()
{
string path = Path.Combine(AppContext.BaseDirectory, "Rhm", "Fixtures", "quantum.rhm");
RhythiaMap map = RhmFile.Read(path);
Assert.Equal("5860246058480dfb", map.Id);
Assert.Equal("nature", map.Artist);
Assert.Equal("chirp", map.Title);
Assert.Equal(465, map.LengthMilliseconds);
Assert.Equal(1, map.Difficulty);
Assert.Equal(["whip"], map.Mappers);
}
[Fact]
public void Read_LeavesCallerStreamOpen()
{
byte[] data = RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson);
using var stream = new MemoryStream(data);
_ = RhmFile.Read(stream);
Assert.True(stream.CanRead);
}
}
}
+92
View File
@@ -0,0 +1,92 @@
using System.IO.Compression;
using System.Text.Json;
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
namespace RhythiaLib.Tests.Rhm
{
public sealed class RhmFileWriteTests
{
[Fact]
public void Encode_WritesExpectedArchiveLayout()
{
byte[] data = RhmFile.Encode(RhmFixtureData.CreateMap());
using var stream = new MemoryStream(data);
using var archive = new ZipArchive(stream, ZipArchiveMode.Read);
ZipArchiveEntry mapEntry = Assert.Single(
archive.Entries,
entry => entry.FullName == "map"
);
Assert.NotNull(archive.GetEntry("audio.mp3"));
Assert.NotNull(archive.GetEntry("cover.png"));
using Stream mapStream = mapEntry.Open();
using JsonDocument json = JsonDocument.Parse(mapStream);
Assert.Equal("audio.mp3", json.RootElement.GetProperty("AudioFileName").GetString());
Assert.Equal("cover.png", json.RootElement.GetProperty("ImagePath").GetString());
Assert.Equal(
JsonValueKind.Number,
json.RootElement.GetProperty("Difficulty").ValueKind
);
}
[Fact]
public void Encode_ConvertsCoordinatesAndDecodeRestoresThem()
{
RhythiaMap map = RhmFixtureData.CreateMap();
map.Notes =
[
new RhythiaNote
{
TimeMilliseconds = 0,
X = 0,
Y = 0,
},
new RhythiaNote
{
TimeMilliseconds = 1,
X = -1,
Y = 1,
},
new RhythiaNote
{
TimeMilliseconds = 2,
X = 1,
Y = -1,
},
];
byte[] data = RhmFile.Encode(map);
using (var stream = new MemoryStream(data))
using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
using (Stream mapStream = archive.GetEntry("map")!.Open())
using (JsonDocument json = JsonDocument.Parse(mapStream))
{
JsonElement notes = json.RootElement.GetProperty("Notes");
AssertStored(notes[0], 1, 1);
AssertStored(notes[1], 0, 0);
AssertStored(notes[2], 2, 2);
}
RhythiaMap decoded = RhmFile.Decode(data);
Assert.Equal((0f, 0f), (decoded.Notes[0].X, decoded.Notes[0].Y));
Assert.Equal((-1f, 1f), (decoded.Notes[1].X, decoded.Notes[1].Y));
Assert.Equal((1f, -1f), (decoded.Notes[2].X, decoded.Notes[2].Y));
}
[Fact]
public void Write_LeavesCallerStreamOpen()
{
using var stream = new MemoryStream();
RhmFile.Write(stream, RhmFixtureData.CreateMap());
Assert.True(stream.CanWrite);
}
private static void AssertStored(JsonElement note, float x, float y)
{
Assert.Equal(x, note.GetProperty("X").GetSingle());
Assert.Equal(y, note.GetProperty("Y").GetSingle());
}
}
}
+92
View File
@@ -0,0 +1,92 @@
using System.IO.Compression;
using System.Text;
using RhythiaLib.Maps;
namespace RhythiaLib.Tests.Rhm
{
internal static class RhmFixtureData
{
public const string ValidMapJson = """
{"OnlineId":null,"OnlineStatus":null,"LegacyId":"test-id","SongName":"Artist - Song","Mappers":["Mapper"],"Title":"Artist - Song","Duration":1000,"Difficulty":3,"CustomDifficultyName":"Test","StarRating":4.5,"Notes":[{"Time":10,"X":1,"Y":1}],"ImagePath":"cover","AudioFileName":"song.mp3"}
""";
public static TheoryData<string> FixturePaths()
{
var data = new TheoryData<string>();
string directory = Path.Combine(AppContext.BaseDirectory, "Rhm", "Fixtures");
if (!Directory.Exists(directory))
return data;
foreach (
string path in Directory.EnumerateFiles(
directory,
"*.rhm",
SearchOption.AllDirectories
)
)
{
data.Add(path);
}
return data;
}
public static RhythiaMap CreateMap()
{
return new RhythiaMap
{
Id = "test-id",
Artist = "Artist",
Title = "Artist - Song",
Rating = 4.5f,
Mappers = ["Mapper"],
Difficulty = 3,
DifficultyName = "Test",
LengthMilliseconds = 1000,
Notes =
[
new RhythiaNote
{
Index = 0,
TimeMilliseconds = 10,
X = 0,
Y = 0,
},
],
Audio = [1, 2, 3],
AudioExtension = ".mp3",
Cover = [4, 5, 6],
};
}
public static byte[] CreateArchive(
string mapJson,
bool includeMap = true,
bool includeAudio = true,
bool includeCover = true
)
{
using var stream = new MemoryStream();
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
{
if (includeMap)
WriteEntry(archive, "map", Encoding.UTF8.GetBytes(mapJson));
if (includeAudio)
WriteEntry(archive, "audio", [1, 2, 3]);
if (includeCover)
WriteEntry(archive, "cover", [4, 5, 6]);
}
return stream.ToArray();
}
private static void WriteEntry(ZipArchive archive, string name, byte[] data)
{
ZipArchiveEntry entry = archive.CreateEntry(name);
using Stream stream = entry.Open();
stream.Write(data);
}
}
}
+38
View File
@@ -0,0 +1,38 @@
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
namespace RhythiaLib.Tests.Rhm
{
public sealed class RhmRoundTripTests
{
[Theory]
[MemberData(nameof(RhmFixtureData.FixturePaths), MemberType = typeof(RhmFixtureData))]
public void Fixture_LogicalRoundTripPreservesData(string path)
{
RhythiaMap original = RhmFile.Read(path);
RhythiaMap decoded = RhmFile.Decode(RhmFile.Encode(original));
Assert.Equal(original.Id, decoded.Id);
Assert.Equal(original.Artist, decoded.Artist);
Assert.Equal(original.Title, decoded.Title);
Assert.Equal(original.Rating, decoded.Rating);
Assert.Equal(original.Mappers, decoded.Mappers);
Assert.Equal(original.Difficulty, decoded.Difficulty);
Assert.Equal(original.DifficultyName, decoded.DifficultyName);
Assert.Equal(original.LengthMilliseconds, decoded.LengthMilliseconds);
Assert.Equal(original.Audio, decoded.Audio);
Assert.Equal(original.Cover, decoded.Cover);
Assert.Equal(original.Notes.Count, decoded.Notes.Count);
for (int index = 0; index < original.Notes.Count; index++)
{
RhythiaNote expected = original.Notes[index];
RhythiaNote actual = decoded.Notes[index];
Assert.Equal(expected.Index, actual.Index);
Assert.Equal(expected.TimeMilliseconds, actual.TimeMilliseconds);
Assert.Equal(expected.X, actual.X);
Assert.Equal(expected.Y, actual.Y);
}
}
}
}
+3
View File
@@ -25,5 +25,8 @@
<None Update="Rhr\Fixtures\*.rhr"> <None Update="Rhr\Fixtures\*.rhr">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Rhm\Fixtures\**\*.rhm">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
</Project> </Project>
+21
View File
@@ -0,0 +1,21 @@
namespace RhythiaLib.Maps
{
public sealed class RhythiaMap
{
public string Id { get; set; } = string.Empty;
public string Artist { get; set; } = string.Empty;
public string ArtistLink { get; set; } = string.Empty;
public string ArtistPlatform { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public float Rating { get; set; }
public List<string> Mappers { get; set; } = [];
public int Difficulty { get; set; }
public string DifficultyName { get; set; } = string.Empty;
public int LengthMilliseconds { get; set; }
public List<RhythiaNote> Notes { get; set; } = [];
public byte[]? Audio { get; set; }
public string? AudioExtension { get; set; }
public byte[]? Cover { get; set; }
public byte[]? Video { get; set; }
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace RhythiaLib.Maps
{
public sealed class RhythiaNote
{
public int Index { get; set; }
public int TimeMilliseconds { get; set; }
public float X { get; set; }
public float Y { get; set; }
}
}
+147
View File
@@ -0,0 +1,147 @@
using System.IO.Compression;
using RhythiaLib.Maps;
namespace RhythiaLib.Rhm.Internal
{
internal static class RhmArchiveCodec
{
private const string MapEntryName = "map";
private const string DefaultCoverEntryName = "cover.png";
public static RhythiaMap Read(Stream stream, RhmReadOptions options)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(options);
if (!stream.CanRead)
throw new ArgumentException("The stream must be readable.", nameof(stream));
RhmValidation.ValidateReadOptions(options);
try
{
using var archive = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true);
ZipArchiveEntry mapEntry =
archive.GetEntry(MapEntryName)
?? throw new InvalidRhmFormatException(
"The RHM archive is missing its map entry."
);
RhmValidation.ValidateEntrySize(mapEntry, options.MaximumMapSize, "map");
RhmMapDto dto;
using (Stream mapStream = mapEntry.Open())
dto = RhmMapCodec.Read(mapStream);
RhmValidation.ValidateDto(dto, options);
ZipArchiveEntry audioEntry =
archive.GetEntry("audio")
?? (
!string.IsNullOrEmpty(dto.AudioFileName)
? archive.GetEntry(dto.AudioFileName)
: null
)
?? throw new InvalidRhmFormatException(
"The RHM archive is missing its required audio entry."
);
if (string.IsNullOrEmpty(dto.ImagePath))
{
throw new InvalidRhmFormatException(
"The RHM map does not specify its required cover entry."
);
}
ZipArchiveEntry coverEntry =
archive.GetEntry(dto.ImagePath)
?? throw new InvalidRhmFormatException(
$"The RHM archive is missing its required cover entry '{dto.ImagePath}'."
);
byte[] audio = ReadEntry(audioEntry, options.MaximumAudioSize, "audio");
byte[] cover = ReadEntry(coverEntry, options.MaximumCoverSize, "cover");
RhythiaMap map = RhmMapConverter.ToModel(dto);
map.Audio = audio;
map.Cover = cover;
string extension = Path.GetExtension(audioEntry.FullName);
map.AudioExtension = string.IsNullOrEmpty(extension) ? null : extension;
return map;
}
catch (InvalidRhmFormatException)
{
throw;
}
catch (InvalidDataException exception)
{
throw new InvalidRhmFormatException(
"The input is not a valid RHM ZIP archive.",
exception
);
}
}
public static void Write(Stream stream, RhythiaMap map)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(map);
if (!stream.CanWrite)
throw new ArgumentException("The stream must be writable.", nameof(stream));
RhmValidation.ValidateMapForWriting(map);
string audioEntryName = GetAudioEntryName(map.AudioExtension);
const string coverEntryName = DefaultCoverEntryName;
RhmMapDto dto = RhmMapConverter.ToDto(map, audioEntryName, coverEntryName);
using var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true);
ZipArchiveEntry mapEntry = archive.CreateEntry(MapEntryName, CompressionLevel.Optimal);
using (Stream mapStream = mapEntry.Open())
RhmMapCodec.Write(mapStream, dto);
WriteEntry(archive, audioEntryName, map.Audio!);
WriteEntry(archive, coverEntryName, map.Cover!);
}
private static byte[] ReadEntry(ZipArchiveEntry entry, long maximumSize, string kind)
{
RhmValidation.ValidateEntrySize(entry, maximumSize, kind);
using Stream input = entry.Open();
using var output = new MemoryStream((int)entry.Length);
input.CopyTo(output);
return output.ToArray();
}
private static void WriteEntry(ZipArchive archive, string name, byte[] data)
{
ZipArchiveEntry entry = archive.CreateEntry(name, CompressionLevel.Optimal);
using Stream output = entry.Open();
output.Write(data);
}
private static string GetAudioEntryName(string? extension)
{
if (string.IsNullOrWhiteSpace(extension))
return "audio";
string trimmed = extension.Trim();
if (trimmed.IndexOfAny(['/', '\\']) >= 0)
{
throw new ArgumentException(
"The audio extension cannot contain path separators.",
nameof(extension)
);
}
if (trimmed == ".")
return "audio";
return trimmed[0] == '.' ? $"audio{trimmed}" : $"audio.{trimmed}";
}
}
}
+41
View File
@@ -0,0 +1,41 @@
using System.Text.Json;
namespace RhythiaLib.Rhm.Internal
{
internal static class RhmMapCodec
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = false,
WriteIndented = false,
};
public static RhmMapDto Read(Stream stream)
{
ArgumentNullException.ThrowIfNull(stream);
try
{
RhmMapDto? map = JsonSerializer.Deserialize<RhmMapDto>(stream, JsonOptions);
return map
?? throw new InvalidRhmFormatException(
"The RHM map JSON has a null root object."
);
}
catch (JsonException exception)
{
throw new InvalidRhmFormatException(
"The RHM map entry contains malformed JSON.",
exception
);
}
}
public static void Write(Stream stream, RhmMapDto map)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(map);
JsonSerializer.Serialize(stream, map, JsonOptions);
}
}
}
@@ -0,0 +1,91 @@
using RhythiaLib.Maps;
namespace RhythiaLib.Rhm.Internal
{
internal static class RhmMapConverter
{
public static RhythiaMap ToModel(RhmMapDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
string displayTitle = dto.Title ?? string.Empty;
string[] titleParts = displayTitle.Split(" - ", 2, StringSplitOptions.None);
var notes = new List<RhythiaNote>(dto.Notes.Count);
foreach (RhmNoteDto note in dto.Notes)
{
notes.Add(
new RhythiaNote
{
Index = notes.Count,
TimeMilliseconds = note.Time,
X = note.X - 1f,
Y = 1f - note.Y,
}
);
}
notes.Sort(
static (left, right) =>
{
int timeComparison = left.TimeMilliseconds.CompareTo(right.TimeMilliseconds);
return timeComparison != 0 ? timeComparison : left.Index.CompareTo(right.Index);
}
);
for (int index = 0; index < notes.Count; index++)
notes[index].Index = index;
return new RhythiaMap
{
Id = !string.IsNullOrEmpty(dto.LegacyId)
? dto.LegacyId
: dto.OnlineId ?? string.Empty,
Artist = titleParts.Length == 2 ? titleParts[0] : string.Empty,
Title = titleParts.Length == 2 ? titleParts[1] : displayTitle,
Rating = (float)dto.StarRating,
Mappers = [.. dto.Mappers],
Difficulty = dto.Difficulty,
DifficultyName = dto.CustomDifficultyName ?? string.Empty,
LengthMilliseconds = dto.Duration,
Notes = notes,
};
}
public static RhmMapDto ToDto(RhythiaMap map, string audioEntryName, string coverEntryName)
{
ArgumentNullException.ThrowIfNull(map);
string displayTitle = string.IsNullOrWhiteSpace(map.Artist)
? map.Title
: $"{map.Artist} - {map.Title}";
var notes = new List<RhmNoteDto>(map.Notes.Count);
foreach (RhythiaNote note in map.Notes)
{
notes.Add(
new RhmNoteDto
{
Time = note.TimeMilliseconds,
X = note.X + 1f,
Y = 1f - note.Y,
}
);
}
return new RhmMapDto
{
LegacyId = map.Id,
SongName = displayTitle,
Mappers = [.. map.Mappers],
Title = displayTitle,
Duration = map.LengthMilliseconds,
Difficulty = map.Difficulty,
CustomDifficultyName = map.DifficultyName,
StarRating = map.Rating,
Notes = notes,
AudioFileName = audioEntryName,
ImagePath = coverEntryName,
};
}
}
}
+19
View File
@@ -0,0 +1,19 @@
namespace RhythiaLib.Rhm.Internal
{
internal sealed class RhmMapDto
{
public string? OnlineId { get; set; }
public object? OnlineStatus { get; set; }
public string? LegacyId { get; set; }
public string SongName { get; set; } = string.Empty;
public List<string> Mappers { get; set; } = [];
public string Title { get; set; } = string.Empty; // no clue what the difference between this and SongName is
public int Duration { get; set; }
public int Difficulty { get; set; }
public string CustomDifficultyName { get; set; } = string.Empty;
public double StarRating { get; set; }
public List<RhmNoteDto> Notes { get; set; } = [];
public string ImagePath { get; set; } = string.Empty;
public string AudioFileName { get; set; } = string.Empty;
}
}
+9
View File
@@ -0,0 +1,9 @@
namespace RhythiaLib.Rhm.Internal
{
internal sealed class RhmNoteDto
{
public int Time { get; set; }
public float X { get; set; }
public float Y { get; set; }
}
}
+167
View File
@@ -0,0 +1,167 @@
using System.IO.Compression;
using RhythiaLib.Maps;
namespace RhythiaLib.Rhm.Internal
{
internal static class RhmValidation
{
public static void ValidateReadOptions(RhmReadOptions options)
{
ArgumentNullException.ThrowIfNull(options);
if (options.MaximumMapSize < 0)
throw new ArgumentOutOfRangeException(
nameof(options),
"Maximum map size must be nonnegative."
);
if (options.MaximumAudioSize < 0)
throw new ArgumentOutOfRangeException(
nameof(options),
"Maximum audio size must be nonnegative."
);
if (options.MaximumCoverSize < 0)
throw new ArgumentOutOfRangeException(
nameof(options),
"Maximum cover size must be nonnegative."
);
if (options.MaximumNoteCount < 0)
throw new ArgumentOutOfRangeException(
nameof(options),
"Maximum note count must be nonnegative."
);
}
public static void ValidateEntrySize(ZipArchiveEntry entry, long maximumSize, string kind)
{
ArgumentNullException.ThrowIfNull(entry);
if (entry.Length > maximumSize)
{
throw new InvalidRhmFormatException(
$"The RHM {kind} entry size of {entry.Length} bytes exceeds "
+ $"the configured maximum of {maximumSize} bytes."
);
}
if (entry.Length > int.MaxValue)
{
throw new InvalidRhmFormatException(
$"The RHM {kind} entry is too large to load into memory."
);
}
}
public static void ValidateDto(RhmMapDto map, RhmReadOptions options)
{
if (map.Difficulty is < 1 or > 5)
throw new InvalidRhmFormatException(
$"RHM difficulty {map.Difficulty} is outside the supported range 1 through 5."
);
if (map.Duration < 0)
throw new InvalidRhmFormatException("The RHM map duration is negative.");
if (map.Mappers is null)
throw new InvalidRhmFormatException("The RHM mappers collection is null.");
if (map.Notes is null)
throw new InvalidRhmFormatException("The RHM notes collection is null.");
if (map.Notes.Count > options.MaximumNoteCount)
{
throw new InvalidRhmFormatException(
$"The RHM note count of {map.Notes.Count} exceeds "
+ $"the configured maximum of {options.MaximumNoteCount}."
);
}
if (!double.IsFinite(map.StarRating))
throw new InvalidRhmFormatException("The RHM star rating is not finite.");
for (int index = 0; index < map.Notes.Count; index++)
{
RhmNoteDto note =
map.Notes[index]
?? throw new InvalidRhmFormatException($"RHM note {index} is null.");
if (note.Time < 0)
throw new InvalidRhmFormatException($"RHM note {index} has a negative time.");
if (!float.IsFinite(note.X) || !float.IsFinite(note.Y))
{
throw new InvalidRhmFormatException(
$"RHM note {index} contains a non-finite coordinate."
);
}
}
}
public static void ValidateMapForWriting(RhythiaMap map)
{
ArgumentNullException.ThrowIfNull(map);
if (map.Audio is null)
throw new ArgumentException("RHM maps require audio data.", nameof(map));
if (map.Cover is null)
throw new ArgumentException("RHM maps require cover-image data.", nameof(map));
if (map.Difficulty is < 1 or > 5)
{
throw new ArgumentOutOfRangeException(
nameof(map),
map.Difficulty,
"RHM difficulty must be between 1 and 5."
);
}
if (map.Title is null)
throw new ArgumentException("The map title cannot be null.", nameof(map));
if (map.Mappers is null)
throw new ArgumentException(
"The map mappers collection cannot be null.",
nameof(map)
);
if (map.Notes is null)
throw new ArgumentException(
"The map notes collection cannot be null.",
nameof(map)
);
if (!float.IsFinite(map.Rating))
throw new ArgumentException("The map rating must be finite.", nameof(map));
if (map.LengthMilliseconds < 0)
throw new ArgumentOutOfRangeException(
nameof(map),
map.LengthMilliseconds,
"The map length cannot be negative."
);
for (int index = 0; index < map.Notes.Count; index++)
{
RhythiaNote note =
map.Notes[index]
?? throw new ArgumentException($"Map note {index} is null.", nameof(map));
if (note.TimeMilliseconds < 0)
{
throw new ArgumentException(
$"Map note {index} has a negative time.",
nameof(map)
);
}
if (!float.IsFinite(note.X) || !float.IsFinite(note.Y))
{
throw new ArgumentException(
$"Map note {index} contains a non-finite coordinate.",
nameof(map)
);
}
}
}
}
}
@@ -0,0 +1,11 @@
namespace RhythiaLib.Rhm
{
public sealed class InvalidRhmFormatException : Exception
{
public InvalidRhmFormatException(string message)
: base(message) { }
public InvalidRhmFormatException(string message, Exception exception)
: base(message, exception) { }
}
}
+48
View File
@@ -0,0 +1,48 @@
using RhythiaLib.Maps;
using RhythiaLib.Rhm.Internal;
namespace RhythiaLib.Rhm
{
public static class RhmFile
{
public static RhythiaMap Read(string path, RhmReadOptions? options = null)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(path);
using FileStream stream = File.OpenRead(path);
return Read(stream, options);
}
public static RhythiaMap Read(Stream stream, RhmReadOptions? options = null)
{
return RhmArchiveCodec.Read(stream, options ?? new RhmReadOptions());
}
public static void Write(string path, RhythiaMap map)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(path);
using FileStream stream = File.OpenWrite(path);
Write(stream, map);
}
public static void Write(Stream stream, RhythiaMap map)
{
RhmArchiveCodec.Write(stream, map);
}
public static byte[] Encode(RhythiaMap map)
{
using var stream = new MemoryStream();
Write(stream, map);
return stream.ToArray();
}
public static RhythiaMap Decode(ReadOnlySpan<byte> data, RhmReadOptions? options = null)
{
byte[] buffer = data.ToArray();
using var stream = new MemoryStream(buffer, writable: false);
return Read(stream, options);
}
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace RhythiaLib.Rhm
{
public sealed class RhmReadOptions
{
public long MaximumMapSize { get; init; } = 16 * 1024 * 1024; // 16 MB
public long MaximumAudioSize { get; init; } = 128 * 1024 * 1024; // 128 MB
public long MaximumCoverSize { get; init; } = 32 * 1024 * 1024; // 32 MB
public int MaximumNoteCount { get; init; } = 5_000_000;
}
}
+59
View File
@@ -0,0 +1,59 @@
## Basic usage
### Read an RHM file
```csharp
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
RhythiaMap map = RhmFile.Read("map.rhm");
Console.WriteLine($"Artist: {map.Artist}");
Console.WriteLine($"Title: {map.Title}");
Console.WriteLine($"Difficulty: {map.Difficulty}");
Console.WriteLine($"Rating: {map.Rating}");
Console.WriteLine($"Length: {map.LengthMilliseconds}ms");
Console.WriteLine($"Notes: {map.Notes.Count}");
```
### Read from a stream
```csharp
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
using var stream = File.OpenRead("map.rhm");
RhythiaMap map = RhmFile.Read(stream);
```
### Decode from bytes
```csharp
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
byte[] data = File.ReadAllBytes("map.rhm");
RhythiaMap map = RhmFile.Decode(data);
```
### Write an RHM file
```csharp
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
RhythiaMap map = RhmFile.Read("map.rhm");
map.Title = "New Title";
RhmFile.Write("new-map.rhm", map);
```
### Encode to bytes
```csharp
using RhythiaLib.Maps;
using RhythiaLib.Rhm;
RhythiaMap map = RhmFile.Read("map.rhm");
byte[] data = RhmFile.Encode(map);
File.WriteAllBytes("new-map.rhm", data);
```