using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System;
using PimDeWitte.UnityMainThreadDispatcher;
using System.Collections;
public class BlockFetcher : MonoBehaviour
{
private string serverUrl = "http://localhost:8000/blocks";
public string texturePath = "Assets/Textures";
public Material blockMaterial;
public string defaultTextureName = "missing_texture";
private const int MAX_VERTICES_PER_CHUNK = 65000;
private List meshChunks = new();
public string[] woodTypes;
public Mesh slabMesh, fenceMesh, stairMesh;
private class MeshChunk
{
public List vertices = new(MAX_VERTICES_PER_CHUNK);
public List triangles = new();
public List uvs = new();
public bool isFull => vertices.Count + 4 >= MAX_VERTICES_PER_CHUNK;
}
[Serializable]
public class BlockTextureConfig
{
public string blockName, top, bottom, front, back, left, right, side;
public bool isBillboard;
public Mesh customMesh;
public void SetDefaults(string defaultName)
{
top ??= defaultName;
bottom ??= defaultName;
if (!string.IsNullOrEmpty(side))
front = back = left = right = side;
else
{
front ??= defaultName;
back ??= defaultName;
left ??= defaultName;
right ??= defaultName;
}
}
}
[Serializable]
public class BlockTintConfig
{
public string blockName;
public Color tintColor;
public string maskName;
public BlockTintConfig(string blockName, Color tintColor, string maskName = null)
{
this.blockName = blockName;
this.tintColor = tintColor;
this.maskName = maskName;
}
}
public BlockTextureConfig[] blockConfigs;
public BlockTintConfig[] blockTintConfigs;
// Process blocks on the main thread using a coroutine
UnityMainThreadDispatcher.Instance().Enqueue(() => StartCoroutine(ProcessBlocksCoroutine(blockDataList)));
}
private async Task GetBlocksDataAsync()
{
using UnityWebRequest webRequest = UnityWebRequest.Get(serverUrl);
var asyncOp = webRequest.SendWebRequest();
private IEnumerator ProcessBlocksCoroutine(List blockDataList)
{
int batchSize = 1000; // Adjust as needed
int totalBlocks = blockDataList.Count;
int processedBlocks = 0;
while (processedBlocks < totalBlocks)
{
int blocksToProcess = Mathf.Min(batchSize, totalBlocks - processedBlocks);
for (int i = 0; i < blocksToProcess; i++)
{
AddBlockFaces(blockDataList[processedBlocks + i]);
}
processedBlocks += blocksToProcess;
// Optional: Update a progress indicator here
yield return null; // Wait for the next frame
}
CreateMesh();
}
private void AddBlockFaces(BlockData block)
{
Vector3 blockPosition = new(block.x, block.y, block.z);
if (!blockConfigMap.TryGetValue(block.block_name, out var config))
{
config = new BlockTextureConfig { blockName = block.block_name };
config.SetDefaults(block.block_name); // Use block's own name
}
var customMeshes = new Dictionary<string, Mesh>
{
{ "_slab", slabMesh },
{ "_fence", fenceMesh },
{ "_stairs", stairMesh }
};
Mesh selectedMesh = config.customMesh;
string replace = null, add = null;
if (selectedMesh == null)
{
foreach (var kvp in customMeshes)
{
if (config.blockName.Contains(kvp.Key))
{
selectedMesh = kvp.Value;
replace = kvp.Key;
if (woodTypes.Any(w => config.front.Contains(w)))
add = "_planks";
break;
}
}
}
if (selectedMesh != null)
AddCustomMeshToChunk(blockPosition, selectedMesh, config.front, replace, add);
else if (config.isBillboard)
AddBillboardFacesToChunk(blockPosition, config);
else
AddDefaultCubeFacesToChunk(blockPosition, config);
private int GetTextureIndexForTextureName(string textureName)
{
if (string.IsNullOrEmpty(textureName))
return defaultTextureIndex;
return blockNameToTextureIndex.TryGetValue(textureName, out int index) ? index : defaultTextureIndex;
}
private Vector2[] GetUVsForTexture(string textureName)
{
int textureIndex = GetTextureIndexForTextureName(textureName);
if (textureIndex >= atlasRects.Length || textureIndex < 0)
{
Debug.LogWarning($"Invalid texture index: {textureIndex} for texture: {textureName}. Using default texture.");
textureIndex = defaultTextureIndex;
}
if (!uvCache.TryGetValue(textureIndex, out Vector2[] uvs))
{
Rect uvRect = atlasRects[textureIndex];
uvs = new[]
{
new Vector2(uvRect.xMin, uvRect.yMin),
new Vector2(uvRect.xMax, uvRect.yMin),
new Vector2(uvRect.xMax, uvRect.yMax),
new Vector2(uvRect.xMin, uvRect.yMax)
};
uvCache[textureIndex] = uvs;
}
return uvs;
To overhaul your code by removing special block arrays and fetching textures and custom block models from the provided GitHub repository, you can follow these steps:
Remove Local Texture and Model Dependencies:
Eliminate any code that loads textures or models from local files.
Remove references to local directories such as texturePath.
Fetch JSON Data from GitHub:
Retrieve the blocks_textures.json and blocks_models.json files from the GitHub repository.
Use UnityWebRequest to asynchronously fetch these JSON files.
Parse the JSON Data:
Create C# classes that represent the structure of the JSON data.
public class BlockTextureMapping
{
public Dictionary<string, string[]> textures;
}
public class BlockModelMapping
{
public Dictionary<string, ModelData> models;
}
public class ModelData
{
public Element[] elements;
// Additional fields as per JSON structure
}
public class Element
{
public float[] from;
public float[] to;
public Face faces;
// Additional fields as per JSON structure
}
public class Face
{
public Dictionary<string, FaceData> faceData;
}
public class FaceData
{
public string texture;
public int[] uv;
// Additional fields as per JSON structure
}
Use a JSON library like Newtonsoft.Json to deserialize the JSON content into these classes.
Fetch Textures from GitHub:
Base URL for textures: https://raw.githubusercontent.com/PrismarineJS/minecraft-assets/master/data/1.20.2/blocks/
For each texture name obtained from the texture mappings, download the texture image.
string textureUrl = $"{baseTextureUrl}{textureName}.png";
UnityWebRequest textureRequest = UnityWebRequestTexture.GetTexture(textureUrl);
yield return textureRequest.SendWebRequest();
if (textureRequest.result == UnityWebRequest.Result.Success)
{
Texture2D texture = DownloadHandlerTexture.GetContent(textureRequest);
// Store or use the texture as needed
}
Ensure you handle cases where a texture might not be available.
Create Texture Atlas Dynamically:
Collect all downloaded Texture2D objects.
Use Texture2D.PackTextures to create a texture atlas.
For each block, use its model data to construct the mesh.
Use the from and to coordinates to create vertices.
Use face data to assign UVs and textures.
Example of creating a cube face:
Vector3[] vertices = new Vector3[4];
// Assign vertex positions based on 'from' and 'to' coordinates
int[] triangles = new int[] {0, 1, 2, 2, 3, 0};
Vector2[] uvs = new Vector2[4];
// Assign UVs based on texture mapping
Handle special cases for complex models (e.g., stairs, slabs) as per the model data.
Update Block Rendering Logic:
Replace hardcoded block configurations with data fetched from the JSON files.
When rendering each block:
Determine the block's model and textures from the mappings.
Use the model data to construct the mesh dynamically.
Assign the correct UVs based on the texture atlas.
Optimize Asset Loading:
Implement caching mechanisms to store downloaded textures and models during runtime.
Avoid re-downloading assets that have already been fetched.
Handle Asynchronous Operations:
Ensure that all network operations are asynchronous to prevent freezing the main thread.
Use async/await patterns or coroutines.
Be cautious when updating Unity objects from asynchronous callbacks; use UnityMainThreadDispatcher or similar methods to run code on the main thread.
Error Handling and Fallbacks:
Implement robust error handling for network failures.
Provide fallback textures or models if assets cannot be fetched.
// Fetch model mappings
string modelsJsonUrl = "https://raw.githubusercontent.com/PrismarineJS/minecraft-assets/master/data/1.20.2/blocks_models.json";
UnityWebRequest modelsRequest = UnityWebRequest.Get(modelsJsonUrl);
await modelsRequest.SendWebRequest();
var modelsJson = modelsRequest.downloadHandler.text;
var blockModels = JsonConvert.DeserializeObject<Dictionary<string, ModelData>>(modelsJson);
// Generate meshes
foreach (var block in blockDataList)
{
if (blockModels.TryGetValue(block.block_name, out var modelData))
{
// Create mesh based on modelData.elements
Mesh blockMesh = new Mesh();
// Build vertices, triangles, and UVs
// Use textureDict to get the textures
// Add mesh to the scene
}
else
{
// Handle blocks without custom models
}
}
Key Considerations:
Thread Safety:
Unity objects should only be manipulated on the main thread.
When downloading assets asynchronously, ensure that any Unity object updates are dispatched to the main thread.
Asset Licensing:
Verify that you have the rights to use the assets from the repository.
Comply with any licensing requirements specified.
Performance Optimization:
Minimize the number of network requests by batching downloads where possible.
Consider using asset bundles or caching mechanisms for frequently used assets.
Error Handling:
Implement retries for network operations.
Provide informative error messages for missing assets.
Resource Management:
Dispose of UnityWebRequest objects properly to free up resources.
Monitor memory usage to prevent leaks, especially when handling many textures.
Summary:
By fetching textures and block models directly from the GitHub repository, you can keep your application up-to-date with the latest assets and reduce local storage requirements. This approach involves:
Dynamically loading and parsing asset data.
Generating meshes and textures at runtime based on the fetched data.
Updating your rendering logic to be data-driven rather than hardcoded.
This overhaul will make your codebase more flexible and scalable, allowing for easier updates and modifications in the future.