Archived
Private
Public Access
1
0
This repository has been archived on 2026-02-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
ProjectBackup/Unity/Minecraft/Assets/Editor/AtlasPacker.cs
2022-11-12 13:10:03 +01:00

99 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Editor {
public class AtlasPacker : EditorWindow {
private int _blockSize = 16;
private int _atlasSizeInBlocks = 16;
private int _atlasSize;
private Object[] _rawTextures = new Object[256];
private List<Texture2D> _sortedTextures = new List<Texture2D>();
private Texture2D _atlas;
[MenuItem("Minecraft/Atlas Packer")]
private static void ShowWindow() {
var window = GetWindow<AtlasPacker>();
window.titleContent = new GUIContent("Atlas Packer");
window.Show();
}
private void OnGUI() {
_atlasSize = _blockSize * _atlasSizeInBlocks;
GUILayout.Label("Minecraft Atlas Packer", EditorStyles.boldLabel);
_blockSize = EditorGUILayout.IntField("Block Size", _blockSize);
_atlasSizeInBlocks = EditorGUILayout.IntField("Atlas Size in Blocks", _atlasSizeInBlocks);
GUILayout.Label(_atlas);
if (GUILayout.Button("Load Textures")) {
LoadTextures();
PackAtlas();
Debug.Log("[Atlas Packer] Loaded " + _sortedTextures.Count + " textures.");
}
if (GUILayout.Button("Clear Textures")) {
_atlas = new Texture2D(_atlasSize, _atlasSize);
Debug.Log("[AtlasPacker] Cleared textures");
}
if (GUILayout.Button("Save Atlas")) {
byte[] bytes = _atlas.EncodeToPNG();
try {
File.WriteAllBytes(Application.dataPath + "/Textures/PackedAtlas.png", bytes);
} catch {
Debug.LogError("[AtlasPacker] Failed to save atlas");
}
}
}
private void LoadTextures() {
_sortedTextures.Clear();
_rawTextures = Resources.LoadAll("AtlasPacker", typeof(Texture2D));
int index = 0;
foreach (var texture in _rawTextures) {
Texture2D t = (Texture2D) texture;
if (t.width != _blockSize || t.height != _blockSize) {
continue;
}
_sortedTextures.Add(t);
index++;
}
}
private void PackAtlas() {
_atlas = new Texture2D(_atlasSize, _atlasSize);
Color[] pixels = new Color[_atlasSize * _atlasSize];
for (int x = 0; x < _atlasSize; x++) {
for (int y = 0; y < _atlasSize; y++) {
int currentBlockX = x / _blockSize;
int currentBlockY = y / _blockSize;
int index = currentBlockY * _atlasSizeInBlocks + currentBlockX;
if (index >= _sortedTextures.Count) {
pixels[(_atlasSize - y - 1) * _atlasSize + x] = Color.clear;
continue;
}
Texture2D texture = _sortedTextures[index];
pixels[(_atlasSize - y - 1) * _atlasSize + x] = texture.GetPixel(x, _blockSize - y - 1);
}
}
_atlas.SetPixels(pixels);
_atlas.Apply();
}
}
}