Example #1
0
        public override unsafe bool ScheduleVertexColorJob(VertexInputData colorInput, NativeSlice <JobHandle> handles)
        {
            Profiler.BeginSample("ScheduleVertexColorJob");
            Profiler.BeginSample("AllocateNativeArray");
            vData = new NativeArray <Color>(colorInput.count, VertexBufferConfigBase.defaultAllocator);
            var vDataPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(vData);

            Profiler.EndSample();

            fixed(void *input = &(colorInput.buffer[colorInput.startOffset]))
            {
                var h = GetColors32Job(
                    input,
                    colorInput.type,
                    colorInput.attributeType,
                    colorInput.byteStride,
                    vData
                    );

                if (h.HasValue)
                {
                    handles[0] = h.Value;
                }
                else
                {
                    Profiler.EndSample();
                    return(false);
                }
            }

            Profiler.EndSample();
            return(true);
        }
Example #2
0
 public AStarJobComparer(NativeArray <float> _G_, int weightsWidth, INT2 destination, float heuristic_search)
 {
     this._F_Ptr           = NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(_G_);
     this._width           = weightsWidth;
     this._dest            = destination;
     this.heuristic_search = heuristic_search;
 }
 GetReadOnlySpan <T>(this NativeArray <T> array) where T : unmanaged
 {
     unsafe {
         var ptr = NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(array);
         return(new Span <T>(ptr, array.Length));
     }
 }
Example #4
0
        public void CaptureFrame(Color32[] pixelBuffer)
        {
            if (preview == null)
            {
                return;
            }

#if OPENCV_USE_UNSAFE_CODE && UNITY_2018_2_OR_NEWER
            unsafe
            {
                NativeArray <Color32> rawTextureData = preview.GetRawTextureData <Color32>();
                int      size    = UnsafeUtility.SizeOf <Color32>() * rawTextureData.Length;
                Color32 *srcAddr = (Color32 *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(rawTextureData);

                fixed(Color32 *dstAddr = pixelBuffer)
                {
                    UnsafeUtility.MemCpy(dstAddr, srcAddr, size);
                }
            }
#else
            byte[]   rawTextureData = preview.GetRawTextureData();
            GCHandle pin            = GCHandle.Alloc(pixelBuffer, GCHandleType.Pinned);
            Marshal.Copy(rawTextureData, 0, pin.AddrOfPinnedObject(), rawTextureData.Length);
            pin.Free();
#endif
        }
        protected override void UpdateTexture()
        {
            // Get the matrix
            switch (matCaptureMethod)
            {
            case MatCaptureMethod.GetRawTextureData_ByteArray:
                Utils.copyToMat(cameraSource.preview.GetRawTextureData(), frameMatrix);
                Core.flip(frameMatrix, frameMatrix, 0);
                break;

            case MatCaptureMethod.GetRawTextureData_NativeArray:

#if OPENCV_USE_UNSAFE_CODE && UNITY_2018_2_OR_NEWER
                // non-memory allocation.
                unsafe
                {
                    var ptr = (IntPtr)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(cameraSource.preview.GetRawTextureData <byte>());
                    Utils.copyToMat(ptr, frameMatrix);
                }
                Core.flip(frameMatrix, frameMatrix, 0);
#else
                Utils.copyToMat(cameraSource.preview.GetRawTextureData(), frameMatrix);
                Core.flip(frameMatrix, frameMatrix, 0);
                Imgproc.putText(frameMatrix, "NativeArray<T> GetRawTextureData() method can be used from Unity 2018.2 or later.", new Point(5, frameMatrix.rows() - 10), Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar(255, 255, 255, 255), 1, Imgproc.LINE_AA, false);
#endif
                break;
            }

            ProcessImage(frameMatrix, grayMatrix, imageProcessingType);

            // Convert to Texture2D
            Utils.fastMatToTexture2D(frameMatrix, texture);
        }
    public unsafe void Controls_CanWriteValueFromBufferIntoState()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        var tempBufferSize = (int)gamepad.stateBlock.alignedSizeInBytes;

        using (var tempBuffer = new NativeArray <byte>(tempBufferSize, Allocator.Temp))
        {
            var tempBufferPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(tempBuffer);

            // The device is the first in the system so is guaranteed to start of offset 0 which
            // means we don't need to adjust the pointer here.
            Debug.Assert(gamepad.stateBlock.byteOffset == 0);

            var vector    = new Vector2(0.1234f, 0.5678f);
            var vectorPtr = UnsafeUtility.AddressOf(ref vector);

            gamepad.leftStick.WriteValueFromBufferIntoState(vectorPtr, UnsafeUtility.SizeOf <Vector2>(), tempBufferPtr);

            var leftStickXPtr = (float *)(tempBufferPtr + gamepad.leftStick.x.stateBlock.byteOffset);
            var leftStickYPtr = (float *)(tempBufferPtr + gamepad.leftStick.y.stateBlock.byteOffset);

            Assert.That(*leftStickXPtr, Is.EqualTo(0.1234).Within(0.00001));
            Assert.That(*leftStickYPtr, Is.EqualTo(0.5678).Within(0.00001));
        }
    }
