Example #1
0
        /// <summary>
        /// Uses the device for the compiler.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <exception cref="System.Exception">No device found. Please invoke Accelerator.Init with a device id to initialize. " +
        ///                     "If you have done the Init and still getting the error please check if OpenCL is installed.</exception>
        /// <exception cref="System.ArgumentException">Device ID out of range.</exception>
        public override void UseDevice(int deviceId = 0)
        {
            _compiledKernels   = new List <ComputeKernel>();
            _compiledInstances = new List <Type>();
            LoadDevices();

            if (_devices.Count == 0)
            {
                throw new Exception("No device found. Please invoke Accelerator.Init with a device id to initialize. " +
                                    "If you have done the Init and still getting the error please check if OpenCL is installed.");
            }

            if (deviceId >= _devices.Count)
            {
                throw new ArgumentException("Device ID out of range.");
            }

            _defaultDevice  = _devices[deviceId];
            _defaultPlatorm = _defaultDevice.Platform;
            ComputeContextPropertyList properties = new ComputeContextPropertyList(_defaultPlatorm);

            _context = new ComputeContext(new ComputeDevice[] { _defaultDevice }, properties, null, IntPtr.Zero);
            Console.WriteLine("Selected device: " + _defaultDevice.Name);
            DeviceID = deviceId;
        }
Example #2
0
        private void Initialize()
        {
            // get the intel integrated GPU
            _integratedIntelGPUPlatform = ComputePlatform.Platforms.Where(n => n.Name.Contains("Intel")).First();

            // create the compute context.
            _context = new ComputeContext(
                ComputeDeviceTypes.Gpu,                                      // use the gpu
                new ComputeContextPropertyList(_integratedIntelGPUPlatform), // use the intel openCL platform
                null,
                IntPtr.Zero);

            // the command queue is the, well, queue of commands sent to the "device" (GPU)
            _commandQueue = new ComputeCommandQueue(
                _context,                       // the compute context
                _context.Devices[0],            // first device matching the context specifications
                ComputeCommandQueueFlags.None); // no special flags

            string kernelSource = null;

            using (StreamReader sr = new StreamReader("kernel.cl"))
            {
                kernelSource = sr.ReadToEnd();
            }

            // create the "program"
            _program = new ComputeProgram(_context, new string[] { kernelSource });

            // compile.
            _program.Build(null, null, null, IntPtr.Zero);
            _kernel = _program.CreateKernel("ComputeMatrix");
        }
Example #3
0
        private static ComputeDevice LoadDevice(ComputePlatform platform)
        {
            int idx;

            while (true)
            {
                Console.WriteLine("\n\nZvolte cislo zariadenia na vypocet:");
                var devicesCount = platform.Devices.Count;
                for (int i = 0; i < devicesCount; i++)
                {
                    Console.WriteLine(i + ": " + platform.Devices[i].Name);
                }


                var parseSucceded = int.TryParse(Console.ReadLine(), out idx);


                if (parseSucceded && -1 < idx && idx < devicesCount)
                {
                    break;
                }
            }
            var device = platform.Devices[idx];

            return(device);
        }
Example #4
0
        /// <summary>
        /// Logs OpenCL context properties.
        /// </summary>
        /// <param name="ext">Print detailed list of extensions as well?</param>
        public static void LogCLProperties(ComputeContext context, bool ext = true)
        {
            ComputePlatform platform = context.Platform;

            Util.LogFormat("OpenCL host: {0}, platform: {1}",
                           Environment.OSVersion, platform.Name);
            Util.LogFormat("Vendor: {0}, version: {1}, profile: {2}",
                           platform.Vendor, platform.Version, platform.Profile);
            // optional extension list:
            if (ext)
            {
                Util.LogFormat("Extensions: {0}",
                               string.Join(", ", platform.Extensions));
            }

            // device list:
            Util.Log("OpenCL devices:");
            foreach (ComputeDevice device in context.Devices)
            {
                Util.LogFormat("Name: {0}", device.Name);
                Util.LogFormat("  Vendor: {0}", device.Vendor);
                Util.LogFormat("  Driver version: {0}", device.DriverVersion);
                Util.LogFormat("  OpenCL version: {0}", device.Version);
                Util.LogFormat("  Compute units: {0}", device.MaxComputeUnits);
                Util.LogFormat("  Global memory: {0} bytes", device.GlobalMemorySize);
                Util.LogFormat("  Local memory: {0} bytes", device.LocalMemorySize);
                Util.LogFormat("  Image support: {0}", device.ImageSupport);
                Util.LogFormat("  Extensions: {0}", device.Extensions.Count);
                if (ext)
                {
                    Util.LogFormat("    {0}", string.Join(", ", device.Extensions));
                }
            }
        }
