Esempio n. 1
0
        public static Device[] GetAllDevices()
        {
            var computeDeviceArrayList = new ArrayList();

            foreach (var platform in ComputePlatform.Platforms)
            {
                IList <ComputeDevice> openclDevices = platform.Devices;
                var properties = new ComputeContextPropertyList(platform);
                using (var context = new ComputeContext(openclDevices, properties, null, IntPtr.Zero))
                {
                    foreach (var openclDevice in context.Devices)
                    {
                        if (IsOpenCLDeviceIgnored(openclDevice))
                        {
                            continue;
                        }
                        computeDeviceArrayList.Add(openclDevice);
                    }
                }
            }
            var computeDevices = Array.ConvertAll(computeDeviceArrayList.ToArray(), item => (ComputeDevice)item);

            Device[] devices     = new Device[computeDevices.Length];
            var      deviceIndex = 0;

            foreach (var computeDevice in computeDevices)
            {
                devices[deviceIndex] = new Device(deviceIndex, computeDevice);
                deviceIndex++;
            }

            return(devices);
        }
Esempio n. 2
0
        void InitComputeKernel()
        {
            if (this.openCLSources == null)
            {
                GetOpenCLSources();
            }

            var properties = new ComputeContextPropertyList(this.computeDevice.Platform);

            this.computeContext = new ComputeContext(new[] { this.computeDevice }, properties, null, IntPtr.Zero);
            this.computeProgram = new ComputeProgram(this.computeContext, this.openCLSources);

            try
            {
                this.computeProgram.Build(new[] { this.computeDevice }, null, null, IntPtr.Zero);
            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(computeProgram.GetBuildLog(this.computeDevice));
            }

            this.computeKernels = this.computeProgram.CreateAllKernels().ToList();
            this.computeKernel  = this.computeKernels.First(k => k.FunctionName == openCLKernelFunction);
        }
Esempio n. 3
0
        private void buttonRunAll_Click(object sender, EventArgs e)
        {
            if (devices.Count == 0)
            {
                MessageBox.Show("No OpenCL device selected!\n\nSelect one or more devices from the list to continue.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            StringBuilder output = new StringBuilder();
            StringWriter  log    = new StringWriter(output);

            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform);
            ComputeContext             context    = new ComputeContext(devices, properties, null, IntPtr.Zero);

            for (int i = 0; i < exampleList.Count; i++)
            {
                if (checkedListExamples.GetItemChecked(i))
                {
                    log.WriteLine("--------------------------------------------------------------------------------");
                    log.WriteLine("Running \"" + exampleList[i].Name + "\"...");
                    log.WriteLine();
                    exampleList[i].Run(context, log);
                    log.WriteLine();
                    log.WriteLine("\"" + exampleList[i].Name + "\" finished.");
                    log.WriteLine("--------------------------------------------------------------------------------");
                    log.Flush();
                }
            }

            log.Close();

            textBoxLog.Lines = ParseLines(output.ToString());
        }
Esempio n. 4
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>();
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            PlotInterval           interval;
            AproximationExpression expression;

            LoadInput(out expression, out interval);


            var platform = LoadPlatform();

            var device = LoadDevice(platform);

            var properties = new ComputeContextPropertyList(platform);
            var context    = new ComputeContext(device.Type, properties, null, IntPtr.Zero);


            var bhcl = new BicubicHermiteCl(context);
            var sw   = Stopwatch.StartNew();
            var mesh = bhcl.CreateMesh(expression, interval);
            var time = sw.ElapsedMilliseconds;

            sw.Stop();

            Console.WriteLine("Cas vypoctu: " + time + " ms.");
            Console.ReadLine();
        }
Esempio n. 6
0
        public string vectorSum()
        {
            string vecSum = @"
                __kernel void vectorSum(__global float *v1, __global float *v2, __global float *v3) {
                    int i = get_global_id(0);
                    v3[i] = v1[i] + v2[i];
                }
            ";
            int    size   = 100000;

            float[] v1_ = new float[size];
            float[] v2_ = new float[size];
            float[] v3_ = new float[size];
            for (var i = 0; i < size; i++)
            {
                v1_[i] = (float)i;
                v2_[i] = (float).5f;
            }
            var platform_ = ComputePlatform.Platforms[0];
            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform_);
            ComputeContext             ctx        = new ComputeContext(ComputeDeviceTypes.Gpu, properties, null, IntPtr.Zero);
            ComputeCommandQueue        commands   = new ComputeCommandQueue(ctx, ctx.Devices[0], ComputeCommandQueueFlags.None);
            ComputeProgram             program    = new ComputeProgram(ctx, vecSum);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
                Console.WriteLine("program build completed");
            }
            catch
            {
                string log = program.GetBuildLog(ctx.Devices[0]);
            }
            ComputeBuffer <float> v1, v2, v3;

            v1 = new ComputeBuffer <float>(ctx, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, v1_);
            v2 = new ComputeBuffer <float>(ctx, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, v2_);
            v3 = new ComputeBuffer <float>(ctx, ComputeMemoryFlags.WriteOnly | ComputeMemoryFlags.CopyHostPointer, v3_);
            long[] worker = { size };
            commands.WriteToBuffer(v1_, v1, false, null);
            commands.WriteToBuffer(v2_, v2, false, null);
            ComputeKernel sumKernal = program.CreateKernel("vectorSum");

            Console.WriteLine("kernal created");
            sumKernal.SetMemoryArgument(0, v1);
            sumKernal.SetMemoryArgument(1, v2);
            sumKernal.SetMemoryArgument(2, v3);
            commands.Execute(sumKernal, null, worker, null, null);
            Console.WriteLine("Executed");
            commands.ReadFromBuffer <float>(v3, ref v3_, false, null);
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < size; i++)
            {
                sb.AppendFormat("{0} + {1} = {2}<br>", v1_[i].ToString(), v2_[i].ToString(), v3_[i].ToString());
            }
            var sum_expression_result = sb.ToString();

            return(sum_expression_result);
        }
Esempio n. 7
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;
        }
Esempio n. 8
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>();
         }
     }
 }
Esempio n. 9
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();
        }
Esempio n. 10
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>();
        }
Esempio n. 11
0
        public virtual void Initialize() {
            platform = ComputePlatform.Platforms[0];
            device = platform.Devices[0];

            properties = new ComputeContextPropertyList(platform);
            context = new ComputeContext(new[] { device }, properties, null, IntPtr.Zero);
            program = new ComputeProgram(context, KernelSrc);
        }
Esempio n. 12
0
 public FindPointOpenCl()
 {
     cpl     = new ComputeContextPropertyList(ComputePlatform.Platforms[0]);
     context = new ComputeContext(ComputeDeviceTypes.Gpu, cpl, null, IntPtr.Zero);
     program = new ComputeProgram(context, new string[] { FindPointCalculationGpu });
     program.Build(null, null, null, IntPtr.Zero);
     kernel = program.CreateKernel("FindPointCalculationGpu");
 }
Esempio n. 13
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));
        }
Esempio n. 14
0
        private async void buttonRunAll_Click(object sender, EventArgs e)
        {
            if (devices.Count == 0)
            {
                MessageBox.Show("No OpenCL device selected!\n\nSelect one or more devices from the list to continue.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            StringBuilder output = new StringBuilder();
            StringWriter  log    = new StringWriter(output);

            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform);
            ComputeContext             context    = new ComputeContext(devices, properties, null, IntPtr.Zero);

            this.buttonRunAll.Enabled  = false;
            this.buttonCopyLog.Enabled = false;

            textBoxLog.Lines = new [] { "Started" };
            try
            {
                for (int i = 0; i < exampleList.Count; i++)
                {
                    if (checkedListExamples.GetItemChecked(i))
                    {
                        log.WriteLine("--------------------------------------------------------------------------------");
                        log.WriteLine($"Running \"{exampleList[i].Name}\"...");
                        log.WriteLine();
                        await Task.Run(() => exampleList[i].Run(context, log));

                        log.WriteLine();
                        log.WriteLine($"\"{exampleList[i].Name}\" finished.");
                        log.WriteLine("--------------------------------------------------------------------------------");
                        log.Flush();

                        textBoxLog.Lines          = ParseLines(output.ToString());
                        textBoxLog.SelectionStart = textBoxLog.TextLength;
                        textBoxLog.ScrollToCaret();
                    }
                }
            }
            catch (Exception ex)
            {
                log.WriteLine($"Error: \"{ex.Message}\".");
            }
            finally
            {
                this.buttonRunAll.Enabled  = true;
                this.buttonCopyLog.Enabled = true;
                log.Close();

                textBoxLog.Lines = ParseLines(output.ToString());
            }

            // cleanup context!
            context.Dispose();
        }
Esempio n. 15
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);
     }
 }
