Exemple #1
0
        /// <summary>
        /// Enqueues a command to map a part of a <see cref="OpenCLImage"/> into the host address space.
        /// </summary>
        /// <param name="image"> The <see cref="OpenCLImage"/> to map. </param>
        /// <param name="blocking"> The mode of operation of this command. If <c>true</c> this call will not return until the command has finished execution. </param>
        /// <param name="flags"> A list of properties for the mapping mode. </param>
        /// <param name="offset"> The <paramref name="image"/> element position where mapping starts. </param>
        /// <param name="region"> The region of elements to map. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        /// <remarks> If <paramref name="blocking"/> is <c>true</c> this method will not return until the command completes. If <paramref name="blocking"/> is <c>false</c> this method will return immediately after the command is enqueued. </remarks>
        public IntPtr Map(OpenCLImage image, bool blocking, OpenCLMemoryMappingFlags flags, SysIntX3 offset, SysIntX3 region, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int eventWaitListSize;

            CLEventHandle[] eventHandles = OpenCLTools.ExtractHandles(events, out eventWaitListSize);

            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;

            IntPtr mappedPtr, rowPitch, slicePitch;

            OpenCLErrorCode error = OpenCLErrorCode.Success;

            mappedPtr = CL10.EnqueueMapImage(Handle, image.Handle, blocking, flags, ref offset, ref region, out rowPitch, out slicePitch, eventWaitListSize, eventHandles, newEventHandle, out error);
            OpenCLException.ThrowOnError(error);

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }

            return(mappedPtr);
        }
Exemple #2
0
        /// <summary>
        /// Enqueues a command to copy a 2D or 3D region of elements between two buffers.
        /// </summary>
        /// <typeparam name="T"> The type of data in the buffers. </typeparam>
        /// <param name="source"> The buffer to copy from. </param>
        /// <param name="destination"> The buffer to copy to. </param>
        /// <param name="sourceOffset"> The <paramref name="source"/> element position where reading starts. </param>
        /// <param name="destinationOffset"> The <paramref name="destination"/> element position where writing starts. </param>
        /// <param name="region"> The region of elements to copy. </param>
        /// <param name="sourceRowPitch"> The size of the source buffer row in bytes. If set to zero then <paramref name="sourceRowPitch"/> equals <c>region.X * sizeof(T)</c>. </param>
        /// <param name="sourceSlicePitch"> The size of the source buffer 2D slice in bytes. If set to zero then <paramref name="sourceSlicePitch"/> equals <c>region.Y * sizeof(T) * sourceRowPitch</c>. </param>
        /// <param name="destinationRowPitch"> The size of the destination buffer row in bytes. If set to zero then <paramref name="destinationRowPitch"/> equals <c>region.X * sizeof(T)</c>. </param>
        /// <param name="destinationSlicePitch"> The size of the destination buffer 2D slice in bytes. If set to zero then <paramref name="destinationSlicePitch"/> equals <c>region.Y * sizeof(T) * destinationRowPitch</c>. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        /// <remarks> Requires OpenCL 1.1. </remarks>
        public void Copy(OpenCLBufferBase source, OpenCLBufferBase destination, SysIntX3 sourceOffset, SysIntX3 destinationOffset, SysIntX3 region, long sourceRowPitch, long sourceSlicePitch, long destinationRowPitch, long destinationSlicePitch, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int sizeofT = Marshal.SizeOf(source.ElementType);

            sourceOffset.X      = new IntPtr(sizeofT * sourceOffset.X.ToInt64());
            destinationOffset.X = new IntPtr(sizeofT * destinationOffset.X.ToInt64());
            region.X            = new IntPtr(sizeofT * region.X.ToInt64());

            int eventWaitListSize;

            CLEventHandle[] eventHandles = OpenCLTools.ExtractHandles(events, out eventWaitListSize);

            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;

            OpenCLErrorCode error = CL11.EnqueueCopyBufferRect(this.Handle, source.Handle, destination.Handle, ref sourceOffset, ref destinationOffset, ref region, new IntPtr(sourceRowPitch), new IntPtr(sourceSlicePitch), new IntPtr(destinationRowPitch), new IntPtr(destinationSlicePitch), eventWaitListSize, eventHandles, newEventHandle);

            OpenCLException.ThrowOnError(error);

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }
        }