Example #5
0
 private void FillDeviceInfo(ComputePlatform platform)
 {
     labelVendor.Text             = platform.Vendor;
     labelProfile.Text            = platform.Profile;
     labelVersion.Text            = platform.Version;
     listBoxExtensions.DataSource = platform.Extensions;
 }
Example #6
0
        public void Load(string directory, string kernelFileName, string function)
        {
#if DEBUG
            DeleteCache();
#endif

            m_platform = ComputePlatform.Platforms[0];

            Context = new ComputeContext(ComputeDeviceTypes.Gpu,
                                         new ComputeContextPropertyList(m_platform), null, IntPtr.Zero);

            m_graphicsCard = Context.Devices[0];

            Queue = new ComputeCommandQueue(Context, m_graphicsCard, ComputeCommandQueueFlags.None);

            ComputeProgram program = new ComputeProgram(Context, GetKernelSource(directory + "/" + kernelFileName));
            try
            {
                program.Build(null, "-I " + directory, null, IntPtr.Zero);
            }
            catch
            {
                string error = program.GetBuildLog(m_graphicsCard);
                throw new Exception(error);
            }

            Program = program.CreateKernel(function);
        }
Example #7
0
    static void Main(string[] args)
    {
        int[] r1 = new int[]
        { 8, 2, 3, 4 };
        int[] r2 = new int[]
        { 4, 3, 2, 5 };
        int[] r3      = new int[4];
        int   rowSize = r1.Length;
        // pick first platform
        ComputePlatform platform = ComputePlatform.Platforms[0];
        // create context with all gpu devices
        ComputeContext context = new ComputeContext(ComputeDeviceTypes.Gpu,
                                                    new ComputeContextPropertyList(platform), null, IntPtr.Zero);
        // create a command queue with first gpu found
        ComputeCommandQueue queue = new ComputeCommandQueue(context,
                                                            context.Devices[0], ComputeCommandQueueFlags.None);
        // load opencl source and
        // create program with opencl source
        ComputeProgram program = new ComputeProgram(context, CalculateKernel);

        // compile opencl source
        program.Build(null, null, null, IntPtr.Zero);
        // load chosen kernel from program
        ComputeKernel kernel = program.CreateKernel("Calc");
        // allocate a memory buffer with the message (the int array)
        ComputeBuffer <int> row1Buffer = new ComputeBuffer <int>(context,
                                                                 ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.UseHostPointer, r1);
        // allocate a memory buffer with the message (the int array)
        ComputeBuffer <int> row2Buffer = new ComputeBuffer <int>(context,
                                                                 ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.UseHostPointer, r2);
        // allocate a memory buffer with the message (the int array)
        ComputeBuffer <int> resultBuffer = new ComputeBuffer <int>(context,
                                                                   ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.UseHostPointer, new int[4]);

        kernel.SetMemoryArgument(0, row1Buffer);   // set the integer array
        kernel.SetMemoryArgument(1, row2Buffer);   // set the integer array
        kernel.SetValueArgument(2, rowSize);       // set the array size
        kernel.SetMemoryArgument(3, resultBuffer); // set the integer array
        // execute kernel
        queue.ExecuteTask(kernel, null);
        // wait for completion
        queue.Finish();
        GCHandle arrCHandle = GCHandle.Alloc(r3, GCHandleType.Pinned);

        queue.Read <int>(resultBuffer, true, 0, r3.Length, arrCHandle.AddrOfPinnedObject(), null);
        Console.WriteLine("display result from gpu buffer:");
        for (int i = 0; i < r3.Length; i++)
        {
            Console.WriteLine(r3[i]);
        }
        arrCHandle.Free();
        row1Buffer.Dispose();
        row2Buffer.Dispose();
        kernel.Dispose();
        program.Dispose();
        queue.Dispose();
        context.Dispose();
        Console.WriteLine("Finished");
        Console.ReadKey();
    }
        /// <summary>
        /// Creates a new context on a collection of devices.
        /// </summary>
        /// <param name="devices"> A collection of devices to associate with the context. </param>
        /// <param name="properties"> A list of context properties of the context. </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 context. 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 context is disposed. If <paramref name="notify"/> is <c>null</c>, no callback function is registered. </param>
        /// <param name="notifyDataPtr"> Optional user data that will be passed to <paramref name="notify"/>. </param>
        public IComputeContext CreateContext(ICollection <IComputeDevice> devices, List <ComputeContextProperty> properties,
                                             ComputeContextNotifier notify, IntPtr notifyDataPtr)
        {
            var context       = new ComputeContext120();
            var deviceHandles = ComputeTools.ExtractHandles(devices, out int handleCount);
            var propertyArray = context.ToIntPtrArray(properties);

            context.Handle = OpenCL120.CreateContext(
                propertyArray,
                handleCount,
                deviceHandles,
                notify,
                notifyDataPtr,
                out ComputeErrorCode error);
            ComputeException.ThrowOnError(error);

            context.SetID(context.Handle.Value);
            var platformProperty = context.GetByName(properties, ComputeContextPropertyName.Platform);

            context.Platform = ComputePlatform.GetByHandle(platformProperty.Value);
            context.Devices  = context.GetDevices();

            logger.Info("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
            return(context);
        }
Example #9
0
        public static void Initialize(ComputeDeviceTypes selectedComputeDeviceTypes, int platformId = 0, int deviceIndex = 0)
        {
            Platform = ComputePlatform.Platforms[platformId];

            Devices = Platform
                      .Devices
                      .Where(d => (long)d.Type == (long)selectedComputeDeviceTypes)
                      .ToArray();

            DeviceIndex = deviceIndex;

            if (Devices.Length > 0)
            {
                Context = new ComputeContext(
                    Devices,
                    new ComputeContextPropertyList(Platform),
                    null,
                    IntPtr.Zero
                    );

                CommandQueue = new ComputeCommandQueue(
                    Context,
                    Devices[DeviceIndex],
                    ComputeCommandQueueFlags.None
                    );

                Enable = true;
            }
        }
Example #10
0
 private GpuPlatform(ComputePlatform platform)
 {
     Platform = platform;
     if (isGpuProcessor(Platform.Name))
     {
         foreach (var device in platform.Devices)
         {
             if (device.Type == ComputeDeviceTypes.Gpu)
             {
                 HasGpu = true;
             }
         }
         if (HasGpu)
         {
             Properties       = new ComputeContextPropertyList(platform);
             Context          = new ComputeContext(platform.Devices, Properties, null, IntPtr.Zero);
             CommandQueueList = new List <ComputeCommandQueue>();
             for (int i = 0; i < platform.Devices.Count; i++)
             {
                 if (platform.Devices[i].Type == ComputeDeviceTypes.Gpu)
                 {
                     CommandQueueList.Add(new ComputeCommandQueue(Context, platform.Devices[i], ComputeCommandQueueFlags.None));
                 }
             }
             Programs = new List <ProgramKernel>();
         }
     }
 }
        public BlockedMatMulThread(ComputePlatform platform, ComputeDevice device, int inN, float[] inA, float[] inB)
        {
            ComputeDevice[] devices = { device };
            context = new ComputeContext(devices, new ComputeContextPropertyList(platform), null, IntPtr.Zero);
            program = new ComputeProgram(context, clProgramSource);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch (BuildProgramFailureComputeException e)
            {
                string buildLog = program.GetBuildLog(device);
                Console.WriteLine(buildLog);
                throw;
            }
            kernel = program.CreateKernel("mmul");
            queue  = new ComputeCommandQueue(context, device, ComputeCommandQueueFlags.None);

            n = inN;
            a = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, inA);
            b = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, inB);
            int resultCount = (int)(device.MaxMemoryAllocationSize / n / n / sizeof(float));

            results = new ComputeBuffer <float> [resultCount];
            for (int i = 0; i < results.Length; ++i)
            {
                results[i] = new ComputeBuffer <float>(context, ComputeMemoryFlags.WriteOnly, n * n);
            }

            HaltRequested     = false;
            operationCounter  = 0;
            completionCounter = 0;
            startTime         = 0;
        }