Esempio n. 16
0
        public static void InitOpenCLService()
        {
            var properties = new ComputeContextPropertyList(Platform);

            context = new ComputeContext(ComputeDeviceTypes.All, properties, null, IntPtr.Zero);
            devices = new List <ComputeDevice>();
            devices.Add(Device);
            commands = new ComputeCommandQueue(context, Device, ComputeCommandQueueFlags.None);
            BuildKernels();
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            int w = 11, h = 11, sx = 5, sy = 5, iters = 2;

            var properties = new ComputeContextPropertyList(ComputePlatform.Platforms[0]);
            var context    = new ComputeContext(ComputeDeviceTypes.All, properties, null, IntPtr.Zero);
            var quene      = new ComputeCommandQueue(context, ComputePlatform.Platforms[0].Devices[0], ComputeCommandQueueFlags.None);

            //Компиляция программы
            var prog = new ComputeProgram(context, Source);

            try
            {
                prog.Build(context.Devices, "", null, IntPtr.Zero);
            }
            catch
            {
                Console.WriteLine(prog.GetBuildLog(context.Devices[0]));
            }
            //Создание ядра
            var kernel = prog.CreateKernel("Test");


            var mat = new float[w * h];

            for (int i = 0; i < w * h; i++)
            {
                mat[i] = (i == w * sy + sx) ? 1f : 0f;
            }

            var mat1 = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.UseHostPointer, mat);
            var mat2 = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadWrite, w * h);

            kernel.SetMemoryArgument(0, mat1);
            kernel.SetMemoryArgument(1, mat2);
            kernel.SetValueArgument(2, iters);
            kernel.SetValueArgument(3, w);
            kernel.SetValueArgument(4, h);

            quene.Execute(kernel, null, new long[] { (long)h, (long)w }, null, null);

            quene.ReadFromBuffer(mat1, ref mat, true, null);

            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    Console.Write($"{mat[i*w+j]:.00} ");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
        protected OpenCLMiner(ComputeDevice aDevice, int aDeviceIndex, String aAlgorithmName)
            : base(aDeviceIndex, aAlgorithmName)
        {
            mDevice = aDevice;
            List <ComputeDevice> deviceList = new List <ComputeDevice>();

            deviceList.Add(mDevice);
            ComputeContextPropertyList properties = new ComputeContextPropertyList(mDevice.Platform);

            mContext = new ComputeContext(deviceList, properties, null, IntPtr.Zero);
            mQueue   = new ComputeCommandQueue(mContext, mDevice, ComputeCommandQueueFlags.None);
        }
Esempio n. 19
0
 private void ConstructOpenCLResources()
 {
     if (this.computeDevice != null)
     {
         var properties = new ComputeContextPropertyList(this.computeDevice.Platform);
         this.computeContext = new ComputeContext(new[] { this.computeDevice }, properties, null, IntPtr.Zero);
         this.computeProgram = new ComputeProgram(this.computeContext, new string[] { KernelCodeH1, KernelCodeH2, KernelCodeH3, KernelCodeH4, KernelCodeMain });
         this.computeProgram.Build(new[] { this.computeDevice }, null, null, IntPtr.Zero);
         this.computeKernels = this.computeProgram.CreateAllKernels().ToList();
         this.computeKernel  = this.computeKernels.First((k) => k.FunctionName == KernelFunction);
     }
 }
Esempio n. 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();
        }
Esempio n. 21
0
        private static ComputeContext GetContext()
        {
            if (ComputePlatform.Platforms.Count > 1)
            {
                Console.WriteLine("More than one platform available, maybe branch out...");
            }

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

            return(context);
        }
Esempio n. 22
0
        public static CLContext CreateContextForDevices(params ComputeDevice[] devices)
        {
            var platform = devices[0].Platform;

            if (!devices.All(d => d.Platform == platform))
            {
                throw new ArgumentException("Devices must belong to the same platform");
            }
            var col   = new List <ComputeDevice> (devices);
            var props = new ComputeContextPropertyList(platform);

            return(new CLContext(new ComputeContext(col, props, null, IntPtr.Zero)));
        }
Esempio n. 23
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));
            }
        }
Esempio n. 24
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);
            }
        }
Esempio n. 25
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
        }
Esempio n. 26
0
        public static void InitCloo()
        {
            if (kernel != null)
            {
                return;
            }

            ComputeContextPropertyList cpl = new ComputeContextPropertyList(ComputePlatform.Platforms[0]);

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

            ComputeProgram program = new ComputeProgram(context, MatrixMultiSource);

            program.Build(null, null, null, IntPtr.Zero);

            kernel = program.CreateKernel("MatrixMulti");
        }
Esempio n. 27
0
        /// <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);
            }
        }
        /// <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);
            }

        }
Esempio n. 29
0
        public static OpenCLDevice[] GetAllOpenCLDevices()
        {
            var  computeDeviceArrayList = new ArrayList();
            bool doneWithAMD            = false;

            foreach (var platform in ComputePlatform.Platforms)
            {
                if (platform.Name == "AMD Accelerated Parallel Processing" && doneWithAMD)
                {
                    continue;
                }

                IList <ComputeDevice> openclDevices = platform.Devices;
                var properties = new ComputeContextPropertyList(platform);
                using (var context = new ComputeContext(openclDevices, properties, null, IntPtr.Zero))
                {
                    foreach (var openclDevice in context.Devices)
                    {
                        if (IsOpenCLDeviceIgnored(openclDevice))
                        {
                            continue;
                        }
                        computeDeviceArrayList.Add(openclDevice);
                    }
                }

                if (platform.Name == "AMD Accelerated Parallel Processing")
                {
                    doneWithAMD = true;
                }
            }
            var computeDevices = Array.ConvertAll(computeDeviceArrayList.ToArray(), item => (ComputeDevice)item);

            OpenCLDevice[] devices     = new OpenCLDevice[computeDevices.Length];
            var            deviceIndex = 0;

            foreach (var computeDevice in computeDevices)
            {
                devices[deviceIndex] = new OpenCLDevice(deviceIndex, computeDevice);
                deviceIndex++;
            }

            return(devices);
        }
Esempio n. 30
0
        public DoubleMatrixOpenCL(int deviceID = 0)
        {
            Func <int, string, Version, bool> deviceSelector = (i, n, v) => i == deviceID;

            deviceSelector = deviceSelector ?? ((i, d, v) => true);
            var device     = ComputePlatform.Platforms.SelectMany(p => p.Devices).Where((d, i) => deviceSelector(i, $"{d.Name} {d.DriverVersion}", d.Version)).First();
            var properties = new ComputeContextPropertyList(device.Platform);

            context = new ComputeContext(new[] { device }, properties, null, IntPtr.Zero);
            // Create the kernel function and set its arguments.
            program = new ComputeProgram(context, clProgramSourceMultiplyMatrix);

            // Create and build the opencl program.
            program.Build(null, null, null, IntPtr.Zero);
            kernel = program.CreateKernel("MatrixMultiply");

            // Create the command queue. This is used to control kernel execution and manage read/write/copy operations.
            commands = new ComputeCommandQueue(context, context.Devices[0], ComputeCommandQueueFlags.None);
        }
Esempio n. 31
0
        public static void Main(string[] args)
        {
            LoadLRIT();
            ComputePlatform[] availablePlatforms = new ComputePlatform[ComputePlatform.Platforms.Count];
            for (int i = 0; i < availablePlatforms.Length; i++)
            {
                availablePlatforms [i] = ComputePlatform.Platforms [i];
                Console.WriteLine(ComputePlatform.Platforms [i].Name);
            }

            var platform = availablePlatforms [0];

            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform);
            ComputeContext             context    = new ComputeContext(platform.Devices, properties, null, IntPtr.Zero);

            CLBuilder(context);
            CLApply2DLUT(context);
            UIConsole.Log("Finish");
        }
Esempio n. 32
0
        private void buildProgramMenuItem_Click(object sender, EventArgs e)
        {
            if (editorTextBox.Text.Length == 0)
            {
                logTextBox.Text = "No source.";
                return;
            }

            string[] logContent;

            ComputeContextPropertyList properties = new ComputeContextPropertyList(configForm.Platform);
            ComputeContext context = new ComputeContext(configForm.Devices, properties, null, IntPtr.Zero);
            ComputeProgram program = new ComputeProgram(context, editorTextBox.Text);
            try
            {
                program.Build(configForm.Devices, configForm.Options, null, IntPtr.Zero);
                logContent = new string[] { "Build succeeded." };
            }
            catch (Exception exception)
            {
                List<string> lineList = new List<string>();
                foreach (ComputeDevice device in context.Devices)
                {
                    string header = "PLATFORM: " + configForm.Platform.Name + ", DEVICE: " + device.Name;
                    lineList.Add(header);

                    StringReader reader = new StringReader(program.GetBuildLog(device));
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        lineList.Add(line);
                        line = reader.ReadLine();
                    }

                    lineList.Add("");
                    lineList.Add(exception.Message);
                }
                logContent = lineList.ToArray();
            }

            logTextBox.Lines = logContent;
        }
Esempio n. 33
0
        public void OpenClMul()
        {
            //ѡȡ�豸
            var platform   = ComputePlatform.Platforms.FirstOrDefault();
            var device     = platform.Devices.FirstOrDefault();
            var properties = new ComputeContextPropertyList(platform);
            var context    = new ComputeContext(new[] { device }, properties, null, IntPtr.Zero);
            ComputeCommandQueue commands = new ComputeCommandQueue(context, context.Devices[0],
                                                                   ComputeCommandQueueFlags.None);
            var code    = File.ReadAllText(@"demos\cls\matrix_mul.cl");
            var program = new ComputeProgram(context, code);

            try
            {
                program.Build(new [] { device }, null, null, IntPtr.Zero);
            }
            catch (Exception ex)
            {
                throw;
            }
            var kernel = program.CreateKernel("MatrixMul");
            int rank   = Rank;
            var result = new ComputeBuffer <int>(context, ComputeMemoryFlags.WriteOnly, rank * rank);
            var matrix = CreateMatrix(context, rank);

            kernel.SetMemoryArgument(0, result);
            kernel.SetMemoryArgument(1, matrix);
            kernel.SetValueArgument(2, rank);
            Console.WriteLine($"Platform: {platform.Name}\n Device: {device.Name}\n Size: {rank}x{rank}");
            Stopwatch sw = Stopwatch.StartNew();

            commands.Execute(kernel, null, new long[] { rank, rank }, null, null);
            int[] resultArray = new int[rank * rank];
            var   arrHandle   = GCHandle.Alloc(resultArray, GCHandleType.Pinned);

            commands.Read(result, true, 0, rank * rank, arrHandle.AddrOfPinnedObject(), null);
            var elapsed = sw.Elapsed;

            Console.WriteLine($"using: {elapsed.TotalMilliseconds} ms\n");
            arrHandle.Free();
            kernel.Dispose();
        }
Esempio n. 34
0
// -- Methods ------------------------------------------------------------
        public void BuildOpenCL()
        {
            cl_Source = File.ReadAllText(Environment.CurrentDirectory + "/OpenClKernel/sha256_kernal.cl");

            cl_Properties = new ComputeContextPropertyList(cl_Platform);

            cl_Context = new ComputeContext(cl_Devices, cl_Properties, null, IntPtr.Zero);

            // Create the command queue. This is used to control kernel execution and manage read/write/copy operations.
            cl_Commands = new ComputeCommandQueue(cl_Context, cl_Context.Devices[0], ComputeCommandQueueFlags.None);

            // Create program object
            cl_Program = new ComputeProgram(cl_Context, cl_Source);

            //Compiles the source codes.
            cl_Program.Build(null, null, null, IntPtr.Zero);

            // Create the kernel function
            cl_Kernel = cl_Program.CreateKernel("search");
        }
Esempio n. 35
0
        public void SetupClContext()
        {
            CanUseDouble = CanUseInterop = false;

            if (clPlatform == null ||
                comboBoxDevice.SelectedIndex >= clPlatform.Devices.Count)
            {
                clDevice  = null;
                clContext = null;
                return;
            }

            try
            {
                clDevice = clPlatform.Devices[comboBoxDevice.SelectedIndex];
                ComputeContextPropertyList properties = new ComputeContextPropertyList(clPlatform);
                IGraphicsContextInternal   ctx        = (IGraphicsContextInternal)GraphicsContext.CurrentContext;
                properties.Add(new ComputeContextProperty(ComputeContextPropertyName.CL_GL_CONTEXT_KHR, ctx.Context.Handle));
                properties.Add(new ComputeContextProperty(ComputeContextPropertyName.CL_WGL_HDC_KHR, OpenGL.wglGetCurrentDC()));
                properties.Add(new ComputeContextProperty(ComputeContextPropertyName.Platform, clPlatform.Handle.Value));
                clContext = new ComputeContext(new ComputeDevice[] { clDevice }, properties, null, IntPtr.Zero);

                // check the double-extension:
                CanUseDouble  = ClInfo.ExtensionCheck(clContext, "cl_khr_fp64");
                CanUseInterop = ClInfo.ExtensionCheck(clContext, "cl_khr_gl_sharing");
                ClInfo.LogCLProperties(clContext, true);
            }
            catch (Exception exc)
            {
                Util.LogFormat("OpenCL error: {0}", exc.Message);
                clDevice  = null;
                clContext = null;
            }

            bool enableDouble = !checkOpenCL.Checked ||
                                CanUseDouble;

            checkDouble.Enabled  = enableDouble;
            checkInterop.Enabled = CanUseInterop;
        }
Esempio n. 36
0
        public GraphicsInterop()
        {
            var glHandle = ((IGraphicsContextInternal)GraphicsContext.CurrentContext).Context.Handle;
            var wglHandle = wglGetCurrentDC();
            _device = ComputePlatform.Platforms[0].Devices[0];
            var p1 = new ComputeContextProperty(ComputeContextPropertyName.Platform, Device.Platform.Handle.Value);
            var p2 = new ComputeContextProperty(ComputeContextPropertyName.CL_GL_CONTEXT_KHR, glHandle);
            var p3 = new ComputeContextProperty(ComputeContextPropertyName.CL_WGL_HDC_KHR, wglHandle);
            var cpl = new ComputeContextPropertyList(new[] { p1, p2, p3 });
            _context = new ComputeContext(ComputeDeviceTypes.Gpu, cpl, null, IntPtr.Zero);
            _queue = new ComputeCommandQueue(Context, Device, ComputeCommandQueueFlags.None);

            GL.ClearColor(0f, 0f, 1f, 1f);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            GL.Ortho(0, 1.0f, 0, 1.0f, -1.0f, 1.0f);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
            GL.GenBuffers(1, out _pub);
            GL.Enable(EnableCap.Texture2D);
            _texture = GL.GenTexture();
        }
Esempio n. 37
0
        public BuddhaCloo()
        {
            clPlatform = ComputePlatform.Platforms[0];
            clProperties = new ComputeContextPropertyList(clPlatform);
            clContext = new ComputeContext(clPlatform.Devices, clProperties, null, IntPtr.Zero);
            clCommands = new ComputeCommandQueue(clContext, clContext.Devices[0], ComputeCommandQueueFlags.None);
            clEvents = new ComputeEventList();
            clProgram = new ComputeProgram(clContext, new string[] { kernelSource });

            R = new Random();
            seed1 = (uint)R.Next();
            seed2 = (uint)R.Next();
            seed3 = (uint)R.Next();
            seed4 = (uint)R.Next();

            /* //Default buddhabrot parameters
             * realMin = -1.5f;
             * realMax = 0.75f;
             * imaginaryMin = -1.5f;
             * imaginaryMax = 1.5f;
             */

            /*
            realMin = -1.05f;
            realMax = -0.9f;
            imaginaryMin = -0.3f;
            imaginaryMax = -0.225f;

            minIter = 20000;
            maxIter = 200000;
            escapeOrbit = 4.0f;

            minColor.R = 20000;
            maxColor.R = 60000;

            minColor.G = 60000;
            maxColor.G = 100000;

            minColor.B = 100000;
            maxColor.B = 200000;
            */

            realMin = -1.22f;
            realMax = -1.0f;
            imaginaryMin = 0.16f;
            imaginaryMax = 0.32f;
            //realMin = -1.5f;
            //realMax = 0.75f;
            //imaginaryMin = -1.5f;
            //imaginaryMax = 1.5f;

            minIter =20;
            maxIter = 1600;
            escapeOrbit = 4.0f;

            minColor.R = 20;
            maxColor.R = 400;

            minColor.G = 400;
            maxColor.G = 800;

            minColor.B = 800;
            maxColor.B = 1600;

            width = 1000;
            height = 700;

            h_outputBuffer = new ColorVectorRGBA[width * height];
            gc_outputBuffer = GCHandle.Alloc(h_outputBuffer, GCHandleType.Pinned);
        }