Exemple #3
0
        private ReadOnlyCollection <byte[]> GetBinaries()
        {
            IntPtr[] binaryLengths = GetArrayInfo <CLProgramHandle, OpenCLProgramInfo, IntPtr>(Handle, OpenCLProgramInfo.BinarySizes, CL10.GetProgramInfo);

            GCHandle[]     binariesGCHandles    = new GCHandle[binaryLengths.Length];
            IntPtr[]       binariesPtrs         = new IntPtr[binaryLengths.Length];
            IList <byte[]> binaries             = new List <byte[]>();
            GCHandle       binariesPtrsGCHandle = GCHandle.Alloc(binariesPtrs, GCHandleType.Pinned);

            try
            {
                for (int i = 0; i < binaryLengths.Length; i++)
                {
                    byte[] binary = new byte[binaryLengths[i].ToInt64()];
                    binariesGCHandles[i] = GCHandle.Alloc(binary, GCHandleType.Pinned);
                    binariesPtrs[i]      = binariesGCHandles[i].AddrOfPinnedObject();
                    binaries.Add(binary);
                }

                IntPtr          sizeRet;
                OpenCLErrorCode error = CL10.GetProgramInfo(Handle, OpenCLProgramInfo.Binaries, new IntPtr(binariesPtrs.Length * IntPtr.Size), binariesPtrsGCHandle.AddrOfPinnedObject(), out sizeRet);
                OpenCLException.ThrowOnError(error);
            }
            finally
            {
                for (int i = 0; i < binaryLengths.Length; i++)
                {
                    binariesGCHandles[i].Free();
                }
                binariesPtrsGCHandle.Free();
            }

            return(new ReadOnlyCollection <byte[]>(binaries));
        }
        /// <summary>
        ///
        /// </summary>
        protected void HookNotifier()
        {
            statusNotify = new OpenCLEventCallback(StatusNotify);
            OpenCLErrorCode error = CL11.SetEventCallback(Handle, (int)OpenCLCommandExecutionStatus.Complete, statusNotify, IntPtr.Zero);

            OpenCLException.ThrowOnError(error);
        }
Exemple #5
0
        static OpenCLPlatform()
        {
            try
            {
                if (platforms != null)
                {
                    return;
                }
                CLPlatformHandle[] handles;
                int             handlesLength;
                OpenCLErrorCode error = CL10.GetPlatformIDs(0, null, out handlesLength);
                OpenCLException.ThrowOnError(error);
                handles = new CLPlatformHandle[handlesLength];

                error = CL10.GetPlatformIDs(handlesLength, handles, out handlesLength);
                OpenCLException.ThrowOnError(error);

                List <OpenCLPlatform> platformList = new List <OpenCLPlatform>(handlesLength);
                foreach (CLPlatformHandle handle in handles)
                {
                    platformList.Add(new OpenCLPlatform(handle));
                }

                platforms = platformList.AsReadOnly();
            }
            catch (DllNotFoundException)
            {
                platforms = new List <OpenCLPlatform>().AsReadOnly();
            }
        }
Exemple #6
0
        /// <summary>
        /// Enqueues a command to map a part of a buffer into the host address space.
        /// </summary>
        /// <param name="buffer"> The buffer to map. </param>
        /// <param name="blocking">  The mode of operation of this call. </param>
        /// <param name="flags"> A list of properties for the mapping mode. </param>
        /// <param name="offset"> The <paramref name="buffer"/> element position where mapping starts. </param>
        /// <param name="region"> The region of elements to map. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        /// <remarks> If <paramref name="blocking"/> is <c>true</c> this method will not return until the command completes. If <paramref name="blocking"/> is <c>false</c> this method will return immediately after the command is enqueued. </remarks>
        public IntPtr Map(OpenCLBufferBase buffer, bool blocking, OpenCLMemoryMappingFlags flags, long offset, long region, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int sizeofT = Marshal.SizeOf(buffer.ElementType);

            int eventWaitListSize;

            CLEventHandle[] eventHandles   = OpenCLTools.ExtractHandles(events, out eventWaitListSize);
            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;

            IntPtr mappedPtr = IntPtr.Zero;

            OpenCLErrorCode error = OpenCLErrorCode.Success;

            mappedPtr = CL10.EnqueueMapBuffer(Handle, buffer.Handle, blocking, flags, new IntPtr(offset * sizeofT), new IntPtr(region * sizeofT), eventWaitListSize, eventHandles, newEventHandle, out error);
            OpenCLException.ThrowOnError(error);

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }

            return(mappedPtr);
        }
Exemple #7
0
        /// <summary>
        /// Enqueues a marker.
        /// </summary>
        public OpenCLEvent AddMarker()
        {
            CLEventHandle   newEventHandle;
            OpenCLErrorCode error = CL10.EnqueueMarker(Handle, out newEventHandle);

            OpenCLException.ThrowOnError(error);
            return(new OpenCLEvent(newEventHandle, this));
        }
Exemple #8
0
        /// <summary>
        /// Creates a new <see cref="OpenCLImage2D"/> from an OpenGL 2D texture object.
        /// </summary>
        /// <param name="context"> A <see cref="OpenCLContext"/> with enabled CL/GL sharing. </param>
        /// <param name="flags"> A bit-field that is used to specify usage information about the <see cref="OpenCLImage2D"/>. Only <c>OpenCLMemoryFlags.ReadOnly</c>, <c>OpenCLMemoryFlags.WriteOnly</c> and <c>OpenCLMemoryFlags.ReadWrite</c> are allowed. </param>
        /// <param name="textureTarget"> One of the following values: GL_TEXTURE_2D, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, or GL_TEXTURE_RECTANGLE. Using GL_TEXTURE_RECTANGLE for texture_target requires OpenGL 3.1. Alternatively, GL_TEXTURE_RECTANGLE_ARB may be specified if the OpenGL extension GL_ARB_texture_rectangle is supported. </param>
        /// <param name="mipLevel"> The mipmap level of the OpenGL 2D texture object to be used. </param>
        /// <param name="textureId"> The OpenGL 2D texture object id to use. </param>
        /// <returns> The created <see cref="OpenCLImage2D"/>. </returns>
        public static OpenCLImage2D CreateFromGLTexture2D(OpenCLContext context, OpenCLMemoryFlags flags, int textureTarget, int mipLevel, int textureId)
        {
            OpenCLErrorCode error = OpenCLErrorCode.Success;
            CLMemoryHandle  image = CL10.CreateFromGLTexture2D(context.Handle, flags, textureTarget, mipLevel, textureId, out error);

            OpenCLException.ThrowOnError(error);

            return(new OpenCLImage2D(image, context, flags));
        }
        /// <summary>
        /// Waits on the host thread for the specified events to complete.
        /// </summary>
        /// <param name="events"> The events to be waited for completition. </param>
        public static void Wait(List <OpenCLEventBase> events)
        {
            int eventWaitListSize;

            CLEventHandle[] eventHandles = OpenCLTools.ExtractHandles(events, out eventWaitListSize);
            OpenCLErrorCode error        = CL10.WaitForEvents(eventWaitListSize, eventHandles);

            OpenCLException.ThrowOnError(error);
        }
Exemple #10
0
        /// <summary>
        /// Creates a new <see cref="OpenCLImage2D"/> from an OpenGL renderbuffer object.
        /// </summary>
        /// <param name="context"> A <see cref="OpenCLContext"/> with enabled CL/GL sharing. </param>
        /// <param name="flags"> A bit-field that is used to specify usage information about the <see cref="OpenCLImage2D"/>. Only <c>OpenCLMemoryFlags.ReadOnly</c>, <c>OpenCLMemoryFlags.WriteOnly</c> and <c>OpenCLMemoryFlags.ReadWrite</c> are allowed. </param>
        /// <param name="renderbufferId"> The OpenGL renderbuffer object id to use. </param>
        /// <returns> The created <see cref="OpenCLImage2D"/>. </returns>
        public static OpenCLImage2D CreateFromGLRenderbuffer(OpenCLContext context, OpenCLMemoryFlags flags, int renderbufferId)
        {
            OpenCLErrorCode error = OpenCLErrorCode.Success;
            CLMemoryHandle  image = CL10.CreateFromGLRenderbuffer(context.Handle, flags, renderbufferId, out error);

            OpenCLException.ThrowOnError(error);

            return(new OpenCLImage2D(image, context, flags));
        }
Exemple #11
0
        /// <summary>
        /// Creates a new <see cref="OpenCLImage3D"/>.
        /// </summary>
        /// <param name="context"> A valid <see cref="OpenCLContext"/> in which the <see cref="OpenCLImage3D"/> is created. </param>
        /// <param name="flags"> A bit-field that is used to specify allocation and usage information about the <see cref="OpenCLImage3D"/>. </param>
        /// <param name="format"> A structure that describes the format properties of the <see cref="OpenCLImage3D"/>. </param>
        /// <param name="width"> The width of the <see cref="OpenCLImage3D"/> in pixels. </param>
        /// <param name="height"> The height of the <see cref="OpenCLImage3D"/> in pixels. </param>
        /// <param name="depth"> The depth of the <see cref="OpenCLImage3D"/> in pixels. </param>
        /// <param name="rowPitch"> The size in bytes of each row of elements of the <see cref="OpenCLImage3D"/>. If <paramref name="rowPitch"/> is zero, OpenCL will compute the proper value based on <see cref="OpenCLImage.Width"/> and <see cref="OpenCLImage.ElementSize"/>. </param>
        /// <param name="slicePitch"> The size in bytes of each 2D slice in the <see cref="OpenCLImage3D"/>. If <paramref name="slicePitch"/> is zero, OpenCL will compute the proper value based on <see cref="OpenCLImage.RowPitch"/> and <see cref="OpenCLImage.Height"/>. </param>
        /// <param name="data"> The data to initialize the <see cref="OpenCLImage3D"/>. Can be <c>IntPtr.Zero</c>. </param>
        public OpenCLImage3D(OpenCLContext context, OpenCLMemoryFlags flags, OpenCLImageFormat format, int width, int height, int depth, long rowPitch, long slicePitch, IntPtr data)
            : base(context, flags)
        {
            OpenCLErrorCode error = OpenCLErrorCode.Success;

            Handle = CL10.CreateImage3D(context.Handle, flags, ref format, new IntPtr(width), new IntPtr(height), new IntPtr(depth), new IntPtr(rowPitch), new IntPtr(slicePitch), data, out error);
            OpenCLException.ThrowOnError(error);

            Init();
        }