Example #7
0
 public static int Encode(NativeArray <byte> data, int width, int height, int components, int quality, byte[] result)
 {
     unsafe
     {
         void *inPtr = NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(data);
         fixed(byte *outPtr = result)
         {
             return(JpegEncoder_Encode(inPtr, width, height, components, quality, outPtr, result.Length));
         }
     }
 }
Example #8
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int entityOffset)
        {
            var destinationPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafePtr(Entities) +
                                 sizeof(Entity) * entityOffset;

            var chunkEntityArray = chunk.GetNativeArray(EntityType);
            var sourcePtr        = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(chunkEntityArray);

            var copySizeInBytes = sizeof(Entity) * chunk.Count;

            UnsafeUtility.MemCpy(destinationPtr, sourcePtr, copySizeInBytes);
        }
Example #9
0
 public ImageFrame(ImageFormat.Format format, int width, int height, int widthStep, NativeArray <byte> pixelData)
 {
     unsafe {
         UnsafeNativeMethods.mp_ImageFrame__ui_i_i_i_Pui8_PF(
             format, width, height, widthStep,
             (IntPtr)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(pixelData),
             ReleasePixelData,
             out var ptr
             ).Assert();
         this.ptr = ptr;
     }
 }
Example #10
0
 public void Encode(NativeArray <byte> pixels, long pts)
 {
     unsafe
     {
         var ret = recorder_encode_frame(
             recorder,
             NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(pixels),
             pts);
         if (ret != 0)
         {
             throw new Exception("recorder_encode_frame() error");
         }
     }
 }
        public void CaptureFrame(Mat matrix)
        {
#if OPENCV_USE_UNSAFE_CODE && UNITY_2018_2_OR_NEWER
            unsafe
            {
                var ptr = (IntPtr)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(preview.GetRawTextureData <byte>());
                Utils.copyToMat(ptr, matrix);
            }
            Core.flip(matrix, matrix, 0);
#else
            Utils.copyToMat(preview.GetRawTextureData(), matrix);
            Core.flip(matrix, matrix, 0);
#endif
        }
Example #12
0
        public unsafe void Execute(ArchetypeChunk chunk, int chunkIndex, int entityOffset)
        {
            var srcComponentData = chunk.GetNativeArray(ComponentType);

            var sourcePtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(srcComponentData);

            var sizeOfComponentType = UnsafeUtility.SizeOf <T>();
            var destinationPtr      = (byte *)NativeArrayUnsafeUtility.GetUnsafePtr(ComponentData) +
                                      sizeOfComponentType * entityOffset;

            var copySizeInBytes = UnsafeUtility.SizeOf <T>() * chunk.Count;

            UnsafeUtility.MemCpy(destinationPtr, sourcePtr, copySizeInBytes);
        }
        public ImageFrame(ImageFormat format, int width, int height, int widthStep, NativeArray <byte> pixelData)
        {
            FreeMemoryHandler memoryHandler = (IntPtr ptr) => { pixelData.Dispose(); };

            freePixelDataHandle = GCHandle.Alloc(memoryHandler, GCHandleType.Pinned);

            unsafe {
                ptr = UnsafeNativeMethods.MpImageFrameCreateWithPixelData(
                    (int)format, width, height, widthStep,
                    (IntPtr)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(pixelData),
                    Marshal.GetFunctionPointerForDelegate(memoryHandler)
                    );
            }

            base.TakeOwnership(ptr);
        }