Example #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Julia"/> class.
        /// </summary>
        public Julia()
            : base()
        {
            this.Mode = ConcurrencyMode.SequentialCPU;

            this.options = new ParallelOptions();

            this.options.MaxDegreeOfParallelism = Environment.ProcessorCount;

            // Initialize OpenCL.
            platform   = ComputePlatform.Platforms[0];
            properties = new ComputeContextPropertyList(platform);
            context    = new ComputeContext(platform.Devices,
                                            properties, null, IntPtr.Zero);

            // Create the OpenCL kernel.
            program = new ComputeProgram(context, new string[] { kernelSource });
            program.Build(null, "-cl-mad-enable", null, IntPtr.Zero);
            kernel = program.CreateKernel("julia");

            // Create objects needed for kernel launch/execution.
            commands = new ComputeCommandQueue(context,
                                               context.Devices[0], ComputeCommandQueueFlags.None);
            events = new ComputeEventList();
        }
Example #13
0
        public OpenCLProxy(bool useSoftware = false)
        {
            HardwareAccelerationEnabled = ComputePlatform.Platforms.Count != 0 && !useSoftware;

            if (HardwareAccelerationEnabled)
            {
                ComputePlatform platform = ComputePlatform.Platforms[0];
                var             devices  = new List <ComputeDevice> {
                    platform.Devices[0]
                };
                var properties = new ComputeContextPropertyList(platform);

                _context  = new ComputeContext(devices, properties, null, IntPtr.Zero);
                _commands = new ComputeCommandQueue(_context, _context.Devices[0], ComputeCommandQueueFlags.None);

                _intComputeBuffers   = new Dictionary <string, ComputeBuffer <int> >();
                _floatComputeBuffers = new Dictionary <string, ComputeBuffer <float> >();

                AcceleratorName = platform.Name;
            }
            else
            {
                AcceleratorName = "CPU";
            }

            _intArguments = new Dictionary <string, int>();
            _intBuffers   = new Dictionary <string, int[]>();

            _floatArguments = new Dictionary <string, float>();
            _floatBuffers   = new Dictionary <string, float[]>();

            _doubleArguments = new Dictionary <string, double>();
        }
