Skip to content

Instantly share code, notes, and snippets.

@LizzyFox-code
Last active May 15, 2024 08:48
Show Gist options
  • Save LizzyFox-code/c9f95610b5c03dc86ed067256246987f to your computer and use it in GitHub Desktop.
Save LizzyFox-code/c9f95610b5c03dc86ed067256246987f to your computer and use it in GitHub Desktop.
Custom single thread job example
[JobProducerType(typeof(JobCustomSingleExtensions.JobCustomSingleStruct<>))]
public interface IJobCustomSingle
{
void Execute();
}
public static class JobCustomSingleExtensions
{
public static void EarlyJobInit<T>() where T : struct, IJobCustomSingle
{
JobCustomSingleStruct<T>.Initialize();
}
private static IntPtr GetReflectionData<T>() where T : struct, IJobCustomSingle
{
JobCustomSingleStruct<T>.Initialize();
return JobCustomSingleStruct<T>.jobReflectionData.Data;
}
public static unsafe JobHandle Schedule<TJob>(this TJob jobData, JobHandle dependsOn = default)
where TJob : struct, IJobCustomSingle
{
var fullData = new JobCustomSingleStruct<TJob>
{
JobData = jobData
};
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref fullData),
GetReflectionData<TJob>(), dependsOn, ScheduleMode.Single);
return JobsUtility.Schedule(ref scheduleParams);
}
public static unsafe JobHandle ScheduleByRef<TJob>(this ref TJob jobData, JobHandle dependsOn = default)
where TJob : struct, IJobCustomSingle
{
var fullData = new JobCustomSingleStruct<TJob>
{
JobData = jobData
};
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref fullData),
GetReflectionData<TJob>(), dependsOn, ScheduleMode.Single);
return JobsUtility.Schedule(ref scheduleParams);
}
[StructLayout(LayoutKind.Sequential)]
internal struct JobCustomSingleStruct<TJob>
where TJob : struct, IJobCustomSingle
{
public TJob JobData;
internal static readonly SharedStatic<IntPtr> jobReflectionData =
SharedStatic<IntPtr>.GetOrCreate<JobCustomSingleStruct<TJob>>();
[BurstDiscard]
internal static void Initialize()
{
if (jobReflectionData.Data == IntPtr.Zero)
{
jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(JobCustomSingleStruct<TJob>),
typeof(TJob), (ExecuteJobFunction)Execute);
}
}
private delegate void ExecuteJobFunction(ref JobCustomSingleStruct<TJob> fullData, IntPtr additionalPtr,
IntPtr bufferRangePatchData,
ref JobRanges ranges, int jobIndex);
public static void Execute(ref JobCustomSingleStruct<TJob> fullData, IntPtr additionalPtr, IntPtr bufferRangePatchData,
ref JobRanges ranges, int jobIndex)
{
fullData.JobData.Execute();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment