Skip to content

Commit

Permalink
fix(lib): write small lumps compressed, even if lzma header increases…
Browse files Browse the repository at this point in the history
… size

Fix for #74.
Closes #74

We were writing out lumps < 22 bytes large as uncompressed since the
LZMA header actually causes the lump to get larger. That causes the BSP
to fail our compression checks in the website repo.

`bspzip` doesn't seem to have our optimization, and it's such an
insignificant amount of data anyway, no problem always writing the header.
  • Loading branch information
tsa96 committed Jan 29, 2025
1 parent 1acd499 commit 02f62d5
Showing 1 changed file with 11 additions and 34 deletions.
45 changes: 11 additions & 34 deletions src/Lumper.Lib/BSP/IO/LumpWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ private LumpHeaderInfo WriteCompressed(Lump lump)
lump.Write(uncompressedStream, Handler);
long uncompressedLength = uncompressedStream.Length;

long compressedLength;
uncompressedStream.Seek(0, SeekOrigin.Begin);

using var mem = new MemoryStream();
Expand All @@ -122,42 +121,20 @@ private LumpHeaderInfo WriteCompressed(Lump lump)
lzmaStream.Dispose();

mem.Seek(0, SeekOrigin.Begin);
long compressedLength = mem.Length;

if (uncompressedLength == 0 || mem.Length > uncompressedLength)
{
// No point compressing empty lumps, also LZMA header takes up 22
// bytes so useless for very small lumps.
if (uncompressedLength > 0)
{
Logger.Debug(
"Compressed lump larger than uncompressed, skipping. "
+ $"(compressed: {mem.Length}, uncompressed: {uncompressedLength})"
);
}
var writer = new BinaryWriter(mem);
const int lzmaId = ('A' << 24) | ('M' << 16) | ('Z' << 8) | 'L';
writer.Write(lzmaId);
writer.Write((int)uncompressedStream.Length);
writer.Write((int)mem.Length - headerSize);
writer.Write(lzmaStream.Properties);

uncompressedStream.Seek(0, SeekOrigin.Begin);
uncompressedStream.CopyTo(BaseStream);
if (writer.BaseStream.Position != headerSize)
throw new InvalidDataException("Failed to compress stream: bad LZMA header");

compressedLength = -1;
}
else
{
mem.Seek(0, SeekOrigin.Begin);
compressedLength = mem.Length;

var writer = new BinaryWriter(mem);
const int lzmaId = ('A' << 24) | ('M' << 16) | ('Z' << 8) | 'L';
writer.Write(lzmaId);
writer.Write((int)uncompressedStream.Length);
writer.Write((int)mem.Length - headerSize);
writer.Write(lzmaStream.Properties);

if (writer.BaseStream.Position != headerSize)
throw new InvalidDataException("Failed to compress stream: bad LZMA header");

mem.Seek(0, SeekOrigin.Begin);
mem.CopyTo(BaseStream);
}
mem.Seek(0, SeekOrigin.Begin);
mem.CopyTo(BaseStream);

return new LumpHeaderInfo
{
Expand Down

0 comments on commit 02f62d5

Please sign in to comment.