Example #14
0
        public rayTracerUI()
        {
            InitializeComponent();

            // pick first platform
            platform = ComputePlatform.Platforms[0];

            // create context with all gpu devices
            context = new ComputeContext(ComputeDeviceTypes.Gpu,
                                         new ComputeContextPropertyList(platform), null, IntPtr.Zero);

            // create a command queue with first gpu found
            queue = new ComputeCommandQueue(context,
                                            context.Devices[0], ComputeCommandQueueFlags.None);

            // load opencl source
            streamReader = new StreamReader("../../kernels.cl");
            string clSource = streamReader.ReadToEnd();

            streamReader.Close();

            // create program with opencl source
            program = new ComputeProgram(context, clSource);

            // compile opencl source
            //program.Build(null, null, null, IntPtr.Zero);

            // load chosen kernel from program
            // kernel = program.CreateKernel("findIntersection");

            threadsTxt.Text = Environment.ProcessorCount.ToString();
        }
Example #15
0
        public static Tuple <List <List <int> >, TimeSpan> MultiplyParallel(List <List <int> > matrixOne, List <List <int> > matrixTwo)
        {
            if (!isRegularMatrix(matrixOne) || !isRegularMatrix(matrixTwo))
            {
                throw new ArgumentException("Non regular matrix detected. Rows size mismatch detected.");
            }
            if (matrixOne[0].Count != matrixTwo.Count)
            {
                throw new ArgumentException("Matrixes is not compatible. Columns count of first matrix is not equal to rows count of second matrix.");
            }
            List <List <int> > result   = new List <List <int> >();
            ComputePlatform    platform = GetGPU();

            if (platform is null)
            {
                throw new PlatformNotSupportedException("Platform doesn't have a dedicated GPU. Run is impossible.");
            }
            ComputeContext      context = new ComputeContext(ComputeDeviceTypes.Gpu, new ComputeContextPropertyList(platform), null, IntPtr.Zero);
            ComputeCommandQueue queue   = new ComputeCommandQueue(context, context.Devices[0], ComputeCommandQueueFlags.None);
            ComputeProgram      program = new ComputeProgram(context, CalculateKernel);

            program.Build(null, null, null, IntPtr.Zero);
            ComputeKernel kernel = program.CreateKernel("Multiply");

            List <ComputeBuffer <int> > rowsMatrixOne    = matrixOne.TransformMatrixToComputerBuffersOfRows(context);
            List <ComputeBuffer <int> > columnsMatrixTwo = matrixTwo.TransformMatrixToComputerBuffersOfColumns(context);
            List <ComputeBuffer <int> > resultRowsMatrix = TwoDToOneDResult(matrixOne.Count, matrixTwo[0].Count, context);

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            for (int i = 0; i < resultRowsMatrix.Count; ++i)
            {
                for (int j = 0; j < resultRowsMatrix[i].Count; ++j)
                {
                    kernel.SetMemoryArgument(0, rowsMatrixOne[i]);
                    kernel.SetMemoryArgument(1, columnsMatrixTwo[j]);
                    kernel.SetMemoryArgument(2, resultRowsMatrix[i]);
                    kernel.SetValueArgument(3, matrixTwo.Count);
                    kernel.SetValueArgument(4, j);

                    queue.ExecuteTask(kernel, null);
                }
            }

            queue.Finish();
            stopwatch.Stop();

            for (int i = 0; i < resultRowsMatrix.Count; ++i)
            {
                int[]    res      = new int[resultRowsMatrix[i].Count];
                GCHandle gCHandle = GCHandle.Alloc(res, GCHandleType.Pinned);
                queue.Read <int>(resultRowsMatrix[i], true, 0, res.Length, gCHandle.AddrOfPinnedObject(), null);
                result.Add(new List <int>(res));
            }

            return(new Tuple <List <List <int> >, TimeSpan>(result, stopwatch.Elapsed));
        }
Example #16
0
        private static ComputeCommandQueue QueueWithDevice(ComputeDevice device)
        {
            List <ComputeDevice>       devices    = new List <ComputeDevice>(new ComputeDevice[] { device });
            ComputePlatform            platform   = device.Platform;
            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform);
            ComputeContext             context    = new ComputeContext(device.Type, properties, null, IntPtr.Zero);

            return(new ComputeCommandQueue(context, context.Devices.FirstOrDefault(), context.Devices.FirstOrDefault().CommandQueueFlags));
        }
