AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-9107398

Koray Üstündağ's questions

Martin Hope
Koray Üstündağ
Asked: 2025-04-14 20:39:42 +0800 CST

Lendo dados incorretos com C# (arquivo PAK personalizado)

  • 5

Estou tentando escrever meu próprio motor de jogo. Empacotei os arquivos, como os recursos dos jogos, para que o motor pudesse lê-los com mais rapidez e facilidade. No entanto, encontrei um problema. Não consegui encontrar a origem do problema. Quando tento ler os dados do arquivo PAK que criei, há um desvio nos dados lidos. Não consigo ler os dados corretamente.

Estrutura do arquivo:

[Header]
[Index Table]
[Asset Data]

Códigos:

namespace EngineCore
{
    public class PakEntry
    {
        public string Name { get; set; }
        public byte Type { get; set; }
        public uint Offset { get; set; }
        public uint Size { get; set; }
    }
}
namespace EngineCore
{
    public interface IPakReaderBackend
    {
        byte[] Read(PakEntry entry);
        void Dispose();
    }
}
using System;
using System.IO;
using System.IO.MemoryMappedFiles;

namespace EngineCore
{
    public class MemoryMappedBackend : IPakReaderBackend, IDisposable
    {
        private readonly MemoryMappedFile mmf;
        private MemoryMappedViewAccessor accessor;

        public MemoryMappedBackend(string path)
        {
            mmf = MemoryMappedFile.CreateFromFile(path, FileMode.Open);
        }

        public byte[] Read(PakEntry entry)
        {
            using var accessor = mmf.CreateViewAccessor(entry.Offset, entry.Size, MemoryMappedFileAccess.Read);
            byte[] buffer = new byte[entry.Size];
            accessor.ReadArray(0, buffer, 0, buffer.Length);
            return buffer;
        }

        public void Dispose()
        {
            accessor?.Dispose();
            mmf?.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
using System.IO;

namespace EngineCore
{
    public class SeekAndReadBackend : IPakReaderBackend
    {
        private readonly string pakFilePath;

        public SeekAndReadBackend(string path)
        {
            pakFilePath = path;
        }

        public byte[] Read(PakEntry entry)
        {
            byte[] buffer = new byte[entry.Size];
            using (FileStream fs = new FileStream(pakFilePath, FileMode.Open, FileAccess.Read))
            {
                fs.Seek(entry.Offset, SeekOrigin.Current);
                fs.Read(buffer, 0, buffer.Length);
            }
            return buffer;
        }

        public void Dispose() { }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace EngineCore
{
    public class PakWriter : IDisposable
    {
        private const string Magic = "TGPAK";
        private const ushort Version = 1;
        private readonly List<PakEntry> entries;
        private readonly MemoryStream dataStream;

        public PakWriter()
        {
            entries = new List<PakEntry>();
            dataStream = new MemoryStream();
        }

        public void AddFile(string filePath, byte type)
        {
            byte[] fileData = File.ReadAllBytes(filePath);
            uint offset = (uint)dataStream.Position;


            dataStream.Write(fileData, 0, fileData.Length);

            entries.Add(new PakEntry
            {
                Name = Path.GetFileName(filePath),
                Type = type,
                Offset = offset,
                Size = (uint)fileData.Length
            });
        }

        public void Save(string outputPath)
        {
            using (FileStream fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    bw.Write(Encoding.ASCII.GetBytes(Magic.PadRight(6, '\0')));
                    bw.Write(Version);
                    bw.Write((uint)entries.Count);
                    long indexOffsetPos = fs.Position;
                    bw.Write((uint)0);

                    dataStream.Seek(0, SeekOrigin.Begin);
                    dataStream.CopyTo(fs);

                    long indexOffset = fs.Position;

                    foreach (var entry in entries)
                    {
                        byte[] nameBytes = Encoding.UTF8.GetBytes(entry.Name);
                        bw.Write((byte)nameBytes.Length);
                        bw.Write(nameBytes);
                        bw.Write(entry.Type);
                        bw.Write(entry.Offset);
                        bw.Write(entry.Size);
                    }

                    fs.Seek(indexOffsetPos, SeekOrigin.Begin);
                    bw.Write((uint)indexOffset);
                }
            }
        }

        public void Dispose()
        {
            entries.Clear();
            dataStream?.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace EngineCore
{
    public class PakReader : IDisposable
    {
        public List<PakEntry> Entries { get; private set; } = new List<PakEntry>();
        private readonly IPakReaderBackend backend;

        public PakReader(string filePath, bool useMemoryMapping = false)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader br = new BinaryReader(fs))
                {
                    string magic = Encoding.ASCII.GetString(br.ReadBytes(6)).TrimEnd('\0');
                    if (magic != "TGPAK") throw new Exception("Invalid pak");

                    ushort version = br.ReadUInt16();
                    uint entryCount = br.ReadUInt32();
                    uint indexOffset = br.ReadUInt32();

                    fs.Seek(indexOffset, SeekOrigin.Begin);
                    for (int i = 0; i < entryCount; i++)
                    {
                        byte nameLen = br.ReadByte();
                        string name = Encoding.UTF8.GetString(br.ReadBytes(nameLen));
                        byte type = br.ReadByte();
                        uint offset = br.ReadUInt32();
                        uint size = br.ReadUInt32();

                        Entries.Add(new PakEntry
                        {
                            Name = name,
                            Type = type,
                            Offset = offset,
                            Size = size
                        });
                    }
                }
            }
            backend = useMemoryMapping ? new MemoryMappedBackend(filePath) : new SeekAndReadBackend(filePath);
        }

        public byte[] Read(string name)
        {
            PakEntry entry = Entries.FirstOrDefault(e => e.Name == name);
            if (entry == null)
            {
                return null;
            }
            return backend.Read(entry);
        }

        public void Dispose()
        {
            backend.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}

Teste

// Write
PakWriter pakW = new PakWriter();
pakW.AddFile("Assets/Test1.txt", 7);
pakW.AddFile("Assets/Test2.txt", 7);
pakW.AddFile("Assets/Player.fbx", 3);
pakW.AddFile("Assets/Wall.res", 5);
pakW.Save("Bin/data.pak");
pakW.Dispose();

// Read
PakReader pakR = new PakReader("Bin/data.pak");
Console.WriteLine("Assets:");
foreach (PakEntry entry in pakR.Entries)
{
    Console.WriteLine($" - {entry.Name} (Type: {entry.Type}, Size: {entry.Size} bytes)");
}
byte[] data = pakR.Read("Test2.txt");
Console.WriteLine("Test2:" + Encoding.UTF8.GetString(data));
Console.ReadLine();
pakR.Dispose();

Saída:

Assets:
 - Test1.txt (Type: 7, Size: 20 bytes)
 - Test2.txt (Type: 7, Size: 20 bytes)
 - Player.fbx (Type: 3, Size: 759512 bytes)
 - Wall.res (Type: 5, Size: 13544 bytes)
Test2:AAAAAAAAAAAAAAAABBBB
c#
  • 1 respostas
  • 50 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve