using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Sandbox.Definitions; using Sandbox.Game.Entities; using VRage.Voxels; using VRage.Voxels.DualContouring; using VRageMath; namespace XFE.SeAgent.Plugin.Graphics { internal sealed partial class RayTracing { private readonly Dictionary voxelCache=new Dictionary(); private readonly HashSet watchedVoxels=new HashSet(); // Bounded jobs: storage reads/meshing are independent and engine mesher // instances are thread-local. Definitions and scene publication stay on // the game thread, in deterministic cell order. private const int VoxelWorkers=4, VoxelRadius=320; private readonly SemaphoreSlim voxelWorker=new SemaphoreSlim(VoxelWorkers); private int voxelChunks,voxelTriangles,voxelRevision; private void ResetVoxels() { foreach(var voxel in watchedVoxels) voxel.RangeChanged-=VoxelChanged; watchedVoxels.Clear(); voxelCache.Clear(); voxelChunks=voxelTriangles=0; } private void VoxelChanged(MyVoxelBase voxel,Vector3I min,Vector3I max,MyStorageDataTypeFlags flags) { // This event may originate outside the game thread. Do not mutate a // cache here. The next game update invalidates the scene atomically. Interlocked.Increment(ref voxelRevision); Interlocked.Increment(ref sceneGeneration); snapshots.Clear(); Interlocked.Exchange(ref resetHistory,1); } private IEnumerable CollectVoxels(Vector3D camera) { int lod=options.VoxelLod, scale=1<().Select(v=>v.RootVoxel).Where(v=>v!=null && !v.Closed && v.PositionComp.WorldAABB.Intersects(sphere)).Distinct().ToArray(); var live=new HashSet(); voxelChunks=voxelTriangles=0; foreach(var root in roots) { if(watchedVoxels.Add(root)) root.RangeChanged+=VoxelChanged; var storage=root.Storage; if(storage==null) continue; var local=Vector3D.Transform(camera,root.PositionComp.WorldMatrixNormalizedInv)+root.SizeInMetresHalf+root.StorageMin; var size=storage.Size; var low=Vector3I.Max(Vector3I.Zero,Vector3I.Floor((local-new Vector3D(VoxelRadius))/meters)); var high=Vector3I.Min((size-Vector3I.One)/meters,Vector3I.Floor((local+new Vector3D(VoxelRadius))/meters)); var cells=new List(); for(int z=low.Z;z<=high.Z;z++) for(int y=low.Y;y<=high.Y;y++) for(int x=low.X;x<=high.X;x++) { var c=new Vector3I(x,y,z); var box=new BoundingBoxD(c*meters,(c+Vector3I.One)*meters); if(box.Intersects(new BoundingSphereD(local,VoxelRadius))) cells.Add(c); } cells.Sort((a,b)=>Vector3D.DistanceSquared(((Vector3D)a+new Vector3D(.5))*meters,local).CompareTo(Vector3D.DistanceSquared(((Vector3D)b+new Vector3D(.5))*meters,local))); var offset=root.SizeInMetresHalf+root.StorageMin; var pending=new Dictionary>(); int scheduled=0, revision=Volatile.Read(ref sceneGeneration); for(int cellNumber=0;cellNumber { await voxelWorker.WaitAsync(); try { if(Volatile.Read(ref sceneGeneration)!=revision) return null; return ((IMyIsoMesher)MyDualContouringMesher.Static).Precalc(storage,lod,min,max,MyStorageDataTypeFlags.ContentAndMaterial,0); } finally { voxelWorker.Release(); } })); } var cellIndex=cells[cellNumber]; string key=root.EntityId+":"+lod+":"+cellIndex; live.Add(key); if(!voxelCache.TryGetValue(key,out var mesh)) { // Engine mesher is thread-local; storage pins and ReadRange // are the same concurrency-safe route used by engine jobs. // The worker receives only storage and value coordinates, // never an entity, definition manager or render collection. var task=pending[cellNumber]; while(!task.IsCompleted) yield return null; var iso=task.GetAwaiter().GetResult(); pending.Remove(cellNumber); if(Volatile.Read(ref sceneGeneration)!=revision) yield break; if(iso!=null && iso.VerticesCount>0 && iso.TrianglesCount>0) { var vertices=new float[iso.VerticesCount*8]; for(int i=0;i0) { var tex=def.RenderParams.TextureSets[0]; vertices[j+5]=MaterialPath(tex.ColorMetalXZnY); vertices[j+6]=MaterialPath(tex.ColorMetalY); vertices[j+7]=1f/Math.Max(1,def.RenderParams.StandardTilingSetup.InitialScale); } else vertices[j+7]=.1f; } var indices=new List(iso.TrianglesCount*3); for(int i=0;i=(cellIndex.X+1)*cell || anchor.Y>=(cellIndex.Y+1)*cell || anchor.Z>=(cellIndex.Z+1)*cell) continue; indices.Add(t.V0);indices.Add(t.V1);indices.Add(t.V2); } if(indices.Count>0) { mesh=new Mesh { Id=++nextMesh,Vertices=vertices,Indices=indices.ToArray(),Materials=Enumerable.Repeat(VoxelFlag,indices.Count/3).ToArray() }; meshesById.Add(mesh.Id,mesh); } } voxelCache[key]=mesh; } if(mesh!=null) { voxelChunks++;voxelTriangles+=mesh.Indices.Length/3; yield return new Placement { Owner=root,Local=Matrix.Identity,Mesh=mesh.Id }; } yield return null; } } foreach(var key in voxelCache.Keys.Where(k=>!live.Contains(k)).ToArray()) voxelCache.Remove(key); foreach(var voxel in watchedVoxels.Where(v=>!roots.Contains(v)).ToArray()) { voxel.RangeChanged-=VoxelChanged;watchedVoxels.Remove(voxel); } } } }