Example #14
0
        /**
         * Copies Pixel Data NativeArray to OpenCV Mat data.
         * <p>
         * <br>This method copies the pixel data NativeArray to the OpenCV Mat data.
         * <br>The Mat object must have the same byte size as the pixel data Array ([total() * elemSize()] byte).
         * <br>Because this method doesn't check bounds, is faster than Mat.put().
         *
         * @param array a pixel data Array.
         * @param mat the Mat object must have the same byte size as the pixel data Array ([total() * elemSize()] byte).
         */
        public static void copyToMat <T>(NativeArray <T> array, Mat mat) where T : struct
        {
            if (mat == null)
            {
                throw new ArgumentNullException("mat");
            }
            if (mat != null)
            {
                mat.ThrowIfDisposed();
            }

            unsafe
            {
                OpenCVForUnity_ByteArrayToMatData((IntPtr)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(array), mat.nativeObj);
            }
        }
        public ImageFrame(ImageFormat.Format format, int width, int height, int widthStep, NativeArray <byte> pixelData)
        {
            Deleter deleter = (IntPtr ptr) => { /** Do nothing (pixelData will be moved) */ };

            deleterHandle = GCHandle.Alloc(deleter, GCHandleType.Pinned);

            unsafe {
                UnsafeNativeMethods.mp_ImageFrame__ui_i_i_i_Pui8_PF(
                    format, width, height, widthStep,
                    (IntPtr)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(pixelData),
                    deleter,
                    out var ptr
                    ).Assert();
                this.ptr = ptr;
            }
        }
Example #16
0
        unsafe void OnReadback(AsyncGPUReadbackRequest request)
        {
            // Metadata retrieval
            using (var metadata = _metadataQueue.Dequeue())
            {
                // Ignore errors.
                if (request.hasError)
                {
                    return;
                }

                // Ignore it if the NDI object has been already disposed.
                if (_send == null || _send.IsInvalid || _send.IsClosed)
                {
                    return;
                }

                // Pixel format (depending on alpha mode)
                var fourcc = _enableAlpha ?
                             Interop.FourCC.UYVA : Interop.FourCC.UYVY;

                // Readback data retrieval
                var data  = request.GetData <byte>();
                var pdata = NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(data);

                // Data size verification
                if (data.Length / sizeof(uint) !=
                    Util.FrameDataCount(_width, _height, _enableAlpha))
                {
                    return;
                }

                // Frame data setup
                var frame = new Interop.VideoFrame
                {
                    Width  = _width, Height = _height, LineStride = _width * 2,
                    FourCC = _enableAlpha ?
                             Interop.FourCC.UYVA : Interop.FourCC.UYVY,
                    FrameFormat = Interop.FrameFormat.Progressive,
                    Data        = (System.IntPtr)pdata, Metadata = metadata
                };

                // Send via NDI
                _send.SendVideoAsync(frame);
            }
        }