Example #17
0
        public static GpuPlatform IsGpuProcesser(ComputePlatform platform)
        {
            GpuPlatform item = new GpuPlatform(platform);

            if (item.HasGpu)
            {
                return(item);
            }
            return(null);
        }
Example #18
0
 public void InitializePlatformPropertiesAndDevices()
 {
     platform   = ComputePlatform.Platforms[0];
     properties = new ComputeContextPropertyList(platform);
     devices    = new List <ComputeDevice>();
     foreach (ComputeDevice device in platform.Devices)
     {
         devices.Add(device);
     }
 }
Example #19
0
        //Initializing everything OpenGL related
        public void OpenGLInit()
        {
            ComputePlatform platform = null;
            ComputeDevice   device   = null;

            for (int p = 0; p < ComputePlatform.Platforms.Count; ++p)
            {
                platform = ComputePlatform.Platforms[p];

                /*Console.WriteLine
                 * ("Platform {0} \"{1}\" has {2} devices attached"
                 * , p
                 * , platform.Name
                 * , platform.Devices.Count);*/

                for (int d = 0; d < platform.Devices.Count; d++)
                {
                    device = platform.Devices[d];
                    //Console.WriteLine("  device [{0}]: {1}", d, device.Name);
                }
            }

            context = new ComputeContext(
                ComputeDeviceTypes.Gpu,
                new ComputeContextPropertyList(platform),
                null,
                IntPtr.Zero);

            queue = new ComputeCommandQueue
                        (context
                        , device
                        , ComputeCommandQueueFlags.Profiling // enable event timing
                        );

            StreamReader reader = new StreamReader("../../GameOfLife.cl");
            string       source = reader.ReadToEnd();

            reader.Close();
            //Console.WriteLine(source);

            program = new ComputeProgram(context, source);
            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch
            {
                Console.WriteLine(program.GetBuildLog(device));   // error log
                System.Environment.Exit(7);
            }
            Console.WriteLine(program.GetBuildLog(device));     // warnings
        }
Example #20
0
        private void LoadProgram()
        {
            this.platform   = ComputePlatform.Platforms[0];
            this.properties = new ComputeContextPropertyList(this.platform);
            this.Context    = new ComputeContext(this.platform.Devices, this.properties, null, IntPtr.Zero);

            this.program = new ComputeProgram(this.Context, new[] { this.sourceProgram.Source });
            this.program.Build(null, "-cl-mad-enable", null, IntPtr.Zero);
            this.Kernel = this.program.CreateKernel(this.sourceProgram.Name);

            this.Commands = new ComputeCommandQueue(this.Context, this.Context.Devices[0], ComputeCommandQueueFlags.None);
            this.Events   = new ComputeEventList();
        }
Example #21
0
 void comboBoxPlatform_SelectedIndexChanged(object sender, EventArgs e)
 {
     devices.Clear();
     platform = ComputePlatform.Platforms[comboBoxPlatform.SelectedIndex];
     object[] availableDevices = new object[platform.Devices.Count];
     for (int i = 0; i < availableDevices.Length; i++)
     {
         availableDevices[i] = platform.Devices[i].Name;
     }
     checkedListDevices.Items.Clear();
     checkedListDevices.Items.AddRange(availableDevices);
     checkedListDevices.SetItemChecked(0, true);
 }
Example #22
0
        public static IGpuHelper CreateHelper(ComputePlatform platform, ComputeDevice device, FPType fptype)
        {
            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform);
            var context = new ComputeContext(new[] { device }, properties, null, IntPtr.Zero);

            if (fptype == FPType.Single)
            {
                return(new GpuHelper <float>(context, fptype));
            }
            else
            {
                return(new GpuHelper <double>(context, fptype));
            }
        }
