using Physics.Components; using Physics.Systems; using Unity.Collections; using Unity.Entities; using Unity.Entities.Content; using Unity.Mathematics; using Unity.Transforms; using UnityEngine; using static Unity.Mathematics.math; namespace Rendering { [UpdateInGroup(typeof(PresentationSystemGroup))] public partial class RenderGravityFieldSystem : SystemBase { private Material _material; private GraphicsBuffer _gravityBuffer; private EntityQuery _gravityQuery; public struct Params : IComponentData { public float PointSize; public float PointDensity; public float SmoothA; public float SmoothB; public float G; } protected override void OnCreate() { _material = new Material(Shader.Find("Custom/GravitationalPotential")); _gravityBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 16, sizeof(float) * 4); _gravityQuery = new EntityQueryBuilder(Allocator.Temp) .WithAll() .Build(EntityManager); EntityManager.AddComponentData(SystemHandle, new Params { PointSize = 0.25f, PointDensity = 2f, SmoothA = 1f, SmoothB = 1f, G = 1f, }); } protected override void OnUpdate() { var config = EntityManager.GetComponentData(World.GetOrCreateSystem()); var p = EntityManager.GetComponentData(SystemHandle); float G = config.G; int size = 200; int density = 2; int gravitySourcesCount = _gravityQuery.CalculateEntityCount(); var gravitySources = new NativeArray(gravitySourcesCount, Allocator.TempJob); int i = 0; foreach (var (particle, transform) in SystemAPI.Query, RefRO>()) { gravitySources[i] = float4(transform.ValueRO.Position, particle.ValueRO.Mass); i++; } _gravityBuffer.SetData(gravitySources); var rp = new RenderParams(_material); rp.matProps = new MaterialPropertyBlock(); rp.matProps.SetBuffer("_Masses", _gravityBuffer); rp.matProps.SetInt("_PointsCount", size); rp.matProps.SetInt("_PointsDensity", density); rp.matProps.SetInt("_MassesCount", gravitySourcesCount); rp.matProps.SetFloat("_G", p.G); rp.matProps.SetFloat("_PointSize", p.PointSize); rp.matProps.SetFloat("_SmoothA", p.SmoothA); rp.matProps.SetFloat("_SmoothB", p.SmoothB); Graphics.RenderPrimitives(rp, MeshTopology.Lines, 8, size * size); gravitySources.Dispose(); } protected override void OnDestroy() { _gravityBuffer.Dispose(); _gravityBuffer = null; } } }