Example #17
0
        /**
         * Draws Detect Result.
         *
         * @param texture2D
         * @param r
         * @param g
         * @param b
         * @param a
         * @param thickness
         */
        public void DrawDetectResult(Texture2D texture2D, int r, int g, int b, int a, int thickness, bool updateMipmaps = false, bool makeNoLongerReadable = false)
        {
            if (texture2D == null)
            {
                throw new ArgumentNullException("texture2D");
            }
            ThrowIfDisposed();

            if (texture2D.format == TextureFormat.RGBA32 || texture2D.format == TextureFormat.RGB24 || texture2D.format == TextureFormat.Alpha8)
            {
#if DLIB_USE_UNSAFE_CODE && UNITY_2018_2_OR_NEWER
                unsafe
                {
                    NativeArray <byte> colors = texture2D.GetRawTextureData <byte>();

                    DlibFaceLandmarkDetector_DrawDetectResult(nativeObj, (IntPtr)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(colors), texture2D.width, texture2D.height, (int)texture2D.format, true, r, g, b, a, thickness);

                    texture2D.LoadRawTextureData(colors);
                    texture2D.Apply(updateMipmaps, makeNoLongerReadable);
                }
#else
                byte[] colors = texture2D.GetRawTextureData();

                GCHandle arrayHandle = GCHandle.Alloc(colors, GCHandleType.Pinned);
                DlibFaceLandmarkDetector_DrawDetectResult(nativeObj, arrayHandle.AddrOfPinnedObject(), texture2D.width, texture2D.height, (int)texture2D.format, true, r, g, b, a, thickness);
                arrayHandle.Free();

                texture2D.LoadRawTextureData(colors);
                texture2D.Apply(updateMipmaps, makeNoLongerReadable);
#endif
            }
            else
            {
                Color32[] colors = texture2D.GetPixels32();

                GCHandle arrayHandle = GCHandle.Alloc(colors, GCHandleType.Pinned);
                DlibFaceLandmarkDetector_DrawDetectResult(nativeObj, arrayHandle.AddrOfPinnedObject(), texture2D.width, texture2D.height, 4, true, r, g, b, a, thickness);
                arrayHandle.Free();

                texture2D.SetPixels32(colors);
                texture2D.Apply(updateMipmaps, makeNoLongerReadable);
            }
        }
        public void CaptureFrame(byte[] pixelBuffer)
        {
#if OPENCV_USE_UNSAFE_CODE && UNITY_2018_2_OR_NEWER
            unsafe
            {
                NativeArray <byte> rawTextureData = preview.GetRawTextureData <byte>();
                int   size    = UnsafeUtility.SizeOf <byte>() * rawTextureData.Length;
                byte *srcAddr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(rawTextureData);

                fixed(byte *dstAddr = pixelBuffer)
                {
                    UnsafeUtility.MemCpy(dstAddr, srcAddr, size);
                }
            }
#else
            byte[] rawTextureData = preview.GetRawTextureData();
            Buffer.BlockCopy(rawTextureData, 0, pixelBuffer, 0, rawTextureData.Length);
#endif
        }
        public override unsafe bool ScheduleVertexUVJobs(IGltfBuffers buffers, int[] uvAccessorIndices, int vertexCount, NativeSlice <JobHandle> handles)
        {
            Profiler.BeginSample("ScheduleVertexUVJobs");
            Profiler.BeginSample("AllocateNativeArray");
            vData = new NativeArray <T>(vertexCount, VertexBufferConfigBase.defaultAllocator);
            var vDataPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(vData);

            Profiler.EndSample();
            uvSetCount = uvAccessorIndices.Length;
            int outputByteStride = uvAccessorIndices.Length * 8;

            for (int i = 0; i < uvAccessorIndices.Length; i++)
            {
                var accIndex = uvAccessorIndices[i];
                buffers.GetAccessor(accIndex, out var uvAcc, out var data, out var byteStride);
                if (uvAcc.isSparse)
                {
                    logger.Error(LogCode.SparseAccessor, "UVs");
                }
                var h = GetUvsJob(
                    data,
                    uvAcc.count,
                    uvAcc.componentType,
                    byteStride,
                    (float2 *)(vDataPtr + (i * 8)),
                    outputByteStride,
                    uvAcc.normalized
                    );
                if (h.HasValue)
                {
                    handles[i] = h.Value;
                }
                else
                {
                    Profiler.EndSample();
                    return(false);
                }
            }
            Profiler.EndSample();
            return(true);
        }
Example #20
0
        // Sets the Ini file name
        // If you set it to non-empty you must also set it to empty at shutdown or Unity will complain about memory leak
        // ImGuiRenderer will do that for you, you only need to care if you use this directly
        public void SetIniFile(string filename)
        {
            if (IniFileNameArray.IsCreated)
            {
                IniFileNameArray.Dispose();
            }

            if (filename == null || filename == "")
            {
                NativePtr->IniFilename = null;
                return;
            }

            IniFileNameArray = new NativeArray <byte>(filename.Length + 1, Allocator.Persistent);
            for (int i = 0; i < filename.Length; i++)
            {
                IniFileNameArray[i] = (byte)filename[i];
            }
            IniFileNameArray[filename.Length] = 0;
            NativePtr->IniFilename            = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(IniFileNameArray);
        }
Example #21
0
        public override unsafe bool ScheduleVertexUVJobs(VertexInputData[] uvInputs, NativeSlice <JobHandle> handles)
        {
            Profiler.BeginSample("ScheduleVertexUVJobs");
            Profiler.BeginSample("AllocateNativeArray");
            vData = new NativeArray <T>(uvInputs[0].count, VertexBufferConfigBase.defaultAllocator);
            var vDataPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(vData);

            Profiler.EndSample();
            uvSetCount = uvInputs.Length;
            int outputByteStride = uvInputs.Length * 8;

            for (int i = 0; i < uvInputs.Length; i++)
            {
                var uvInput = uvInputs[i];
                fixed(void *input = &(uvInput.buffer[uvInput.startOffset]))
                {
                    var h = GetUvsJob(
                        input,
                        uvInput.count,
                        uvInput.type,
                        uvInput.byteStride,
                        (Vector2 *)(vDataPtr + (i * 8)),
                        outputByteStride,
                        uvInput.normalize
                        );

                    if (h.HasValue)
                    {
                        handles[i] = h.Value;
                    }
                    else
                    {
                        Profiler.EndSample();
                        return(false);
                    }
                }
            }
            Profiler.EndSample();
            return(true);
        }