Example #23
0
        public PrOpenClCalculation()
        {
            m_Platform       = ComputePlatform.Platforms.First();
            m_Device         = m_Platform.Devices.First();
            m_ComputeContext = new ComputeContext(new [] { m_Device }, new ComputeContextPropertyList(m_Platform), null, IntPtr.Zero);
            m_CommandQueue   = new ComputeCommandQueue(m_ComputeContext, m_Device, ComputeCommandQueueFlags.None);
            m_Program        = new ComputeProgram(m_ComputeContext, ProgramSource);
            m_Program.Build(new [] { m_Device }, "", null, IntPtr.Zero);
            m_Kernel = m_Program.CreateKernel("Test");

            long count = 100;

            var result = new int[count];
            var a      = new int[count];

            for (int i = 0; i < count; i++)
            {
                a[i] = i;
            }

            var resultDev = new ComputeBuffer <int>(m_ComputeContext,
                                                    ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.UseHostPointer,
                                                    result);

            var aDev = new ComputeBuffer <int>(m_ComputeContext,
                                               ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.UseHostPointer,
                                               a);


            var bDev = new ComputeBuffer <int>(m_ComputeContext,
                                               ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.UseHostPointer,
                                               a);

            //Задаем их для нашего ядра
            m_Kernel.SetMemoryArgument(0, resultDev);
            m_Kernel.SetMemoryArgument(1, aDev);
            m_Kernel.SetMemoryArgument(2, bDev);

            //Вызываем ядро количество потоков равно count
            m_CommandQueue.Execute(m_Kernel, null, new[] { count }, null, null);

            //Читаем результат из переменной
            m_CommandQueue.ReadFromBuffer(resultDev, ref result, true, null);

            //Выводим результат
            foreach (var i in result)
            {
                Console.WriteLine(i);
            }
        }
Example #24
0
        public Render(
            ComputeDevice cDevice,
            string kernelSource,
            uint width, uint height,
            uint workers,
            float reMin  = -2.0f,
            float reMax  = 1.0f,
            float imMin  = -1.0f,
            float imMax  = 1.0f,
            uint maxIter = 200)
        {
            this.width   = width;
            this.height  = height;
            this.workers = workers;
            this.reMin   = reMin;
            this.reMax   = reMax;
            this.imMin   = imMin;
            this.imMax   = imMax;
            this.maxIter = maxIter;

            clPlatform   = cDevice.Platform;
            clProperties = new ComputeContextPropertyList(clPlatform);
            clContext    = new ComputeContext(clPlatform.Devices, clProperties, null, IntPtr.Zero);
            clCommands   = new ComputeCommandQueue(clContext, cDevice, ComputeCommandQueueFlags.None);
            clProgram    = new ComputeProgram(clContext, new string[] { kernelSource });

            h_resultBuf     = new byte[width * height * 4];
            gc_resultBuffer = GCHandle.Alloc(h_resultBuf, GCHandleType.Pinned);

            int i = kernelSource.IndexOf("__kernel");

            if (i > -1)
            {
                int j = kernelSource.IndexOf("(", i);
                if (j > -1)
                {
                    string   raw   = kernelSource.Substring(i + 8, j - i - 8);
                    string[] parts = raw.Trim().Split(' ');
                    for (int k = parts.Length - 1; k != 0; k--)
                    {
                        if (!string.IsNullOrEmpty(parts[k]))
                        {
                            KernelName = parts[k];
                            break;
                        } // if
                    }     // for k
                }         // if j
            }             // if i
        }
