private void LoadProgram() { Cl.ErrorCode error; if (!System.IO.File.Exists(programPath)) { Console.WriteLine("Program doesn't exist at path " + programPath); return; } string programSource = System.IO.File.ReadAllText(programPath); _program = Cl.Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error); CheckErr(error, "Cl.CreateProgramWithSource"); //Compile kernel source #if DEBUG error = Cl.Cl.BuildProgram(_program, 0, null, string.Format("-g -s \"{0}\"", programPath), null, IntPtr.Zero); #else error = Cl.Cl.BuildProgram(_program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); #endif CheckErr(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.Cl.GetProgramBuildInfo(_program, _device, Cl.ProgramBuildInfo.Status, out error).CastTo <Cl.BuildStatus>() != Cl.BuildStatus.Success) { CheckErr(error, "Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.Cl.GetProgramBuildInfo(_program, _device, Cl.ProgramBuildInfo.Log, out error)); return; } }
public LGFlow() { alpha = (float)15; mode = 1; w = (float)1.9; kernelSize = 3; sigma = 0; pyramidLevel = 5; iteration = 1; flowInterval = 2; threshold = (float)0.5; sources[0] = File_Handler.getKernelSourceFromLibrary("PushImgFlow.cl"); sources[1] = File_Handler.getKernelSourceFromLibrary("LocalGlobalFlow1.cl"); sources[2] = File_Handler.getKernelSourceFromLibrary("LocalGlobalFlow2.cl"); sources[3] = File_Handler.getKernelSourceFromLibrary("LocalGlobalFlow_J.cl"); sources[4] = File_Handler.getKernelSourceFromLibrary("LocalGlobalFlow3.cl"); Platform[] platforms = Cl.GetPlatformIDs(out error); Console.WriteLine("Error code: " + error.ToString()); devices = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out error); Console.WriteLine("Error code: " + error.ToString()); device = devices[0]; context = Cl.CreateContext(null, 1, devices, null, IntPtr.Zero, out error); Console.WriteLine("Error code: " + error.ToString()); program = Cl.CreateProgramWithSource(context, 5, sources, null, out error); Console.WriteLine("Error code: " + error.ToString()); Cl.BuildProgram(program, 1, devices, string.Empty, null, IntPtr.Zero); commandQueue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error); Console.WriteLine("Error code: " + error.ToString()); }
public Horn_Schunck() { maxIteration = 10; alpha = 5; flowInterval = 3; w = 1; eps = (float)0.01; threshold = (float)0.5; pyramidLevel = 0; pyramidOn = 0; warps = 1; sources[0] = File_Handler.getKernelSourceFromLibrary("HornSchunck.cl"); Platform[] platforms = Cl.GetPlatformIDs(out error); Console.WriteLine("Error code: " + error.ToString()); devices = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out error); Console.WriteLine("Error code: " + error.ToString()); device = devices[0]; context = Cl.CreateContext(null, 1, devices, null, IntPtr.Zero, out error); Console.WriteLine("Error code: " + error.ToString()); program = Cl.CreateProgramWithSource(context, 1, sources, null, out error); Console.WriteLine("Error code: " + error.ToString()); Cl.BuildProgram(program, 1, devices, string.Empty, null, IntPtr.Zero); commandQueue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error); Console.WriteLine("Error code: " + error.ToString()); }
public static Program BuildProgram(Context context, Device device, string programText, out ErrorCode error) { OpenCL.Net.Program program = Cl.CreateProgramWithSource(context, 1, new[] { programText }, null, out error); error |= Cl.BuildProgram(program, 1, new[] { device }, string.Empty, null, IntPtr.Zero); return(program); }
public L1Flow() { tau = (float)0.25; lambda = (float)0.15; theta = (float)0.3; epsilon = (float)0.01; maxiter = 1; warps = 1; pyramidLevel = 2; threshold = (float)0.5; flowInterval = 2; sources[0] = File_Handler.getKernelSourceFromLibrary("TvL1gradrho.cl"); sources[1] = File_Handler.getKernelSourceFromLibrary("TvL1_divP_Flow.cl"); sources[2] = File_Handler.getKernelSourceFromLibrary("TvL1_calcP.cl"); Platform[] platforms = Cl.GetPlatformIDs(out error); Console.WriteLine("Error code: " + error.ToString()); devices = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out error); Console.WriteLine("Error code: " + error.ToString()); device = devices[0]; context = Cl.CreateContext(null, 1, devices, null, IntPtr.Zero, out error); Console.WriteLine("Error code: " + error.ToString()); program = Cl.CreateProgramWithSource(context, 3, sources, null, out error); Console.WriteLine("Error code: " + error.ToString()); Cl.BuildProgram(program, 1, devices, string.Empty, null, IntPtr.Zero); commandQueue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error); Console.WriteLine("Error code: " + error.ToString()); }
protected override void AddKernel(OpenCL.Net.Program program) { kernelResize = new KernelResize(context, commandQueue, program, out error); kernelLaplacian = new KernelLaplacian(context, commandQueue, program, out error); kernelSobel = new KernelSobel(context, commandQueue, program, out error); kernelGrayscale = new KernelGrayscale(context, commandQueue, program, out error); //kernelHybrid = new KernelHybrid(context, commandQueue, program, out error); kernelQuantize = new KernelQuantize(context, commandQueue, program, out error); kernelGenerateUnicode = new KernelGenerateUnicode(context, commandQueue, program, out error); kernelGammaCorrection = new KernelGammaCorrection(context, commandQueue, program, out error); kernelContrastStretch = new KernelContrastStretch(context, commandQueue, program, out error); }
public float [] MathFunctionsSingleTest(int[] input) { if (input.Length == 0) { return(new float[0]); } var source = @"#pragma OPENCL EXTENSION cl_khr_fp64 : enable __kernel void kernelCode(__global int* ___input___, __global float* ___result___) { int n0; float ___final___10; int ___flag___11; int ___id___ = get_global_id(0); n0 = ___input___[___id___]; float pi = 3.14159274f; float c = cos(((float) n0)); float s = sin(((float) n0)); float f = floor(pi); float sq = sqrt(((float) (n0 * n0))); float ex = exp(pi); float p = powr(pi, 2.0f); float a = fabs(c); float l = log(((float) n0)); ___final___10 = ((((((((f * pi) * c) * s) * sq) * ex) * p) * a) * l); ___result___[___id___] = ___final___10; } "; var output = new float[input.Length]; ErrorCode error; var a = Cl.CreateBuffer(env.Context, MemFlags.ReadOnly | MemFlags.None | MemFlags.UseHostPtr, (IntPtr)(input.Length * sizeof(int)), input, out error); var b = Cl.CreateBuffer(env.Context, MemFlags.WriteOnly | MemFlags.None | MemFlags.UseHostPtr, (IntPtr)(input.Length * sizeof(float)), output, out error); var max = Cl.GetDeviceInfo(env.Devices[0], DeviceInfo.MaxWorkGroupSize, out error).CastTo <uint>(); OpenCL.Net.Program program = Cl.CreateProgramWithSource(env.Context, 1u, new string[] { source }, null, out error); error = Cl.BuildProgram(program, (uint)env.Devices.Length, env.Devices, " -cl-fast-relaxed-math -cl-mad-enable ", null, IntPtr.Zero); OpenCL.Net.Kernel kernel = Cl.CreateKernel(program, "kernelCode", out error); error = Cl.SetKernelArg(kernel, 0, a); error = Cl.SetKernelArg(kernel, 1, b); Event eventID; error = Cl.EnqueueNDRangeKernel(env.CommandQueues[0], kernel, (uint)1, null, new IntPtr[] { (IntPtr)input.Length }, new IntPtr[] { (IntPtr)1 }, (uint)0, null, out eventID); env.CommandQueues[0].ReadFromBuffer(b, output); a.Dispose(); b.Dispose(); //env.Dispose(); return(output); }
public ClKernel(Context context, CommandQueue commandQueue, OpenCL.Net.Program program, string KernelName, out ErrorCode error) { this.context = context; this.commandQueue = commandQueue; origin = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 }; kernel = Cl.CreateKernel(program, KernelName, out error); if (error != ErrorCode.Success) { initialized = false; } else { initialized = true; } }
public static Kernel LoadAndBuildKernel(string kernelFilePath, string kernelName) { // Attempt to read file if (!System.IO.File.Exists(kernelFilePath)) { Console.WriteLine("Program doesn't exist at path " + kernelFilePath); Console.ReadKey(); System.Environment.Exit(1); } string kernelSource = System.IO.File.ReadAllText(kernelFilePath); // Create program OpenCL.Net.Program clProgram = Cl.CreateProgramWithSource(context, 1, new[] { kernelSource }, null, out ClError); CheckErr(ClError, "CL.LoadAndBuildKernel: Cl.CreateProgramWithSource"); //Compile kernel source ClError = Cl.BuildProgram(clProgram, 1, new[] { device }, string.Empty, null, IntPtr.Zero); CheckErr(ClError, "CL.LoadAndBuildKernel: Cl.BuildProgram " + kernelFilePath); //Check for any compilation errors if (Cl.GetProgramBuildInfo(clProgram, device, ProgramBuildInfo.Status, out ClError).CastTo <BuildStatus>() != BuildStatus.Success) { CheckErr(ClError, "CL.LoadAndBuildKernel: Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(clProgram, device, ProgramBuildInfo.Log, out ClError)); Console.ReadKey(); System.Environment.Exit(1); } //Create the required kernel (entry function) Kernel kernel = Cl.CreateKernel(clProgram, kernelName, out ClError); CheckErr(ClError, "CL.LoadAndBuildKernel: Cl.CreateKernel " + kernelName); return(kernel); }
public void initialize(ComputeContext computeContext, Misc.Vector2<int> inputMapSize) { ErrorCode errorCode; bufferForCounterMap = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, (int)(inputMapSize.x * inputMapSize.y), out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForCounterOutputMap = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, (int)(inputMapSize.x * inputMapSize.y), out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForChangeMade = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, 1, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); program = Cl.CreateProgramWithSource(computeContext.context, 1, new[] { getOpenClSource() }, null, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.BuildProgram(program, 1, new[] { computeContext.chosenDevice }, "", null, IntPtr.Zero); if (errorCode != ErrorCode.Success) { OpenCL.Net.InfoBuffer logInfoBuffer = Cl.GetProgramBuildInfo(program, computeContext.chosenDevice, ProgramBuildInfo.Log, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); throw new ComputeContext.OpenClError(); } kernelNarrow = Cl.CreateKernel(program, "narrow", out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelNarrow, 4, (IntPtr)4, inputMapSize.x); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelNarrow, 5, (IntPtr)4, inputMapSize.y); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); }
public void initialize(ComputeContext computeContext, int searchRadius, Misc.Vector2<int> inputMapSize) { List<Vector2<int>> relativePositions; ErrorCode errorCode; int[] relativePositionsArray; OpenCL.Net.Event eventWriteBufferForRelativePositions; relativePositions = calculateRelativePositionsForRadius(searchRadius); numberOfAllocatedInputAndOutputPositions = 50000; bufferForInputMap = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, (int)(inputMapSize.x * inputMapSize.y), out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForRelativePositions = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, relativePositions.Count * 2, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); relativePositionsArray = convertRelativePositionsToArray(relativePositions); // copy relative positions into buffer errorCode = Cl.EnqueueWriteBuffer<int>(computeContext.commandQueue, bufferForRelativePositions, OpenCL.Net.Bool.True, relativePositionsArray, 0, new Event[] { }, out eventWriteBufferForRelativePositions); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForInputPositions = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, numberOfAllocatedInputAndOutputPositions * 2, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForOutputPositions = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, numberOfAllocatedInputAndOutputPositions * 2, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForFoundNewPosition = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, numberOfAllocatedInputAndOutputPositions, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); program = Cl.CreateProgramWithSource(computeContext.context, 1, new[] { getOpenClSource() }, null, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.BuildProgram(program, 1, new[] { computeContext.chosenDevice }, "", null, IntPtr.Zero); if (errorCode != ErrorCode.Success) { OpenCL.Net.InfoBuffer logInfoBuffer = Cl.GetProgramBuildInfo(program, computeContext.chosenDevice, ProgramBuildInfo.Log, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); throw new ComputeContext.OpenClError(); } kernelNearestPoint = Cl.CreateKernel(program, "findNearestPoint", out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<int>(kernelNearestPoint, 0, bufferForInputMap); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<int>(kernelNearestPoint, 1, bufferForRelativePositions); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<int>(kernelNearestPoint, 2, bufferForInputPositions); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<int>(kernelNearestPoint, 3, bufferForOutputPositions); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<int>(kernelNearestPoint, 4, bufferForFoundNewPosition); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelNearestPoint, 5, (IntPtr)4, relativePositions.Count); // number of relative positions ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelNearestPoint, 6, (IntPtr)4, inputMapSize.x); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelNearestPoint, 7, (IntPtr)4, inputMapSize.y); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); Cl.ReleaseEvent(eventWriteBufferForRelativePositions); }
public int[] ClosestPoints(double[,] source_points, double[,] target_points) { System.Diagnostics.Trace.Assert(source_points.GetLength(1) == target_points.GetLength(1)); int[] ans = new int[source_points.GetLength(0)]; CL.ErrorCode error; byte[] source_points_byte_array = new byte[Marshal.SizeOf(typeof(double)) * source_points.Length]; byte[] target_points_byte_array = new byte[Marshal.SizeOf(typeof(double)) * target_points.Length]; byte[] dims_byte_array = new byte[Marshal.SizeOf(typeof(int)) * 3]; byte[] output_byte_array = new byte[Marshal.SizeOf(typeof(int)) * ans.Length]; int[] dims = new[] { source_points.GetLength(1), source_points.GetLength(0), target_points.GetLength(0) }; MyCL.memcpy(ref source_points, ref source_points_byte_array); MyCL.memcpy(ref target_points, ref target_points_byte_array); MyCL.memcpy(ref dims, ref dims_byte_array); lock (cl_lock) { if (!program_initialized) { program_initialized = true; string programPath = Path.Combine(Environment.CurrentDirectory, "../../ClosestPoints.cl"); if (!File.Exists(programPath)) { throw new Exception("Program doesn't exist at path " + programPath); } string programSource = System.IO.File.ReadAllText(programPath); program = CL.Cl.CreateProgramWithSource(MyCL.context, 1, new[] { programSource }, null, out error); MyCL.CheckErr(error, "Cl.CreateProgramWithSource"); error = CL.Cl.BuildProgram(program, 1, new[] { MyCL.device }, string.Empty, null, IntPtr.Zero); MyCL.CheckErr(error, "Cl.BuildProgram"); if (CL.Cl.GetProgramBuildInfo(program, MyCL.device, CL.ProgramBuildInfo.Status, out error).CastTo <CL.BuildStatus>() != CL.BuildStatus.Success) { MyCL.CheckErr(error, "Cl.GetProgramBuildInfo"); throw new Exception($"Cl.GetProgramBuildInfo != Success\r\n{CL.Cl.GetProgramBuildInfo(program, MyCL.device, CL.ProgramBuildInfo.Log, out error)}"); } } using (CL.Kernel kernel = CL.Cl.CreateKernel(program, "weighted_sum", out error)) { MyCL.CheckErr(error, "Cl.CreateKernel"); //OpenCL memory buffer that will keep our image's byte[] data. using (CL.IMem source_points_buffer = CL.Cl.CreateBuffer(MyCL.context, CL.MemFlags.CopyHostPtr | CL.MemFlags.ReadOnly, source_points_byte_array, out CL.ErrorCode err1), target_points_buffer = CL.Cl.CreateBuffer(MyCL.context, CL.MemFlags.CopyHostPtr | CL.MemFlags.ReadOnly, target_points_byte_array, out CL.ErrorCode err2), dims_buffer = CL.Cl.CreateBuffer(MyCL.context, CL.MemFlags.CopyHostPtr | CL.MemFlags.ReadOnly, dims_byte_array, out CL.ErrorCode err3), output_buffer = CL.Cl.CreateBuffer(MyCL.context, CL.MemFlags.CopyHostPtr | CL.MemFlags.WriteOnly, output_byte_array, out CL.ErrorCode err4)) { MyCL.CheckErr(err1, "Cl.CreateBuffer source_points"); MyCL.CheckErr(err2, "Cl.CreateBuffer target_points"); MyCL.CheckErr(err3, "Cl.CreateBuffer dims"); MyCL.CheckErr(err4, "Cl.CreateBuffer output"); int intPtrSize = Marshal.SizeOf(typeof(IntPtr)); error = CL.Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, source_points_buffer) | CL.Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, target_points_buffer) | CL.Cl.SetKernelArg(kernel, 2, (IntPtr)intPtrSize, dims_buffer) | CL.Cl.SetKernelArg(kernel, 3, (IntPtr)intPtrSize, output_buffer); MyCL.CheckErr(error, "Cl.SetKernelArg"); //Create a command queue, where all of the commands for execution will be added using (CL.CommandQueue cmdQueue = CL.Cl.CreateCommandQueue(MyCL.context, MyCL.device, (CL.CommandQueueProperties) 0, out error)) { MyCL.CheckErr(error, "Cl.CreateCommandQueue"); CL.Event clevent; IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)source_points.GetLength(0) }; error = CL.Cl.EnqueueNDRangeKernel( cmdQueue, kernel, 1, null,//not used workGroupSizePtr, null, 0, null, out clevent); CL.Cl.ReleaseEvent(clevent); MyCL.CheckErr(error, "Cl.EnqueueNDRangeKernel"); error = CL.Cl.Finish(cmdQueue); MyCL.CheckErr(error, "Cl.Finish"); error = CL.Cl.EnqueueReadBuffer(cmdQueue, output_buffer, CL.Bool.True, 0, Marshal.SizeOf(typeof(byte)) * output_byte_array.Length, output_byte_array, 0, null, out clevent); CL.Cl.ReleaseEvent(clevent); MyCL.CheckErr(error, "Cl.EnqueueReadBuffer"); MyCL.memcpy(ref output_byte_array, ref ans); //CL.Cl.ReleaseCommandQueue(cmdQueue); } //CL.Cl.ReleaseMemObject(data_buffer); //CL.Cl.ReleaseMemObject(offsets_x_buffer); //CL.Cl.ReleaseMemObject(offsets_y_buffer); //CL.Cl.ReleaseMemObject(weights_buffer); //CL.Cl.ReleaseMemObject(dims_buffer); //CL.Cl.ReleaseMemObject(output_buffer); } //CL.Cl.ReleaseKernel(kernel); } } return(ans); }
public KernelGenerateUnicode(Context context, CommandQueue commandQueue, OpenCL.Net.Program program, out ErrorCode error) : base(context, commandQueue, program, KERNEL_NAME, out error) { }
public KernelContrastStretch(Context context, CommandQueue commandQueue, OpenCL.Net.Program program, out ErrorCode error) : base(context, commandQueue, program, KERNEL_NAME, out error) { }
public HTTPResponse GetResponse(HTTPRequest request) { HTTPResponse response = new HTTPResponse(200); StringBuilder sb = new StringBuilder(); ErrorCode error; if (!_isInit) { init(); _isInit = true; } if (request.Method == HTTPRequest.METHOD_GET) { sb.Append("<html><body>"); sb.Append(GenUploadForm()); sb.Append("</body></html>"); response.Body = Encoding.UTF8.GetBytes(sb.ToString()); return(response); } else if (request.Method == HTTPRequest.METHOD_POST) { sb.Append(request.Body); response.Body = Encoding.UTF8.GetBytes(sb.ToString()); string programPath = System.Environment.CurrentDirectory + "/Kernel.cl"; if (!System.IO.File.Exists(programPath)) { Console.WriteLine("Program doesn't exist at path " + programPath); return(new HTTPResponse(404)); } sb.Append("<html><body>"); string programSource = System.IO.File.ReadAllText(programPath); using (OpenCL.Net.Program program = Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error)) { LogError(error, "Cl.CreateProgramWithSource"); error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); LogError(error, "Cl.BuildProgram"); if (Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo <OpenCL.Net.BuildStatus>() != BuildStatus.Success) { LogError(error, "Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Log, out error)); return(new HTTPResponse(404)); } Kernel kernel = Cl.CreateKernel(program, "answer", out error); LogError(error, "Cl.CreateKernel"); Random rand = new Random(); int[] input = (from i in Enumerable.Range(0, 100) select(int) rand.Next()).ToArray(); int[] output = new int[100]; var buffIn = _context.CreateBuffer(input, MemFlags.ReadOnly); var buffOut = _context.CreateBuffer(output, MemFlags.WriteOnly); int IntPtrSize = Marshal.SizeOf(typeof(IntPtr)); error = Cl.SetKernelArg(kernel, 0, (IntPtr)IntPtrSize, buffIn); error |= Cl.SetKernelArg(kernel, 1, (IntPtr)IntPtrSize, buffOut); LogError(error, "Cl.SetKernelArg"); CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error); LogError(error, "Cl.CreateCommandQueue"); Event clevent; error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, new[] { (IntPtr)100, (IntPtr)1 }, null, 0, null, out clevent); LogError(error, "Cl.EnqueueNDRangeKernel"); error = Cl.Finish(cmdQueue); LogError(error, "Cl.Finih"); error = Cl.EnqueueReadBuffer(cmdQueue, buffOut, OpenCL.Net.Bool.True, 0, 100, output, 0, null, out clevent); LogError(error, "Cl.EnqueueReadBuffer"); error = Cl.Finish(cmdQueue); LogError(error, "Cl.Finih"); Cl.ReleaseKernel(kernel); Cl.ReleaseCommandQueue(cmdQueue); Cl.ReleaseMemObject(buffIn); Cl.ReleaseMemObject(buffOut); sb.Append("<pre>"); for (int i = 0; i != 100; i++) { sb.Append(input[i] + " % 42 = " + output[i] + "<br />"); } sb.Append("</pre>"); } sb.Append("</body></html>"); response.Body = Encoding.UTF8.GetBytes(sb.ToString()); return(response); } return(new HTTPResponse(501)); }
private void FixImage() { Event e; ErrorCode error; OpenCL.Net.Program program = Cl.CreateProgramWithSource(context, 1, new[] { script }, null, out error); error = Cl.BuildProgram(program, 0, null, string.Empty, null, IntPtr.Zero); //MessageBox.Show(error.ToString()); Kernel kernel = Cl.CreateKernel(program, "fixImage", out error); int intPtrSize = Marshal.SizeOf(typeof(IntPtr)); Mem dest; OpenCL.Net.ImageFormat clImageFormat = new OpenCL.Net.ImageFormat(OpenCL.Net.ChannelOrder.RGBA, OpenCL.Net.ChannelType.Unsigned_Int8); int inputImgWidth, inputImgHeight; Image img = Image.FromFile(path); inputImgWidth = img.Width; inputImgHeight = img.Height; Bitmap bmp = new Bitmap(img); float[] buffer = new float[40960 * count]; float[] array = new float[] { radius, O.X, O.Y }; dest = (Mem)Cl.CreateBuffer(context, MemFlags.WriteOnly, new IntPtr(count * 40960 * sizeof(float)), out error); Mem P = (Mem)Cl.CreateBuffer(context, MemFlags.ReadWrite, Marshal.SizeOf(typeof(PointF)) * 10240 * count, out error); Mem data = (Mem)Cl.CreateBuffer(context, MemFlags.ReadOnly, Marshal.SizeOf(typeof(PointF)) * points.Count, out error); Mem ptr = (Mem)Cl.CreateBuffer(context, MemFlags.ReadOnly, 3 * sizeof(float), out error); Cl.EnqueueWriteBuffer(queue, P, Bool.True, IntPtr.Zero, new IntPtr(Marshal.SizeOf(typeof(PointF)) * 10240 * count), map.ToArray(), 0, null, out e); Cl.EnqueueWriteBuffer(queue, data, Bool.True, IntPtr.Zero, new IntPtr(Marshal.SizeOf(typeof(PointF)) * points.Count), points.ToArray(), 0, null, out e); Cl.EnqueueWriteBuffer(queue, ptr, Bool.True, IntPtr.Zero, (IntPtr)3, array, 0, null, out e); error = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, dest); error |= Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, P); error |= Cl.SetKernelArg(kernel, 2, (IntPtr)intPtrSize, data); error |= Cl.SetKernelArg(kernel, 3, (IntPtr)intPtrSize, ptr); error |= Cl.SetKernelArg(kernel, 4, (IntPtr)intPtrSize, points.Count); IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)count, (IntPtr)10240 }; Cl.EnqueueNDRangeKernel(queue, kernel, 2, null, workGroupSizePtr, null, 0, null, out e); Cl.Finish(queue); error |= Cl.EnqueueReadBuffer(queue, dest, Bool.True, IntPtr.Zero, new IntPtr(sizeof(float) * 40960 * count), buffer, 0, null, out e); Cl.ReleaseKernel(kernel); Cl.ReleaseCommandQueue(queue); Cl.ReleaseMemObject(dest); Cl.ReleaseMemObject(P); Cl.ReleaseMemObject(data); for (int i = 0; i < buffer.Length; i += 4) { int dx = (int)Math.Round(buffer[i]); int dy = (int)Math.Round(buffer[i + 1]); int sx = (int)Math.Round(buffer[i + 2]); int sy = (int)Math.Round(buffer[i + 3]); bool test = (sx >= 0 && sx < img.Width) && (sy >= 0 && sy < img.Height); Color src = test ? bmp.GetPixel(sx, sy) : Color.White; if ((dx >= 0 && dx < img.Width) && (dy >= 0 && dy < img.Height)) { bmp.SetPixel(dx, dy, src); } } int index = path.LastIndexOf('.'); string ext = path.Substring(index + 1); newPath = path.Substring(0, index) + $"_final.{ext}"; System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg; if (ext == "bmp") { format = System.Drawing.Imaging.ImageFormat.Bmp; } else if (ext == "png") { format = System.Drawing.Imaging.ImageFormat.Png; } bmp.Save(newPath, format); }
private void init(string oclProgramSourcePath) { string kernelSource = File.ReadAllText(oclProgramSourcePath); string[] kernelNames = new string[] { "accumulate", "quickBlurImgH", "quickBlurImgV", "upsizeImg", "halfSizeImgH", "halfSizeImgV", "getLumaImg", "mapToGreyscaleBmp", "getContrastImg", "capHolesImg", "maxReduceImgH", "maxReduceImgV", "mapToFauxColorsBmp", "quickSpikesFilterImg", "convolveImg" }; bool gpu = true; //err = clGetDeviceIDs(NULL, gpu ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU, 1, &device_id, NULL); // NVidia driver doesn't seem to support a NULL first param (properties) // http://stackoverflow.com/questions/19140989/how-to-remove-cl-invalid-platform-error-in-opencl-code // now get all the platform IDs Platform[] platforms = Cl.GetPlatformIDs(out err); assert(err, "Error: Failed to get platform ids!"); InfoBuffer deviceInfo = Cl.GetPlatformInfo(platforms[0], PlatformInfo.Name, out err); assert(err, "error retrieving platform name"); Console.WriteLine("Platform name: {0}\n", deviceInfo.ToString()); // Arbitrary, should be configurable Device[] devices = Cl.GetDeviceIDs(platforms[0], gpu ? DeviceType.Gpu : DeviceType.Cpu, out err); assert(err, "Error: Failed to create a device group!"); _device = devices[0]; // Arbitrary, should be configurable deviceInfo = Cl.GetDeviceInfo(_device, DeviceInfo.Name, out err); assert(err, "error retrieving device name"); Debug.WriteLine("Device name: {0}", deviceInfo.ToString()); deviceInfo = Cl.GetDeviceInfo(_device, DeviceInfo.ImageSupport, out err); assert(err, "error retrieving device image capability"); Debug.WriteLine("Device supports img: {0}", (deviceInfo.CastTo <Bool>() == Bool.True)); // Create a compute context // _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out err); assert(err, "Error: Failed to create a compute context!"); // Create the compute program from the source buffer // _program = Cl.CreateProgramWithSource(_context, 1, new[] { kernelSource }, new[] { (IntPtr)kernelSource.Length }, out err); assert(err, "Error: Failed to create compute program!"); // Build the program executable // err = Cl.BuildProgram(_program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); assert(err, "Error: Failed to build program executable!"); InfoBuffer buffer = Cl.GetProgramBuildInfo(_program, _device, ProgramBuildInfo.Log, out err); Debug.WriteLine("build success: {0}", buffer.CastTo <BuildStatus>() == BuildStatus.Success); foreach (string kernelName in kernelNames) { // Create the compute kernel in the program we wish to run // OpenCL.Net.Kernel kernel = Cl.CreateKernel(_program, kernelName, out err); assert(err, "Error: Failed to create compute kernel!"); _kernels.Add(kernelName, kernel); } // Create a command queue // _commandsQueue = Cl.CreateCommandQueue(_context, _device, CommandQueueProperties.None, out err); assert(err, "Error: Failed to create a command commands!"); }
private void init(string oclProgramSourcePath) { string kernelSource = File.ReadAllText(oclProgramSourcePath); string[] kernelNames = new string[] { "accumulate", "quickBlurImgH", "quickBlurImgV", "upsizeImg", "halfSizeImgH", "halfSizeImgV", "getLumaImg", "mapToGreyscaleBmp", "getContrastImg", "capHolesImg", "maxReduceImgH", "maxReduceImgV", "mapToFauxColorsBmp", "quickSpikesFilterImg", "convolveImg" }; bool gpu = true; //err = clGetDeviceIDs(NULL, gpu ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU, 1, &device_id, NULL); // NVidia driver doesn't seem to support a NULL first param (properties) // http://stackoverflow.com/questions/19140989/how-to-remove-cl-invalid-platform-error-in-opencl-code // now get all the platform IDs Platform[] platforms = Cl.GetPlatformIDs(out err); assert(err, "Error: Failed to get platform ids!"); InfoBuffer deviceInfo = Cl.GetPlatformInfo(platforms[0], PlatformInfo.Name, out err); assert(err, "error retrieving platform name"); Console.WriteLine("Platform name: {0}\n", deviceInfo.ToString()); // Arbitrary, should be configurable Device[] devices = Cl.GetDeviceIDs(platforms[0], gpu ? DeviceType.Gpu : DeviceType.Cpu, out err); assert(err, "Error: Failed to create a device group!"); _device = devices[0]; // Arbitrary, should be configurable deviceInfo = Cl.GetDeviceInfo(_device, DeviceInfo.Name, out err); assert(err, "error retrieving device name"); Debug.WriteLine("Device name: {0}", deviceInfo.ToString()); deviceInfo = Cl.GetDeviceInfo(_device, DeviceInfo.ImageSupport, out err); assert(err, "error retrieving device image capability"); Debug.WriteLine("Device supports img: {0}", (deviceInfo.CastTo<Bool>() == Bool.True)); // Create a compute context // _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out err); assert(err, "Error: Failed to create a compute context!"); // Create the compute program from the source buffer // _program = Cl.CreateProgramWithSource(_context, 1, new[] { kernelSource }, new[] { (IntPtr)kernelSource.Length }, out err); assert(err, "Error: Failed to create compute program!"); // Build the program executable // err = Cl.BuildProgram(_program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); assert(err, "Error: Failed to build program executable!"); InfoBuffer buffer = Cl.GetProgramBuildInfo(_program, _device, ProgramBuildInfo.Log, out err); Debug.WriteLine("build success: {0}", buffer.CastTo<BuildStatus>() == BuildStatus.Success); foreach (string kernelName in kernelNames) { // Create the compute kernel in the program we wish to run // OpenCL.Net.Kernel kernel = Cl.CreateKernel(_program, kernelName, out err); assert(err, "Error: Failed to create compute kernel!"); _kernels.Add(kernelName, kernel); } // Create a command queue // _commandsQueue = Cl.CreateCommandQueue(_context, _device, CommandQueueProperties.None, out err); assert(err, "Error: Failed to create a command commands!"); }
public void initialize(ComputeContext computeContext, int kernelRadius, Misc.Vector2<int> inputMapSize) { ErrorCode errorCode; float[] kernelArray; OpenCL.Net.Event eventWriteBufferCompletedKernel; bufferForInputMap = Cl.CreateBuffer<float>(computeContext.context, MemFlags.AllocHostPtr, (int)(inputMapSize.x * inputMapSize.y), out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForTemporary = Cl.CreateBuffer<float>(computeContext.context, MemFlags.AllocHostPtr, (int)(inputMapSize.x * inputMapSize.y), out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForOutputMap = Cl.CreateBuffer<float>(computeContext.context, MemFlags.AllocHostPtr, (int)(inputMapSize.x * inputMapSize.y), out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); kernelArray = calculateKernel(kernelRadius); bufferForKernelArray = Cl.CreateBuffer<float>(computeContext.context, MemFlags.AllocHostPtr, kernelArray.Length, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); // copy kernel into buffer errorCode = Cl.EnqueueWriteBuffer<float>(computeContext.commandQueue, bufferForKernelArray, OpenCL.Net.Bool.True, kernelArray, 0, null, out eventWriteBufferCompletedKernel); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); string programLocation = Assembly.GetEntryAssembly().Location; string pathToLoad = Path.Combine(Path.GetDirectoryName(programLocation), "..\\..\\", "ComputationBackend\\OpenCl\\src\\Blur.cl"); string openClSource = File.ReadAllText(pathToLoad); program = Cl.CreateProgramWithSource(computeContext.context, 1, new[] { openClSource }, null, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.BuildProgram(program, 1, new[] { computeContext.chosenDevice }, "", null, IntPtr.Zero); if (errorCode != ErrorCode.Success) { OpenCL.Net.InfoBuffer logInfoBuffer = Cl.GetProgramBuildInfo(program, computeContext.chosenDevice, ProgramBuildInfo.Log, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); throw new ComputeContext.OpenClError(); } kernelBlurX = Cl.CreateKernel(program, "blurX", out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); //errorCode = Cl.SetKernelArg<float>(kernelBlurX, 0, bufferForInputMap); //ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<float>(kernelBlurX, 1, bufferForKernelArray); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); //errorCode = Cl.SetKernelArg<float>(kernelBlurX, 2, bufferForTemporary); //ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelBlurX, 3, (IntPtr)4, kernelRadius); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelBlurX, 4, (IntPtr)4, inputMapSize.x); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); kernelBlurY = Cl.CreateKernel(program, "blurY", out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); //errorCode = Cl.SetKernelArg<float>(kernelBlurY, 0, bufferForTemporary); //ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<float>(kernelBlurY, 1, bufferForKernelArray); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); //errorCode = Cl.SetKernelArg<float>(kernelBlurY, 2, bufferForOutputMap); //ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelBlurY, 3, (IntPtr)4, kernelRadius); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelBlurY, 4, (IntPtr)4, inputMapSize.x); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg(kernelBlurY, 5, (IntPtr)4, inputMapSize.y); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); Cl.ReleaseEvent(eventWriteBufferCompletedKernel); }
public HTTPResponse GetResponse(HTTPRequest request) { HTTPResponse response = new HTTPResponse(200); StringBuilder sb = new StringBuilder(); ErrorCode error; if (!_isInit) { init(); _isInit = true; } if (request.Method == HTTPRequest.METHOD_GET) { // Input form, this can be place by any HTML page sb.Append("<html><body>"); sb.Append(GenUploadForm()); sb.Append("</body></html>"); response.Body = Encoding.UTF8.GetBytes(sb.ToString()); return(response); } else if (request.Method == HTTPRequest.METHOD_POST) { // Get remote image from URL string url = Uri.UnescapeDataString(request.GetRequestByKey("imageUploadUrl")); byte[] data; try { data = DownloadImageFromUrl(url); } catch (Exception) { return(new HTTPResponse(400)); } // https://www.codeproject.com/Articles/502829/GPGPU-image-processing-basics-using-OpenCL-NET // Convert image to bitmap binary Image inputImage = Image.FromStream(new MemoryStream(data)); if (inputImage == null) { return(new HTTPResponse(500)); } int imagewidth = inputImage.Width; int imageHeight = inputImage.Height; Bitmap bmpImage = new Bitmap(inputImage); BitmapData bitmapData = bmpImage.LockBits(new Rectangle(0, 0, bmpImage.Width, bmpImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int inputImageByteSize = bitmapData.Stride * bitmapData.Height; byte[] inputByteArray = new byte[inputImageByteSize]; Marshal.Copy(bitmapData.Scan0, inputByteArray, 0, inputImageByteSize); // Load kernel source code string programPath = System.Environment.CurrentDirectory + "/Kernel.cl"; if (!System.IO.File.Exists(programPath)) { return(new HTTPResponse(404)); } string programSource = System.IO.File.ReadAllText(programPath); using (OpenCL.Net.Program program = Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error)) { // Create kernel LogError(error, "Cl.CreateProgramWithSource"); error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); LogError(error, "Cl.BuildProgram"); if (Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo <OpenCL.Net.BuildStatus>() != BuildStatus.Success) { LogError(error, "Cl.GetProgramBuildInfo"); return(new HTTPResponse(404)); } Kernel kernel = Cl.CreateKernel(program, _parameters["KernelFunction"], out error); LogError(error, "Cl.CreateKernel"); // Create image memory objects OpenCL.Net.ImageFormat clImageFormat = new OpenCL.Net.ImageFormat(ChannelOrder.RGBA, ChannelType.Unsigned_Int8); IMem inputImage2DBuffer = Cl.CreateImage2D(_context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, clImageFormat, (IntPtr)bitmapData.Width, (IntPtr)bitmapData.Height, (IntPtr)0, inputByteArray, out error); LogError(error, "CreateImage2D input"); byte[] outputByteArray = new byte[inputImageByteSize]; IMem outputImage2DBuffer = Cl.CreateImage2D(_context, MemFlags.CopyHostPtr | MemFlags.WriteOnly, clImageFormat, (IntPtr)bitmapData.Width, (IntPtr)bitmapData.Height, (IntPtr)0, outputByteArray, out error); LogError(error, "CreateImage2D output"); // Set arguments int IntPtrSize = Marshal.SizeOf(typeof(IntPtr)); error = Cl.SetKernelArg(kernel, 0, (IntPtr)IntPtrSize, inputImage2DBuffer); error |= Cl.SetKernelArg(kernel, 1, (IntPtr)IntPtrSize, outputImage2DBuffer); LogError(error, "Cl.SetKernelArg"); // Create command queue CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error); LogError(error, "Cl.CreateCommandQueue"); Event clevent; // Copy input image from the host to the GPU IntPtr[] originPtr = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 }; IntPtr[] regionPtr = new IntPtr[] { (IntPtr)imagewidth, (IntPtr)imageHeight, (IntPtr)1 }; IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)imagewidth, (IntPtr)imageHeight, (IntPtr)1 }; error = Cl.EnqueueWriteImage(cmdQueue, inputImage2DBuffer, Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, inputByteArray, 0, null, out clevent); LogError(error, "Cl.EnqueueWriteImage"); // Run the kernel error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent); LogError(error, "Cl.EnqueueNDRangeKernel"); // Wait for finish event error = Cl.Finish(cmdQueue); LogError(error, "Cl.Finish"); // Read the output image back from GPU error = Cl.EnqueueReadImage(cmdQueue, outputImage2DBuffer, Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, outputByteArray, 0, null, out clevent); LogError(error, "Cl.EnqueueReadImage"); error = Cl.Finish(cmdQueue); LogError(error, "Cl.Finih"); // Release memory Cl.ReleaseKernel(kernel); Cl.ReleaseCommandQueue(cmdQueue); Cl.ReleaseMemObject(inputImage2DBuffer); Cl.ReleaseMemObject(outputImage2DBuffer); // Convert binary bitmap to JPEG image and return as response GCHandle pinnedOutputArray = GCHandle.Alloc(outputByteArray, GCHandleType.Pinned); IntPtr outputBmpPointer = pinnedOutputArray.AddrOfPinnedObject(); Bitmap outputBitmap = new Bitmap(imagewidth, imageHeight, bitmapData.Stride, PixelFormat.Format32bppArgb, outputBmpPointer); MemoryStream msOutput = new MemoryStream(); outputBitmap.Save(msOutput, System.Drawing.Imaging.ImageFormat.Jpeg); response.Body = msOutput.ToArray(); response.Type = "image/jpeg"; return(response); } } return(new HTTPResponse(501)); }
/* Broken at the moment. */ public void GetStatGPU(string file) { var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); stopwatch.Restart(); ErrorCode err; using (OpenCL.Net.Program program = Cl.CreateProgramWithSource(clInfo._context, 1, new[] { clInfo.KernelSrc }, null, out err)) { clInfo.CheckErr(err, "Cl.CreateProgramWithSource"); //Compile Kernels & check errors. err = Cl.BuildProgram(program, 1, new[] { clInfo._device }, string.Empty, null, IntPtr.Zero); clInfo.CheckErr(err, "Cl.BuildProgram"); if (Cl.GetProgramBuildInfo(program, clInfo._device, ProgramBuildInfo.Status, out err).CastTo <BuildStatus>() != BuildStatus.Success) { clInfo.CheckErr(err, "Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(program, clInfo._device, ProgramBuildInfo.Log, out err)); } //Specify the specific kernel for use Kernel kernel = Cl.CreateKernel(program, "satAvg", out err); clInfo.CheckErr(err, "Cl.CreateKernel"); int intPtrSize = 0; intPtrSize = Marshal.SizeOf(typeof(IntPtr)); IMem image2DBuffer; OpenCL.Net.ImageFormat imageFormat = new OpenCL.Net.ImageFormat(ChannelOrder.RGBA, ChannelType.Unsigned_Int8); int imageWidth, imageHeight, imageBytesSize, imageStride; using (FileStream imgStream = new FileStream(file, FileMode.Open)) { Image image = Image.FromStream(imgStream); if (image == null) { Console.Error.WriteLine($"failed to open file {file}"); return; } imageWidth = image.Width; imageHeight = image.Height; //Create a bitmap from the file with the correct channel settings. Bitmap inputBitmap = new Bitmap(image); BitmapData bitmapDat = inputBitmap.LockBits(new Rectangle(0, 0, inputBitmap.Width, inputBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); imageStride = bitmapDat.Stride; imageBytesSize = imageStride * bitmapDat.Height; byte[] inputByteArray = new byte[imageBytesSize]; Marshal.Copy(bitmapDat.Scan0, inputByteArray, 0, imageBytesSize); //Create & populate memory buffer for use in Kernel image2DBuffer = Cl.CreateImage2D(clInfo._context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, imageFormat, (IntPtr)inputBitmap.Width, (IntPtr)inputBitmap.Height, (IntPtr)0, inputByteArray, out err); clInfo.CheckErr(err, "Cl.CreateImage2D output"); } //Create an output buffer for the average saturation of the image. float saturation = 0; IMem sat = Cl.CreateBuffer(clInfo._context, MemFlags.CopyHostPtr | MemFlags.WriteOnly, (IntPtr)intPtrSize, (object)saturation, out err); clInfo.CheckErr(err, "Cl.CreateBuffer saturation"); //Passing buffers to the CL kernel err = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, image2DBuffer); //TODO: Figure out how to pass a float to the kernel //err |= Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, sat ); clInfo.CheckErr(err, "Cl.SetKernelArg"); //Create & queue commands CommandQueue cmdQueue = Cl.CreateCommandQueue(clInfo._context, clInfo._device, CommandQueueProperties.None, out err); clInfo.CheckErr(err, "Cl.CreateCommandQueue"); Event @event; //Transfer image data to kernel buffers IntPtr[] originPtr = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 }; IntPtr[] regionPtr = new IntPtr[] { (IntPtr)imageWidth, (IntPtr)imageHeight, (IntPtr)1 }; IntPtr[] workGroupPtr = new IntPtr[] { (IntPtr)imageWidth, (IntPtr)imageHeight, (IntPtr)1 }; err = Cl.EnqueueReadImage(cmdQueue, image2DBuffer, Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, null, 0, null, out @event); clInfo.CheckErr(err, "Cl.EnqueueReadImage"); //Execute the kerenl err = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, workGroupPtr, null, 0, null, out @event); clInfo.CheckErr(err, "Cl.EnqueueNDRangeKernel"); err = Cl.Finish(cmdQueue); clInfo.CheckErr(err, "Cl.Finish"); Cl.ReleaseKernel(kernel); Cl.ReleaseCommandQueue(cmdQueue); Cl.ReleaseMemObject(image2DBuffer); } Console.WriteLine(stopwatch.Elapsed); stopwatch.Stop(); }
public void initialize(ComputeContext computeContext, int kernelPositionsLength, Misc.Vector2<int> inputMapSize) { ErrorCode errorCode; OpenCL.Net.Event eventWriteBufferCompletedKernel; this.kernelPositionsLength = kernelPositionsLength; kernelResults = new float[kernelPositionsLength]; bufferForPositions = Cl.CreateBuffer<int>(computeContext.context, MemFlags.AllocHostPtr, 2 * kernelPositionsLength, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForInputMap = Cl.CreateBuffer<float>(computeContext.context, MemFlags.AllocHostPtr, (int)(inputMapSize.x * inputMapSize.y), out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); OpenCL.Net.IMem<float> bufferForKernel = Cl.CreateBuffer<float>(computeContext.context, MemFlags.AllocHostPtr, (kernelWidth * kernelWidth), out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); bufferForKernelResults = Cl.CreateBuffer<float>(computeContext.context, MemFlags.AllocHostPtr, kernelPositionsLength, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.EnqueueWriteBuffer<float>(computeContext.commandQueue, bufferForKernel, OpenCL.Net.Bool.True, this.kernelArray, 0, null, out eventWriteBufferCompletedKernel); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); program = Cl.CreateProgramWithSource(computeContext.context, 1, new[] { getProgramSource(inputMapSize.x, kernelPositionsLength) }, null, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.BuildProgram(program, 1, new[] { computeContext.chosenDevice }, "", null, IntPtr.Zero); if (errorCode != ErrorCode.Success) { OpenCL.Net.InfoBuffer logInfoBuffer = Cl.GetProgramBuildInfo(program, computeContext.chosenDevice, ProgramBuildInfo.Log, out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); throw new ComputeContext.OpenClError(); } kernel = Cl.CreateKernel(program, "kernel0", out errorCode); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<float>(kernel, 0, bufferForInputMap); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<float>(kernel, 1, bufferForKernel); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<int>(kernel, 2, bufferForPositions); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); errorCode = Cl.SetKernelArg<float>(kernel, 3, bufferForKernelResults); ComputeContext.throwErrorIfNotSuccessfull(errorCode, ""); Cl.ReleaseEvent(eventWriteBufferCompletedKernel); }
private string getProgramSource(int inputMapWidth, int kernelPositionsLength) { ProgramRepresentation.Program program; string innerOpenclProgram; string outerOpenclProgram; Dictionary<string, int> arrayWidths; program = ProgramRepresentation.Program.createProgramForParallelRadialKernel(); arrayWidths = new Dictionary<string, int>(); arrayWidths.Add("kernelArray", kernelWidth); arrayWidths.Add("resultMap", kernelPositionsLength); innerOpenclProgram = ProgramRepresentation.OpenClGenerator.generateSource(program, inputMapWidth, arrayWidths); outerOpenclProgram = ""; outerOpenclProgram += "__kernel void kernel0(__global float* inputMap, __global const float* kernelArray, __global int* positions, __global float* resultMap){"; outerOpenclProgram += "const int indexX = get_global_id(0);\n"; outerOpenclProgram += innerOpenclProgram; outerOpenclProgram += "}"; return outerOpenclProgram; }
public KernelLaplacian(Context context, CommandQueue commandQueue, OpenCL.Net.Program program, out ErrorCode error) : base(context, commandQueue, program, KERNEL_NAME, out error) { }
private void LoadProgram() { Cl.ErrorCode error; if (!System.IO.File.Exists(programPath)) { Console.WriteLine("Program doesn't exist at path " + programPath); return; } string programSource = System.IO.File.ReadAllText(programPath); program = Cl.Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error); CheckErr(error, "Cl.CreateProgramWithSource"); //Compile kernel source #if DEBUG var args = string.Format("-g -s \"{0}\"", programPath); error = Cl.Cl.BuildProgram(program, 0, null, args, null, IntPtr.Zero); #else error = Cl.Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); #endif CheckErr(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.Cl.GetProgramBuildInfo(program, _device, Cl.ProgramBuildInfo.Status, out error).CastTo<Cl.BuildStatus>() != Cl.BuildStatus.Success) { CheckErr(error, "Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.Cl.GetProgramBuildInfo(program, _device, Cl.ProgramBuildInfo.Log, out error)); return; } }