Example #22
0
    public static int Encode(NativeArray <byte> data, int width, int height, int components, int quality, byte[] result)
    {
        unsafe
        {
            void *inPtr = NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(data);
            fixed(byte *outPtr = result)
            {
                IntPtr handle = tjInitCompress();

                try
                {
                    IntPtr buffer = (IntPtr)outPtr;

                    // careful with this, on Windows C long is 32-bit, but we use C# long which is always 64-bit
                    // but as long as Windows is little-endian, it'll work fine
                    ulong buffer_size = (ulong)result.Length;

                    int ok = tjCompress2(
                        handle,
                        (IntPtr)inPtr,
                        width,
                        width * components,
                        height,
                        components == 3 ? PixelFormat.RGB : PixelFormat.RGBX,
                        ref buffer,
                        ref buffer_size,
                        Subsample.Samp420,
                        quality,
                        Flags.BottomUp | Flags.NoRealloc);

                    return((ok == 0) ? (int)buffer_size : -1);
                }
                finally
                {
                    tjDestroy(handle);
                }
            }
        }
    }
Example #23
0
    unsafe void OnCompleteReadback(AsyncGPUReadbackRequest request)
    {
        if (_sendInstance == IntPtr.Zero)
        {
            return;
        }

        var ptr = (IntPtr)NativeArrayUnsafeUtility.
                  GetUnsafeReadOnlyPtr(request.GetData <byte>());

        var format = NDIlib.frame_format_type_e.frame_format_type_progressive;

        var frame = new NDIlib.video_frame_v2_t
        {
            xres   = _width, yres = _height,
            FourCC = _pixelFormat.ToFourCC(), frame_format_type = format,
            p_data = ptr, line_stride_in_bytes = _width * 2
        };

        // Send via NDI
        NDIlib.send_send_video_async_v2(_sendInstance, ref frame);
    }
Example #24
0
 public unsafe ImageFrame(ImageFormat.Types.Format format, int width, int height, int widthStep, NativeArray <byte> pixelData, Deleter deleter)
     : this(format, width, height, widthStep, (IntPtr)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(pixelData), deleter)
 {
 }
Example #25
0
        public override unsafe JobHandle?ScheduleVertexBonesJob(
            IGltfBuffers buffers,
            int weightsAccessorIndex,
            int jointsAccessorIndex
            )
        {
            Profiler.BeginSample("ScheduleVertexBonesJob");
            Profiler.BeginSample("AllocateNativeArray");

            buffers.GetAccessor(weightsAccessorIndex, out var weightsAcc, out var weightsData, out var weightsByteStride);
            if (weightsAcc.isSparse)
            {
                logger.Error(LogCode.SparseAccessor, "bone weights");
            }
            vData = new NativeArray <VBones>(weightsAcc.count, VertexBufferConfigBase.defaultAllocator);
            var vDataPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(vData);

            Profiler.EndSample();

            JobHandle weightsHandle;
            JobHandle jointsHandle;

            {
                var h = GetWeightsJob(
                    weightsData,
                    weightsAcc.count,
                    weightsAcc.componentType,
                    weightsByteStride,
                    (float4 *)vDataPtr,
                    32,
                    weightsAcc.normalized
                    );
                if (h.HasValue)
                {
                    weightsHandle = h.Value;
                }
                else
                {
                    Profiler.EndSample();
                    return(null);
                }
            }

            {
                buffers.GetAccessor(jointsAccessorIndex, out var jointsAcc, out var jointsData, out var jointsByteStride);
                if (jointsAcc.isSparse)
                {
                    logger.Error(LogCode.SparseAccessor, "bone joints");
                }
                var h = GetJointsJob(
                    jointsData,
                    jointsAcc.count,
                    jointsAcc.componentType,
                    jointsByteStride,
                    (uint4 *)(vDataPtr + 16),
                    32,
                    logger
                    );
                if (h.HasValue)
                {
                    jointsHandle = h.Value;
                }
                else
                {
                    Profiler.EndSample();
                    return(null);
                }
            }

            var jobHandle = JobHandle.CombineDependencies(weightsHandle, jointsHandle);

            var skinWeights = (int)QualitySettings.skinWeights;

            if (skinWeights < 4)
            {
                var job = new SortJointsByWeightsJob {
                    bones       = vData,
                    skinWeights = math.max(1, skinWeights)
                };
                jobHandle = job.Schedule(vData.Length, GltfImport.DefaultBatchCount, jobHandle);
            }

            Profiler.EndSample();
            return(jobHandle);
        }