Esempio n. 38
0
        private void runTestsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder output = new StringBuilder();
            StringWriter writer = new StringWriter(output);

            Console.SetOut(writer);

            ComputeContextPropertyList properties = new ComputeContextPropertyList(settingsForm.Platform);
            ComputeContext context = new ComputeContext(settingsForm.Devices, properties, null, IntPtr.Zero);
            TestBase.SetContext(context);

            Console.WriteLine("Platform: " + context.Platform.Name);
            Console.Write("Devices:");
            foreach (ComputeDevice device in context.Devices)
                Console.Write(" " + device.Name + "    ");
            Console.WriteLine();

            new DummyTest().Run();
            new MappingTest().Run();
            new ProgramTest().Run();
            new KernelsTest().Run();
            new VectorAddTest().Run();

            Console.SetOut(Console.Out);
            writer.Close();

            logTextBox.Lines = ParseLines(output.ToString());
        }
Esempio n. 39
0
        /// <summary>
        /// Creates a new <see cref="ComputeContext"/> on all the <see cref="ComputeDevice"/>s that match the specified <see cref="ComputeDeviceTypes"/>.
        /// </summary>
        /// <param name="deviceType"> A bit-field that identifies the type of <see cref="ComputeDevice"/> to associate with the <see cref="ComputeContext"/>. </param>
        /// <param name="properties"> A <see cref="ComputeContextPropertyList"/> of the <see cref="ComputeContext"/>. </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="ComputeContext"/>. 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="ComputeContext"/> 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 ComputeContext(ComputeDeviceTypes deviceType, ComputeContextPropertyList properties, ComputeContextNotifier notify, IntPtr userDataPtr)
        {
            unsafe
            {
                IntPtr[] propertyArray = (properties != null) ? properties.ToIntPtrArray() : null;
                callback = notify;

                ComputeErrorCode error = ComputeErrorCode.Success;
                Handle = CL10.CreateContextFromType(propertyArray, deviceType, notify, userDataPtr, &error);
                ComputeException.ThrowOnError(error);

                this.properties = properties;
                ComputeContextProperty platformProperty = properties.GetByName(ComputeContextPropertyName.Platform);
                this.platform = ComputePlatform.GetByHandle(platformProperty.Value);
                this.devices = GetDevices();
            }

            resourceTable.Add(GetHashCode(), this);
            Trace.WriteLine("Created " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").");
        }
Esempio n. 40
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="deviceType">device type</param>
 /// <param name="properties">context properties</param>
 /// <param name="notify">context notify</param>
 /// <param name="userDataPtr">user data pointer</param>
 public ClooContext(ComputeDeviceTypes deviceType, ComputeContextPropertyList properties, ComputeContextNotifier notify, System.IntPtr userDataPtr)
     : base(deviceType, properties, notify, userDataPtr)
 {
     foreach (ComputeDevice device in base.Devices)
         _devices.Add(ClooDevice.FromBaseDevice(device));
 }
Esempio n. 41
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="devices">list of devices</param>
 /// <param name="properties">context properties</param>
 /// <param name="notify">context notify</param>
 /// <param name="userDataPtr">user data pointer</param>
 public ClooContext(IEnumerable<ClooDevice> devices, ComputeContextPropertyList properties, ComputeContextNotifier notify, System.IntPtr userDataPtr)
     : base(devices.Cast<ComputeDevice>().ToList(), properties, notify, userDataPtr)
 {
     _devices.AddRange(devices);
 }
Esempio n. 42
0
        /// <summary>
        /// Creates a new <see cref="ComputeContext"/> on a collection of <see cref="ComputeDevice"/>s.
        /// </summary>
        /// <param name="devices"> A collection of <see cref="ComputeDevice"/>s to associate with the <see cref="ComputeContext"/>. </param>
        /// <param name="properties"> A <see cref="ComputeContextPropertyList"/> of the <see cref="ComputeContext"/>. </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="ComputeContext"/>. 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="ComputeContext"/> 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 ComputeContext(ICollection<ComputeDevice> devices, ComputeContextPropertyList properties, ComputeContextNotifier notify, IntPtr notifyDataPtr)
        {
            int handleCount;
            CLDeviceHandle[] deviceHandles = ComputeTools.ExtractHandles(devices, out handleCount);
            IntPtr[] propertyArray = (properties != null) ? properties.ToIntPtrArray() : null;
            callback = notify;

            ComputeErrorCode error = ComputeErrorCode.Success;
            Handle = CL10.CreateContext(propertyArray, handleCount, deviceHandles, notify, notifyDataPtr, out error);
            ComputeException.ThrowOnError(error);
            
            SetID(Handle.Value);
            
            this.properties = properties;
            ComputeContextProperty platformProperty = properties.GetByName(ComputeContextPropertyName.Platform);
            this.platform = ComputePlatform.GetByHandle(platformProperty.Value);
            this.devices = GetDevices();

            Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information");
        }
Esempio n. 43
0
        /// <summary>
        /// Creates a new <c>ComputeContext</c> on a collection of <c>ComputeDevice</c>s.
        /// </summary>
        /// <param name="devices"> A collection of <c>ComputeDevice</c>s to associate with the <c>ComputeContext</c>. </param>
        /// <param name="properties"> A <c>ComputeContextPropertyList</c> of the <c>ComputeContext</c>. </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 <c>ComputeContext</c>. 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 <c>ComputeContext</c> 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 ComputeContext(ICollection<ComputeDevice> devices, ComputeContextPropertyList properties, ComputeContextNotifier notify, IntPtr notifyDataPtr)
        {
            unsafe
            {
                IntPtr[] deviceHandles = Tools.ExtractHandles(devices);
                IntPtr[] propertyArray = (properties != null) ? properties.ToIntPtrArray() : null;
                callback = notify;

                ComputeErrorCode error = ComputeErrorCode.Success;
                Handle = CL10.CreateContext(propertyArray, devices.Count, deviceHandles, notify, notifyDataPtr, &error);
                ComputeException.ThrowOnError(error);

                this.properties = properties;
                ComputeContextProperty platformProperty = properties.GetByName(ComputeContextPropertyName.Platform);
                this.platform = ComputePlatform.GetByHandle(platformProperty.Value);
                this.devices = GetDevices();
            }
        }
Esempio n. 44
0
 static void Main(string[] args)
 {
     if (args.Length <= 1)
       {
     System.Console.WriteLine(String.Format("Usage: {0} {{generator}} {{port}} [options]", System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location)));
     System.Console.WriteLine("  generator: the generator to use");
     System.Console.WriteLine("     s : SimpleCalculator");
     System.Console.WriteLine("     c : PreCompiledCalculator");
     System.Console.WriteLine("     t : ThreadCalculator with PreCompiledCalculator");
     System.Console.WriteLine("     g : OpenCLCalculator");
     System.Console.WriteLine("     gl: List avialable platforms and devices for OpenCL");
     System.Console.WriteLine("  port: the port to listen on");
     System.Console.WriteLine("  options: additional options for the generators");
     System.Console.WriteLine("     ThreadCalculator: [threadnum]");
     System.Console.WriteLine("       number of threads to use (default:2)");
     System.Console.WriteLine("     OpenCLCalculator: [platformnum] [devicenum]");
     System.Console.WriteLine("       The platform and device to use (default:0/0)");
     return;
       }
       CreateCalculatorFactory fact = null;
       switch (args[0])
       {
     case "s": fact = () => new SimpleCalculatorFactory(); break;
     case "c": fact = () => new PreCompiledCalculatorFactory(); break;
     case "t":
       {
     int tnum = 2;
     if (args.Length > 2 && (!int.TryParse(args[2], out tnum) || tnum <= 0))
     {
       System.Console.WriteLine("Invalid number of threads");
       return;
     }
     System.Console.WriteLine(String.Format("Using {0} threads", tnum));
     fact = () => new ThreadCalculatorFactory(tnum, new PreCompiledCalculatorFactory());
       }
       break;
     case "g":
       {
     int pnum = 0;
     int dnum = 0;
     if (args.Length > 3 && ((!int.TryParse(args[2], out pnum) || pnum < 0 || pnum > ComputePlatform.Platforms.Count)))
     {
       System.Console.WriteLine("Invalid platform number. Run with 'gl' generator to get the list of avialable platforms and devices.");
       return;
     }
     if (args.Length > 3 && ((!int.TryParse(args[3], out dnum) || dnum < 0 || dnum > ComputePlatform.Platforms[pnum].Devices.Count)))
     {
       System.Console.WriteLine("Invalid device number. Run with 'gl' generator to get the list of avialable platforms and devices.");
       return;
     }
     if (args.Length==3)
     {
       System.Console.WriteLine("Missing device number");
       return;
     }
     if (ComputePlatform.Platforms.Count == 0)
     {
       System.Console.WriteLine("No OpenCL Platform available");
       return;
     }
     System.Console.WriteLine(String.Format("Using {0} Device {1}", ComputePlatform.Platforms[pnum].Name, ComputePlatform.Platforms[pnum].Devices[dnum].Name));
     ComputePlatform selected = ComputePlatform.Platforms[pnum];
     var devices = new List<ComputeDevice>();
     devices.Add(selected.Devices[dnum]);
     ComputeContextPropertyList properties = new ComputeContextPropertyList(selected);
     ComputeContext context = new ComputeContext(devices, properties, null, IntPtr.Zero);
     fact = () => new OpenCLCalculatorFactory(context);
       }
       break;
     case "gl":
       for (int i = 0; i < ComputePlatform.Platforms.Count; i++)
       {
     System.Console.WriteLine("Platform " + i + ": " + ComputePlatform.Platforms[i].Name);
     var platform = ComputePlatform.Platforms[i];
     for (int ii = 0; ii < platform.Devices.Count; ii++)
     {
       System.Console.WriteLine("  Device " + ii + ": " + platform.Devices[ii].Name);
     }
       }
       return;
       }
       int port;
       if (!int.TryParse(args[1], out port) || port < 1024 || port > 65535)
       {
     System.Console.WriteLine("Invalid port specified. Must be in range {1024..65535}");
       }
       System.Console.WriteLine(String.Format("Starting server on port {0}",port));
       DistributedCalculatorServer s = new DistributedCalculatorServer(fact, IPAddress.Any, 6079);
       s.Run();
 }
Esempio n. 45
0
        public static void InitializeOpenCL()
        {
            string source = File.ReadAllText("MonteCarloSimulate.cl");

            //Choose Device
            ComputePlatform platform = ComputePlatform.Platforms[0];

            openCLDevice = platform.QueryDevices()[0];

            ComputeContextPropertyList properties =
                new ComputeContextPropertyList(platform);

            //Setup of stuff on our side
            openCLContext = new ComputeContext(ComputeDeviceTypes.All,
                properties, null, IntPtr.Zero);

            //Build the program, which gets us the kernel
            openCLProgram = new ComputeProgram(openCLContext, source);
            openCLProgram.Build(null, null, null, IntPtr.Zero);
            //can use notify as the 3rd command... if you want this to be non-blocking

            openCLKernel = openCLProgram.CreateKernel("MonteCarloSimulate");


        }
Esempio n. 46
0
        private static ComputeContext GetContext()
        {
            if (ComputePlatform.Platforms.Count > 1)
                Console.WriteLine("More than one platform available, maybe branch out...");

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

            return context;
        }
Esempio n. 47
0
        public static void Test()
        {
            string source = File.ReadAllText("MonteCarloSimulate.cl");

            //Choose Device
            ComputePlatform platform = ComputePlatform.Platforms[0];

            ComputeDevice device = platform.QueryDevices()[0];

            ComputeContextPropertyList properties =
                new ComputeContextPropertyList(platform);

            //Setup of stuff on our side
            ComputeContext context = new ComputeContext(ComputeDeviceTypes.All,
                properties, null, IntPtr.Zero);

            //Build the program, which gets us the kernel
            ComputeProgram program = new ComputeProgram(context, source);
            program.Build(null, null, null, IntPtr.Zero);
            //can use notify as the 3rd command... if you want this to be non-blocking

            ComputeKernel kernel = program.CreateKernel("MonteCarloSimulate");


            //Create arguments
            int sideSize = 4096;
            int[] inMatrixA = new int[sideSize * sideSize];
            int[] inMatrixB = new int[sideSize * sideSize];
            int[] outMatrixC = new int[sideSize * sideSize];
            Random random = new Random((int)DateTime.Now.Ticks);

            if (sideSize <= 32)
                for (int y = 0; y < sideSize; y++)
                    for (int x = 0; x < sideSize; x++)
                    {
                        inMatrixA[y * sideSize + x] = random.Next(3);
                        inMatrixB[y * sideSize + x] = random.Next(3);
                        outMatrixC[y * sideSize + x] = 0;
                    }


            ComputeBuffer<int> bufferMatrixA = new ComputeBuffer<int>(context,
                ComputeMemoryFlags.UseHostPointer, inMatrixA);

            ComputeBuffer<int> bufferMatrixB = new ComputeBuffer<int>(context,
                ComputeMemoryFlags.UseHostPointer, inMatrixB);

            ComputeBuffer<int> bufferMatrixC = new ComputeBuffer<int>(context,
                ComputeMemoryFlags.UseHostPointer, outMatrixC);

            long localWorkSize = Math.Min(device.MaxComputeUnits, sideSize);


            //Sets arguments
            kernel.SetMemoryArgument(0, bufferMatrixA);
            kernel.SetMemoryArgument(1, bufferMatrixB);
            kernel.SetMemoryArgument(2, bufferMatrixC);
            kernel.SetLocalArgument(3, sideSize * 2);
            kernel.SetValueArgument<int>(4, sideSize);
            //kernel.SetLocalArgument(1, localWorkSize);            

            string offset = " ";
            for (int x = 0; x < sideSize; x++)
                offset += "  ";

            if (sideSize <= 32)
                for (int y = 0; y < sideSize; y++)
                {
                    Console.Write(offset);
                    for (int x = 0; x < sideSize; x++)
                        Console.Write(inMatrixA[y * sideSize + x] + " ");
                    Console.WriteLine();
                }




            //Runs commands
            ComputeCommandQueue commands = new ComputeCommandQueue(context,
                context.Devices[0], ComputeCommandQueueFlags.None);

            long executionTime = DateTime.Now.Ticks;

            //Execute kernel
            //globalWorkSize in increments of localWorkSize (max of device.MaxComputeUnits or kernel.GetWorkGroupSize())
            commands.Execute(kernel, null,
                new long[] { Math.Min(sideSize, 16), Math.Min(sideSize, 16) },
                new long[] { localWorkSize, 1 }, null);

            //globalWorkSize can be any size
            //localWorkSize product much not be greater than device.MaxComputeUnits
            //and it must not be greater than kernel.GetWorkGroupSize()
            //ESSENTIALLY, the program iterates through globalWorkSize
            //in increments of localWorkSize. Both are multidimensional,
            //but this just saves us the time of doing that
            //(1 dimension can be put to multiple if the max dimension lengths
            //are known very easily with remainder).

            //Also, you should probably use this
            //kernel.GetPreferredWorkGroupSizeMultiple(device);

            commands.Finish();

            commands.ReadFromBuffer(bufferMatrixC, ref outMatrixC, true, null);

            commands.Finish();
            executionTime = DateTime.Now.Ticks - executionTime;


            GC.Collect();
            program.Dispose();

            Console.WriteLine();
            if (sideSize <= 32)
                for (int y = 0; y < sideSize; y++)
                {
                    for (int x = 0; x < sideSize; x++)
                        Console.Write(inMatrixB[y * sideSize + x] + " ");
                    Console.Write(" ");
                    for (int x = 0; x < sideSize; x++)
                        Console.Write(outMatrixC[y * sideSize + x] + " ");

                    Console.WriteLine();
                }

            int testY = random.Next(sideSize);
            int testX = random.Next(sideSize);

            int sum = 0;
            for (int q = 0; q < sideSize; q++)
                sum += inMatrixA[q * sideSize + testX] *
                    inMatrixB[testY * sideSize + q];

            Console.WriteLine(sum == outMatrixC[testY * sideSize + testX]);

            Console.WriteLine(executionTime / 10000.0);

        }
Esempio n. 48
0
        private void buttonRunAll_Click(object sender, EventArgs e)
        {
            if (devices.Count == 0)
            {
                MessageBox.Show("No OpenCL device selected!\n\nSelect one or more devices from the list to continue.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            StringBuilder output = new StringBuilder();
            StringWriter log = new StringWriter(output);

            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform);
            ComputeContext context = new ComputeContext(devices, properties, null, IntPtr.Zero);

            for (int i = 0; i < exampleList.Count; i++)
            {
                if (checkedListExamples.GetItemChecked(i))
                {
                    log.WriteLine("--------------------------------------------------------------------------------");
                    log.WriteLine("Running \"" + exampleList[i].Name + "\"...");
                    log.WriteLine();
                    exampleList[i].Run(context, log);
                    log.WriteLine();
                    log.WriteLine("\"" + exampleList[i].Name + "\" finished.");
                    log.WriteLine("--------------------------------------------------------------------------------");
                    log.Flush();
                }
            }

            log.Close();

            textBoxLog.Lines = ParseLines(output.ToString());

            // cleanup context!
            context.Dispose();
        }
Esempio n. 49
0
        public void Start(IMinerContext context)
        {
            string code;

            var kernelRes = Assembly.GetExecutingAssembly().GetManifestResourceStream("BitMaker.Miner.Cloo.Miner.cl");
            using (var rdr = new StreamReader(kernelRes))
                code = clProgramSource;

            var platform = ComputePlatform.Platforms[0];
            var properties = new ComputeContextPropertyList(platform);
            device = platform.Devices[0];
            ccontext = new ComputeContext(platform.Devices, properties, null, IntPtr.Zero);
            program = new ComputeProgram(ccontext, clProgramSource);
            program.Build(null, null, notify, IntPtr.Zero);
        }
Esempio n. 50
0
        /// <summary>Initializes OpenCL and reads devices. Uses previously created context and command queue if supplied. In that case DevicesToUse is ignored.</summary>
        public static void InitCL(ComputeDeviceTypes DevicesToUse, ComputeContext PrevCtx, ComputeCommandQueue PrevCQ)
        {
            if (CLAcceleration != CLAccelerationType.UsingCL)
            {
                try
                {
                    if (ComputePlatform.Platforms.Count > 0) CLAccel = CLAccelerationType.UsingCL;
                    else CLAccel = CLAccelerationType.NotUsingCL;

                    //Program.Event = new List<ComputeEventBase>();

                    CLPlatforms = new List<ComputePlatform>();
                    foreach (ComputePlatform pp in ComputePlatform.Platforms) CLPlatforms.Add(pp);

                    ComputeContextPropertyList Properties = new ComputeContextPropertyList(ComputePlatform.Platforms[0]);

                    if (PrevCtx == null)
                    {
                        Program.Context = new ComputeContext(DevicesToUse, Properties, null, IntPtr.Zero);
                    }
                    else Program.Context = PrevCtx;

                    CLDevices = new List<ComputeDevice>();
                    for (int i = 0; i < Program.Context.Devices.Count; i++)
                    {
                        CLDevices.Add(Program.Context.Devices[i]);

                    }

                    Program.CommQueues = new List<ComputeCommandQueue>();
                    Program.AsyncCommQueues = new List<ComputeCommandQueue>();
                    Program.DefaultCQ = -1;

                    if (PrevCQ == null)
                    {
                        for (int i = 0; i < CLDevices.Count; i++)
                        {
                            //Comandos para os devices
                            ComputeCommandQueue CQ = new ComputeCommandQueue(Program.Context, CLDevices[i], ComputeCommandQueueFlags.None);

                            ComputeCommandQueue AsyncCQ = new ComputeCommandQueue(Program.Context, CLDevices[i], ComputeCommandQueueFlags.OutOfOrderExecution);

                            //Comando para a primeira GPU
                            if ((CLDevices[i].Type == ComputeDeviceTypes.Gpu || CLDevices[i].Type == ComputeDeviceTypes.Accelerator) && Program.DefaultCQ < 0)
                                Program.DefaultCQ = i;

                            Program.CommQueues.Add(CQ);
                            Program.AsyncCommQueues.Add(AsyncCQ);

                        }
                        //Só tem CPU
                        if (Program.DefaultCQ < 0 && Program.CommQueues.Count > 0) Program.DefaultCQ = 0;
                    }
                    else
                    {
                        Program.CommQueues.Add(PrevCQ);
                        Program.DefaultCQ = 0;
                    }
                }
                catch (Exception ex)
                {
                    CLInitErr = ex.ToString();
                    CLAccel = CLAccelerationType.NotUsingCL;
                }
            }
        }
Esempio n. 51
0
        private void runTestsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder output = new StringBuilder();
            StringWriter log = new StringWriter(output);

            ComputeContextPropertyList properties = new ComputeContextPropertyList(configForm.Platform);
            ComputeContext context = new ComputeContext(configForm.Devices, properties, null, IntPtr.Zero);

            log.WriteLine("Platform: " + context.Platform.Name);
            log.Write("Devices:");
            foreach (ComputeDevice device in context.Devices)
                log.Write(" " + device.Name + "    ");
            log.WriteLine();

            DummyTest.Run(log);
            MappingTest.Run(log, context);
            ProgramTest.Run(log, context);
            KernelsTest.Run(log, context);
            VectorAddTest.Run(log, context);
            CL11Test.Run(log, context);

            log.Close();

            logTextBox.Lines = ParseLines(output.ToString());
        }
Esempio n. 52
0
 public GraphicsInterop(IGraphicsContext context, ComputeDevice device)
 {
     var os = Environment.OSVersion.Platform;
     ComputeContextProperty platformDependantCcp;
     switch (os)
     {
         case PlatformID.Unix:
             platformDependantCcp = GetUnixCcp();
             break;
         case PlatformID.MacOSX:
             platformDependantCcp = GetMacCcp(context);
             break;
         default:
             platformDependantCcp = GetWindowsCcp();
             break;
     }
     var glHandle = ((IGraphicsContextInternal)context).Context.Handle;
     var p1 = new ComputeContextProperty(ComputeContextPropertyName.Platform, device.Platform.Handle.Value);
     var p2 = new ComputeContextProperty(ComputeContextPropertyName.CL_GL_CONTEXT_KHR, glHandle);
     var cpl = new ComputeContextPropertyList(new[] { p1, p2, platformDependantCcp });
     _context = new ComputeContext(ComputeDeviceTypes.Gpu, cpl, null, IntPtr.Zero);
     _queue = new ComputeCommandQueue(Context, device, ComputeCommandQueueFlags.None);
     GL.ClearColor(0f, 0f, 1f, 1f);
     GL.MatrixMode(MatrixMode.Projection);
     GL.LoadIdentity();
     GL.Ortho(0, 1.0f, 0, 1.0f, -1.0f, 1.0f);
     GL.MatrixMode(MatrixMode.Modelview);
     GL.LoadIdentity();
     GL.GenBuffers(1, out _pub);
     GL.Enable(EnableCap.Texture2D);
     _texture = GL.GenTexture();
 }
Esempio n. 53
0
        public TerrainGen()
        {
            #if CPU_DEBUG
            var platform = ComputePlatform.Platforms[1];
            #else
            var platform = ComputePlatform.Platforms[0];
            #endif
            _devices = new List<ComputeDevice>();
            _devices.Add(platform.Devices[0]);
            _properties = new ComputeContextPropertyList(platform);
            _context = new ComputeContext(_devices, _properties, null, IntPtr.Zero);
            _cmdQueue = new ComputeCommandQueue(_context, _devices[0], ComputeCommandQueueFlags.None);

            #region setup generator kernel
            bool loadFromSource = Gbl.HasRawHashChanged[Gbl.RawDir.Scripts];
            loadFromSource = true;
            _chunkWidthInBlocks = Gbl.LoadContent<int>("TGen_ChunkWidthInBlocks");
            _chunkWidthInVerts = _chunkWidthInBlocks + 1;
            _blockWidth = Gbl.LoadContent<int>("TGen_BlockWidthInMeters");
            float lacunarity = Gbl.LoadContent<float>("TGen_Lacunarity");
            float gain = Gbl.LoadContent<float>("TGen_Gain");
            int octaves = Gbl.LoadContent<int>("TGen_Octaves");
            float offset = Gbl.LoadContent<float>("TGen_Offset");
            float hScale = Gbl.LoadContent<float>("TGen_HScale");
            float vScale = Gbl.LoadContent<float>("TGen_VScale");

            _genConstants = new ComputeBuffer<float>(_context, ComputeMemoryFlags.ReadOnly, 8);
            var genArr = new[]{
                lacunarity,
                gain,
                offset,
                octaves,
                hScale,
                vScale,
                _blockWidth,
                _chunkWidthInBlocks
            };

            _cmdQueue.WriteToBuffer(genArr, _genConstants, false, null);
            if (loadFromSource){
                _generationPrgm = new ComputeProgram(_context, Gbl.LoadScript("TGen_Generator"));
            #if CPU_DEBUG
                _generationPrgm.Build(null, @"-g -s D:\Projects\Gondola\Scripts\GenTerrain.cl", null, IntPtr.Zero); //use option -I + scriptDir for header search
            #else
                _generationPrgm.Build(null, "", null, IntPtr.Zero);//use option -I + scriptDir for header search
            #endif
                Gbl.SaveBinary(_generationPrgm.Binaries, "TGen_Generator");
            }
            else{
                var binary = Gbl.LoadBinary("TGen_Generator");
                _generationPrgm = new ComputeProgram(_context, binary, _devices);
                _generationPrgm.Build(null, "", null, IntPtr.Zero);
            }
            //loadFromSource = false;

            _terrainGenKernel = _generationPrgm.CreateKernel("GenTerrain");
            _normalGenKernel = _generationPrgm.CreateKernel("GenNormals");

            //despite the script using float3 for these fields, we need to consider it to be float4 because the
            //implementation is basically a float4 wrapper that uses zero for the last variable
            _geometry = new ComputeBuffer<float>(_context, ComputeMemoryFlags.None, _chunkWidthInVerts*_chunkWidthInVerts*4);
            _normals = new ComputeBuffer<ushort>(_context, ComputeMemoryFlags.None, _chunkWidthInVerts * _chunkWidthInVerts * 4);
            _binormals = new ComputeBuffer<byte>(_context, ComputeMemoryFlags.None, _chunkWidthInVerts*_chunkWidthInVerts*4);
            _tangents = new ComputeBuffer<byte>(_context, ComputeMemoryFlags.None, _chunkWidthInVerts*_chunkWidthInVerts*4);
            _uvCoords = new ComputeBuffer<float>(_context, ComputeMemoryFlags.None, _chunkWidthInVerts*_chunkWidthInVerts*2);

            _terrainGenKernel.SetMemoryArgument(0, _genConstants);
            _terrainGenKernel.SetMemoryArgument(3, _geometry);
            _terrainGenKernel.SetMemoryArgument(4, _uvCoords);

            _normalGenKernel.SetMemoryArgument(0, _genConstants);
            _normalGenKernel.SetMemoryArgument(3, _geometry);
            _normalGenKernel.SetMemoryArgument(4, _normals);
            _normalGenKernel.SetMemoryArgument(5, _binormals);
            _normalGenKernel.SetMemoryArgument(6, _tangents);

            #endregion

            #region setup quadtree kernel

            if (loadFromSource){
                _qTreePrgm = new ComputeProgram(_context, Gbl.LoadScript("TGen_QTree"));
            #if CPU_DEBUG
                _qTreePrgm.Build(null, @"-g -s D:\Projects\Gondola\Scripts\Quadtree.cl", null, IntPtr.Zero);
            #else
                _qTreePrgm.Build(null, "", null, IntPtr.Zero);
            #endif
                Gbl.SaveBinary(_qTreePrgm.Binaries, "TGen_QTree");
            }
            else{
                var binary = Gbl.LoadBinary("TGen_QTree");
                _qTreePrgm = new ComputeProgram(_context, binary, _devices);
                _qTreePrgm.Build(null, "", null, IntPtr.Zero);
            }

            _qTreeKernel = _qTreePrgm.CreateKernel("QuadTree");
            _crossCullKernel = _qTreePrgm.CreateKernel("CrossCull");

            _activeVerts = new ComputeBuffer<byte>(_context, ComputeMemoryFlags.None, _chunkWidthInVerts*_chunkWidthInVerts);

            _dummy = new ComputeBuffer<int>(_context, ComputeMemoryFlags.None, 50);
            var rawNormals = new ushort[_chunkWidthInVerts * _chunkWidthInVerts * 4];
            _emptyVerts = new byte[_chunkWidthInVerts*_chunkWidthInVerts];
            for (int i = 0; i < _emptyVerts.Length; i++){
                _emptyVerts[i] = 1;
            }
            _cmdQueue.WriteToBuffer(rawNormals, _normals, true, null);
            _cmdQueue.WriteToBuffer(_emptyVerts, _activeVerts, true, null);

            _qTreeKernel.SetValueArgument(1, _chunkWidthInBlocks);
            _qTreeKernel.SetMemoryArgument(2, _normals);
            _qTreeKernel.SetMemoryArgument(3, _activeVerts);
            _qTreeKernel.SetMemoryArgument(4, _dummy);

            _crossCullKernel.SetValueArgument(1, _chunkWidthInBlocks);
            _crossCullKernel.SetMemoryArgument(2, _normals);
            _crossCullKernel.SetMemoryArgument(3, _activeVerts);
            _crossCullKernel.SetMemoryArgument(4, _dummy);

            #endregion

            #region setup winding kernel

            if (loadFromSource){
                _winderPrgm = new ComputeProgram(_context, Gbl.LoadScript("TGen_VertexWinder"));
            #if CPU_DEBUG
                _winderPrgm.Build(null, @"-g -s D:\Projects\Gondola\Scripts\VertexWinder.cl", null, IntPtr.Zero);
            #else
                _winderPrgm.Build(null, "", null, IntPtr.Zero);
            #endif
                Gbl.SaveBinary(_winderPrgm.Binaries, "TGen_VertexWinder");
            }
            else{
                var binary = Gbl.LoadBinary("TGen_VertexWinder");
                _winderPrgm = new ComputeProgram(_context, binary, _devices);
                _winderPrgm.Build(null, "", null, IntPtr.Zero);
            }

            _winderKernel = _winderPrgm.CreateKernel("VertexWinder");
            _indicies = new ComputeBuffer<int>(_context, ComputeMemoryFlags.None, (_chunkWidthInBlocks)*(_chunkWidthInBlocks)*8);

            _winderKernel.SetMemoryArgument(0, _activeVerts);
            _winderKernel.SetMemoryArgument(1, _indicies);

            _emptyIndices = new int[(_chunkWidthInBlocks)*(_chunkWidthInBlocks)*8];
            for (int i = 0; i < (_chunkWidthInBlocks)*(_chunkWidthInBlocks)*8; i++){
                _emptyIndices[i] = 0;
            }
            _cmdQueue.WriteToBuffer(_emptyIndices, _indicies, true, null);

            #endregion

            if (loadFromSource){
                Gbl.AllowMD5Refresh[Gbl.RawDir.Scripts] = true;
            }

            _cmdQueue.Finish();
        }
Esempio n. 54
0
        /// <summary>
        /// Initializes local fields and the underlying compute context.
        /// </summary>
        public void Initialize()
        {
            if (this.context == null)
            {
                var devices = ComputePlatform.Platforms.SelectMany(a => a.Devices).Where(a => a.Extensions.Contains("cl_khr_fp64")).Take(1).ToArray();
                ComputeContextPropertyList list = new ComputeContextPropertyList(devices[0].Platform);
                this.context = new ComputeContext(devices, list, null, IntPtr.Zero);
            }

            this.program = new ComputeProgram(this.context, File.ReadAllText("Mandelbrot.cl"));

            this.program.Build(null, null, null, IntPtr.Zero);

            this.mandelbrot = this.program.CreateKernel("Mandelbrot");
            this.toBitmap = this.program.CreateKernel("ToBitmap");

            this.resultBuffer = new ComputeBuffer<int>(this.context, ComputeMemoryFlags.ReadWrite, this.ImageWidth * this.ImageHeight);
            this.bitmapBuffer = new ComputeBuffer<byte>(this.context, ComputeMemoryFlags.ReadWrite, this.ImageWidth * this.ImageHeight * 4);

            this.mandelbrot.SetMemoryArgument(7, this.resultBuffer);
            this.toBitmap.SetMemoryArgument(1, this.resultBuffer);
            this.toBitmap.SetMemoryArgument(2, this.bitmapBuffer);

            this.commandQueue = new ComputeCommandQueue(this.context, this.context.Devices.OrderBy(a => a.Type).Where(a => a.Extensions.Contains("cl_khr_fp64")).First(), ComputeCommandQueueFlags.None);
        }
Esempio n. 55
0
        /// <summary>
        /// Creates a new <c>ComputeContext</c> on all the <c>ComputeDevice</c>s that match the specified <c>ComputeDeviceTypes</c>.
        /// </summary>
        /// <param name="deviceType"> A bit-field that identifies the type of <c>ComputeDevice</c> to associate with the <c>ComputeContext</c>. </param>
        /// <param name="properties"> A <c>ComputeContextPropertyList</c> of the <c>ComputeContext</c>. </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 <c>ComputeContext</c>. 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 <c>ComputeContext</c> 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 ComputeContext(ComputeDeviceTypes deviceType, ComputeContextPropertyList properties, ComputeContextNotifier notify, IntPtr userDataPtr)
        {
            unsafe
            {
                IntPtr[] propertyArray = (properties != null) ? properties.ToIntPtrArray() : null;
                callback = notify;

                ComputeErrorCode error = ComputeErrorCode.Success;
                Handle = CL10.CreateContextFromType(propertyArray, deviceType, notify, userDataPtr, &error);
                ComputeException.ThrowOnError(error);

                this.properties = properties;
                ComputeContextProperty platformProperty = properties.GetByName(ComputeContextPropertyName.Platform);
                this.platform = ComputePlatform.GetByHandle(platformProperty.Value);
                this.devices = GetDevices();
            }
        }
Esempio n. 56
0
        static void Main(string[] args)
        {
            #region
            const string programName = "Prime Number";

            Stopwatch stopWatch = new Stopwatch();

            string clProgramSource = KernelProgram();

            Console.WriteLine("Environment OS:");
            Console.WriteLine("-----------------------------------------");
            Console.WriteLine(Environment.OSVersion);
            #endregion
            if (ComputePlatform.Platforms.Count == 0)
            {
                Console.WriteLine("No OpenCL Platforms are availble!");
            }
            else
            {
                #region 1
                // step 1 choose the first available platform
                ComputePlatform platform = ComputePlatform.Platforms[0];

                // output the basic info
                BasicInfo(platform);

                Console.WriteLine("Program: " + programName);
                Console.WriteLine("-----------------------------------------");
                #endregion
                //Cpu 10 seconds Gpu 28 seconds
                int count = 64;

                int[] output_Z = new int[count * count * count];

                int[] input_X = new int[count * count * count];

                for (int x = 0; x < count * count * count; x++)
                {
                    input_X[x] = x;
                }
                #region 2
                // step 2 create context for that platform and all devices
                ComputeContextPropertyList properties = new ComputeContextPropertyList(platform);
                ComputeContext context = new ComputeContext(platform.Devices, properties, null, IntPtr.Zero);

                // step 3 create and build program
                ComputeProgram program = new ComputeProgram(context, clProgramSource);
                program.Build(platform.Devices, null, null, IntPtr.Zero);
                #endregion
                // step 4 create memory objects
                ComputeBuffer<int> a = new ComputeBuffer<int>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, input_X);
                ComputeBuffer<int> z = new ComputeBuffer<int>(context, ComputeMemoryFlags.WriteOnly, output_Z.Length);

                // step 5 create kernel object with same kernel programe name VectorAdd
                ComputeKernel kernel = program.CreateKernel("PrimeNumber");

                // step 6 set kernel arguments
                //kernel.SetMemoryArgument(0, a);
                kernel.SetMemoryArgument(0, a);
                kernel.SetMemoryArgument(1, z);

                ComputeEventList eventList = new ComputeEventList();

                //for (int j = 0; j < context.Devices.Count; j++)
                // query available devices n,...,1,0.  cpu first then gpu
                for (int j = context.Devices.Count-1; j > -1; j--)
                {
                    #region 3
                    stopWatch.Start();

                    // step 7 create command queue on that context on that device
                    ComputeCommandQueue commands = new ComputeCommandQueue(context, context.Devices[j], ComputeCommandQueueFlags.None);

                    // step 8 run the kernel program
                    commands.Execute(kernel, null, new long[] { count, count, count }, null, eventList);
                    //Application.DoEvents();

                    #endregion
                    // step 9 read results
                    commands.ReadFromBuffer(z, ref output_Z, false, eventList);
                    #region 4
                    commands.Finish();

                    string fileName = "C:\\primenumber\\PrimeNumberGPU.txt";
                    StreamWriter file = new StreamWriter(fileName, true);

                    FileInfo info = new FileInfo(fileName);
                    long fs = info.Length;

                    // 1 MegaByte = 1.049e+6 Byte
                    int index = 1;
                    if (fs == 1.049e+6)
                    {
                        fileName = "C:\\primenumber\\PrimeNumberGPU" + index.ToString() + ".txt";
                        file = new System.IO.StreamWriter(fileName, true);
                        index++;
                    }
                    #endregion

                    for (uint xx = 0; xx < count * count * count; xx++)
                    {
                        if (output_Z[xx] != 0 && output_Z[xx] != 1)
                        {
                            Console.WriteLine(output_Z[xx]);
                            file.Write(output_Z[xx]);
                            file.Write("x");
                        }
                    }
                    #region 5
                    file.Close();
                    stopWatch.Stop();

                    ComputeCommandProfilingInfo start = ComputeCommandProfilingInfo.Started;
                    ComputeCommandProfilingInfo end = ComputeCommandProfilingInfo.Ended;
                    double time = 10e-9 * (end - start);
                    //Console.WriteLine("Nanosecond: " + time);

                    TimeSpan ts = stopWatch.Elapsed;
                    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
                    Console.WriteLine(context.Devices[j].Name.Trim() + " Elapsed Time " + elapsedTime);

                    Console.WriteLine("-----------------------------------------");
                    #endregion
                }
                Console.ReadLine();
            }
        }
Esempio n. 57
0
        /// <summary>
        /// Creates a new <c>ComputeContext</c> on a collection of <c>ComputeDevice</c>s.
        /// </summary>
        /// <param name="devices"> A collection of <c>ComputeDevice</c>s to associate with the <c>ComputeContext</c>. </param>
        /// <param name="properties"> A <c>ComputeContextPropertyList</c> of the <c>ComputeContext</c>. </param>
        /// <param name="notify"> A callback function that can be registered by the application. This callback function will be used by the OpenCL implementation to report information on errors that occur in the <c>ComputeContext</c>. This 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. 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 ComputeContext(ICollection<ComputeDevice> devices, ComputeContextPropertyList properties, ComputeContextNotifier notify, IntPtr notifyDataPtr)
        {
            unsafe
            {
                IntPtr[] deviceHandles = Tools.ExtractHandles(devices);
                IntPtr[] propertiesList = (properties != null) ? properties.ToIntPtrArray() : null;
                IntPtr notifyFuncPtr = (notify != null) ? Marshal.GetFunctionPointerForDelegate(notify) : IntPtr.Zero;

                ComputeErrorCode error = ComputeErrorCode.Success;
                fixed (IntPtr* propertiesPtr = propertiesList)
                fixed (IntPtr* deviceHandlesPtr = deviceHandles)
                    Handle = CL10.CreateContext(
                        propertiesPtr,
                        devices.Count,
                        deviceHandlesPtr,
                        notifyFuncPtr,
                        notifyDataPtr,
                        &error);
                ComputeException.ThrowOnError(error);

                this.properties = properties;
                ComputeContextProperty platformProperty = properties.GetByName(ComputeContextPropertyName.Platform);
                this.platform = ComputePlatform.GetByHandle(platformProperty.Value);
                this.devices = GetDevices();
            }
        }
Esempio n. 58
0
        // Constructor function
        public GPUCompute(ComputeModeFormat SetComputeMode = ComputeModeFormat.kRelease)         
        {
            ComputePlatform platform = ComputePlatform.Platforms[0];
            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform);
            IList<ComputeDevice> devices = new List<ComputeDevice>();
            devices.Add(platform.Devices[0]);
            Console.WriteLine("Platform name: {0}", platform.Devices[0].Name);
            context_ = new ComputeContext(devices, properties, null, IntPtr.Zero);
            compute_mode_ = SetComputeMode;
            Console.WriteLine("Compute Mode: {0}", compute_mode_);
            // built the GPU program            
            if (compute_mode_ == ComputeModeFormat.kAddVectorTest)
                program_ = new ComputeProgram(context_, clProgramSource_vector_add_);
            else if (compute_mode_ == ComputeModeFormat.kPredictWithFeaturesTest)
                program_ = new ComputeProgram(context_, clProgramSource_dfprocess_);
            else if (compute_mode_ == ComputeModeFormat.kRelease)
                program_ = new ComputeProgram(context_, clProgramSource_predict_);
            else if (compute_mode_ == ComputeModeFormat.kRelease2D)
                program_ = new ComputeProgram(context_, clProgramSource_predict_2d_);
            else if (compute_mode_ == ComputeModeFormat.kTestBreathFrist)
                program_ = new ComputeProgram(context_, clProgramSource_predict_test_breath_first_tree_);     
            else if (compute_mode_ == ComputeModeFormat.kTest2D)
                program_ = new ComputeProgram(context_, clProgramSource_predict_test_2d_);     
            program_.Build(null, null, null, IntPtr.Zero); 
            // end building
            Console.WriteLine("Build success");            
            count_ = 640 * 480;            

            // set up some of the kernel arguments, some of which are set in other functions
            if (compute_mode_ == ComputeModeFormat.kAddVectorTest)
            {
                kernel_ = program_.CreateKernel("AddVectorWithTrees");                
                //commands_ = new ComputeCommandQueue(context_, context_.Devices[0], ComputeCommandQueueFlags.None);                
                a_ = new ComputeBuffer<short>(context_, ComputeMemoryFlags.ReadOnly, count_);
                c_ = new ComputeBuffer<short>(context_, ComputeMemoryFlags.WriteOnly, count_);
                kernel_.SetMemoryArgument(0, a_);
                kernel_.SetMemoryArgument(2, c_);
            }
            else if (compute_mode_ == ComputeModeFormat.kPredictWithFeaturesTest) {
                kernel_ = program_.CreateKernel("DFProcess");                                
            }
            else if (compute_mode_ == ComputeModeFormat.kRelease || compute_mode_ == ComputeModeFormat.kRelease2D || compute_mode_ == ComputeModeFormat.kTestBreathFrist || compute_mode_ == ComputeModeFormat.kTest2D)
            {
                kernel_ = program_.CreateKernel("Predict");
            }
            commands_ = new ComputeCommandQueue(context_, context_.Devices[0], ComputeCommandQueueFlags.None);                
            Console.WriteLine("Sucessfully create kernel");
        }