Exemple #12
0
        /// <summary>
        /// Creates a new <see cref="OpenCLSubBuffer{T}"/> from a specified <see cref="OpenCLBuffer{T}"/>.
        /// </summary>
        /// <param name="buffer"> The buffer to create the <see cref="OpenCLSubBuffer{T}"/> from. </param>
        /// <param name="flags"> A bit-field that is used to specify allocation and usage information about the <see cref="OpenCLBuffer{T}"/>. </param>
        /// <param name="offset"> The index of the element of <paramref name="buffer"/>, where the <see cref="OpenCLSubBuffer{T}"/> starts. </param>
        /// <param name="count"> The number of elements of <paramref name="buffer"/> to include in the <see cref="OpenCLSubBuffer{T}"/>. </param>
        public OpenCLSubBuffer(OpenCLBuffer buffer, OpenCLMemoryFlags flags, long offset, long count)
            : base(buffer.Context, flags, buffer.ElementType, new long[] { count })
        {
            SysIntX2        region = new SysIntX2(offset * Marshal.SizeOf(buffer.ElementType), count * Marshal.SizeOf(buffer.ElementType));
            OpenCLErrorCode error;
            CLMemoryHandle  handle = CL11.CreateSubBuffer(Handle, flags, OpenCLBufferCreateType.Region, ref region, out error);

            OpenCLException.ThrowOnError(error);

            Init();
        }
Exemple #13
0
        /// <summary>
        /// Builds (compiles and links) a program executable from the program source or binary for all or some of the <see cref="OpenCLProgram.Devices"/>.
        /// </summary>
        /// <param name="devices"> A subset or all of <see cref="OpenCLProgram.Devices"/>. If <paramref name="devices"/> is <c>null</c>, the executable is built for every item of <see cref="OpenCLProgram.Devices"/> for which a source or a binary has been loaded. </param>
        /// <param name="options"> A set of options for the OpenCL compiler. </param>
        /// <param name="notify"> A delegate instance that represents a reference to a notification routine. This routine is a callback function that an application can register and which will be called when the program executable has been built (successfully or unsuccessfully). If <paramref name="notify"/> is not <c>null</c>, <see cref="OpenCLProgram.Build"/> does not need to wait for the build to complete and can return immediately. If <paramref name="notify"/> is <c>null</c>, <see cref="OpenCLProgram.Build"/> does not return until the build has completed. The callback function may be called asynchronously by the OpenCL implementation. It is the application's responsibility to ensure that the callback function is thread-safe and that the delegate instance doesn't get collected by the Garbage Collector until the build operation triggers the callback. </param>
        /// <param name="notifyDataPtr"> Optional user data that will be passed to <paramref name="notify"/>. </param>
        public void Build(IList <OpenCLDevice> devices, string options, OpenCLProgramBuildNotifier notify, IntPtr notifyDataPtr)
        {
            int handleCount;

            CLDeviceHandle[] deviceHandles = OpenCLTools.ExtractHandles(devices, out handleCount);
            buildOptions = (options != null) ? options : "";
            buildNotify  = notify;

            OpenCLErrorCode error = CL10.BuildProgram(Handle, handleCount, deviceHandles, options, buildNotify, notifyDataPtr);

            OpenCLException.ThrowOnError(error);
        }
Exemple #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="flags"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        protected static ICollection <OpenCLImageFormat> GetSupportedFormats(OpenCLContext context, OpenCLMemoryFlags flags, OpenCLMemoryType type)
        {
            int             formatCountRet = 0;
            OpenCLErrorCode error          = CL10.GetSupportedImageFormats(context.Handle, flags, type, 0, null, out formatCountRet);

            OpenCLException.ThrowOnError(error);

            OpenCLImageFormat[] formats = new OpenCLImageFormat[formatCountRet];
            error = CL10.GetSupportedImageFormats(context.Handle, flags, type, formatCountRet, formats, out formatCountRet);
            OpenCLException.ThrowOnError(error);

            return(new Collection <OpenCLImageFormat>(formats));
        }
Exemple #15
0
        /// <summary>
        /// Creates a new <see cref="OpenCLProgram"/> from a specified list of binaries.
        /// </summary>
        /// <param name="context"> A <see cref="OpenCLContext"/>. </param>
        /// <param name="binaries"> A list of binaries, one for each item in <paramref name="devices"/>. </param>
        /// <param name="devices"> A subset of the <see cref="OpenCLContext.Devices"/>. If <paramref name="devices"/> is <c>null</c>, OpenCL will associate every binary from <see cref="OpenCLProgram.Binaries"/> with a corresponding <see cref="OpenCLDevice"/> from <see cref="OpenCLContext.Devices"/>. </param>
        public OpenCLProgram(OpenCLContext context, IList <byte[]> binaries, IList <OpenCLDevice> devices)
        {
            int count;

            CLDeviceHandle[] deviceHandles = (devices != null) ?
                                             OpenCLTools.ExtractHandles(devices, out count) :
                                             OpenCLTools.ExtractHandles(context.Devices, out count);

            IntPtr[]        binariesPtrs    = new IntPtr[count];
            IntPtr[]        binariesLengths = new IntPtr[count];
            int[]           binariesStats   = new int[count];
            OpenCLErrorCode error           = OpenCLErrorCode.Success;

            GCHandle[] binariesGCHandles = new GCHandle[count];

            try
            {
                for (int i = 0; i < count; i++)
                {
                    binariesGCHandles[i] = GCHandle.Alloc(binaries[i], GCHandleType.Pinned);
                    binariesPtrs[i]      = binariesGCHandles[i].AddrOfPinnedObject();
                    binariesLengths[i]   = new IntPtr(binaries[i].Length);
                }

                Handle = CL10.CreateProgramWithBinary(
                    context.Handle,
                    count,
                    deviceHandles,
                    binariesLengths,
                    binariesPtrs,
                    binariesStats,
                    out error);
                OpenCLException.ThrowOnError(error);
            }
            finally
            {
                for (int i = 0; i < count; i++)
                {
                    binariesGCHandles[i].Free();
                }
            }


            this.binaries = new ReadOnlyCollection <byte[]>(binaries);
            this.context  = context;
            this.devices  = new ReadOnlyCollection <OpenCLDevice>(
                (devices != null) ? devices : context.Devices);

            //Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
        }