Example #25
0
        /// <summary>
        /// Creates a new context on all the devices that match the specified <see cref="ComputeDeviceTypes"/>.
        /// </summary>
        /// <param name="deviceType"> A bit-field that identifies the type of device to associate with the context. </param>
        /// <param name="properties"> A list of context properties of the context. </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 context. 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 context 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 IComputeContext CreateContext(ComputeDeviceTypes deviceType, List <ComputeContextProperty> properties,
                                             ComputeContextNotifier notify, IntPtr userDataPtr)
        {
            var context       = new ComputeContext100();
            var propertyArray = context.ToIntPtrArray(properties);

            context.Handle = OpenCL100.CreateContextFromTypeWrapper(propertyArray, deviceType, notify, userDataPtr);
            context.SetID(context.Handle.Value);
            var platformProperty = context.GetByName(properties, ComputeContextPropertyName.Platform);

            context.Platform = ComputePlatform.GetByHandle(platformProperty.Value);
            context.Devices  = context.GetDevices();
            logger.Info("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
            return(context);
        }
Example #26
0
        /// <summary>
        /// Compiles the OpenCL program on a given platform
        /// </summary>
        /// <param name="platform">The platform to run this program on</param>
        public void Compile(ComputePlatform platform)
        {
            if (context != null)
            {
                return;
            }

            // Creating context on platform
            context = new ComputeContext(ComputeDeviceTypes.All, new ComputeContextPropertyList(platform), null, IntPtr.Zero); // CPU Fallback?

            // Reading the static source file
            string include = Resources.noise;

            // Stub
            string stub =
                @"
            __kernel void cl_main(__global Single3 *input, __global int *perm, __global float *output) { 
                int index = get_global_id(0);
                Single3 in_pos = input[index];      
                output[index] = " + module.Code + @";
            }

            __kernel void cl_main_range(ImplicitCube cube, __global int *perm, __global float *output) {
                int index = cube.lengthY * cube.lengthX * get_global_id(2) + cube.lengthX * get_global_id(1) + get_global_id(0);
                Single3 in_pos = { cube.startX + get_global_id(0) * cube.offsetX, cube.startY + get_global_id(1) * cube.offsetY, cube.startZ + get_global_id(2) * cube.offsetZ };
                output[index] = " + module.Code + @";
            }";

            completeSource = include + stub;

            ComputeProgram program = new ComputeProgram(context, completeSource);

            try
            {
                program.Build(context.Platform.Devices, null, null, IntPtr.Zero);
            }
            catch
            {
                // TODO: Replace this nasty exception re-throwing
                throw new Exception(program.GetBuildLog(program.Devices[0]));
            }

            kernelExplicit = program.CreateKernel("cl_main");
            kernelImplicit = program.CreateKernel("cl_main_range");

            setupPermutationBuffer();
            queue = new ComputeCommandQueue(context, context.Devices[0], ComputeCommandQueueFlags.None);
        }
Example #27
0
        private void PlatformCombox_SelectedIndexChanged(object sender, EventArgs e)
        {
            var comboBox = sender as ComboBox;

            if (comboBox == null)
            {
                return;
            }

            _selectedComputePlatform = (ComputePlatform)comboBox.SelectedItem;

            DeviceCombox.DataSource    = _selectedComputePlatform.Devices.ToList();
            DeviceCombox.DisplayMember = "Name";

            Console.WriteLine("Selected platform : " + _selectedComputePlatform.Name);
        }
Example #28
0
        private void DeviceCombox_SelectedIndexChanged(object sender, EventArgs e)
        {
            var comboBox = sender as ComboBox;

            if (comboBox == null)
            {
                return;
            }

            var selectedDevice = (ComputeDevice)comboBox.SelectedItem;

            Console.WriteLine("Selected device : " + selectedDevice.Name);

            _selectedComputePlatform = (ComputePlatform)PlatformCombox.SelectedItem;
            _selectedComputeDevice   = (ComputeDevice)DeviceCombox.SelectedItem;
        }
Example #29
0
        //ComputeBuffer<int> input5_dev;

        public override void Init()
        {
            // pick first platform
            ComputePlatform platform = ComputePlatform.Platforms[0];

            // create context with all gpu devices
            ComputeContext context = new ComputeContext(ComputeDeviceTypes.Gpu, new ComputeContextPropertyList(platform), null, IntPtr.Zero);

            // create a command queue with first gpu found
            queue = new ComputeCommandQueue(context, context.Devices[0], ComputeCommandQueueFlags.None);

            // load opencl source
            StreamReader streamReader = new StreamReader("main.cl");
            string       clSource     = streamReader.ReadToEnd();

            streamReader.Close();

            // create program with opencl source
            ComputeProgram program = new ComputeProgram(context, clSource);

            // compile opencl source
            program.Build(null, null, null, IntPtr.Zero);

            result_dev     = new ComputeBuffer <byte>(context, ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.AllocateHostPointer, results.Length);
            resultCalc_dev = new ComputeBuffer <double>(context, ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.AllocateHostPointer, calculatables.Length);

            // init input parameters
            input1_dev = new ComputeBuffer <int>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, DataGenerator.In1);
            input2_dev = new ComputeBuffer <int>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, DataGenerator.In2);
            input3_dev = new ComputeBuffer <double>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, DataGenerator.In3);
            input4_dev = new ComputeBuffer <byte>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, DataGenerator.In4_3_bytes);
            //input5_dev = new ComputeBuffer<int>(context, ComputeMemoryFlags.ReadOnly, DataFeeder.width);

            // load chosen kernel from program
            kernel = program.CreateKernel("Proccess");

            int i = 0;

            kernel.SetMemoryArgument(i++, result_dev);
            kernel.SetMemoryArgument(i++, resultCalc_dev);
            kernel.SetMemoryArgument(i++, input1_dev);
            kernel.SetMemoryArgument(i++, input2_dev);
            kernel.SetMemoryArgument(i++, input3_dev);
            kernel.SetMemoryArgument(i++, input4_dev);
            kernel.SetValueArgument(i++, DataGenerator.Width);
            kernel.SetValueArgument(i++, DataGenerator.Height);
        }
        /// <summary>
        /// Construct an OpenCL platform.
        /// </summary>
        ///
        /// <param name="platform">The OpenCL platform.</param>
        public EncogCLPlatform(ComputePlatform platform)
        {
            this.platform = platform;
            this.devices  = new List <EncogCLDevice>();
            ComputeContextPropertyList cpl = new ComputeContextPropertyList(platform);

            this.context = new ComputeContext(ComputeDeviceTypes.Default, cpl, null, IntPtr.Zero);
            this.Name    = platform.Name;
            this.Vender  = platform.Vendor;
            this.Enabled = true;

            foreach (ComputeDevice device in context.Devices)
            {
                EncogCLDevice adapter = new EncogCLDevice(this, device);
                this.devices.Add(adapter);
            }
        }
