Chunk_T_.AsSpan256_TTo_().md

July 25, 2024 ยท View on GitHub

Friflo.Engine.ECS

Friflo.Engine.ECS.Chunk<T>

Chunk.AsSpan256() Method

Return the components as a System.Span<> of type TTo - which can be assigned to Vector256{TTo}'s.
The returned System.Span<> contains padding elements on its tail to enable safe conversion to a Vector256{TTo}.
See Example..

public System.Span<TTo> AsSpan256<TTo>()
    where TTo : struct, System.ValueType, System.ValueType;

Type parameters

TTo

Returns

System.Span<TTo>

Remarks

By adding padding elements the returned System.Span<> can be converted to Vector256's
without the need of an additional for loop to process the elements at the tail of the System.Span<>.

Vectorization example:

// e.g. using: struct ByteComponent : IComponent { public byte value; }
var add = Vector256.Create<byte>(1);                // create byte[32] vector - all values = 1
foreach (var (component, _) in query.Chunks)
{    
    var bytes   = component.AsSpan256<byte>();      // bytes.Length - multiple of 32
    var step    = component.StepSpan256;            // step = 32
    for (int n = 0; n < bytes.Length; n += step) {
        var slice   = bytes.Slice(n, step);
        var value   = Vector256.Create<byte>(slice);
        var result  = Vector256.Add(value, add);    // execute 32 add instructions at once
        result.CopyTo(slice);
    }
}