using System.Collections.Generic; using System.IO; using Data; using UnityEngine; namespace Managers { public class PackagesImageManager : Utils.Singleton { public Dictionary> packagesImages = new(); public Dictionary> sprites = new(); public void Init() { if (packagesImages.Count > 0) return; var imageDef = Managers.DefineManager.Instance.QueryDefinesByType(); foreach (var ima in imageDef) { if (ima.path == null || ima.packID == null) continue; var pack = Managers.DefineManager.Instance.GetDefinePackage(ima); var path = Path.Combine(pack.packRootPath, ima.path); var texture = Configs.ConfigProcessor.LoadTextureByIO(path); if (texture == null) continue; var packId = ima.packID; if (!packagesImages.ContainsKey(packId)) packagesImages[packId] = new Dictionary(); packagesImages[packId].Add(ima.name, texture); SplitTextureIntoSprites(packId, ima.name, texture, ima.hCount, ima.wCount, ima.pixelsPerUnit); } } private void SplitTextureIntoSprites( string packId, string baseName, Texture2D texture, int rows, int cols, int pixelsPerUnit) { if (texture == null || rows <= 0 || cols <= 0) { Debug.LogError("Invalid parameters for splitting texture."); return; } var textureWidth = texture.width; var textureHeight = texture.height; var tileWidth = textureWidth / cols; var tileHeight = textureHeight / rows; if (tileWidth * cols != textureWidth || tileHeight * rows != textureHeight) { Debug.LogError("Texture dimensions are not divisible by the specified rows and columns."); return; } if (!sprites.ContainsKey(packId)) sprites[packId] = new Dictionary(); for (var row = 0; row < rows; row++) { for (var col = 0; col < cols; col++) { Rect spriteRect = new(col * tileWidth, row * tileHeight, tileWidth, tileHeight); var sprite = Sprite.Create(texture, spriteRect, new Vector2(0.5f, 0.5f), pixelsPerUnit); var index = (rows - row - 1) * cols + col; var spriteName = $"{baseName}_{index}"; sprites[packId][spriteName] = sprite; } } } public void Reload() { packagesImages.Clear(); sprites.Clear(); Init(); } public Sprite GetSprite(string packID, string name) { if (string.IsNullOrEmpty(packID)) { foreach (var kvp in sprites) { if (kvp.Value.TryGetValue(name, out var sprite)) return sprite; } } else { if (!sprites.TryGetValue(packID, out var dict)) return null; dict.TryGetValue(name, out var sprite); return sprite; } return null; } public Sprite GetSprite(string packID, string name, int index) { var fullName = $"{name}_{index}"; return GetSprite(packID, fullName); } } }