Exemple #16
0
        internal OpenCLKernel(string functionName, OpenCLProgram program)
        {
            OpenCLErrorCode error = OpenCLErrorCode.Success;

            Handle = CL10.CreateKernel(program.Handle, functionName, out error);
            OpenCLException.ThrowOnError(error);

            SetID(Handle.Value);

            context           = program.Context;
            this.functionName = functionName;
            this.program      = program;

            //Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
        }
Exemple #17
0
        /// <summary>
        /// Creates a new <see cref="OpenCLProgram"/> from a source code string.
        /// </summary>
        /// <param name="context"> A <see cref="OpenCLContext"/>. </param>
        /// <param name="source"> The source code for the <see cref="OpenCLProgram"/>. </param>
        /// <remarks> The created <see cref="OpenCLProgram"/> is associated with the <see cref="OpenCLContext.Devices"/>. </remarks>
        public OpenCLProgram(OpenCLContext context, string source)
        {
            OpenCLErrorCode error = OpenCLErrorCode.Success;

            Handle = CL10.CreateProgramWithSource(context.Handle, 1, new string[] { source }, null, out error);
            OpenCLException.ThrowOnError(error);

            SetID(Handle.Value);

            this.context = context;
            this.devices = context.Devices;
            this.source  = new ReadOnlyCollection <string>(new string[] { source });

            //Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
        }
Exemple #18
0
        /// <summary>
        /// Creates a new <see cref="OpenCLUserEvent"/>.
        /// </summary>
        /// <param name="context"> The <see cref="OpenCLContext"/> in which the <see cref="OpenCLUserEvent"/> is created. </param>
        /// <remarks> Requires OpenCL 1.1. </remarks>
        public OpenCLUserEvent(OpenCLContext context)
        {
            OpenCLErrorCode error;

            Handle = CL11.CreateUserEvent(context.Handle, out error);
            OpenCLException.ThrowOnError(error);

            SetID(Handle.Value);

            Type    = (OpenCLCommandType)GetInfo <CLEventHandle, OpenCLEventInfo, uint>(Handle, OpenCLEventInfo.CommandType, CL10.GetEventInfo);
            Context = context;
            HookNotifier();

            //Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
        }
Exemple #19
0
        /// <summary>
        /// Creates a new <see cref="OpenCLSampler"/>.
        /// </summary>
        /// <param name="context"> A <see cref="OpenCLContext"/>. </param>
        /// <param name="normalizedCoords"> The usage state of normalized coordinates when accessing a <see cref="OpenCLImage"/> in a <see cref="OpenCLKernel"/>. </param>
        /// <param name="addressing"> The <see cref="OpenCLImageAddressing"/> mode of the <see cref="OpenCLSampler"/>. Specifies how out-of-range image coordinates are handled while reading. </param>
        /// <param name="filtering"> The <see cref="OpenCLImageFiltering"/> mode of the <see cref="OpenCLSampler"/>. Specifies the type of filter that must be applied when reading data from an image. </param>
        public OpenCLSampler(OpenCLContext context, bool normalizedCoords, OpenCLImageAddressing addressing, OpenCLImageFiltering filtering)
        {
            OpenCLErrorCode error = OpenCLErrorCode.Success;

            Handle = CL10.CreateSampler(context.Handle, normalizedCoords, addressing, filtering, out error);
            OpenCLException.ThrowOnError(error);

            SetID(Handle.Value);

            this.addressing       = addressing;
            this.context          = context;
            this.filtering        = filtering;
            this.normalizedCoords = normalizedCoords;

            //Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
        }
