HN 日本語サマリー

← 一覧へ戻る
プログラミング

ファイルをMinecraftの世界に変換する

Converting Files into Minecraft Worlds (wuemeli.com)

59 pointsby wuemeli18 コメント

要約

この記事では、任意のファイルをMinecraftの世界に変換するプロジェクトについて解説しています。各バイトをMinecraftのブロックにマッピングするパレットを生成し、ファイルの内容を3D空間に配置して.mca形式のリージョンファイルとして保存する仕組みを説明しています。エンコードとデコードのプロセス、およびそのためのコード例も紹介されています。

全文翻訳

ファイルをMinecraftワールドに変換する - パート1

Minecraftの映画をMinecraft内に保存したいと思ったことはありますか?ない?残念、なぜなら今できるからです。

アイデア

最近、ファイルをMinecraftワールドに変換するというくだらないアイデアを思いつきました。これが私を3Dジオメトリ、バイトレイアウト、そしてMinecraftについて多くのことを学ぶ、非常にクールなウサギの穴へと導きました。

中心的なアイデアは非常にシンプルです。任意のファイルを受け取り、それをMinecraftブロックで表示できるようにしたいのです。

その過程で、私はコードに小さなテキストファイルが2.3エクサバイトの大きさであると信じ込ませることもできました。

なぜ

なぜダメなのか。

パレットジェネレーター

最初に必要なのはルックアップテーブルです。1バイトは256個の値(0〜255)のいずれかを持つことができ、幸いなことに、Minecraftには256個以上のブロックがあります。そのため、各バイトに独自のブロックを割り当てることができます。バイト 0 は石になり、バイト 1 は花崗岩になり、255 まで続きます。

多くのブロックは、それ自体で変化したり、配置に依存したりする状態を持ちます。小麦、ニンジン、その他の作物は age を持ち、水や溶岩は level を持ちます。もしバイト 42 が小麦としてデコードされ、その小麦が成長段階を経た場合、私のデコーダーは間違ったバイトを読み込み、ファイル全体が台無しになってしまいます。

まず mcdata_rs を使って1.21.11のブロックデータを取得し、age や level の状態を持つもの(および後述するベッドやチェスト)をすべて除外し、最初の256個のブロックを取って、それをRustファイルに固定配列として書き込みます。

(ビデオの最後で、ブロックが良質なブロックのみにフィルタリングされるプロセスを見ることができます)

コード:

use mcdata_rs::mc_data;
use std::{fs, path::Path};

const NAUGHTY_LIST: &[&str] = &[
    "sand",
    "gravel",
    "anvil",
    "dragon_egg",
    "scaffolding",
    "dripstone",
    "snow",
    "farmland",
    "chest",
    "_bed",
    "door",
    "ice",
    "grass_block",
];

fn main() {
    let data_1_21_11 = mc_data("1.21.11").expect("Failed to download Minecraft Block Data");
    let palette = data_1_21_11
        .blocks_array
        .iter()
        .filter(|b| b.bounding_box.eq("block"))
        .filter(|b| {
            !b.states
                .iter()
                .any(|s| matches!(s.name.as_str(), "age" | "level" | "part"))
        })
        .filter(|b| !NAUGHTY_LIST.iter().any(|g| b.name.contains(g)))
        .collect::<Vec<_>>();

    let names: Vec<&str> = palette.iter().take(256).map(|b| b.name.as_str()).collect();

    let mut out = String::new();
    out.push_str("pub const PALETTE: [&str; 256] = [\n");
    //TODO: make this cleaner
    for name in &names {
        out.push_str("    \"minecraft:");
        out.push_str(name);
        out.push_str("\",\n");
    }
    out.push_str("];\n");

    let out_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/palette.rs");
    fs::write(out_path, out).expect("Failed to write palette");
    println!("Wrote {:?} blocks to palette.rs", names.len());
}

これにより、PALETTE: [&str; 256] が得られ、変換を行う2つの関数は非常にシンプルです。

pub fn byte_to_block(byte: u8) -> &'static str {
    PALETTE[byte as usize]
}
pub fn block_to_byte(block: &str) -> Result<u8, SulfurError> {
    PALETTE
        .iter()
        .position(|palette_block| *palette_block == block)
        .map(|i| {
            u8::try_from(i).expect("palette has exactly 256 entries so this will never happen")
        })
        .ok_or(SulfurError::BlockNotInPalette(block.to_string()))
}

byte_to_block は単なる配列インデックスであり、block_to_byte は逆引きです。

実装

バイトがブロックにマッピングされたので、各ブロックがどこに配置されるかを決定する必要があります。

まず16x16の床を埋め、次に1ブロック上に移動し、16x16x16の立方体が完全に埋まったら、次の立方体にジャンプします。この16x16x16の立方体はセクションと呼ばれ、4096ブロックです。

しかし、1つのセクションは始まりにすぎません。MinecraftワールドはY -64 からY 320 まであり、これは384ブロック、つまり24個のセクションが積み重なったものです。そのため、1つのセクションで停止するのではなく、次のチャンクに横移動する前に、底から上まで、すべての24セクションのチャンク列を埋めます。

