JOCL v2.6.0-rc-20250722
JOCL, OpenCL® API Binding for Java™ (public API).
HighLevelBindingTest.java
Go to the documentation of this file.
1/*
2 * Copyright 2010 JogAmp Community. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without modification, are
5 * permitted provided that the following conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright notice, this list of
8 * conditions and the following disclaimer.
9 *
10 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
11 * of conditions and the following disclaimer in the documentation and/or other materials
12 * provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
15 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
16 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
21 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
22 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 *
24 * The views and conclusions contained in the software and documentation are those of the
25 * authors and should not be interpreted as representing official policies, either expressed
26 * or implied, of JogAmp Community.
27 */
28
29package com.jogamp.opencl;
30
31import com.jogamp.opencl.CLMemory.Mem;
32import com.jogamp.opencl.CLMemory.GLObjectType;
33import com.jogamp.opencl.CLSampler.AddressingMode;
34import com.jogamp.opencl.CLSampler.FilteringMode;
35import com.jogamp.opencl.CLImageFormat.ChannelOrder;
36import com.jogamp.opencl.CLImageFormat.ChannelType;
37import com.jogamp.opencl.CLDevice.FPConfig;
38import com.jogamp.opencl.CLDevice.GlobalMemCacheType;
39import com.jogamp.opencl.CLDevice.LocalMemType;
40import com.jogamp.opencl.CLDevice.Type;
41import com.jogamp.opencl.CLDevice.Capabilities;
42import com.jogamp.opencl.llb.CL;
43import com.jogamp.opencl.test.util.MiscUtils;
44import com.jogamp.opencl.test.util.UITestCase;
45
46import java.io.IOException;
47import java.io.InputStream;
48import java.nio.ByteBuffer;
49import java.util.Arrays;
50import java.util.EnumSet;
51import java.util.Map;
52
53import org.junit.BeforeClass;
54import org.junit.FixMethodOrder;
55import org.junit.Test;
56import org.junit.runners.MethodSorters;
57
58import static org.junit.Assert.*;
59import static java.lang.System.*;
60import static com.jogamp.opencl.test.util.MiscUtils.*;
61import static com.jogamp.opencl.util.CLPlatformFilters.*;
62import static com.jogamp.opencl.CLVersion.*;
63import static com.jogamp.opencl.CLDevice.Type.*;
64import static com.jogamp.common.nio.Buffers.*;
65
66/**
67 * Test testing the high level bindings.
68 * @author Michael Bien, et.al
69 */
70@FixMethodOrder(MethodSorters.NAME_ASCENDING)
71public class HighLevelBindingTest extends UITestCase {
72
73 @BeforeClass
74 public static void setUpClass() throws Exception {
75 out.println("OS: " + System.getProperty("os.name"));
76 out.println("ARCH: " + System.getProperty("os.arch"));
77 out.println("VM: " + System.getProperty("java.vm.name"));
78 out.println("lib path: " + System.getProperty("java.library.path"));
79 }
80
81 @Test
82 public void enumsTest() {
83
84 // enum tests
85 final EnumSet<FPConfig> singleFPConfig = FPConfig.valuesOf(CL.CL_FP_DENORM | CL.CL_FP_ROUND_TO_INF);
86 assertEquals(0, FPConfig.valuesOf(0).size());
87 assertTrue(singleFPConfig.contains(FPConfig.DENORM));
88 assertTrue(singleFPConfig.contains(FPConfig.ROUND_TO_INF));
89
90 // CLDevice enums
91 for (final FPConfig e : FPConfig.values()) {
92 final EnumSet<FPConfig> set = FPConfig.valuesOf(e.CONFIG);
93 assertTrue(set.contains(e));
94 }
95 for (final GlobalMemCacheType e : GlobalMemCacheType.values()) {
96 assertEquals(e, GlobalMemCacheType.valueOf(e.TYPE));
97 }
98 for (final LocalMemType e : LocalMemType.values()) {
99 assertEquals(e, LocalMemType.valueOf(e.TYPE));
100 }
101 for (final Type e : Type.values()) {
102 assertEquals(e, Type.valueOf(e.TYPE));
103 }
104 for (final Capabilities e : Capabilities.values()) {
105 assertEquals(e, Capabilities.valueOf(e.CAPS));
106 }
107
108 // CLMemory enums
109 for (final Mem e : Mem.values()) {
110 assertEquals(e, Mem.valueOf(e.CONFIG));
111 }
112
113 for (final GLObjectType e : GLObjectType.values()) {
114 assertEquals(e, GLObjectType.valueOf(e.TYPE));
115 }
116
117 // CLSampler enums
118 for (final AddressingMode e : AddressingMode.values()) {
119 assertEquals(e, AddressingMode.valueOf(e.MODE));
120 }
121 for (final FilteringMode e : FilteringMode.values()) {
122 assertEquals(e, FilteringMode.valueOf(e.MODE));
123 }
124
125 // CLImage enums
126 for (final ChannelOrder e : ChannelOrder.values()) {
127 assertEquals(e, ChannelOrder.valueOf(e.ORDER));
128 }
129 for (final ChannelType e : ChannelType.values()) {
130 assertEquals(e, ChannelType.valueOf(e.TYPE));
131 }
132
133 }
134
135
136
137 @Test
138 public void contextlessTest() {
139
140 out.println(" - - - highLevelTest; contextless - - - ");
141
142 // platform/device info tests
143 final CLPlatform[] clPlatforms = CLPlatform.listCLPlatforms();
144
145 for (final CLPlatform platform : clPlatforms) {
146
147 out.println("platform info:");
148 out.println(" name: "+platform.getName());
149 out.println(" id: "+platform.ID);
150 out.println(" profile: "+platform.getProfile());
151 out.println(" spec version: "+platform.getSpecVersion());
152 out.println(" impl version: "+platform.getVersion().getImplVersion());
153 out.println(" vendor: "+platform.getVendor());
154 out.println(" max FLOPS device: "+platform.getMaxFlopsDevice());
155 out.println(" extensions: "+platform.getExtensions());
156
157 final CLDevice[] clDevices = platform.listCLDevices();
158 for (final CLDevice device : clDevices) {
159 out.println("device info:");
160 out.println(" name: "+device.getName());
161 out.println(" profile: "+device.getProfile());
162 out.println(" vendor: "+device.getVendor());
163 out.println(" vendor id: "+device.getVendorID());
164 out.println(" version: "+device.getVersion());
165// out.println(" C version: "+device.getCVersion()); //CL 1.1
166 out.println(" driver version: "+device.getDriverVersion());
167 out.println(" type: "+device.getType());
168 out.println(" mem base addr align: "+device.getMemBaseAddrAlign());
169 out.println(" global mem: "+device.getGlobalMemSize()/(1024*1024)+" MB");
170 out.println(" max alloc mem: "+device.getMaxMemAllocSize()/(1024*1024)+" MB");
171 out.println(" max param size: "+device.getMaxParameterSize()+" byte");
172 out.println(" local mem: "+device.getLocalMemSize()/1024+" KB");
173 out.println(" local mem type: "+device.getLocalMemType());
174 out.println(" global mem cache size: "+device.getGlobalMemCacheSize());
175 out.println(" global mem cacheline size: "+device.getGlobalMemCachelineSize());
176 out.println(" global mem cache type: "+device.getGlobalMemCacheType());
177 out.println(" constant buffer size: "+device.getMaxConstantBufferSize());
178 out.println(" error correction support: "+device.isErrorCorrectionSupported());
179 out.println(" queue properties: "+device.getQueueProperties());
180 out.println(" clock: "+device.getMaxClockFrequency()+" MHz");
181 out.println(" timer res: "+device.getProfilingTimerResolution()+" ns");
182 out.println(" max work group size: "+device.getMaxWorkGroupSize());
183 out.println(" max compute units: "+device.getMaxComputeUnits());
184 out.println(" max work item dimensions: "+device.getMaxWorkItemDimensions());
185 out.println(" max work item sizes: "+Arrays.toString(device.getMaxWorkItemSizes()));
186 out.println(" compiler available: "+device.isCompilerAvailable());
187 out.println(" image support: "+device.isImageSupportAvailable());
188 out.println(" max read image args: "+device.getMaxReadImageArgs());
189 out.println(" max write image args: "+device.getMaxWriteImageArgs());
190 out.println(" max image2d dimensions: "+Arrays.asList(device.getMaxImage2dWidth(), device.getMaxImage2dHeight()));
191 out.println(" max image3d dimensions: "+Arrays.asList(device.getMaxImage2dWidth(), device.getMaxImage2dHeight(), device.getMaxImage3dDepth()));
192 out.println(" number of address bits: "+device.getAddressBits());
193 out.println(" half FP available: "+device.isHalfFPAvailable());
194 out.println(" double FP available: "+device.isDoubleFPAvailable());
195 out.println(" little endian: "+device.isLittleEndian());
196 out.println(" half FP config: "+device.getHalfFPConfig());
197 out.println(" single FP config: "+device.getSingleFPConfig());
198 out.println(" double FP config: "+device.getDoubleFPConfig());
199 out.println(" execution capabilities: "+device.getExecutionCapabilities());
200 out.println(" gl memory sharing: "+device.isGLMemorySharingSupported());
201 out.println(" extensions: "+device.getExtensions());
202 }
203 }
204
205 }
206
207 @Test
208 public void platformTest() {
209 @SuppressWarnings("unchecked")
210 final
211 CLPlatform platformGPU = CLPlatform.getDefault(version(CL_1_0), type(GPU));
212 @SuppressWarnings("unchecked")
213 final
214 CLPlatform platformCPU = CLPlatform.getDefault(version(CL_1_0), type(CPU));
215
216 if(platformGPU != null) {
217 assertTrue(platformGPU.listCLDevices(GPU).length > 0);
218 }else if(platformCPU != null) {
219 assertTrue(platformCPU.listCLDevices(CPU).length > 0);
220 }else{
221 fail("please tell us about your hardware");
222 }
223 }
224
225 @Test
226 public void createContextTest() {
227
228 out.println(" - - - highLevelTest; create context - - - ");
229
230 final CLPlatform platform = CLPlatform.getDefault();
231 final CLDevice[] devices = platform.listCLDevices();
232 final int deviceCount = devices.length;
233
235 assertNotNull(c);
236 assertEquals(deviceCount, c.getDevices().length);
237 c.release();
238
239 c = CLContext.create(platform);
240 assertNotNull(c);
241 assertEquals(deviceCount, c.getDevices().length);
242 c.release();
243
244 for (final CLDevice device : devices) {
245 c = CLContext.create(device);
246 assertNotNull(c);
247 assertEquals(1, c.getDevices().length);
248 c.release();
249 }
250
252 assertNotNull(c);
253 assertEquals(deviceCount, c.getDevices().length);
254 c.release();
255
256 c = CLContext.create(platform, CLDevice.Type.ALL);
257 assertNotNull(c);
258 assertEquals(deviceCount, c.getDevices().length);
259 c.release();
260
261
262 //Exceptions
263 try{
265 fail("create with null device");
266 }catch(final IllegalArgumentException ex) {
267 // expected
268 }
269 try{
271 fail("create with null CLDevice.Type");
272 }catch(final IllegalArgumentException ex) {
273 // expected
274 }
275 try{
277 fail("create with null CLDevice.Type");
278 }catch(final IllegalArgumentException ex) {
279 // expected
280 }
281
282 }
283
284 @Test
285 public void vectorAddGMTest() throws IOException {
286
287 out.println(" - - - highLevelTest; global memory kernel - - - ");
288
289 final CLPlatform[] clPlatforms = CLPlatform.listCLPlatforms();
290 final CLContext context = CLContext.create(clPlatforms[0]);
291
292 final CLDevice[] contextDevices = context.getDevices();
293
294 out.println("context devices:");
295 for (final CLDevice device : contextDevices) {
296 out.println(" "+device.toString());
297 }
298
299 out.println("max FLOPS device: " + context.getMaxFlopsDevice());
300
301 final InputStream stream = getClass().getResourceAsStream("testkernels.cl");
302 final CLProgram program = context.createProgram(stream).build();
303
304 final CLDevice[] programDevices = program.getCLDevices();
305 final CLDevice device = programDevices[0];
306
307 assertEquals(contextDevices.length, programDevices.length);
308
309 out.println("build log:\n"+program.getBuildLog());
310 out.println("build status:\n"+program.getBuildStatus());
311
312 final String source = program.getSource();
313 assertFalse(source.trim().isEmpty());
314// out.println("source:\n"+source);
315
316 final Map<CLDevice, byte[]> binaries = program.getBinaries();
317 assertFalse(binaries.isEmpty());
318
319 int elementCount = 11444777; // Length of float arrays to process (odd # for illustration)
320 final int localWorkSize = device.getMaxWorkItemSizes()[0]; // set and log Global and Local work size dimensions
321 int globalWorkSize = 0;
322
323 ByteBuffer srcA = null;
324 ByteBuffer srcB = null;
325 ByteBuffer dest = null;
326 boolean allocated = false;
327 int divisor = 1;
328 while( !allocated ) {
329 try {
330 // round up to the nearest multiple of the LocalWorkSize
331 globalWorkSize = roundUp(localWorkSize, elementCount);
332 out.println("allocating three buffers of size: "+globalWorkSize);
333 srcA = newDirectByteBuffer(globalWorkSize*SIZEOF_INT);
334 srcB = newDirectByteBuffer(globalWorkSize*SIZEOF_INT);
335 dest = newDirectByteBuffer(globalWorkSize*SIZEOF_INT);
336 allocated = true;
337 }
338 catch( final OutOfMemoryError oome ) {
339 ++divisor;
340 elementCount /= divisor;
341 out.println("not enough direct buffer memory; retrying with smaller buffers");
342 }
343 }
344
345 fillBuffer(srcA, 23456);
346 fillBuffer(srcB, 46987);
347
348 final CLBuffer<ByteBuffer> clBufferA = context.createBuffer(srcA, Mem.READ_ONLY);
349 final CLBuffer<ByteBuffer> clBufferB = context.createBuffer(srcB, Mem.READ_ONLY);
350 final CLBuffer<ByteBuffer> clBufferC = context.createBuffer(dest, Mem.WRITE_ONLY);
351
352 final CLKernel vectorAddKernel = program.createCLKernel("VectorAddGM");
353
354 vectorAddKernel.setArg(0, clBufferA)
355 .setArg(1, clBufferB)
356 .setArg(2, clBufferC)
357 .setArg(3, elementCount);
358
359 final CLCommandQueue queue = device.createCommandQueue();
360
361 // Asynchronous write of data to GPU device, blocking read later
362 queue.putWriteBuffer(clBufferA, false)
363 .putWriteBuffer(clBufferB, false)
364 .put1DRangeKernel(vectorAddKernel, 0, globalWorkSize, localWorkSize)
365 .putReadBuffer(clBufferC, true)
366 .finish().release();
367
368 out.println("a+b=c result snapshot: ");
369 for(int i = 0; i < 10; i++)
370 out.print(dest.getInt()+", ");
371 out.println("...; "+dest.remaining()/SIZEOF_INT + " more");
372
373 assertTrue(3 == context.getMemoryObjects().size());
374 clBufferA.release();
375 assertTrue(2 == context.getMemoryObjects().size());
376
377 assertTrue(2 == context.getMemoryObjects().size());
378 clBufferB.release();
379 assertTrue(1 == context.getMemoryObjects().size());
380
381 assertTrue(1 == context.getMemoryObjects().size());
382 clBufferC.release();
383 assertTrue(0 == context.getMemoryObjects().size());
384
385
386 assertTrue(1 == context.getPrograms().size());
387 program.release();
388 assertTrue(0 == context.getPrograms().size());
389
390 context.release();
391 }
392 public static void main(final String[] args) throws IOException {
393 final String tstname = HighLevelBindingTest.class.getName();
394 org.junit.runner.JUnitCore.main(tstname);
395 }
396
397}
OpenCL buffer object wrapping an optional NIO buffer.
Definition: CLBuffer.java:46
The command queue is used to queue a set of operations for a specific CLDevice.
CLCommandQueue put1DRangeKernel(final CLKernel kernel, final long globalWorkOffset, final long globalWorkSize, final long localWorkSize)
Calls {@native clEnqueueNDRangeKernel}.
CLCommandQueue finish()
Calls {@native clFinish}.
CLCommandQueue putWriteBuffer(final CLBuffer<?> writeBuffer, final boolean blockingRead)
Calls {@native clEnqueueWriteBuffer}.
CLCommandQueue putReadBuffer(final CLBuffer<?> readBuffer, final boolean blockingRead)
Calls {@native clEnqueueReadBuffer}.
void release()
Releases the OpenCL resource.
CLContext is responsible for managing objects such as command-queues, memory, program and kernel obje...
Definition: CLContext.java:79
List< CLMemory<? extends Buffer > > getMemoryObjects()
Returns a read only shapshot of all allocated memory objects associated with this context.
Definition: CLContext.java:590
CLDevice[] getDevices()
Returns all devices associated with this CLContext.
Definition: CLContext.java:638
CLProgram createProgram(final String src)
Creates a program from the given sources, the returned program is not build yet.
Definition: CLContext.java:243
static CLContext create()
Creates a context on all available devices (CL_DEVICE_TYPE_ALL).
Definition: CLContext.java:139
final CLBuffer<?> createBuffer(final int size, final Mem... flags)
Creates a CLBuffer with the specified flags.
Definition: CLContext.java:341
CLDevice getMaxFlopsDevice()
Returns the device with maximal FLOPS from this context.
Definition: CLContext.java:611
List< CLProgram > getPrograms()
Returns a read only shapshot of all programs associated with this context.
Definition: CLContext.java:581
This object represents an OpenCL device.
Definition: CLDevice.java:53
CLCommandQueue createCommandQueue()
Definition: CLDevice.java:72
int[] getMaxWorkItemSizes()
Returns the maximum number of work-items that can be specified in each dimension of the work-group.
Definition: CLDevice.java:339
High level abstraction for an OpenCL Kernel.
Definition: CLKernel.java:53
CLKernel setArg(final int argumentIndex, final CLMemory<?> value)
Definition: CLKernel.java:175
CLPlatfrorm representing a OpenCL implementation (e.g.
Definition: CLPlatform.java:99
CLDevice[] listCLDevices()
Lists all physical devices available on this platform.
static CLPlatform[] listCLPlatforms()
Lists all available OpenCL implementations.
static CLPlatform getDefault()
Returns the default OpenCL platform or null when no platform found.
Represents a OpenCL program executed on one or more CLDevices.
Definition: CLProgram.java:64
String getBuildLog()
Returns the build log of this program on all devices.
Definition: CLProgram.java:538
Map< CLDevice, byte[]> getBinaries()
Returns the binaries for this program in an ordered Map containing the device as key and the program ...
Definition: CLProgram.java:624
String getSource()
Returns the source code of this program.
Definition: CLProgram.java:609
CLProgram build()
Builds this program for all devices associated with the context.
Definition: CLProgram.java:226
CLDevice[] getCLDevices()
Returns all devices associated with this program.
Definition: CLProgram.java:507
Map< CLDevice, Status > getBuildStatus()
Returns the build status enum of this program for each device as Map.
Definition: CLProgram.java:558
void release()
Releases this program with its kernels.
Definition: CLProgram.java:478
CLKernel createCLKernel(final String kernelName)
Creates a kernel with the specified kernel name.
Definition: CLProgram.java:410
Test testing the high level bindings.
static void main(final String[] args)
Enumeration for the execution capabilities of the device.
Definition: CLDevice.java:749
static Capabilities valueOf(final int caps)
Definition: CLDevice.java:770
Describes floating-point capability of the device.
Definition: CLDevice.java:854
ROUND_TO_INF
round to positive and negative infinity rounding modes supported.
Definition: CLDevice.java:874
static EnumSet< FPConfig > valuesOf(final int bitfield)
Returns a EnumSet for the given bitfield.
Definition: CLDevice.java:899
DENORM
denorms are supported.
Definition: CLDevice.java:859
Type of global memory cache supported.
Definition: CLDevice.java:917
static GlobalMemCacheType valueOf(final int bitfield)
Returns the matching GlobalMemCacheType for the given cl type.
Definition: CLDevice.java:947
Type of local memory cache supported.
Definition: CLDevice.java:960
static LocalMemType valueOf(final int clLocalCacheType)
Returns the matching LocalMemCacheType for the given cl type.
Definition: CLDevice.java:984
Enumeration for the type of a device.
Definition: CLDevice.java:798
static Type valueOf(final long clDeviceType)
Definition: CLDevice.java:831
Specifies the number of channels and the channel layout i.e.
static ChannelOrder valueOf(final int orderFlag)
Describes the size of the channel data type.
static ChannelType valueOf(final int channelFlag)
static GLObjectType valueOf(final int type)
Definition: CLMemory.java:456
Configures the mapping process.
Definition: CLMemory.java:402
Memory settings for configuring CLMemory.
Definition: CLMemory.java:289
WRITE_ONLY
Enum representing CL_MEM_WRITE_ONLY.
Definition: CLMemory.java:305
READ_ONLY
Enum representing CL_MEM_READ_ONLY.
Definition: CLMemory.java:313
static Mem valueOf(final int bufferFlag)
Definition: CLMemory.java:351
static AddressingMode valueOf(final int mode)
Definition: CLSampler.java:141
static FilteringMode valueOf(final int mode)
Definition: CLSampler.java:114
Java bindings to OpenCL, the Open Computing Language.
Definition: CL.java:26
static final int CL_FP_DENORM
Define "CL_FP_DENORM" with expression '(1 << 0)', CType: int.
Definition: CL.java:285
static final int CL_FP_ROUND_TO_INF
Define "CL_FP_ROUND_TO_INF" with expression '(1 << 4)', CType: int.
Definition: CL.java:443