Example #26
0
        public override unsafe JobHandle?ScheduleVertexBonesJob(
            IGltfBuffers buffers,
            int weightsAccessorIndex,
            int jointsAccessorIndex
            )
        {
            Profiler.BeginSample("ScheduleVertexBonesJob");
            Profiler.BeginSample("AllocateNativeArray");

            buffers.GetAccessor(weightsAccessorIndex, out var weightsAcc, out var weightsData, out var weightsByteStride);
            if (weightsAcc.isSparse)
            {
                logger.Error(LogCode.SparseAccessor, "bone weights");
            }
            vData = new NativeArray <VBones>(weightsAcc.count, VertexBufferConfigBase.defaultAllocator);
            var vDataPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(vData);

            Profiler.EndSample();

            JobHandle weightsHandle;
            JobHandle jointsHandle;

            {
                var h = GetWeightsJob(
                    weightsData,
                    weightsAcc.count,
                    weightsAcc.componentType,
                    weightsByteStride,
                    (float4 *)vDataPtr,
                    32,
                    weightsAcc.normalized
                    );
                if (h.HasValue)
                {
                    weightsHandle = h.Value;
                }
                else
                {
                    Profiler.EndSample();
                    return(null);
                }
            }

            {
                buffers.GetAccessor(jointsAccessorIndex, out var jointsAcc, out var jointsData, out var jointsByteStride);
                if (jointsAcc.isSparse)
                {
                    logger.Error(LogCode.SparseAccessor, "bone joints");
                }
                var h = GetJointsJob(
                    jointsData,
                    jointsAcc.count,
                    jointsAcc.componentType,
                    jointsByteStride,
                    (uint4 *)(vDataPtr + 16),
                    32,
                    logger
                    );
                if (h.HasValue)
                {
                    jointsHandle = h.Value;
                }
                else
                {
                    Profiler.EndSample();
                    return(null);
                }
            }

            var jobHandle = JobHandle.CombineDependencies(weightsHandle, jointsHandle);

            var skinWeights = (int)QualitySettings.skinWeights;

#if UNITY_EDITOR
            // If this is design-time import, fix and import all weights.
            if (!UnityEditor.EditorApplication.isPlaying || skinWeights < 4)
            {
                if (!UnityEditor.EditorApplication.isPlaying)
                {
                    skinWeights = 4;
                }
#else
            if (skinWeights < 4)
            {
#endif
                var job = new SortAndRenormalizeBoneWeightsJob {
                    bones       = vData,
                    skinWeights = math.max(1, skinWeights)
                };
                jobHandle = job.Schedule(vData.Length, GltfImport.DefaultBatchCount, jobHandle);
            }
#if GLTFAST_SAFE
            else
            {
                // Re-normalizing alone is sufficient
                var job = new RenormalizeBoneWeightsJob {
                    bones = vData,
                };
                jobHandle = job.Schedule(vData.Length, GltfImport.DefaultBatchCount, jobHandle);
            }
#endif

            Profiler.EndSample();
            return(jobHandle);
        }
Example #27
0
 unsafe public static void *ToPtr(NativeArray <byte> data)
 {
     unsafe {
         return(NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(data));
     }
 }
Example #28
0
        public override unsafe bool ScheduleVertexBonesJob(
            VertexInputData weightsInput,
            VertexInputData jointsInput,
            NativeSlice <JobHandle> handles
            )
        {
            Profiler.BeginSample("ScheduleVertexBonesJob");
            Profiler.BeginSample("AllocateNativeArray");
            vData = new NativeArray <VBones>(weightsInput.count, VertexBufferConfigBase.defaultAllocator);
            var vDataPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(vData);

            Profiler.EndSample();

            fixed(void *input = &(weightsInput.buffer[weightsInput.startOffset]))
            {
                var h = GetWeightsJob(
                    input,
                    weightsInput.count,
                    weightsInput.type,
                    weightsInput.byteStride,
                    (Vector4 *)vDataPtr,
                    32,
                    weightsInput.normalize
                    );

                if (h.HasValue)
                {
                    handles[0] = h.Value;
                }
                else
                {
                    Profiler.EndSample();
                    return(false);
                }
            }

            fixed(void *input = &(jointsInput.buffer[jointsInput.startOffset]))
            {
                var h = GetJointsJob(
                    input,
                    jointsInput.count,
                    jointsInput.type,
                    jointsInput.byteStride,
                    (uint *)(vDataPtr + 16),
                    32,
                    logger
                    );

                if (h.HasValue)
                {
                    handles[1] = h.Value;
                }
                else
                {
                    Profiler.EndSample();
                    return(false);
                }
            }

            Profiler.EndSample();
            return(true);
        }
Example #29
0
        unsafe JobHandle?GetColors32Job(
            void *input,
            GLTFComponentType inputType,
            GLTFAccessorAttributeType attributeType,
            int inputByteStride,
            NativeArray <Color> output
            )
        {
            Profiler.BeginSample("PrepareColors32");
            JobHandle?jobHandle = null;

            if (attributeType == GLTFAccessorAttributeType.VEC3)
            {
                switch (inputType)
                {
                case GLTFComponentType.UnsignedByte:
                {
                    var job = new Jobs.GetColorsVec3UInt8Job {
                        input           = (byte *)input,
                        inputByteStride = inputByteStride > 0 ? inputByteStride : 3,
                        result          = output
                    };
                    jobHandle = job.Schedule(output.Length, GLTFast.DefaultBatchCount);
                }
                break;

                case GLTFComponentType.Float:
                {
                    var job = new Jobs.GetColorsVec3FloatJob {
                        input           = (float *)input,
                        inputByteStride = inputByteStride > 0 ? inputByteStride : 12,
                        result          = output
                    };
                    jobHandle = job.Schedule(output.Length, GLTFast.DefaultBatchCount);
                }
                break;

                case GLTFComponentType.UnsignedShort:
                {
                    var job = new Jobs.GetColorsVec3UInt16Job {
                        input           = (System.UInt16 *)input,
                        inputByteStride = inputByteStride > 0 ? inputByteStride : 6,
                        result          = output
                    };
                    jobHandle = job.Schedule(output.Length, GLTFast.DefaultBatchCount);
                }
                break;

                default:
                    Debug.LogErrorFormat(GLTFast.ErrorUnsupportedColorFormat, attributeType);
                    break;
                }
            }
            else if (attributeType == GLTFAccessorAttributeType.VEC4)
            {
                switch (inputType)
                {
                case GLTFComponentType.UnsignedByte:
                {
                    var job = new Jobs.GetColorsVec4UInt8Job {
                        input           = (byte *)input,
                        inputByteStride = inputByteStride > 0 ? inputByteStride : 4,
                        result          = output
                    };
                    jobHandle = job.Schedule(output.Length, GLTFast.DefaultBatchCount);
                }
                break;

                case GLTFComponentType.Float:
                {
                    var job = new Jobs.MemCopyJob();
                    job.bufferSize = output.Length * 16;
                    job.input      = input;
                    job.result     = NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(output);
                    jobHandle      = job.Schedule();
                }
                break;

                case GLTFComponentType.UnsignedShort:
                {
                    var job = new Jobs.GetColorsVec4UInt16Job {
                        input           = (System.UInt16 *)input,
                        inputByteStride = inputByteStride > 0 ? inputByteStride : 8,
                        result          = output
                    };
                    jobHandle = job.Schedule(output.Length, GLTFast.DefaultBatchCount);
                }
                break;

                default:
                    Debug.LogErrorFormat(GLTFast.ErrorUnsupportedColorFormat, attributeType);
                    break;
                }
            }
            else
            {
                Debug.LogErrorFormat(GLTFast.ErrorUnsupportedType, "color accessor", inputType);
            }
            Profiler.EndSample();
            return(jobHandle);
        }
Example #30
0
        public override unsafe JobHandle?ScheduleVertexJobs(
            VertexInputData posInput,
            VertexInputData?nrmInput     = null,
            VertexInputData?tanInput     = null,
            VertexInputData[] uvInputs   = null,
            VertexInputData?colorInput   = null,
            VertexInputData?weightsInput = null,
            VertexInputData?jointsInput  = null
            )
        {
            Profiler.BeginSample("ScheduleVertexJobs");
            Profiler.BeginSample("AllocateNativeArray");
            vData = new NativeArray <VType>(posInput.count, defaultAllocator);
            var vDataPtr = (byte *)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(vData);

            Profiler.EndSample();

            int jobCount         = 1;
            int outputByteStride = 12; // sizeof Vector3

            hasNormals = nrmInput.HasValue || calculateNormals;
            if (hasNormals)
            {
                if (nrmInput.HasValue)
                {
                    jobCount++;
                }
                outputByteStride += 12;
            }

            hasTangents = tanInput.HasValue || calculateTangents;
            if (hasTangents)
            {
                if (tanInput.HasValue)
                {
                    jobCount++;
                }
                outputByteStride += 16;
            }

            if (uvInputs != null && uvInputs.Length > 0)
            {
                jobCount += uvInputs.Length;
                switch (uvInputs.Length)
                {
                case 1:
                    texCoords = new VertexBufferTexCoords <VTexCoord1>();
                    break;

                default:
                    texCoords = new VertexBufferTexCoords <VTexCoord2>();
                    break;
                }
            }

            hasColors = colorInput.HasValue;
            if (hasColors)
            {
                jobCount++;
                colors = new VertexBufferColors();
            }

            hasBones = weightsInput.HasValue && jointsInput.HasValue;
            if (hasBones)
            {
                jobCount += 2;
                bones     = new VertexBufferBones();
            }

            NativeArray <JobHandle> handles = new NativeArray <JobHandle>(jobCount, Allocator.Temp);
            int handleIndex = 0;

            fixed(void *input = &(posInput.buffer[posInput.startOffset]))
            {
                var h = GetVector3sJob(
                    input,
                    posInput.count,
                    posInput.type,
                    posInput.byteStride,
                    (Vector3 *)vDataPtr,
                    outputByteStride,
                    posInput.normalize
                    );

                if (h.HasValue)
                {
                    handles[handleIndex] = h.Value;
                    handleIndex++;
                }
                else
                {
                    Profiler.EndSample();
                    return(null);
                }
            }

            if (nrmInput.HasValue)
            {
                fixed(void *input = &(nrmInput.Value.buffer[nrmInput.Value.startOffset]))
                {
                    var h = GetVector3sJob(
                        input,
                        nrmInput.Value.count,
                        nrmInput.Value.type,
                        nrmInput.Value.byteStride,
                        (Vector3 *)(vDataPtr + 12),
                        outputByteStride,
                        nrmInput.Value.normalize
                        );

                    if (h.HasValue)
                    {
                        handles[handleIndex] = h.Value;
                        handleIndex++;
                    }
                    else
                    {
                        Profiler.EndSample();
                        return(null);
                    }
                }
            }

            if (tanInput.HasValue)
            {
                fixed(void *input = &(tanInput.Value.buffer[tanInput.Value.startOffset]))
                {
                    var h = GetTangentsJob(
                        input,
                        tanInput.Value.count,
                        tanInput.Value.type,
                        tanInput.Value.byteStride,
                        (Vector4 *)(vDataPtr + 24),
                        outputByteStride,
                        tanInput.Value.normalize
                        );

                    if (h.HasValue)
                    {
                        handles[handleIndex] = h.Value;
                        handleIndex++;
                    }
                    else
                    {
                        Profiler.EndSample();
                        return(null);
                    }
                }
            }

            if (texCoords != null)
            {
                texCoords.ScheduleVertexUVJobs(uvInputs, new NativeSlice <JobHandle>(handles, handleIndex, uvInputs.Length));
                handleIndex++;
            }

            if (hasColors)
            {
                colors.ScheduleVertexColorJob(colorInput.Value, new NativeSlice <JobHandle>(handles, handleIndex, 1));
                handleIndex++;
            }

            if (hasBones)
            {
                bones.ScheduleVertexBonesJob(weightsInput.Value, jointsInput.Value, new NativeSlice <JobHandle>(handles, handleIndex, 2));
                handleIndex += 2;
            }

            var handle = (jobCount > 1) ? JobHandle.CombineDependencies(handles) : handles[0];

            handles.Dispose();
            Profiler.EndSample();
            return(handle);
        }