リージョンファイル(.mca)は32x32のチャンクグリッドなので、すべてを掛け合わせると:

32 x 32 チャンク x 24 セクション x 4096 ブロック = リージョンあたり約96 MiB

pub fn cube_coords(byte_location: usize) -> silverfish::Coords {
    const SECTION_SIZE: usize = 16;
    const BLOCKS_PER_SECTION: usize = SECTION_SIZE * SECTION_SIZE * SECTION_SIZE;
    const MAX_CHUNKS: usize = 32;
    const SECTIONS_PER_COLUMN: usize = 24;
    const MIN_Y: i32 = -64;

    let inside_section = byte_location % BLOCKS_PER_SECTION;
    let section_number = byte_location / BLOCKS_PER_SECTION;

    let x_inside = inside_section % SECTION_SIZE;
    let y_inside = inside_section / (SECTION_SIZE * SECTION_SIZE);
    let z_inside = (inside_section / SECTION_SIZE) % SECTION_SIZE;

    let layer = section_number / SECTIONS_PER_COLUMN;
    let section_x = layer % MAX_CHUNKS;
    let section_y = section_number % SECTIONS_PER_COLUMN;
    let section_z = (layer / MAX_CHUNKS) % MAX_CHUNKS;

    let x = u32::try_from(section_x * SECTION_SIZE + x_inside).expect("coordinate overflow");
    let y =
        MIN_Y + i32::try_from(section_y * SECTION_SIZE + y_inside).expect("coordinate overflow");
    let z = u32::try_from(section_z * SECTION_SIZE + z_inside).expect("coordinate overflow");

    (x, y, z).into()
}

おそらくテストの方が分かりやすいでしょう。

  • バイト 0 → (0, -64, 0) - ワールドの最下部
  • バイト 1 → (1, -64, 0)
  • バイト 15 → (15, -64, 0) - 最初の行の終わり
  • バイト 16 → (0, -64, 1) - 次の行の後ろ
  • バイト 255 → (15, -64, 15) - 床が満杯
  • バイト 256 → (0, -63, 0) - 上に1つ
  • バイト 4095 → (15, -49, 15) - セクションが満杯
  • バイト 4096 → (0, -48, 0) - 次のセクション上、同じチャンク列内
  • バイト 4096 * 24 → (16, -64, 0) - チャンク列全体が満杯(24セクション)、1チャンク横に移動
  • バイト 4096 * 24 * 32 → (0, -64, 16) - チャンクのその行が満杯、Zでラップ

最終的な結果は以下のようになります。

[画像: エンコードされたデータ; 正確には私のCargo.lock]

エンコーディング

ファイルを読み込み、空のリージョンを作成し、小さなヘッダー(詳細は後述)を書き込み、次に各バイトをウォークし、ブロックに変換し、その cube_coords に配置します。その後、.mca リージョンファイルに書き込みます。

pub fn file_to_region(
    source_file: impl AsRef<Path>,
    region_file: impl AsRef<Path>,
) -> Result<(), SulfurError> {
    let source_file = source_file.as_ref();
    let region_file = region_file.as_ref();

    if !source_file.exists() {
        return Err(SulfurError::InputFileNotFound);
    }

    let input_file = std::fs::read(source_file)?;

    if HEADER_SIZE + input_file.len() > REGION_CAPACITY {
        return Err(SulfurError::EncodedPayloadTooLarge);
    }

    let mut region = Region::default();
    region.set_config(Config::new(true, true, Config::DEFAULT_WORLD_HEIGHT))?;

    let header = Header::new(input_file.len() as u64).to_bytes();

    for (location, byte) in header.iter().enumerate() {
        region.set_block(cube_coords(location), byte_to_block(*byte))?;
    }

    for (byte_location, byte) in input_file.iter().enumerate() {
        region.set_block(
            cube_coords(header.len() + byte_location),
            byte_to_block(*byte),
        )?;
    }

    region.write_blocks()?;
    region.write(&mut std::fs::File::create(region_file)?)?;

    Ok(())
}

デコーディング

リージョンをロードし、ヘッダーブロックをバイトに戻して元のファイルのサイズを調べ、次に正確にその数のペイロードブロックを読み込み、各ブロックを block_to_byte で処理し、バイトをディスクにストリームし直します。