Exemple #20
0
        /// <summary>
        /// Enqueues a command to execute a single <see cref="OpenCLKernel"/>.
        /// </summary>
        /// <param name="kernel"> The <see cref="OpenCLKernel"/> to execute. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        public void ExecuteTask(OpenCLKernel kernel, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int eventWaitListSize;

            CLEventHandle[] eventHandles   = OpenCLTools.ExtractHandles(events, out eventWaitListSize);
            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;
            OpenCLErrorCode error          = CL10.EnqueueTask(Handle, kernel.Handle, eventWaitListSize, eventHandles, newEventHandle);

            OpenCLException.ThrowOnError(error);

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// Enqueues a command to read data from a <see cref="OpenCLImage"/>.
        /// </summary>
        /// <param name="source"> The <see cref="OpenCLImage"/> to read from. </param>
        /// <param name="blocking"> The mode of operation of this command. If <c>true</c> this call will not return until the command has finished execution. </param>
        /// <param name="offset"> The <paramref name="source"/> element position where reading starts. </param>
        /// <param name="region"> The region of elements to read. </param>
        /// <param name="rowPitch"> The <see cref="OpenCLImage.RowPitch"/> of <paramref name="source"/> or 0. </param>
        /// <param name="slicePitch"> The <see cref="OpenCLImage.SlicePitch"/> of <paramref name="source"/> or 0. </param>
        /// <param name="destination"> A pointer to a preallocated memory area to read the data into. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        /// <remarks> If <paramref name="blocking"/> is <c>true</c> this method will not return until the command completes. If <paramref name="blocking"/> is <c>false</c> this method will return immediately after the command is enqueued. </remarks>
        public void Read(OpenCLImage source, bool blocking, SysIntX3 offset, SysIntX3 region, long rowPitch, long slicePitch, IntPtr destination, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int eventWaitListSize;

            CLEventHandle[] eventHandles   = OpenCLTools.ExtractHandles(events, out eventWaitListSize);
            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;
            OpenCLErrorCode error          = CL10.EnqueueReadImage(Handle, source.Handle, blocking, ref offset, ref region, new IntPtr(rowPitch), new IntPtr(slicePitch), destination, eventWaitListSize, eventHandles, newEventHandle);

            OpenCLException.ThrowOnError(error);

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Creates a new <see cref="OpenCLCommandQueue"/>.
        /// </summary>
        /// <param name="context"> A <see cref="OpenCLContext"/>. </param>
        /// <param name="device"> A <see cref="OpenCLDevice"/> associated with the <paramref name="context"/>. It can either be one of <see cref="OpenCLContext.Devices"/> or have the same <see cref="OpenCLDeviceTypes"/> as the <paramref name="device"/> specified when the <paramref name="context"/> is created. </param>
        /// <param name="properties"> The properties for the <see cref="OpenCLCommandQueue"/>. </param>
        public OpenCLCommandQueue(OpenCLContext context, OpenCLDevice device, OpenCLCommandQueueProperties properties)
        {
            OpenCLErrorCode error = OpenCLErrorCode.Success;

            Handle = CL10.CreateCommandQueue(context.Handle, device.Handle, properties, out error);
            OpenCLException.ThrowOnError(error);

            SetID(Handle.Value);

            this.device  = device;
            this.context = context;

            outOfOrderExec = ((properties & OpenCLCommandQueueProperties.OutOfOrderExecution) == OpenCLCommandQueueProperties.OutOfOrderExecution);
            profiling      = ((properties & OpenCLCommandQueueProperties.Profiling) == OpenCLCommandQueueProperties.Profiling);

            Events = new List <OpenCLEventBase>();

            //Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
        }
Exemple #23
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="HandleType"></typeparam>
        /// <typeparam name="InfoType"></typeparam>
        /// <typeparam name="QueriedType"></typeparam>
        /// <param name="handle"></param>
        /// <param name="paramName"></param>
        /// <param name="getInfoDelegate"></param>
        /// <returns></returns>
        protected QueriedType GetInfo <HandleType, InfoType, QueriedType>
            (HandleType handle, InfoType paramName, GetInfoDelegate <HandleType, InfoType> getInfoDelegate)
            where QueriedType : struct
        {
            QueriedType result   = new QueriedType();
            GCHandle    gcHandle = GCHandle.Alloc(result, GCHandleType.Pinned);

            try
            {
                IntPtr          sizeRet;
                OpenCLErrorCode error = getInfoDelegate(handle, paramName, (IntPtr)Marshal.SizeOf(result), gcHandle.AddrOfPinnedObject(), out sizeRet);
                OpenCLException.ThrowOnError(error);
            }
            finally
            {
                result = (QueriedType)gcHandle.Target;
                gcHandle.Free();
            }
            return(result);
        }
Exemple #24
0
        /// <summary>
        /// Enqueues a command to copy data between <see cref="OpenCLImage"/>s.
        /// </summary>
        /// <param name="source"> The <see cref="OpenCLImage"/> to copy from. </param>
        /// <param name="destination"> The <see cref="OpenCLImage"/> to copy to. </param>
        /// <param name="sourceOffset"> The <paramref name="source"/> element position where reading starts. </param>
        /// <param name="destinationOffset"> The <paramref name="destination"/> element position where writing starts. </param>
        /// <param name="region"> The region of elements to copy. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        public void Copy(OpenCLImage source, OpenCLImage destination, SysIntX3 sourceOffset, SysIntX3 destinationOffset, SysIntX3 region, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int eventWaitListSize;

            CLEventHandle[] eventHandles = OpenCLTools.ExtractHandles(events, out eventWaitListSize);

            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;

            OpenCLErrorCode error = CL10.EnqueueCopyImage(Handle, source.Handle, destination.Handle, ref sourceOffset, ref destinationOffset, ref region, eventWaitListSize, eventHandles, newEventHandle);

            OpenCLException.ThrowOnError(error);

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }
        }