Example #31
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="platform"></param>
        public CLx(ComputePlatform platform)
        {
            if (platform.Extensions.Contains("cl_ext_device_fission"))
            {
                clCreateSubDevicesEXT = (Delegates.clCreateSubDevicesEXT)Marshal.GetDelegateForFunctionPointer(CL10.GetExtensionFunctionAddress("clCreateSubDevicesEXT"), typeof(Delegates.clCreateSubDevicesEXT));
                clReleaseDeviceEXT = (Delegates.clReleaseDeviceEXT)Marshal.GetDelegateForFunctionPointer(CL10.GetExtensionFunctionAddress("clReleaseDeviceEXT"), typeof(Delegates.clReleaseDeviceEXT));
                clRetainDeviceEXT = (Delegates.clRetainDeviceEXT)Marshal.GetDelegateForFunctionPointer(CL10.GetExtensionFunctionAddress("clRetainDeviceEXT"), typeof(Delegates.clRetainDeviceEXT));
            }

            if (platform.Extensions.Contains("cl_ext_migrate_memobject"))
                clEnqueueMigrateMemObjectEXT = (Delegates.clEnqueueMigrateMemObjectEXT)Marshal.GetDelegateForFunctionPointer(CL10.GetExtensionFunctionAddress("clEnqueueMigrateMemObjectEXT"), typeof(Delegates.clEnqueueMigrateMemObjectEXT));

            if (platform.Extensions.Contains("cl_khr_gl_sharing"))
                clGetGLContextInfoKHR = (Delegates.clGetGLContextInfoKHR)Marshal.GetDelegateForFunctionPointer(CL10.GetExtensionFunctionAddress("clGetGLContextInfoKHR"), typeof(Delegates.clGetGLContextInfoKHR));

            if (platform.Extensions.Contains("cl_khr_icd"))
                clIcdGetPlatformIDsKHR = (Delegates.clIcdGetPlatformIDsKHR)Marshal.GetDelegateForFunctionPointer(CL10.GetExtensionFunctionAddress("clIcdGetPlatformIDsKHR"), typeof(Delegates.clIcdGetPlatformIDsKHR));
        }
Example #32
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="platform"></param>
        public CLx(ComputePlatform platform)
        {
            if (platform.Extensions.Contains("cl_ext_device_fission") && !CLInterface.IsOpenCL12Available())
            {
                clCreateSubDevicesEXT = (Delegates.clCreateSubDevicesEXT)Marshal.GetDelegateForFunctionPointer(CLInterface.CL11.GetExtensionFunctionAddress("clCreateSubDevicesEXT"), typeof(Delegates.clCreateSubDevicesEXT));
                clReleaseDeviceEXT = (Delegates.clReleaseDeviceEXT)Marshal.GetDelegateForFunctionPointer(CLInterface.CL11.GetExtensionFunctionAddress("clReleaseDeviceEXT"), typeof(Delegates.clReleaseDeviceEXT));
                clRetainDeviceEXT = (Delegates.clRetainDeviceEXT)Marshal.GetDelegateForFunctionPointer(CLInterface.CL11.GetExtensionFunctionAddress("clRetainDeviceEXT"), typeof(Delegates.clRetainDeviceEXT));
            }

            if (platform.Extensions.Contains("cl_ext_migrate_memobject") && !CLInterface.IsOpenCL12Available())
                clEnqueueMigrateMemObjectEXT = (Delegates.clEnqueueMigrateMemObjectEXT)Marshal.GetDelegateForFunctionPointer(CLInterface.CL11.GetExtensionFunctionAddress("clEnqueueMigrateMemObjectEXT"), typeof(Delegates.clEnqueueMigrateMemObjectEXT));

            if (platform.Extensions.Contains("cl_khr_gl_sharing"))
            {
                if (!CLInterface.IsOpenCL12Available()) clGetGLContextInfoKHR = (Delegates.clGetGLContextInfoKHR)Marshal.GetDelegateForFunctionPointer(CLInterface.CL11.GetExtensionFunctionAddress("clGetGLContextInfoKHR"), typeof(Delegates.clGetGLContextInfoKHR));
                else clGetGLContextInfoKHR = (Delegates.clGetGLContextInfoKHR)Marshal.GetDelegateForFunctionPointer(CLInterface.CL12.GetExtensionFunctionAddressForPlatform(platform.Handle, "clGetGLContextInfoKHR"), typeof(Delegates.clGetGLContextInfoKHR));
            }
            //if (platform.Extensions.Contains("cl_khr_icd"))
            //    clIcdGetPlatformIDsKHR = (Delegates.clIcdGetPlatformIDsKHR)Marshal.GetDelegateForFunctionPointer(CLBindings.cl12.GetExtensionFunctionAddress("clIcdGetPlatformIDsKHR"), typeof(Delegates.clIcdGetPlatformIDsKHR));
        }