pub fn region_to_file(
    region_file: impl AsRef<Path>,
    output_file: impl AsRef<Path>,
) -> Result<(), SulfurError> {
    let region_file = region_file.as_ref();
    let output_file = output_file.as_ref();

    if !region_file.exists() {
        return Err(SulfurError::InputFileNotFound);
    }

    let region = Region::from_region(&mut std::fs::File::open(region_file)?, (0, 0))?;

    let header_coords: Vec<Coords> = (0..HEADER_SIZE).map(cube_coords).collect();
    let header_batch = region.get_blocks(&header_coords)?;

    let raw_header_bytes = header_coords
        .iter()
        .map(|coord| {
            let block = header_batch
                .get(*coord)?
                .ok_or(SulfurError::MissingBlockAt(*coord))?;
            block_to_byte(&block.name.to_str())
        })
        .collect::<Result<Vec<u8>, _>>()?;

    let (header, header_len) = Header::from_bytes(&raw_header_bytes)?;

    let file_size =
        usize::try_from(header.file_size).map_err(|_| SulfurError::EncodedPayloadTooLarge)?;

    let end =
        header_len
            .checked_add(file_size)
            .ok_or(SulfurError::EncodedPayloadTooLarge)?;

    let coords: Vec<Coords> = (header_len..end).map(cube_coords).collect();

    let batch = region.get_blocks(&coords)?;

    let mut file_buffer = std::io::BufWriter::new(std::fs::File::create(output_file)?);

    for coord in &coords {
        let block = batch
            .get(*coord)?
            .ok_or(SulfurError::MissingBlockAt(*coord))?;
        file_buffer.write_all(&[block_to_byte(&block.name.to_str())?])?;
    }

    file_buffer.flush()?;

    Ok(())
}

私が犯した間違い

フラットスラブ

私の cube_coords の最初のバージョンは機能しましたが、ワールドの大部分を捨てていました。Y 0 から始まる単一の16ブロック高のレイヤーにのみブロックを配置し、セクションを水平方向に広げていました。

pub fn cube_coords(byte_location: usize) -> silverfish::Coords {
    const SECTION_SIZE: usize = 16;
    const BLOCKS_PER_SECTION: usize = SECTION_SIZE * SECTION_SIZE * SECTION_SIZE;
    const BASE_Y: usize = 0;
    const MAX_BLOCKS: usize = 32;
    let inside_section = byte_location % BLOCKS_PER_SECTION;
    let section_number = byte_location / BLOCKS_PER_SECTION;
    let x_inside = inside_section % SECTION_SIZE;
    let y_inside = inside_section / (SECTION_SIZE * SECTION_SIZE);
    let z_inside = (inside_section / SECTION_SIZE) % SECTION_SIZE;
    let section_x = section_number % MAX_BLOCKS;
    let section_z = (section_number / MAX_BLOCKS) % MAX_BLOCKS;
    let x = u32::try_from(section_x * SECTION_SIZE + x_inside).expect("coordinate overflow");
    let y = i32::try_from(BASE_Y + y_inside).expect("coordinate overflow");
    let z = u32::try_from(section_z * SECTION_SIZE + z_inside).expect("coordinate overflow");
    (x, y, z).into()
}

y が15を超えることがなかったため、すべてのワールドは高さ16ブロックのフラットな512x512スラブとして出力されました。これはリージョンあたり約4 MiBですが、リージョンは最大約96 MiBを保持できます。

容量オーバーフロー

あの2.3エクサバイトを覚えていますか?

問題は、.mca ファイルの最初の8バイトを読み取り、それをファイルサイズとして使用しようとしたことでした。これにより、2338328528344327162 という値が得られ、それを喜んで長さとして扱おうとしました…2.3エクサバイト。

問題は、生のリージョンファイルには独自のフォーマットと独自のヘッダーがあるため、最初に取得していたバイトは決して私たちのデータではなかったということです。

修正はヘッダーを使用することでした。

const MAGIC: [u8; 4] = *b"SULF";
// magic + size
pub const HEADER_SIZE: usize = 12;
pub struct Header {
    pub file_size: u64,
}
impl Header {
    pub fn new(file_size: u64) -> Self {
        Self { file_size }
    }
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        bytes.extend(&MAGIC);
        bytes.extend(&self.file_size.to_le_bytes());
        bytes
    }
    pub fn from_bytes(bytes: &[u8]) -> Result<(Self, usize), SulfurError> {
        if bytes.len() < HEADER_SIZE {
            return Err(SulfurError::InvalidHeaderSize(HEADER_SIZE, bytes.len()));
        }
        if bytes[0..4] != MAGIC {
            return Err(SulfurError::InvalidMagicBytes);
        }
        let size_bytes = bytes[MAGIC.len()..HEADER_SIZE]
            .try_into()
            .map_err(|_| SulfurError::InvalidHeaderSize(HEADER_SIZE, bytes.len()))?;
        let file_size = u64::from_le_bytes(size_bytes);
        Ok((Self::new(file_size), HEADER_SIZE))
    }
}
見えないブロック

ベッドとダブルチェストが見えませんでした。どちらも「マルチブロック」です。ベッドは頭と足、ダブルチェストは2つの半分です。デコーダーは壊れませんでしたが、見た目が非常に悪かったです。 NAUGHTY_LIST 配列に追加しました。

仕上げ

Jebは本当にすごかった。(彼はAnvil File Formatを書いた)

そしてはい、Minecraftの映画は(ひどくダウンサンプリングされて)収まります。

将来的には、クリーパー/TNT保護のようなものを追加し、大きなマルチリージョンワールドを出力できるようにして、どんなに大きなファイルでもエンコードできるようにする予定です。

このようなブログ記事を書くのは初めてです。改善点があれば、私にメールを送ってください。

自分で試してみたい方は、リポジトリはこちらです。

https://codeberg.org/wuemeli/sulfur (スターを忘れないでください :)