Exemple #25
0
        /// <summary>
        /// Enqueues a command to unmap a buffer or a <see cref="OpenCLImage"/> from the host address space.
        /// </summary>
        /// <param name="memory"> The <see cref="OpenCLMemory"/>. </param>
        /// <param name="mappedPtr"> The host address returned by a previous call to <see cref="OpenCLCommandQueue.Map"/>. This pointer is <c>IntPtr.Zero</c> after this method returns. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        public void Unmap(OpenCLMemory memory, ref IntPtr mappedPtr, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int eventWaitListSize;

            CLEventHandle[] eventHandles   = OpenCLTools.ExtractHandles(events, out eventWaitListSize);
            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;
            OpenCLErrorCode error          = CL10.EnqueueUnmapMemObject(Handle, memory.Handle, mappedPtr, eventWaitListSize, eventHandles, newEventHandle);

            OpenCLException.ThrowOnError(error);

            mappedPtr = IntPtr.Zero;

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Enqueues a command to write data to a buffer.
        /// </summary>
        /// <param name="destination"> The buffer to write to. </param>
        /// <param name="blocking"> The mode of operation of this command. If <c>true</c> this call will not return until the command has finished execution. </param>
        /// <param name="destinationOffset"> The <paramref name="destination"/> element position where writing starts. </param>
        /// <param name="region"> The region of elements to write. </param>
        /// <param name="source"> The data written to the buffer. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        /// <remarks> If <paramref name="blocking"/> is <c>true</c> this method will not return until the command completes. If <paramref name="blocking"/> is <c>false</c> this method will return immediately after the command is enqueued. </remarks>
        public void Write(OpenCLBufferBase destination, bool blocking, long destinationOffset, long region, IntPtr source, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int sizeofT = Marshal.SizeOf(destination.ElementType);

            int eventWaitListSize;

            CLEventHandle[] eventHandles   = OpenCLTools.ExtractHandles(events, out eventWaitListSize);
            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;
            OpenCLErrorCode error          = CL10.EnqueueWriteBuffer(Handle, destination.Handle, blocking, new IntPtr(destinationOffset * sizeofT), new IntPtr(region * sizeofT), source, eventWaitListSize, eventHandles, newEventHandle);

            OpenCLException.ThrowOnError(error);

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }
        }
Exemple #27
0
        /// <summary>
        /// Enqueues a command to execute a range of <see cref="OpenCLKernel"/>s in parallel.
        /// </summary>
        /// <param name="kernel"> The <see cref="OpenCLKernel"/> to execute. </param>
        /// <param name="globalWorkOffset"> An array of values that describe the offset used to calculate the global ID of a work-item instead of having the global IDs always start at offset (0, 0,... 0). </param>
        /// <param name="globalWorkSize"> An array of values that describe the number of global work-items in dimensions that will execute the kernel function. The total number of global work-items is computed as global_work_size[0] *...* global_work_size[work_dim - 1]. </param>
        /// <param name="localWorkSize"> An array of values that describe the number of work-items that make up a work-group (also referred to as the size of the work-group) that will execute the <paramref name="kernel"/>. The total number of work-items in a work-group is computed as local_work_size[0] *... * local_work_size[work_dim - 1]. </param>
        /// <param name="events"> A collection of events that need to complete before this particular command can be executed. If <paramref name="events"/> is not <c>null</c> or read-only a new <see cref="OpenCLEvent"/> identifying this command is created and attached to the end of the collection. </param>
        public void Execute(OpenCLKernel kernel, long[] globalWorkOffset, long[] globalWorkSize, long[] localWorkSize, IReadOnlyList <OpenCLEventBase> events = null, IList <OpenCLEventBase> newEvents = null)
        {
            int eventWaitListSize;

            CLEventHandle[] eventHandles = OpenCLTools.ExtractHandles(events, out eventWaitListSize);

            CLEventHandle[] newEventHandle = (newEvents != null) ? new CLEventHandle[1] : null;

            OpenCLErrorCode error = CL10.EnqueueNDRangeKernel(Handle, kernel.Handle, globalWorkSize.Length, OpenCLTools.ConvertArray(globalWorkOffset), OpenCLTools.ConvertArray(globalWorkSize), OpenCLTools.ConvertArray(localWorkSize), eventWaitListSize, eventHandles, newEventHandle);

            OpenCLException.ThrowOnError(error);

            if (newEvents != null)
            {
                lock (newEvents)
                {
                    newEvents.Add(new OpenCLEvent(newEventHandle[0], this));
                }
            }
        }
