using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Physics;
using UnityEngine;
namespace GarmentButton.VerletIntegration.Interaction
{
[UpdateInGroup(typeof(VerletIntegrationPhysicsGroupSystems))]
[BurstCompile]
public partial struct SetActiveStateInteractionFlagSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<EndSimulationEntityCommandBufferSystem.Singleton>();
state.RequireForUpdate<SimulationSingleton>();
state.RequireForUpdate<FlagInteractionEnableTag>();
state.RequireForUpdate<InteractableWithClothTag>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var ecbSingleton = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer(state.WorldUnmanaged);
state.Dependency = new DisableFlagJob
{
ECB = ecbSingleton,
}.Schedule(state.Dependency);
state.Dependency = new ActiveInteractionFlagJob
{
PlayerLookUp = SystemAPI.GetComponentLookup<InteractableWithClothTag>(true),
FlagLookUp = SystemAPI.GetComponentLookup<FlagInteractionEnableTag>(true),
BufferLookup = SystemAPI.GetBufferLookup<CurrentInteractable>(),
ECB = ecbSingleton
}.Schedule(SystemAPI.GetSingleton<SimulationSingleton>(), state.Dependency);
}
}
[BurstCompile]
public partial struct ActiveInteractionFlagJob : ITriggerEventsJob
{
[ReadOnly] public ComponentLookup<InteractableWithClothTag> PlayerLookUp;
[ReadOnly] public ComponentLookup<FlagInteractionEnableTag> FlagLookUp;
public BufferLookup<CurrentInteractable> BufferLookup;
public EntityCommandBuffer ECB;
[BurstCompile]
public void Execute(TriggerEvent triggerEvent)
{
Entity entityA = triggerEvent.EntityA;
Entity entityB = triggerEvent.EntityB;
bool isBodyATrigger = FlagLookUp.HasComponent(entityA);
bool isBodyBTrigger = FlagLookUp.HasComponent(entityB);
// Ignoring Triggers overlapping other Triggers
if (isBodyATrigger && isBodyBTrigger)
return;
bool isBodyADynamic = PlayerLookUp.HasComponent(entityA);
bool isBodyBDynamic = PlayerLookUp.HasComponent(entityB);
// Ignoring overlapping static bodies
if ((isBodyATrigger && !isBodyBDynamic) ||
(isBodyBTrigger && !isBodyADynamic) ||
(!isBodyATrigger && !isBodyBTrigger) ||
(!isBodyADynamic && !isBodyBDynamic))
return;
var triggerEntity = isBodyATrigger ? entityA : entityB;
var dynamicEntity = isBodyATrigger ? entityB : entityA;
BufferLookup.TryGetBuffer(triggerEntity, out var buffer);
buffer.Add(new CurrentInteractable()
{
Entity = dynamicEntity,
});
/*ECB.AppendToBuffer(triggerEntity, new CurrentInteractable()
{
Entity = dynamicEntity,
});*/
ECB.SetComponentEnabled<FlagInteractionEnableTag>(triggerEntity, true);
}
}
[BurstCompile]
public partial struct DisableFlagJob : IJobEntity
{
public EntityCommandBuffer ECB;
public void Execute(Entity entity, in FlagInteractionEnableTag interact,ref DynamicBuffer<CurrentInteractable> buffer)
{
buffer.Clear();
ECB.SetComponentEnabled<FlagInteractionEnableTag>(entity, false);
}
}
}