Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using UnityEngine;
- using Unity.Jobs;
- using Unity.Collections;
- using Unity.Mathematics;
- using Unity.Entities;
- using Voxels;
- using TerrainGeneration.TerrainMasks;
- using Unity.VisualScripting;
- using System;
- using UnityEditor.PackageManager;
- namespace TerrainGeneration
- {
- public static class VoxelGridGenerator
- {
- private static BlobAssetReference<TerrainMaskList> terrainMaskList;
- /// <summary>
- /// Generates a voxel grid based on masks2D and masks3D
- /// </summary>
- public static NativeVoxelGrid GenerateGrid(Vector3Int gridSize, Vector3Int position, float surfaceLevel, int stepSize)
- {
- NativeVoxelGrid voxelGrid = new(gridSize.x, gridSize.y, gridSize.z, Allocator.TempJob);
- if (!terrainMaskList.IsCreated) throw new ArgumentException("TerrainMaskList has not been created. You should call GenerateJobTerrainMasks() before GenerateGrid().");
- VoxelGridJob voxelGridJob = new()
- {
- voxelGrid = voxelGrid,
- terrainMasks = terrainMaskList,
- positionOffset = new float3(position.x, position.y, position.z),
- gridSize = new int3(gridSize.x, gridSize.y, gridSize.z),
- surfaceLevel = surfaceLevel,
- stepSize = stepSize
- };
- JobHandle handle = voxelGridJob.Schedule(gridSize.x * gridSize.z, 16);
- handle.Complete();
- return voxelGrid;
- }
- /// <summary>
- /// The masks modified to work in jobs
- /// </summary>
- public static void GenerateJobTerrainMasks(List<TerrainMask2D> masks2D, List<TerrainMask3D> masks3D)
- {
- var builder = new BlobBuilder(Allocator.Persistent);
- ref TerrainMaskList terrainMaskListRoot = ref builder.ConstructRoot<TerrainMaskList>();
- int count = masks2D.Count + masks3D.Count;
- BlobBuilderArray<JobTerrainMask> arrayBuilder = builder.Allocate(
- ref terrainMaskListRoot.terrainMasks,
- count
- );
- // Fill 2D masks
- for (int i = 0; i < masks2D.Count; i++)
- {
- masks2D[i].ToJobMask(ref arrayBuilder[i], ref builder);
- }
- // Fill 3D masks
- for (int i = 0; i < masks3D.Count; i++)
- {
- masks3D[i].ToJobMask(ref arrayBuilder[i + masks2D.Count], ref builder);
- }
- var result = builder.CreateBlobAssetReference<TerrainMaskList>(Allocator.Persistent);
- builder.Dispose();
- terrainMaskList = result;
- }
- public static void Dispose()
- {
- if (terrainMaskList.IsCreated) terrainMaskList.Dispose();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement