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 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()); }
/// <summary> /// /// </summary> /// <param name="sourceGpuCode">CL code to execute</param> /// <param name="methodeName">main methode name (__kernal xxxxx())</param> /// <returns></returns> public static OpenClBridge CompileProgramFromSource(string sourceGpuCode, string methodeName) { #region create program Program program = Cl.CreateProgramWithSource(Context, 1, new[] { sourceGpuCode }, null, out ErrorCode error); if (error != ErrorCode.Success) { throw new GPUException("Compile0x1", Cl.GetProgramBuildInfo(program, Device, ProgramBuildInfo.Log, out error).ToString()); } if (Cl.BuildProgram(program, 1, new[] { Device }, string.Empty, null, IntPtr.Zero) != ErrorCode.Success) { throw new GPUException("Compile0x2", Cl.GetProgramBuildInfo(program, Device, ProgramBuildInfo.Log, out error).ToString()); } if (Cl.GetProgramBuildInfo(program, Device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>() != BuildStatus.Success) { throw new GPUException("Compile0x3", Cl.GetProgramBuildInfo(program, Device, ProgramBuildInfo.Log, out error).ToString()); } #endregion create program #region create kernal Kernel kernel = Cl.CreateKernel(program, methodeName, out error); if (error != ErrorCode.Success) { throw new GPUException("Compile0x4", error.ToString()); } return(new OpenClBridge(kernel, sourceGpuCode, methodeName)); #endregion create kernal }
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()); }
private Kernel CompileKernel(string kernelName) { ErrorCode error; if (!File.Exists(PROGRAM_PATH)) { throw new IOException("Program does not exist at path."); } string programSource = File.ReadAllText(PROGRAM_PATH); using (Program program = Cl.CreateProgramWithSource(context, 1, new[] { programSource }, null, out error)) { CheckErr(error, "Cl.CreateProgramWithSource"); //Compile kernel source error = Cl.BuildProgram(program, 1, new[] { device }, "-Werror", null, IntPtr.Zero); InfoBuffer log = Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Log, out error); Console.WriteLine(log); CheckErr(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>() != BuildStatus.Success) { CheckErr(error, "Cl.GetProgramBuildInfo"); } //Create the required kernel (entry function) Kernel kernel = Cl.CreateKernel(program, kernelName, out error); CheckErr(error, "Cl.CreateKernel"); return(kernel); } }
public void Run() { ErrorCode e = ErrorCode.Unknown; uint num = 0; err = Cl.GetPlatformIDs(1, platforms, out num); InfoBuffer platformbuf = Cl.GetPlatformInfo(platforms[0], PlatformInfo.Name, out e); device = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out e); InfoBuffer devicebuf = Cl.GetDeviceInfo(device[0], DeviceInfo.Name, out e); IntPtr ptr = new IntPtr(); IntPtr ptr2 = new IntPtr(); context = Cl.CreateContext(null, 1, new[] { device[0] }, null, ptr, out e); InfoBuffer contextbuff = new InfoBuffer(); e = Cl.GetContextInfo(context, ContextInfo.Devices, ptr, contextbuff, out ptr2); Program pg = Cl.CreateProgramWithSource(context, 1, new[] { correctSource }, null, out e); e = Cl.BuildProgram(pg, 1, new[] { device[0] }, string.Empty, null, IntPtr.Zero); InfoBuffer pgbuild = Cl.GetProgramBuildInfo(pg, device[0], ProgramBuildInfo.Log, out e); // Cl.BuildProgram(pg,1,device,"-cl-std=CL") }
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); }
private void CompileKernels(ExecutionContext executionContext) { var sources = SourceLoader.CreateProgramCollection(_source); _program = Cl.CreateProgramWithSource( executionContext.OpenClContext, (uint)sources.Length, sources, null, out var error ); if (error != ErrorCode.Success) { throw new NerotiqException($"Error creating program with source: {error}"); } error = Cl.BuildProgram(_program, 1, new[] { executionContext.Device }, string.Empty, null, IntPtr.Zero); if (error != ErrorCode.Success) { if (error == ErrorCode.BuildProgramFailure) { var buildInfoLog = Cl.GetProgramBuildInfo(_program, executionContext.Device, ProgramBuildInfo.Log, out var buildInfoError); throw new NerotiqException($"Error building program: {error}: {buildInfoLog}"); } throw new NerotiqException($"Error building program: {error}"); } // Get the kernels. _updateKernel = Cl.CreateKernel(_program, "update", out error); if (error != ErrorCode.Success) { throw new NerotiqException($"Error creating kernel update: {error}"); } }
public Program(Context context, string source) : this() { if (context == Context.Null) { throw new ArgumentNullException("context"); } if (source == null) { throw new ArgumentNullException("source"); } unsafe { var bytes = Encoding.ASCII.GetByteCount(source); byte *strings = stackalloc byte[bytes]; fixed(char *source_ptr = source) { Encoding.ASCII.GetBytes(source_ptr, source.Length, strings, bytes); } UIntPtr length = new UIntPtr((uint)bytes); int errcode = 0; Handle = Cl.CreateProgramWithSource(context.Handle, 1, &strings, &length, &errcode); ClHelper.GetError(errcode); } }
public static void Main(string[] args) { int dimX = GetParameter("--dimX", 322, args); int dimY = GetParameter("--dimY", 242, args); int N = GetParameter("--N", 97760, args); bool lmem = GetFlag("--lmem", args); Console.WriteLine("Poisson equation solver: dimX = {0} dimY = {1} N = {2}, LMem: {3}", dimX, dimY, N, lmem); string options = string.Join(" ", args.Where(arg => arg.IndexOf("--") == -1)); Console.WriteLine("OpenCL program build options: " + options); Cl.ErrorCode error; Cl.Device device = (from platformid in Cl.GetPlatformIDs(out error) from deviceid in Cl.GetDeviceIDs(platformid, Cl.DeviceType.Gpu, out error) select deviceid).First(); clSafeCall(error); Cl.Context context = Cl.CreateContext(null, 1, new[] { device }, null, IntPtr.Zero, out error); clSafeCall(error); // create program from C# kernel IRBuildOptions.AutoInline = GetFlag("--inline", args); IRBuildOptions.WasteRegisters = GetFlag("--rwaste", args); Console.WriteLine("IR code build options: AutoInline: {0}; WasteRegisters: {1}", IRBuildOptions.AutoInline, IRBuildOptions.WasteRegisters); Cl.Program pcsharp = typeof(MainClass).BuildIR().ToGPUClProgram(device, context); // create program from OpenCL kernel Cl.Program popencl = Cl.CreateProgramWithSource(context, 1, new[] { PoissonRBSORCl }, null, out error); clSafeCall(error); // perform bandwidth comparison float x0 = (float)(-0.5 * Math.PI); float y0 = (float)(-0.5 * Math.PI); float x1 = -x0; float y1 = -y0; float omega = 0.8f; Console.WriteLine("C# benchmark:"); long tcsharp = PoissonRBSOR(device, context, pcsharp, lmem, x0, y0, x1, y1, dimX, dimY, N, omega, "unigpu.bin", options); pcsharp.Dispose(); Console.WriteLine("OpenCL benchmark:"); long topencl = PoissonRBSOR(device, context, popencl, lmem, x0, y0, x1, y1, dimX, dimY, N, omega, "opencl.bin", options); popencl.Dispose(); Console.WriteLine("OpenCL advantage: {0}", (double)tcsharp / (double)topencl); context.Dispose(); }
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); }
/// <summary> /// Creates the program from source code /// </summary> /// <param name="sourceCode">source code</param> public void CreateProgram(string[] sourceCode) { string source = ""; for (int i = 0; i < sourceCode.Length; i++) { source += sourceCode[i]; } _program = Cl.CreateProgramWithSource(_handle.Context, 1, new[] { source }, new[] { new IntPtr(source.Length) }, out _error); CLException.CheckException(_error); }
private static Kernel _CompileKernel(this Context context, string source, string kernelName, out string errors, string options = null) { errors = string.Empty; ErrorCode error; var devicesInfoBuffer = Cl.GetContextInfo(context, ContextInfo.Devices, out error); var devices = devicesInfoBuffer.CastToArray <Device>((devicesInfoBuffer.Size / Marshal.SizeOf(typeof(IntPtr)))); var program = Cl.CreateProgramWithSource(context, 1, new[] { source }, new[] { (IntPtr)source.Length }, out error); error = Cl.BuildProgram(program, (uint)devices.Length, devices, options == null ? string.Empty : options, null, IntPtr.Zero); if (error != ErrorCode.Success) { errors = string.Join("\n", from device in devices select Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Log, out error).ToString()); return(new Kernel()); } return(Cl.CreateKernel(program, kernelName, out error)); }
public static ComputeProgram CreateProgram(params string[] code) { var prog = Cl.CreateProgramWithSource(_context, 1, code, null, out var err); Cl.BuildProgram(prog, 1, new[] { _device }, "", null, IntPtr.Zero); if (Cl.GetProgramBuildInfo(prog, _device, ProgramBuildInfo.Status, out err).CastTo <BuildStatus>() != BuildStatus.Success) { Console.WriteLine("Program Build Failure!"); throw new Exception(); } ComputeProgram program = new ComputeProgram() { prog = prog }; return(program); }
public static Program Compile(string source) { Program program = Cl.CreateProgramWithSource(Context, 1, new[] { source }, null, out ErrorCode error); if (error != ErrorCode.Success) { throw new GPUException("Compile0x1", Cl.GetProgramBuildInfo(program, Device, ProgramBuildInfo.Log, out error).ToString()); } if (Cl.BuildProgram(program, 1, new[] { Device }, string.Empty, null, IntPtr.Zero) != ErrorCode.Success) { throw new GPUException("Compile0x2", Cl.GetProgramBuildInfo(program, Device, ProgramBuildInfo.Log, out error).ToString()); } if (Cl.GetProgramBuildInfo(program, Device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>() != BuildStatus.Success) { throw new GPUException("Compile0x3", Cl.GetProgramBuildInfo(program, Device, ProgramBuildInfo.Log, out error).ToString()); } return(program); }
/// <summary> /// Load a C Script to a readable program. /// </summary> /// <param name="path">The path of the .c file</param> /// <param name="device">The device to compile for</param> /// <param name="context">The context of the device</param> /// <returns></returns> public static Program LoadProgram(string[] filePaths, string[] includeDirectoriesPath, Device device, Context context) { string[] files = new string[filePaths.Length]; for (int i = 0; i < filePaths.Length; i++) { files[i] = LoadC(filePaths[i]); } string args = ""; for (int i = 0; i < includeDirectoriesPath.Length; i++) { args += "-I " + @includeDirectoriesPath[i] + " "; } Program program = Cl.CreateProgramWithSource(context, (uint)files.Length, files, null, out ErrorCode builderror); builderror = Cl.BuildProgram(program, 0, null, args, null, IntPtr.Zero); //string[] paths = path.Split('\\'); //string filename = paths[paths.Length - 1]; if (Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Status, out ErrorCode error).CastTo <BuildStatus>() != BuildStatus.Success) { if (builderror != ErrorCode.Success) { //Console.ForegroundColor = ConsoleColor.Red; Log.Print("Error during compilation:\n" + Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Log, out error)); } } else { //Console.ForegroundColor = ConsoleColor.Green; Log.Print("C files compiled with no error."); } Console.ResetColor(); return(program); }
public OpenClCompiler(Device device, string source) { _device = device; _ctx = device.CreateContext(); Source = source; _program = new Program(Cl.CreateProgramWithSource(_ctx, 1, new string[] { source }, null, out ErrorCode error)); Cl.BuildProgram(_program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); KernelCount = _program.NumKernels; Methodes = _program.KernelNames; _kernels = new Kernel[KernelCount]; if ((error = Cl.CreateKernelsInProgram(_program, KernelCount, _kernels, out _)) != ErrorCode.Success) { throw new Exception($"{error}"); } _queue = Cl.CreateCommandQueue(_ctx, _device, CommandQueueProperties.None, out _); }
public OpenClCompiler(Device device, string source) { _device = device; _ctx = device.CreateContext(); SVMCapabilities capabilities = _device.SvmCapabilities; IsCoarseGrainBufferSupported = (capabilities & SVMCapabilities.SvmCoarseGrainBuffer) == SVMCapabilities.SvmCoarseGrainBuffer; IsFineGrainBufferSupported = (capabilities & SVMCapabilities.SvmFineGrainBuffer) == SVMCapabilities.SvmFineGrainBuffer; IsFineGrainSystemSupported = (capabilities & SVMCapabilities.SvmFineGrainSystem) == SVMCapabilities.SvmFineGrainSystem; IsAtomicSupported = (capabilities & SVMCapabilities.SvmAtomics) == SVMCapabilities.SvmAtomics; Source = source; _program = new Program(Cl.CreateProgramWithSource(_ctx, 1, new string[] { source }, null, out ErrorCode error)); Cl.BuildProgram(_program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); KernelCount = _program.NumKernels; Methodes = _program.KernelNames; _kernels = new Kernel[KernelCount]; Cl.CreateKernelsInProgram(_program, KernelCount, _kernels, out _); }
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); }
private static void LoadKernel(string file, string name, out Program?program, out Kernel?kernel) { ErrorCode error; if (File.Exists(file)) { string programSource = File.ReadAllText(file); program = Cl.CreateProgramWithSource(context, 1, new[] { programSource }, null, out error); ErrorCheck(error, "Cl.CreateProgramWithSource"); //Compile kernel source error = Cl.BuildProgram(program.Value, 1, new[] { device }, string.Empty, null, IntPtr.Zero); ErrorCheck(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.GetProgramBuildInfo(program.Value, device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>() != BuildStatus.Success) { ErrorCheck(error, "Cl.GetProgramBuildInfo"); Cl.ReleaseContext(context); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(program.Value, device, ProgramBuildInfo.Log, out error)); Console.ReadKey(); } //Create the required kernel (entry function) kernel = Cl.CreateKernel(program.Value, name, out error); ErrorCheck(error, "Cl.CreateKernel"); } else { program = null; kernel = null; } }
private void ready() { ErrorCode error; context = Cl.CreateContext(null, 1, new[] { device }, null, IntPtr.Zero, out error); string source = System.IO.File.ReadAllText("kernels.cl"); program = Cl.CreateProgramWithSource(context, 1, new[] { source }, null, out error); error = Cl.BuildProgram(program, 1, new[] { device }, string.Empty, null, IntPtr.Zero); InfoBuffer buildStatus = Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Status, out error); if (buildStatus.CastTo <BuildStatus>() != BuildStatus.Success) { throw new Exception($"OpenCL could not build the kernel successfully: {buildStatus.CastTo<BuildStatus>()}"); } allGood(error); Kernel[] kernels = Cl.CreateKernelsInProgram(program, out error); kernel = kernels[0]; allGood(error); queue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error); allGood(error); dataOut = Cl.CreateBuffer(context, MemFlags.WriteOnly, (IntPtr)(globalSize * sizeof(int)), out error); allGood(error); var intSizePtr = new IntPtr(Marshal.SizeOf(typeof(int))); error |= Cl.SetKernelArg(kernel, 2, new IntPtr(Marshal.SizeOf(typeof(IntPtr))), dataOut); error |= Cl.SetKernelArg(kernel, 3, intSizePtr, new IntPtr(worldSeed)); error |= Cl.SetKernelArg(kernel, 4, intSizePtr, new IntPtr(globalSize)); allGood(error); }
// Partially from OpenTK demo - Submitted by "mfagerlund" public void AddArrayAddsCorrectly() { const string correctSource = @" // Simple test; c[i] = a[i] + b[i] __kernel void add_array(__global float *a, __global float *b, __global float *c) { int xid = get_global_id(0); c[xid] = a[xid] + b[xid]; } __kernel void sub_array(__global float *a, __global float *b, __global float *c) { int xid = get_global_id(0); c[xid] = a[xid] - b[xid]; } "; ErrorCode error; using (Program program = Cl.CreateProgramWithSource(_context, 1, new[] { correctSource }, null, out error)) { Assert.AreEqual(error, ErrorCode.Success); error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); Assert.AreEqual(ErrorCode.Success, error); Assert.AreEqual(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>(), BuildStatus.Success); Kernel[] kernels = Cl.CreateKernelsInProgram(program, out error); Kernel kernel = kernels[0]; const int cnBlockSize = 4; const int cnBlocks = 3; IntPtr cnDimension = new IntPtr(cnBlocks * cnBlockSize); // allocate host vectors float[] A = new float[cnDimension.ToInt32()]; float[] B = new float[cnDimension.ToInt32()]; float[] C = new float[cnDimension.ToInt32()]; // initialize host memory Random rand = new Random(); for (int i = 0; i < A.Length; i++) { A[i] = rand.Next() % 256; B[i] = rand.Next() % 256; } //Cl.IMem hDeviceMemA = Cl.CreateBuffer(_context, Cl.MemFlags.CopyHostPtr | Cl.MemFlags.ReadOnly, (IntPtr)(sizeof(float) * cnDimension.ToInt32()), A, out error); //Assert.AreEqual(Cl.ErrorCode.Success, error); IMem <float> hDeviceMemA = Cl.CreateBuffer(_context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, A, out error); Assert.AreEqual(ErrorCode.Success, error); IMem hDeviceMemB = Cl.CreateBuffer(_context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, (IntPtr)(sizeof(float) * cnDimension.ToInt32()), B, out error); Assert.AreEqual(ErrorCode.Success, error); IMem hDeviceMemC = Cl.CreateBuffer(_context, MemFlags.WriteOnly, (IntPtr)(sizeof(float) * cnDimension.ToInt32()), IntPtr.Zero, out error); Assert.AreEqual(ErrorCode.Success, error); CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error); Event clevent; int intPtrSize = 0; intPtrSize = Marshal.SizeOf(typeof(IntPtr)); // setup parameter values error = Cl.SetKernelArg(kernel, 0, new IntPtr(intPtrSize), hDeviceMemA); Assert.AreEqual(ErrorCode.Success, error); error = Cl.SetKernelArg(kernel, 1, new IntPtr(intPtrSize), hDeviceMemB); Assert.AreEqual(ErrorCode.Success, error); error = Cl.SetKernelArg(kernel, 2, new IntPtr(intPtrSize), hDeviceMemC); Assert.AreEqual(ErrorCode.Success, error); // write data from host to device error = Cl.EnqueueWriteBuffer(cmdQueue, hDeviceMemA, Bool.True, IntPtr.Zero, new IntPtr(cnDimension.ToInt32() * sizeof(float)), A, 0, null, out clevent); Assert.AreEqual(ErrorCode.Success, error); error = Cl.EnqueueWriteBuffer(cmdQueue, hDeviceMemB, Bool.True, IntPtr.Zero, new IntPtr(cnDimension.ToInt32() * sizeof(float)), B, 0, null, out clevent); Assert.AreEqual(ErrorCode.Success, error); // execute kernel error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 1, null, new IntPtr[] { cnDimension }, null, 0, null, out clevent); Assert.AreEqual(ErrorCode.Success, error, error.ToString()); // copy results from device back to host IntPtr event_handle = IntPtr.Zero; error = Cl.EnqueueReadBuffer(cmdQueue, hDeviceMemC, Bool.True, 0, C.Length, C, 0, null, out clevent); Assert.AreEqual(ErrorCode.Success, error, error.ToString()); for (int i = 0; i < A.Length; i++) { Assert.That(A[i] + B[i], Is.EqualTo(C[i])); } Cl.Finish(cmdQueue); Cl.ReleaseMemObject(hDeviceMemA); Cl.ReleaseMemObject(hDeviceMemB); Cl.ReleaseMemObject(hDeviceMemC); } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); uint platformCount; ErrorCode result = Cl.GetPlatformIDs(0, null, out platformCount); Console.WriteLine("{0} platforms found", platformCount); var platformIds = new Platform[platformCount]; result = Cl.GetPlatformIDs(platformCount, platformIds, out platformCount); var platformCounter = 0; foreach (var platformId in platformIds) { IntPtr paramSize; result = Cl.GetPlatformInfo(platformId, PlatformInfo.Name, IntPtr.Zero, InfoBuffer.Empty, out paramSize); using (var buffer = new InfoBuffer(paramSize)) { result = Cl.GetPlatformInfo(platformIds[0], PlatformInfo.Name, paramSize, buffer, out paramSize); Console.WriteLine($"Platform {platformCounter}: {buffer}"); } platformCounter++; } Console.WriteLine($"Using first platform..."); uint deviceCount; result = Cl.GetDeviceIDs(platformIds[0], DeviceType.All, 0, null, out deviceCount); Console.WriteLine("{0} devices found", deviceCount); var deviceIds = new Device[deviceCount]; result = Cl.GetDeviceIDs(platformIds[0], DeviceType.All, deviceCount, deviceIds, out var numberDevices); var selectedDevice = deviceIds[0]; var context = Cl.CreateContext(null, 1, new[] { selectedDevice }, null, IntPtr.Zero, out var error); const string kernelSrc = @" // Simple test; c[i] = a[i] + b[i] __kernel void add_array(__global float *a, __global float *b, __global float *c) { int xid = get_global_id(0); c[xid] = a[xid] + b[xid] - 1500; } __kernel void sub_array(__global float *a, __global float *b, __global float *c) { int xid = get_global_id(0); c[xid] = a[xid] - b[xid] - 2000; } __kernel void double_everything(__global float *a) { int xid = get_global_id(0); a[xid] = a[xid] * 2; } "; var src = kernelSrc; Console.WriteLine("=== src ==="); Console.WriteLine(src); Console.WriteLine("============"); var program = Cl.CreateProgramWithSource(context, 1, new[] { src }, null, out var error2); error2 = Cl.BuildProgram(program, 1, new[] { selectedDevice }, string.Empty, null, IntPtr.Zero); if (error2 == ErrorCode.BuildProgramFailure) { Console.Error.WriteLine(Cl.GetProgramBuildInfo(program, selectedDevice, ProgramBuildInfo.Log, out error)); } Console.WriteLine(error2); // Get the kernels. var kernels = Cl.CreateKernelsInProgram(program, out error); Console.WriteLine($"Program contains {kernels.Length} kernels."); var kernelAdd = kernels[0]; var kernelDouble = kernels[2]; // float[] A = new float[1000]; float[] B = new float[1000]; float[] C = new float[1000]; for (var i = 0; i < 1000; i++) { A[i] = i; B[i] = i; } IMem <float> hDeviceMemA = Cl.CreateBuffer(context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, A, out error); IMem <float> hDeviceMemB = Cl.CreateBuffer(context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, B, out error); IMem <float> hDeviceMemC = Cl.CreateBuffer(context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, C, out error); // Create a command queue. var cmdQueue = Cl.CreateCommandQueue(context, selectedDevice, CommandQueueProperties.None, out error); int intPtrSize = 0; intPtrSize = Marshal.SizeOf(typeof(IntPtr)); error = Cl.SetKernelArg(kernelDouble, 0, new IntPtr(intPtrSize), hDeviceMemA); error = Cl.SetKernelArg(kernelAdd, 0, new IntPtr(intPtrSize), hDeviceMemA); error = Cl.SetKernelArg(kernelAdd, 1, new IntPtr(intPtrSize), hDeviceMemB); error = Cl.SetKernelArg(kernelAdd, 2, new IntPtr(intPtrSize), hDeviceMemC); // write data from host to device Event clevent; error = Cl.EnqueueWriteBuffer(cmdQueue, hDeviceMemA, Bool.True, IntPtr.Zero, new IntPtr(1000 * sizeof(float)), A, 0, null, out clevent); error = Cl.EnqueueWriteBuffer(cmdQueue, hDeviceMemB, Bool.True, IntPtr.Zero, new IntPtr(1000 * sizeof(float)), B, 1, new [] { clevent }, out clevent); // execute kernel error = Cl.EnqueueNDRangeKernel(cmdQueue, kernelDouble, 1, null, new IntPtr[] { new IntPtr(1000) }, null, 1, new [] { clevent }, out clevent); var infoBuffer = Cl.GetEventInfo(clevent, EventInfo.CommandExecutionStatus, out var e2); error = Cl.EnqueueNDRangeKernel(cmdQueue, kernelAdd, 1, null, new IntPtr[] { new IntPtr(1000) }, null, 1, new [] { clevent }, out clevent); Console.WriteLine($"Run result: {error}"); error = Cl.EnqueueReadBuffer(cmdQueue, hDeviceMemC, Bool.False, 0, C.Length, C, 1, new [] { clevent }, out clevent); Cl.WaitForEvents(1, new [] { clevent }); for (var i = 0; i < 1000; i++) { Console.WriteLine($"[{i}]: {C[i]}"); } program.Dispose(); foreach (var res in typeof(SourceLoader).Assembly.GetManifestResourceNames()) { Console.WriteLine(res); } }
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)); }
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 ScryptTest() { ErrorCode error; //Load and compile kernel source code. string programPath = System.Environment.CurrentDirectory + "/../../scrypt.cl"; //Cl if (!System.IO.File.Exists(programPath)) { Console.WriteLine("Program doesn't exist at path " + programPath); return; } string programSource = System.IO.File.ReadAllText(programPath); IntPtr[] sz = new IntPtr[programSource.Length * 2]; Program program = Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error); if (1 == 1) { CheckErr(error, "Cl.CreateProgramWithSource"); // status = clBuildProgram(clState->program, 1, &devices[gpu], ""-D LOOKUP_GAP=%d -D CONCURRENT_THREADS=%d -D WORKSIZE=%d", NULL, NULL); //Compile kernel source error = Cl.BuildProgram(program, 1, new[] { _device }, "-D LOOKUP_GAP=1 -D CONCURRENT_THREADS=1 -D WORKSIZE=1", null, IntPtr.Zero); CheckErr(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>() != BuildStatus.Success && 1 == 0) { CheckErr(error, "Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Log, out error)); return; } //Create the required kernel (entry function) [search] Kernel kernel = Cl.CreateKernel(program, "search", out error); CheckErr(error, "Cl.CreateKernel"); int intPtrSize = 0; intPtrSize = Marshal.SizeOf(typeof(IntPtr)); //Image's RGBA data converted to an unmanaged[] array byte[] inputByteArray; //OpenCL memory buffer that will keep our image's byte[] data. Mem inputImage2DBuffer; //Create a command queue, where all of the commands for execution will be added CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error); CheckErr(error, "Cl.CreateCommandQueue"); clState _clState = new clState(); _clState.cl_command_queue = cmdQueue; _clState.cl_kernel = kernel; _clState.cl_context = _context; IntPtr buffersize = new IntPtr(1024); IntPtr blank_res = new IntPtr(1024); Object thrdataRes = new Object(); //int buffersize = 1024; OpenCL.Net.Event clevent; // status |= clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0, buffersize, blank_res, 0, NULL, NULL); dev_blk_ctx blk = new dev_blk_ctx(); ErrorCode err = queue_scrypt_kernel(_clState, blk); ErrorCode status = Cl.EnqueueWriteBuffer(_clState.cl_command_queue, _clState.outputBuffer, OpenCL.Net.Bool.True, new IntPtr(0), buffersize, blank_res, 0, null, out clevent); IntPtr[] globalThreads = new IntPtr[0]; IntPtr[] localThreads = new IntPtr[0]; //uint16 workdim = new uint16(1); uint workdim = 1; status = Cl.EnqueueNDRangeKernel(_clState.cl_command_queue, _clState.cl_kernel, workdim, null, globalThreads, localThreads, 0, null, out clevent); CheckErr(error, "Cl.EnqueueNDRangeKernel"); IntPtr offset = new IntPtr(0); status = Cl.EnqueueReadBuffer(_clState.cl_command_queue, _clState.outputBuffer, OpenCL.Net.Bool.False, offset, buffersize, thrdataRes, 0, null, out clevent); //Wait for completion of all calculations on the GPU. error = Cl.Finish(_clState.cl_command_queue); CheckErr(error, "Cl.Finish"); //Clean up memory Cl.ReleaseKernel(_clState.cl_kernel); Cl.ReleaseCommandQueue(_clState.cl_command_queue); } }
public void ImagingTest(string inputImagePath, string outputImagePath) { ErrorCode error; //Load and compile kernel source code. string programPath = System.Environment.CurrentDirectory + "/../../imagingtest.cl"; //The path to the source file may vary if (!System.IO.File.Exists(programPath)) { Console.WriteLine("Program doesn't exist at path " + programPath); return; } string programSource = System.IO.File.ReadAllText(programPath); using (Program program = Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error)) { CheckErr(error, "Cl.CreateProgramWithSource"); //Compile kernel source error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); CheckErr(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>() != BuildStatus.Success && 1 == 0) { CheckErr(error, "Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Log, out error)); return; } //Create the required kernel (entry function) Kernel kernel = Cl.CreateKernel(program, "imagingTest", out error); CheckErr(error, "Cl.CreateKernel"); int intPtrSize = 0; intPtrSize = Marshal.SizeOf(typeof(IntPtr)); //Image's RGBA data converted to an unmanaged[] array byte[] inputByteArray; //OpenCL memory buffer that will keep our image's byte[] data. Mem inputImage2DBuffer; OpenCL.Net.ImageFormat clImageFormat = new OpenCL.Net.ImageFormat(ChannelOrder.RGBA, ChannelType.Unsigned_Int8); int inputImgWidth, inputImgHeight; int inputImgBytesSize; int inputImgStride; //Try loading the input image using (FileStream imageFileStream = new FileStream(inputImagePath, FileMode.Open)) { System.Drawing.Image inputImage = System.Drawing.Image.FromStream(imageFileStream); if (inputImage == null) { Console.WriteLine("Unable to load input image"); return; } inputImgWidth = inputImage.Width; inputImgHeight = inputImage.Height; System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(inputImage); //Get raw pixel data of the bitmap //The format should match the format of clImageFormat BitmapData bitmapData = bmpImage.LockBits(new Rectangle(0, 0, bmpImage.Width, bmpImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);//inputImage.PixelFormat); inputImgStride = bitmapData.Stride; inputImgBytesSize = bitmapData.Stride * bitmapData.Height; //Copy the raw bitmap data to an unmanaged byte[] array inputByteArray = new byte[inputImgBytesSize]; Marshal.Copy(bitmapData.Scan0, inputByteArray, 0, inputImgBytesSize); //Allocate OpenCL image memory buffer inputImage2DBuffer = (OpenCL.Net.Mem)OpenCL.Net.Cl.CreateImage2D(_context, OpenCL.Net.MemFlags.CopyHostPtr | OpenCL.Net.MemFlags.ReadOnly, clImageFormat, (IntPtr)bitmapData.Width, (IntPtr)bitmapData.Height, (IntPtr)0, inputByteArray, out error); CheckErr(error, "Cl.CreateImage2D input"); } //Unmanaged output image's raw RGBA byte[] array byte[] outputByteArray = new byte[inputImgBytesSize]; //Allocate OpenCL image memory buffer OpenCL.Net.Mem outputImage2DBuffer = (OpenCL.Net.Mem)OpenCL.Net.Cl.CreateImage2D(_context, OpenCL.Net.MemFlags.CopyHostPtr | OpenCL.Net.MemFlags.WriteOnly, clImageFormat, (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)0, outputByteArray, out error); CheckErr(error, "Cl.CreateImage2D output"); //Pass the memory buffers to our kernel function error = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, inputImage2DBuffer); error |= Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, outputImage2DBuffer); CheckErr(error, "Cl.SetKernelArg"); //Create a command queue, where all of the commands for execution will be added CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error); CheckErr(error, "Cl.CreateCommandQueue"); OpenCL.Net.Event clevent; //Copy input image from the host to the GPU. IntPtr[] originPtr = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 }; //x, y, z IntPtr[] regionPtr = new IntPtr[] { (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)1 }; //x, y, z IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)1 }; error = Cl.EnqueueWriteImage(cmdQueue, inputImage2DBuffer, OpenCL.Net.Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, inputByteArray, 0, null, out clevent); CheckErr(error, "Cl.EnqueueWriteImage"); //Execute our kernel (OpenCL code) // CommandQueue q = new OpenCL.Net.CommandQueue(); //enqueue nd range kernel // error = cmdQueue.EnqueueKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent); // OpenCL.Net.Cl.EnqueueNDRangeKernel( OpenCL.Net.Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent); CheckErr(error, "Cl.EnqueueNDRangeKernel"); //Wait for completion of all calculations on the GPU. error = Cl.Finish(cmdQueue); CheckErr(error, "Cl.Finish"); //Read the processed image from GPU to raw RGBA data byte[] array error = Cl.EnqueueReadImage(cmdQueue, outputImage2DBuffer, OpenCL.Net.Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, outputByteArray, 0, null, out clevent); CheckErr(error, "Cl.clEnqueueReadImage"); //Clean up memory Cl.ReleaseKernel(kernel); Cl.ReleaseCommandQueue(cmdQueue); Cl.ReleaseMemObject(inputImage2DBuffer); Cl.ReleaseMemObject(outputImage2DBuffer); //Get a pointer to our unmanaged output byte[] array GCHandle pinnedOutputArray = GCHandle.Alloc(outputByteArray, GCHandleType.Pinned); IntPtr outputBmpPointer = pinnedOutputArray.AddrOfPinnedObject(); //Create a new bitmap with processed data and save it to a file. Bitmap outputBitmap = new Bitmap(inputImgWidth, inputImgHeight, inputImgStride, PixelFormat.Format32bppArgb, outputBmpPointer); outputBitmap.Save(outputImagePath, System.Drawing.Imaging.ImageFormat.Png); pinnedOutputArray.Free(); } }
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); }
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)); }
public void ProgramAndKernelTests() { const string correctSource = @" // Simple test; c[i] = a[i] + b[i] __kernel void add_array(__global float *a, __global float *b, __global float *c) { int xid = get_global_id(0); c[xid] = a[xid] + b[xid]; } __kernel void sub_array(__global float *a, __global float *b, __global float *c) { int xid = get_global_id(0); c[xid] = a[xid] - b[xid]; } "; const string sourceWithErrors = @" // Erroneous kernel __kernel void add_array(__global float *a, __global float *b, __global float *c) { foo(); // <-- Error right here! int xid = get_global_id(0); c[xid] = a[xid] + b[xid]; }"; ErrorCode error; using (Program program = Cl.CreateProgramWithSource(_context, 1, new[] { sourceWithErrors }, null, out error)) { Assert.AreEqual(error, ErrorCode.Success); error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); Assert.AreNotEqual(ErrorCode.Success, error); Assert.AreEqual(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>(), BuildStatus.Error); Console.WriteLine("There were error(s) compiling the provided kernel"); Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Log, out error)); } using (Program program = Cl.CreateProgramWithSource(_context, 1, new[] { correctSource }, null, out error)) { Assert.AreEqual(error, ErrorCode.Success); error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); Assert.AreEqual(ErrorCode.Success, error); Assert.AreEqual(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>(), BuildStatus.Success); // Try to get information from the program Assert.AreEqual(Cl.GetProgramInfo(program, ProgramInfo.Context, out error).CastTo <Context>(), _context); Assert.AreEqual(Cl.GetProgramInfo(program, ProgramInfo.NumDevices, out error).CastTo <int>(), 1); Assert.AreEqual(Cl.GetProgramInfo(program, ProgramInfo.Devices, out error).CastTo <Device>(0), _device); Console.WriteLine("Program source was:"); Console.WriteLine(Cl.GetProgramInfo(program, ProgramInfo.Source, out error)); Kernel kernel = Cl.CreateKernel(program, "add_array", out error); Assert.AreEqual(error, ErrorCode.Success); kernel.Dispose(); Kernel[] kernels = Cl.CreateKernelsInProgram(program, out error); Assert.AreEqual(error, ErrorCode.Success); Assert.AreEqual(kernels.Length, 2); Assert.AreEqual("add_array", Cl.GetKernelInfo(kernels[0], KernelInfo.FunctionName, out error).ToString()); Assert.AreEqual("sub_array", Cl.GetKernelInfo(kernels[1], KernelInfo.FunctionName, out error).ToString()); } }