Exemple #28
0
        /// <summary>
        /// Creates a new <see cref="OpenCLContext"/> on all the <see cref="OpenCLDevice"/>s that match the specified <see cref="OpenCLDeviceTypes"/>.
        /// </summary>
        /// <param name="deviceType"> A bit-field that identifies the type of <see cref="OpenCLDevice"/> to associate with the <see cref="OpenCLContext"/>. </param>
        /// <param name="properties"> A <see cref="OpenCLContextPropertyList"/> of the <see cref="OpenCLContext"/>. </param>
        /// <param name="notify"> A delegate instance that refers to a notification routine. This routine is a callback function that will be used by the OpenCL implementation to report information on errors that occur in the <see cref="OpenCLContext"/>. The callback function may be called asynchronously by the OpenCL implementation. It is the application's responsibility to ensure that the callback function is thread-safe and that the delegate instance doesn't get collected by the Garbage Collector until <see cref="OpenCLContext"/> is disposed. If <paramref name="notify"/> is <c>null</c>, no callback function is registered. </param>
        /// <param name="userDataPtr"> Optional user data that will be passed to <paramref name="notify"/>. </param>
        public OpenCLContext(OpenCLDeviceType deviceType, OpenCLContextPropertyList properties, OpenCLContextNotifier notify, IntPtr userDataPtr)
        {
            IntPtr[] propertyArray = (properties != null) ? properties.ToIntPtrArray() : null;
            callback = notify;

            OpenCLErrorCode error = OpenCLErrorCode.Success;

            Handle = CL10.CreateContextFromType(propertyArray, deviceType, notify, userDataPtr, out error);
            OpenCLException.ThrowOnError(error);

            SetID(Handle.Value);

            this.properties = properties;
            OpenCLContextProperty platformProperty = properties.GetByName(OpenCLContextProperties.Platform);

            this.platform = OpenCLPlatform.GetByHandle(platformProperty.Value);
            this.devices  = GetDevices();

            //Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
        }
Exemple #29
0
        /// <summary>
        /// Gets a read-only collection of available <see cref="OpenCLDevice"/>s on the <see cref="OpenCLPlatform"/>.
        /// </summary>
        /// <returns> A read-only collection of the available <see cref="OpenCLDevice"/>s on the <see cref="OpenCLPlatform"/>. </returns>
        /// <remarks> This method resets the <c>OpenCLPlatform.Devices</c>. This is useful if one or more of them become unavailable (<c>OpenCLDevice.Available</c> is <c>false</c>) after a <see cref="OpenCLContext"/> and <see cref="OpenCLCommandQueue"/>s that use the <see cref="OpenCLDevice"/> have been created and commands have been queued to them. Further calls will trigger an <c>OutOfResourcesOpenCLException</c> until this method is executed. You will also need to recreate any <see cref="OpenCLResource"/> that was created on the no longer available <see cref="OpenCLDevice"/>. </remarks>
        public ReadOnlyCollection <OpenCLDevice> QueryDevices()
        {
            int             handlesLength = 0;
            OpenCLErrorCode error         = CL10.GetDeviceIDs(Handle, OpenCLDeviceType.All, 0, null, out handlesLength);

            OpenCLException.ThrowOnError(error);

            CLDeviceHandle[] handles = new CLDeviceHandle[handlesLength];
            error = CL10.GetDeviceIDs(Handle, OpenCLDeviceType.All, handlesLength, handles, out handlesLength);
            OpenCLException.ThrowOnError(error);

            OpenCLDevice[] devices = new OpenCLDevice[handlesLength];
            for (int i = 0; i < handlesLength; i++)
            {
                devices[i] = new OpenCLDevice(this, handles[i]);
            }

            this.devices = new ReadOnlyCollection <OpenCLDevice>(devices);

            return(this.devices);
        }
Exemple #30
0
        /// <summary>
        /// Creates a <see cref="OpenCLKernel"/> for every <c>kernel</c> function in <see cref="OpenCLProgram"/>.
        /// </summary>
        /// <returns> The collection of created <see cref="OpenCLKernel"/>s. </returns>
        /// <remarks> <see cref="OpenCLKernel"/>s are not created for any <c>kernel</c> functions in <see cref="OpenCLProgram"/> that do not have the same function definition across all <see cref="OpenCLProgram.Devices"/> for which a program executable has been successfully built. </remarks>
        public ICollection <OpenCLKernel> CreateAllKernels()
        {
            ICollection <OpenCLKernel> kernels = new Collection <OpenCLKernel>();
            int kernelsCount = 0;

            CLKernelHandle[] kernelHandles;

            OpenCLErrorCode error = CL10.CreateKernelsInProgram(Handle, 0, null, out kernelsCount);

            OpenCLException.ThrowOnError(error);

            kernelHandles = new CLKernelHandle[kernelsCount];
            error         = CL10.CreateKernelsInProgram(Handle, kernelsCount, kernelHandles, out kernelsCount);
            OpenCLException.ThrowOnError(error);

            for (int i = 0; i < kernelsCount; i++)
            {
                kernels.Add(new OpenCLKernel(kernelHandles[i], this));
            }

            return(kernels);
        }