Added support for OpenCL & CL/GL interop + minor improvements. [WIP]

This commit is contained in:
Ioannis Tsakpinis 2010-09-26 23:43:24 +00:00
parent 4318d4d9f8
commit 1aa9ab5104
360 changed files with 19079 additions and 4193 deletions

View file

@ -32,19 +32,19 @@
<mkdir dir="${lwjgl.temp}/native/macosx" taskname="initialiazing temp/macosx folder" />
<mkdir dir="${lwjgl.temp}/native/solaris" taskname="initialiazing temp/solaris folder" />
</target>
<!-- Cleans up any files created during the execution of this script -->
<target name="clean" description="Cleans the diectories controlled by this ant script" depends="clean-generated">
<target name="clean" description="Cleans the directories controlled by this ant script" depends="clean-generated">
<delete dir="${lwjgl.temp}" quiet="true" failonerror="false" taskname="cleaning temp folder" />
<delete dir="${lwjgl.docs}/javadoc" quiet="true" failonerror="false" taskname="cleaning javadoc folder" />
<delete dir="${lwjgl.bin}" quiet="true" failonerror="false" taskname="cleaning bin folder" />
</target>
<!-- Creates a distribution of LWJGL -->
<target name="release" description="Creates a distribution of LWJGL using supplied native binaries">
<!-- Warn user -->
<echo message="Before running the release target, please manually compile all platforms and place required files in ${lwjgl.lib}/windows, ${lwjgl.lib}/linux and ${lwjgl.lib}/macosx${line.separator}Missing files will result in a successfull built, but with incomplete release zips"/>
<input
<input
message="All data in the ${lwjgl.dist} folder will be deleted. Continue? "
validargs="yes,no"
addproperty="do.delete"
@ -53,7 +53,7 @@
<equals arg1="no" arg2="${do.delete}"/>
</condition>
<fail if="do.abort">Build aborted by user.</fail>
<!-- prepare -->
<delete dir="${lwjgl.dist}" quiet="true" failonerror="false" />
<antcall target="clean" />
@ -72,19 +72,19 @@
<antcall target="-jars_NoDEP" />
<antcall target="javadoc" />
<antcall target="applet-release" />
<!-- copy resources to res folder -->
<copy todir="${lwjgl.temp}/res">
<fileset dir="res"/>
</copy>
<!-- copy docs -->
<copy todir="${lwjgl.temp}/doc">
<fileset dir="${lwjgl.docs}">
<patternset refid="lwjgl-docs.fileset" />
</fileset>
</copy>
<!-- create distribution from files in libs/ and temp/ -->
<antcall target="-distribution_javadoc" />
<antcall target="-distribution_source" />
@ -105,7 +105,7 @@
</fileset>
</move>
</target>
<!-- Packages the java files -->
<target name="-createdebugjars">
<!-- Create lwjgl.jar -->
@ -116,7 +116,7 @@
</manifest>
</jar>
</target>
<!-- Packages the java files -->
<target name="-createjars">
<!-- Create lwjgl.jar -->
@ -126,7 +126,7 @@
<attribute name="Sealed" value="true"/>
</manifest>
</jar>
<!-- Create lwjgl_util_applet.jar -->
<jar destfile="${lwjgl.temp}/jar/lwjgl_util_applet.jar" taskname="lwjgl_util_applet.jar">
<fileset refid="lwjgl_util_applet.fileset" />
@ -151,7 +151,7 @@
<target name="-distribute">
<delete>
<fileset dir="${lwjgl.temp}/native/" includes="**/*"/>
</delete>
</delete>
<copy todir="${lwjgl.temp}/jar">
<fileset dir="${lwjgl.lib}/" includes="*.jar"/>
@ -175,20 +175,20 @@
<fileset dir="${lwjgl.lib}/solaris">
<patternset refid="lwjgl-solaris.fileset" />
</fileset>
</copy>
</copy>
<!-- create base package -->
<zip destfile="${lwjgl.dist}/lwjgl-${lwjgl.version}.zip">
<zipfileset dir="${lwjgl.temp}" prefix="lwjgl-${lwjgl.version}/">
<patternset refid="lwjgl_base"/>
</zipfileset>
</zipfileset>
</zip>
<!-- create applet package -->
<zip destfile="${lwjgl.dist}/lwjgl_applet-${lwjgl.version}.zip">
<zipfileset dir="." prefix="lwjgl_applet-${lwjgl.version}/">
<patternset refid="lwjgl_applet"/>
</zipfileset>
</zipfileset>
</zip>
</target>
@ -196,14 +196,14 @@
<target name="-distribution_javadoc">
<zip destfile="${lwjgl.dist}/lwjgl-docs-${lwjgl.version}.zip" basedir="${lwjgl.docs}" includes="javadoc/**" />
</target>
<!-- Creates a versioned distribution of the source code -->
<target name="-distribution_source">
<zip destfile="${lwjgl.dist}/lwjgl-source-${lwjgl.version}.zip">
<fileset refid="lwjgl.source.fileset" />
</zip>
</target>
</target>
<!-- Generates the native headers from source files -->
<target name="headers" description="invokes javah on java classes" depends="compile">
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/linux" force="yes">
@ -251,17 +251,18 @@
<class name="org.lwjgl.openal.AL" />
<class name="org.lwjgl.opengl.GLContext" />
<class name="org.lwjgl.opengl.Pbuffer" />
<class name="org.lwjgl.opengl.AMDDebugOutputCallback" />
<class name="org.lwjgl.opengl.ARBDebugOutputCallback" />
<class name="org.lwjgl.opengl.CallbackUtil" />
<class name="org.lwjgl.opencl.CL" />
<class name="org.lwjgl.opencl.CallbackUtil" />
</javah>
</target>
<target name="touch-version">
<touch file="${lwjgl.src.native}/windows/org_lwjgl_opengl_Display.c"/>
<touch file="${lwjgl.src.native}/linux/org_lwjgl_opengl_Display.c"/>
<touch file="${lwjgl.src.native}/macosx/org_lwjgl_opengl_Display.m"/>
</target>
<target name="version-mismatch">
<loadfile srcfile="${lwjgl.src}/java/org/lwjgl/WindowsSysImplementation.java" property="lwjgl.java.windows.version">
<filterchain>
@ -276,7 +277,7 @@
<containsstring contains="JNI_VERSION ="/>
</tokenfilter>
</filterchain>
</loadfile>
</loadfile>
<loadfile srcfile="${lwjgl.src}/java/org/lwjgl/MacOSXSysImplementation.java" property="lwjgl.java.macosx.version">
<filterchain>
<tokenfilter>
@ -297,7 +298,7 @@
<containsstring contains="#define org_lwjgl_LinuxSysImplementation_JNI_VERSION"/>
</tokenfilter>
</filterchain>
</loadfile>
</loadfile>
<loadfile srcfile="${lwjgl.src.native}/macosx/org_lwjgl_MacOSXSysImplementation.h" property="lwjgl.native.macosx.version">
<filterchain>
<tokenfilter>
@ -307,14 +308,14 @@
</loadfile>
<echo>
lwjgl.java.windows.version = ${lwjgl.java.windows.version}
lwjgl.native.windows.version = ${lwjgl.native.windows.version}
lwjgl.native.windows.version = ${lwjgl.native.windows.version}
lwjgl.java.linux.version = ${lwjgl.java.linux.version}
lwjgl.native.linux.version = ${lwjgl.native.linux.version}
lwjgl.native.linux.version = ${lwjgl.native.linux.version}
lwjgl.java.macosx.version = ${lwjgl.java.macosx.version}
lwjgl.native.macosx.version = ${lwjgl.native.macosx.version}
lwjgl.native.macosx.version = ${lwjgl.native.macosx.version}
</echo>
</target>
<macrodef name="version-check">
<attribute name="platform"/>
<sequential>
@ -325,7 +326,7 @@
<pathelement path="${java.class.path}"/>
</classpath>
</java>
<fail message="Unable to load native library: ${nativetest.err}">
<condition>
<not>
@ -333,27 +334,28 @@
</not>
</condition>
</fail>
<echo message="Successfully executed NativeTest"/>
</sequential>
</macrodef>
<!-- Compiles the Java source code -->
<target name="compile" description="Compiles the java source code" depends="-initialize">
<javac debug="yes" destdir="${lwjgl.bin}" source="1.4" target="1.4" classpath="${lwjgl.lib}/jinput.jar:${lwjgl.lib}/AppleJavaExtensions.jar" taskname="core">
<javac debug="yes" destdir="${lwjgl.bin}" source="1.5" target="1.5" classpath="${lwjgl.lib}/jinput.jar:${lwjgl.lib}/AppleJavaExtensions.jar" taskname="core">
<src path="${lwjgl.src}/java/"/>
<src path="${lwjgl.src}/generated/"/>
<include name="org/lwjgl/*.java"/>
<include name="org/lwjgl/input/**"/>
<include name="org/lwjgl/opengl/**"/>
<include name="org/lwjgl/openal/**"/>
<include name="org/lwjgl/opencl/**"/>
<include name="org/lwjgl/util/**"/>
<exclude name="org/lwjgl/util/generator/**"/>
</javac>
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/test/**" source="1.4" target="1.4" taskname="test" />
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/examples/**" source="1.4" target="1.4" taskname="examples" />
</target>
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/test/**" source="1.5" target="1.5" taskname="test" />
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/examples/**" source="1.5" target="1.5" taskname="examples" />
</target>
<target name="compile_native" depends="headers, touch-version, version-mismatch" description="Compiles the native files">
<condition property="lwjgl.platform.windows">
<os family="windows" />
@ -374,7 +376,7 @@
<os name="Mac OS X" />
</condition>
<antcall target="-compile_native_macosx" />
</target>
</target>
<!-- Compiles LWJGL on Win32 platforms -->
<target name="-compile_native_win32" if="lwjgl.platform.windows">
@ -410,7 +412,7 @@
<copy file="${lwjgl.bin}/lwjgl/liblwjgl.jnilib" todir="${lwjgl.lib}/macosx"/>
<version-check platform="macosx"/>
</target>
<target name="repack200" description="Pack200-repack a jar file">
<pack200 src="${input}" destfile="${output}" repack="true"/>
</target>
@ -430,7 +432,7 @@
<arg value="${output}"/>
</java>
</target>
<target name="compress-sign-class">
<antcall target="repack200">
<param name="input" value="${dir}${jarfile}.jar"/>
@ -450,14 +452,14 @@
<!--delete file="${dir}${jarfile}.jar"/-->
<rename src="${dir}${jarfile}-repack.jar" dest="${dir}${jarfile}.jar" replace="yes"/>
</target>
<target name="compress-resource">
<antcall target="lzma">
<param name="input" value="${input}"/>
<param name="output" value="${output}"/>
</antcall>
</target>
<target name="applettest" depends="applet">
<exec executable="appletviewer">
<arg value="-J-Djava.security.policy=applet/appletviewer.policy"/>
@ -487,8 +489,8 @@
<sysproperty key="java.library.path" value="${native_path_expanded}"/>
<arg line="${args}"/>
</java>
</target>
</target>
<!-- Creates the Javadoc -->
<target name="javadoc" description="Creates javadoc from java source code">
<javadoc destdir="${lwjgl.docs}/javadoc" classpath="${lwjgl.lib}/jinput.jar" author="true" version="true" use="true" source="1.4" windowtitle="LWJGL API" useexternalfile="true">

View file

@ -2,19 +2,22 @@
<!-- ================================================================== -->
<!-- Global properties for build -->
<!-- ================================================================== -->
<property name="lwjgl.src" location="src" />
<property name="lwjgl.src.native" location="${lwjgl.src}/native" />
<property name="lwjgl.src.headers" location="${lwjgl.src.native}/common" />
<property name="lwjgl.src.templates" location="${lwjgl.src}/templates" />
<property name="lwjgl.bin" location="bin" />
<property name="lwjgl.lib" location="libs" />
<property name="lwjgl.dist" location="dist" />
<property name="lwjgl.docs" location="doc" />
<property name="lwjgl.temp" location="temp" />
<property name="lwjgl.res" location="res" />
<property name="lwjgl.src" location="src" />
<property name="lwjgl.src.native" location="${lwjgl.src}/native" />
<property name="lwjgl.src.headers" location="${lwjgl.src.native}/common" />
<property name="lwjgl.src.templates" location="${lwjgl.src}/templates" />
<property name="lwjgl.bin" location="bin" />
<property name="lwjgl.lib" location="libs" />
<property name="lwjgl.dist" location="dist" />
<property name="lwjgl.docs" location="doc" />
<property name="lwjgl.temp" location="temp" />
<property name="lwjgl.res" location="res" />
<property name="lwjgl.version" value="2.6" />
<property name="opengl-template-pattern" value="org/lwjgl/opengl/GL*.java,org/lwjgl/opengl/ARB*.java,org/lwjgl/opengl/AMD*.java,org/lwjgl/opengl/APPLE*.java,org/lwjgl/opengl/ATI*.java,org/lwjgl/opengl/EXT*.java,org/lwjgl/opengl/NV*.java,org/lwjgl/opengl/NVX*.java,org/lwjgl/opengl/HP*.java,org/lwjgl/opengl/IBM*.java,org/lwjgl/opengl/SUN*.java,org/lwjgl/opengl/SGIS*.java,org/lwjgl/opengl/GREMEDY*.java"/>
<property name="opencl-template-pattern-extensions" value="org/lwjgl/opencl/KHR*.java,org/lwjgl/opencl/EXT*.java,org/lwjgl/opencl/APPLE*.java,org/lwjgl/opencl/AMD*.java,org/lwjgl/opencl/NV*.java"/>
<property name="opencl-template-pattern" value="org/lwjgl/opencl/CL*.java,${opencl-template-pattern-extensions}"/>
<!-- ================================================================== -->
<!-- Filesets used for targets -->
<!-- ================================================================== -->
@ -39,18 +42,16 @@
<include name="org/lwjgl/test/**" />
<include name="org/lwjgl/examples/**" />
</fileset>
<!-- More files to include in the lwjgl_test.jar file -->
<fileset id="lwjgl_test_extra.fileset" dir="${lwjgl.src}/java">
<exclude name="**.*" />
<include name="org/lwjgl/test/opengl/shaders/shaderFP.fp" />
<include name="org/lwjgl/test/opengl/shaders/shaderFP.vp" />
<include name="org/lwjgl/test/opengl/shaders/shaderFSH.fsh" />
<include name="org/lwjgl/test/opengl/shaders/shaderFSH.vsh" />
<include name="org/lwjgl/test/opengl/shaders/shaderVP.vp" />
<include name="org/lwjgl/test/opengl/shaders/shaderVSH.vsh" />
<include name="org/lwjgl/test/opengl/shaders/shaderUNI.vsh" />
</fileset>
<include name="org/lwjgl/test/opengl/shaders/*.fp" />
<include name="org/lwjgl/test/opengl/shaders/*.vp" />
<include name="org/lwjgl/test/opengl/shaders/*.vsh" />
<include name="org/lwjgl/test/opengl/shaders/*.fsh" />
<include name="org/lwjgl/test/opencl/gl/*.cl />
</fileset>
<!-- Files to include in the lwjgl_util.jar file -->
<fileset id="lwjgl_util.fileset" dir="${lwjgl.bin}">
@ -66,7 +67,7 @@
<include name="org/lwjgl/test/applet/**"/>
<include name="org/lwjgl/test/opengl/awt/AWTGearsCanvas.class"/>
</fileset>
<!-- Files to make Javadoc from -->
<fileset id="lwjgl.javadoc.fileset" dir="${lwjgl.src}">
<include name="**/*.java" />
@ -95,15 +96,15 @@
<include name="jinput-dx8*.dll" />
<include name="jinput-raw*.dll" />
</patternset>
<!-- Files to include in linux, glibc2.3 package -->
<patternset id="lwjgl-linux.fileset">
<include name="liblwjgl*.so" />
<include name="libopenal*.so" />
<include name="libopenal*.so" />
<include name="libjinput-linux.so" />
<include name="libjinput-linux64.so" />
</patternset>
<!-- Files to include in mac os x package -->
<patternset id="lwjgl-macosx.fileset">
<include name="liblwjgl.jnilib" />
@ -111,13 +112,13 @@
<include name="libjinput-osx.jnilib" />
<include name="libjinput-osx-legacy.jnilib" />
</patternset>
<!-- Files to include in solaris package -->
<patternset id="lwjgl-solaris.fileset">
<include name="liblwjgl*.so" />
<include name="libopenal.so" />
<include name="libopenal.so" />
</patternset>
<!-- Files to include in source distribution -->
<fileset id="lwjgl.source.fileset" dir=".">
<include name="build.xml" />
@ -132,7 +133,7 @@
<exclude name="res/Missing_you.mod" />
<exclude name="res/phero*.*" />
</patternset>
<!-- files in the optional package -->
<patternset id="lwjgl_optional">
<include name="res/**" />
@ -143,15 +144,15 @@
<include name="doc/CREDITS" />
<include name="doc/LICENSE" />
<include name="doc/README" />
</patternset>
</patternset>
<!-- files in the lwjgl_applet package -->
<patternset id="lwjgl_applet">
<include name="applet/**" />
<exclude name="applet/appletviewer.policy" />
<exclude name="applet/lwjglkeystore" />
</patternset>
</patternset>
<uptodate property="lwjgl.main.built" targetfile="${lwjgl.lib}/windows/lwjgl.dll" >
<srcfiles dir= "${lwjgl.src.native}/common" includes="*.c*"/>
<srcfiles dir= "${lwjgl.src.native}/windows" includes="*.c"/>

View file

@ -11,21 +11,38 @@
<!-- Compiles the Java generator source code -->
<target name="generators" description="Compiles the native method generators">
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/util/generator/**.java" source="1.5" target="1.5" taskname="generator">
<include name="org/lwjgl/util/generator/openal/**.java"/>
<include name="org/lwjgl/util/generator/opengl/**.java"/>
<include name="org/lwjgl/util/generator/opencl/**.java"/>
<compilerarg value="-Xlint:all"/>
</javac>
<!-- Compile helper classes used by the templates -->
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" source="1.4" target="1.4" taskname="generator">
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" source="1.5" target="1.5" taskname="generator">
<include name="org/lwjgl/PointerWrapper.java"/>
<include name="org/lwjgl/PointerBuffer.java"/>
<!-- OpenGL -->
<include name="org/lwjgl/opengl/GLSync.java"/>
<include name="org/lwjgl/opengl/AMDDebugOutputCallback.java"/>
<include name="org/lwjgl/opengl/ARBDebugOutputCallback.java"/>
<include name="org/lwjgl/opengl/PointerWrapper.java"/>
<!-- OpenCL -->
<include name="org/lwjgl/opencl/CLPlatform.java"/>
<include name="org/lwjgl/opencl/CLDevice.java"/>
<include name="org/lwjgl/opencl/CLContext.java"/>
<include name="org/lwjgl/opencl/CLContextCallback.java"/>
<include name="org/lwjgl/opencl/CLCommandQueue.java"/>
<include name="org/lwjgl/opencl/CLMem.java"/>
<include name="org/lwjgl/opencl/CLMemObjectDestructorCallback.java"/>
<include name="org/lwjgl/opencl/CLBuildProgramCallback.java"/>
<include name="org/lwjgl/opencl/CLNativeKernel.java"/>
<include name="org/lwjgl/opencl/CLEventCallback.java"/>
<include name="org/lwjgl/opencl/CLFunctionAddress.java"/>
</javac>
</target>
<!-- Proxy target to generate it all -->
<target name="generate-all" depends="generate-openal, generate-opengl, generate-opengl-capabilities, generate-opengl-references" description="Generates java and native source"/>
<target name="generate-all" depends="generate-openal, generate-opengl, generate-opengl-capabilities, generate-opengl-references, generate-opencl, generate-opencl-capabilities" description="Generates java and native source"/>
<target name="generate-debug" depends="generate-openal-debug, generate-opengl-debug, generate-opengl-capabilities-debug, generate-opengl-references" description="Generates java and native source"/>
<target name="generate-debug" depends="generate-openal-debug, generate-opengl-debug, generate-opengl-capabilities-debug, generate-opengl-references, generate-opencl-debug, generate-opencl-capabilities-debug" description="Generates java and native source with debug functionality"/>
<!-- Generate OpenAL -->
<target name="generate-openal" depends="generators" description="Generates java and native source for AL">
@ -39,7 +56,7 @@
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated"/>
<arg value="-Atypemap=org.lwjgl.util.generator.ALTypeMap"/>
<arg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<fileset dir="${lwjgl.src.templates}" includes="org/lwjgl/openal/AL10.java, org/lwjgl/openal/AL11.java, org/lwjgl/openal/EFX10.java"/>
</apply>
</target>
@ -56,7 +73,7 @@
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated"/>
<arg value="-Atypemap=org.lwjgl.util.generator.ALTypeMap"/>
<arg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<arg value="-Ageneratechecks"/>
<fileset dir="${lwjgl.src.templates}" includes="org/lwjgl/openal/AL10.java, org/lwjgl/openal/AL11.java, org/lwjgl/openal/EFX10.java"/>
</apply>
@ -75,7 +92,7 @@
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.GLTypeMap"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<fileset dir="${lwjgl.src.templates}" includes="${opengl-template-pattern}"/>
</apply>
</target>
@ -94,17 +111,17 @@
<arg path="${lwjgl.src.native}/generated"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.GLTypeMap"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<fileset dir="${lwjgl.src.templates}" includes="${opengl-template-pattern}"/>
</apply>
</target>
<!-- Generate references -->
<!-- Generate OpenGL references -->
<target name="generate-opengl-references" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.ReferencesGeneratorProcessorFactory"/>
<arg value="org.lwjgl.util.generator.opengl.GLReferencesGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
@ -113,12 +130,12 @@
</apply>
</target>
<!-- Generate context capabilities -->
<!-- Generate OpenGL context capabilities -->
<target name="generate-opengl-capabilities" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.ContextGeneratorProcessorFactory"/>
<arg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
@ -128,12 +145,12 @@
</apply>
</target>
<!-- Generate context capabilities [DEBUG] -->
<!-- Generate OpenGL context capabilities [DEBUG] -->
<target name="generate-opengl-capabilities-debug" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.ContextGeneratorProcessorFactory"/>
<arg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
@ -143,4 +160,72 @@
<fileset dir="${lwjgl.src.templates}" includes="${opengl-template-pattern}"/>
</apply>
</target>
<!-- Generate OpenCL -->
<target name="generate-opencl" depends="generators" description="Generates java and native source for CL">
<apply executable="apt" parallel="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<fileset dir="${lwjgl.src.templates}" includes="${opencl-template-pattern}"/>
</apply>
</target>
<!-- Generate OpenCL [DEBUG] -->
<target name="generate-opencl-debug" depends="generators" description="Generates java and native source for CL">
<apply executable="apt" parallel="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<fileset dir="${lwjgl.src.templates}" includes="${opencl-template-pattern}"/>
</apply>
</target>
<!-- Generate OpenCL capabilities -->
<target name="generate-opencl-capabilities" depends="generators" description="Generates capabilities for CL">
<apply executable="apt" parallel="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates}" includes="${opencl-template-pattern}"/>
</apply>
</target>
<!-- Generate OpenCL capabilities [DEBUG] -->
<target name="generate-opencl-capabilities-debug" depends="generators" description="Generates capabilities for CL">
<apply executable="apt" parallel="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates}" includes="${opencl-template-pattern}"/>
</apply>
</target>
</project>

View file

@ -16,7 +16,7 @@
<fileset dir="." includes="*.so"/>
</delete>
</target>
<target name="compile">
<exec executable="uname" outputproperty="hwplatform">
<arg value="-m"/>
@ -27,10 +27,10 @@
<condition property="cflags_pthread" value="-pthreads" else="-pthread">
<os name="SunOS" />
</condition>
<condition property="version_script_flags32" value="" else="-Wl,--version-script=${native}/linux/lwjgl.map">
<condition property="version_script_flags32" value="" else="-Wl,--version-script='${native}/linux/lwjgl.map'">
<os name="SunOS" />
</condition>
<condition property="version_script_flags64" value="-m64" else="-Wl,--version-script=${native}/linux/lwjgl.map">
<condition property="version_script_flags64" value="-m64" else="-Wl,--version-script='${native}/linux/lwjgl.map'">
<and>
<os name="SunOS" />
</and>
@ -50,7 +50,7 @@
</or>
</not>
</condition>
<!-- On linux, the 64 bit jre doesn't have the 32 bit libs -->
<condition property="build.64bit.only">
<and>
@ -58,11 +58,11 @@
<equals arg1="${hwplatform}" arg2="x86_64"/>
</and>
</condition>
<antcall target="compile32"/>
<antcall target="compile64"/>
</target>
<target name="compile32" unless="build.64bit.only">
<mkdir dir="x32"/>
<apply dir="x32" executable="gcc" skipemptyfilesets="true" failonerror="true">
@ -89,7 +89,7 @@
</apply>
</target>
<target name="compile64" unless="build.32bit.only">
<target name="compile64" unless="build.32bit.only">
<mkdir dir="x64"/>
<apply dir="x64" executable="gcc" skipemptyfilesets="true" failonerror="true">
<arg line="${cflags64} ${cflags_pthread}"/>

View file

@ -87,13 +87,27 @@ public class BufferChecks {
}
}
/** Helper methods to ensure an IntBuffer is null-terminated */
/** Helper method to ensure an IntBuffer is null-terminated */
public static void checkNullTerminated(IntBuffer buf) {
if ( buf.get(buf.limit() - 1) != 0 ) {
throw new IllegalArgumentException("Missing null termination");
}
}
/** Helper method to ensure a LongBuffer is null-terminated */
public static void checkNullTerminated(LongBuffer buf) {
if ( buf.get(buf.limit() - 1) != 0 ) {
throw new IllegalArgumentException("Missing null termination");
}
}
/** Helper method to ensure a PointerBuffer is null-terminated */
public static void checkNullTerminated(PointerBuffer buf) {
if ( buf.get(buf.limit() - 1) != 0 ) {
throw new IllegalArgumentException("Missing null termination");
}
}
public static void checkNotNull(Object o) {
if ( LWJGLUtil.CHECKS && o == null)
throw new IllegalArgumentException("Null argument");
@ -138,6 +152,15 @@ public class BufferChecks {
}
}
public static void checkDirect(PointerBuffer buf) {
// NO-OP, PointerBuffer is always direct.
}
public static void checkArray(Object[] array) {
if ( LWJGLUtil.CHECKS && array == null )
throw new IllegalArgumentException("Invalid array");
}
/**
* This is a separate call to help inline checkBufferSize.
*/
@ -145,6 +168,18 @@ public class BufferChecks {
throw new IllegalArgumentException("Number of remaining buffer elements is " + buf.remaining() + ", must be at least " + size);
}
private static void throwBufferSizeException(PointerBuffer buf, int size) {
throw new IllegalArgumentException("Number of remaining pointer buffer elements is " + buf.remaining() + ", must be at least " + size);
}
private static void throwArraySizeException(Object[] array, int size) {
throw new IllegalArgumentException("Number of array elements is " + array.length + ", must be at least " + size);
}
private static void throwArraySizeException(long[] array, int size) {
throw new IllegalArgumentException("Number of array elements is " + array.length + ", must be at least " + size);
}
/**
* Helper method to ensure a buffer is big enough to receive data from a
* glGet* operation.
@ -202,4 +237,21 @@ public class BufferChecks {
checkDirect(buf);
}
}
}
public static void checkBuffer(PointerBuffer buf, int size) {
if ( LWJGLUtil.CHECKS && buf.remaining() < size ) {
throwBufferSizeException(buf, size);
}
}
public static void checkArray(Object[] array, int size) {
if ( LWJGLUtil.CHECKS && array.length < size )
throwArraySizeException(array, size);
}
public static void checkArray(long[] array, int size) {
if ( LWJGLUtil.CHECKS && array.length < size )
throwArraySizeException(array, size);
}
}

View file

@ -120,6 +120,16 @@ public final class BufferUtils {
return createByteBuffer(size << 3).asDoubleBuffer();
}
/**
* Construct a PointerBuffer with the specified number
* of elements.
* @param size The size, in memory addresses
* @return a PointerBuffer
*/
public static PointerBuffer createPointerBuffer(int size) {
return PointerBuffer.allocateDirect(size);
}
/**
* @return n, where buffer_element_size=2^n.
*/

View file

@ -59,9 +59,9 @@ public class LWJGLUtil {
public static final String PLATFORM_LINUX_NAME = "linux";
public static final String PLATFORM_MACOSX_NAME = "macosx";
public static final String PLATFORM_WINDOWS_NAME = "windows";
/** LWJGL Logo - 16 by 16 pixels */
public static final ByteBuffer LWJGLIcon16x16 = BufferUtils.createByteBuffer(16 * 16 * 4).put(new byte[] {
public static final ByteBuffer LWJGLIcon16x16 = BufferUtils.createByteBuffer(16 * 16 * 4).put(new byte[] {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -1, -62, -41, -24, -1, 116, -92, -53, -1, 80, -117,
-67, -1, 84, -114, -65, -1, -122, -81, -46, -1, -25, -17, -10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
@ -106,7 +106,7 @@ public class LWJGLUtil {
});
/** LWJGL Logo - 32 by 32 pixels */
public static final ByteBuffer LWJGLIcon32x32 = BufferUtils.createByteBuffer(32 * 32 * 4).put(new byte[] {
public static final ByteBuffer LWJGLIcon32x32 = BufferUtils.createByteBuffer(32 * 32 * 4).put(new byte[] {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -6, -4, -3, -1, -53, -35,
@ -269,11 +269,23 @@ public class LWJGLUtil {
public static final boolean CHECKS = !getPrivilegedBoolean("org.lwjgl.util.NoChecks");
private static final int PLATFORM;
static {
LWJGLIcon16x16.flip();
LWJGLIcon32x32.flip();
final String osName = getPrivilegedProperty("os.name");
if ( osName.startsWith("Windows") )
PLATFORM = PLATFORM_WINDOWS;
else if ( osName.startsWith("Linux") || osName.startsWith("FreeBSD") || osName.startsWith("SunOS") )
PLATFORM = PLATFORM_LINUX;
else if ( osName.startsWith("Mac OS X") )
PLATFORM = PLATFORM_MACOSX;
else
throw new LinkageError("Unknown platform: " + osName);
}
/**
* @see #PLATFORM_WINDOWS
* @see #PLATFORM_LINUX
@ -281,19 +293,9 @@ public class LWJGLUtil {
* @return the current platform type
*/
public static int getPlatform() {
String osName = getPrivilegedProperty("os.name");
if (osName.startsWith("Windows")) {
return PLATFORM_WINDOWS;
} else if (osName.startsWith("Linux") || osName.startsWith("FreeBSD") || osName.startsWith("SunOS")) {
return PLATFORM_LINUX;
} else if (osName.startsWith("Mac OS X")) {
return PLATFORM_MACOSX;
} else {
throw new LinkageError("Unknown platform: " + osName);
}
return PLATFORM;
}
/**
* @see #PLATFORM_WINDOWS_NAME
@ -312,7 +314,7 @@ public class LWJGLUtil {
default:
return "unknown";
}
}
}
/**
* Locates the paths required by a library.
@ -357,7 +359,7 @@ public class LWJGLUtil {
String alternative_path = getPrivilegedProperty("org.lwjgl.librarypath");
if (alternative_path != null) {
possible_paths.add(alternative_path + File.separator + platform_lib_name);
}
}
// Add all possible paths from java.library.path
String java_library_path = getPrivilegedProperty("java.library.path");
@ -449,16 +451,16 @@ public class LWJGLUtil {
*/
private static boolean getPrivilegedBoolean(final String property_name) {
Boolean value = (Boolean)AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
public Object run() {
return new Boolean(Boolean.getBoolean(property_name));
}
});
return value.booleanValue();
}
}
/**
* Prints the given message to System.err if DEBUG is true.
*
*
* @param msg Message to print
*/
public static void log(String msg) {
@ -466,7 +468,7 @@ public class LWJGLUtil {
System.err.println(msg);
}
}
/**
* Method to determine if the current system is running a version of
* Mac OS X better than the given version. This is only useful for Mac OS X
@ -489,5 +491,5 @@ public class LWJGLUtil {
}
return major > major_required || (major == major_required && minor >= minor_required);
}
}

View file

@ -0,0 +1,924 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl;
import java.lang.reflect.Method;
import java.nio.*;
/**
* This class is a container for architecture independent pointer data.
* The interface mirrors the NIO LongBuffer API for convenience.
*
* @author Spasi
*/
public class PointerBuffer implements Comparable {
private static final boolean is64Bit;
static {
// Use reflection so that we can compile this class for the Generator.
boolean is64 = false;
try {
Method m = Class.forName("org.lwjgl.Sys").getDeclaredMethod("is64Bit", (Class[])null);
is64 = ((Boolean)m.invoke(null, (Object[])null)).booleanValue();
} catch (Throwable t) {
// ignore
} finally {
is64Bit = is64;
}
}
protected final ByteBuffer pointers;
protected final Buffer view;
protected final IntBuffer view32;
protected final LongBuffer view64;
public PointerBuffer(final int capacity) {
this(BufferUtils.createByteBuffer(capacity * getPointerSize()));
}
public PointerBuffer(final ByteBuffer source) {
if ( !source.isDirect() )
throw new IllegalArgumentException("ByteBuffer is not direct");
pointers = source.slice().order(source.order());
if ( is64Bit ) {
view32 = null;
view = view64 = pointers.asLongBuffer();
} else {
view = view32 = pointers.asIntBuffer();
view64 = null;
}
}
/**
* Returns the ByteBuffer that backs this PointerBuffer.
*
* @return the pointer ByteBuffer
*/
public ByteBuffer getBuffer() {
return pointers;
}
/**
* Returns the pointer size in bytes, based on the underlying architecture.
*
* @return The pointer size in bytes
*/
public static int getPointerSize() {
return is64Bit ? 8 : 4;
}
/**
* Returns this buffer's capacity. </p>
*
* @return The capacity of this buffer
*/
public final int capacity() {
return view.capacity();
}
/**
* Returns this buffer's position. </p>
*
* @return The position of this buffer
*/
public final int position() {
return view.position();
}
/**
* Returns this buffer's position, in bytes. </p>
*
* @return The position of this buffer in bytes.
*/
public final int positionByte() {
return position() * getPointerSize();
}
/**
* Sets this buffer's position. If the mark is defined and larger than the
* new position then it is discarded. </p>
*
* @param newPosition The new position value; must be non-negative
* and no larger than the current limit
*
* @return This buffer
*
* @throws IllegalArgumentException If the preconditions on <tt>newPosition</tt> do not hold
*/
public final PointerBuffer position(int newPosition) {
view.position(newPosition);
return this;
}
/**
* Returns this buffer's limit. </p>
*
* @return The limit of this buffer
*/
public final int limit() {
return view.limit();
}
/**
* Sets this buffer's limit. If the position is larger than the new limit
* then it is set to the new limit. If the mark is defined and larger than
* the new limit then it is discarded. </p>
*
* @param newLimit The new limit value; must be non-negative
* and no larger than this buffer's capacity
*
* @return This buffer
*
* @throws IllegalArgumentException If the preconditions on <tt>newLimit</tt> do not hold
*/
public final PointerBuffer limit(int newLimit) {
view.limit(newLimit);
return this;
}
/**
* Sets this buffer's mark at its position. </p>
*
* @return This buffer
*/
public final PointerBuffer mark() {
view.mark();
return this;
}
/**
* Resets this buffer's position to the previously-marked position.
* <p/>
* <p> Invoking this method neither changes nor discards the mark's
* value. </p>
*
* @return This buffer
*
* @throws java.nio.InvalidMarkException If the mark has not been set
*/
public final PointerBuffer reset() {
view.reset();
return this;
}
/**
* Clears this buffer. The position is set to zero, the limit is set to
* the capacity, and the mark is discarded.
* <p/>
* <p> Invoke this method before using a sequence of channel-read or
* <i>put</i> operations to fill this buffer. For example:
* <p/>
* <blockquote><pre>
* buf.clear(); // Prepare buffer for reading
* in.read(buf); // Read data</pre></blockquote>
* <p/>
* <p> This method does not actually erase the data in the buffer, but it
* is named as if it did because it will most often be used in situations
* in which that might as well be the case. </p>
*
* @return This buffer
*/
public final PointerBuffer clear() {
view.clear();
return this;
}
/**
* Flips this buffer. The limit is set to the current position and then
* the position is set to zero. If the mark is defined then it is
* discarded.
* <p/>
* <p> After a sequence of channel-read or <i>put</i> operations, invoke
* this method to prepare for a sequence of channel-write or relative
* <i>get</i> operations. For example:
* <p/>
* <blockquote><pre>
* buf.put(magic); // Prepend header
* in.read(buf); // Read data into rest of buffer
* buf.flip(); // Flip buffer
* out.write(buf); // Write header + data to channel</pre></blockquote>
* <p/>
* <p> This method is often used in conjunction with the {@link
* java.nio.ByteBuffer#compact compact} method when transferring data from
* one place to another. </p>
*
* @return This buffer
*/
public final PointerBuffer flip() {
view.flip();
return this;
}
/**
* Rewinds this buffer. The position is set to zero and the mark is
* discarded.
* <p/>
* <p> Invoke this method before a sequence of channel-write or <i>get</i>
* operations, assuming that the limit has already been set
* appropriately. For example:
* <p/>
* <blockquote><pre>
* out.write(buf); // Write remaining data
* buf.rewind(); // Rewind buffer
* buf.get(array); // Copy data into array</pre></blockquote>
*
* @return This buffer
*/
public final PointerBuffer rewind() {
view.rewind();
return this;
}
/**
* Returns the number of elements between the current position and the
* limit. </p>
*
* @return The number of elements remaining in this buffer
*/
public final int remaining() {
return view.remaining();
}
/**
* Tells whether there are any elements between the current position and
* the limit. </p>
*
* @return <tt>true</tt> if, and only if, there is at least one element
* remaining in this buffer
*/
public final boolean hasRemaining() {
return view.hasRemaining();
}
/**
* Allocates a new pointer buffer.
* <p/>
* <p> The new buffer's position will be zero, its limit will be its
* capacity, and its mark will be undefined. </p>
*
* @param capacity The new buffer's capacity, in pointers
*
* @return The new pointer buffer
*
* @throws IllegalArgumentException If the <tt>capacity</tt> is a negative integer
*/
public static PointerBuffer allocateDirect(int capacity) {
return new PointerBuffer(capacity);
}
/**
* This method is used in slice and duplicate instead of normal object construction,
* so that subclasses can return themselves.
*
* @param source
*
* @return A new PointerBuffer instance
*/
protected PointerBuffer newInstance(final ByteBuffer source) {
return new PointerBuffer(source);
}
/**
* Creates a new pointer buffer whose content is a shared subsequence of
* this buffer's content.
* <p/>
* <p> The content of the new buffer will start at this buffer's current
* position. Changes to this buffer's content will be visible in the new
* buffer, and vice versa; the two buffers' position, limit, and mark
* values will be independent.
* <p/>
* <p> The new buffer's position will be zero, its capacity and its limit
* will be the number of longs remaining in this buffer, and its mark
* will be undefined. The new buffer will be direct if, and only if, this
* buffer is direct, and it will be read-only if, and only if, this buffer
* is read-only. </p>
*
* @return The new pointer buffer
*/
public PointerBuffer slice() {
final int pointerSize = getPointerSize();
pointers.position(view.position() * pointerSize);
pointers.limit(view.limit() * pointerSize);
try {
// We're slicing in the constructor.
return newInstance(pointers);
} finally {
pointers.clear();
}
}
/**
* Creates a new pointer buffer that shares this buffer's content.
* <p/>
* <p> The content of the new buffer will be that of this buffer. Changes
* to this buffer's content will be visible in the new buffer, and vice
* versa; the two buffers' position, limit, and mark values will be
* independent.
* <p/>
* <p> The new buffer's capacity, limit and position will be
* identical to those of this buffer. The new buffer will be direct if,
* and only if, this buffer is direct, and it will be read-only if, and
* only if, this buffer is read-only. </p>
*
* @return The new pointer buffer
*/
public PointerBuffer duplicate() {
final PointerBuffer buffer = newInstance(pointers);
buffer.position(view.position());
buffer.limit(view.limit());
return buffer;
}
/**
* Creates a new, read-only pointer buffer that shares this buffer's
* content.
* <p/>
* <p> The content of the new buffer will be that of this buffer. Changes
* to this buffer's content will be visible in the new buffer; the new
* buffer itself, however, will be read-only and will not allow the shared
* content to be modified. The two buffers' position, limit, and mark
* values will be independent.
* <p/>
* <p> The new buffer's capacity, limit and position will be
* identical to those of this buffer.
* <p/>
* <p> If this buffer is itself read-only then this method behaves in
* exactly the same way as the {@link #duplicate duplicate} method. </p>
*
* @return The new, read-only pointer buffer
*/
public PointerBuffer asReadOnlyBuffer() {
final PointerBuffer buffer = new PointerBufferR(pointers);
buffer.position(view.position());
buffer.limit(view.limit());
return buffer;
}
public boolean isReadOnly() {
return false;
}
/**
* Relative <i>get</i> method. Reads the long at this buffer's
* current position, and then increments the position. </p>
*
* @return The long at the buffer's current position
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public long get() {
if ( is64Bit )
return view64.get();
else
return view32.get() & 0x00000000FFFFFFFFL;
}
/**
* Relative <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
* <p/>
* <p> Writes the given long into this buffer at the current
* position, and then increments the position. </p>
*
* @param l The long to be written
*
* @return This buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
* @throws ReadOnlyBufferException If this buffer is read-only
*/
public PointerBuffer put(long l) {
if ( is64Bit )
view64.put(l);
else
view32.put((int)l);
return this;
}
/**
* Convenience put that accepts PointerWrapper objects.
*
* @see #put(long)
*/
public PointerBuffer put(final PointerWrapper pointer) {
return put(pointer.getPointer());
}
/**
* Convenience put on a target ByteBuffer.
*
* @param target the target ByteBuffer
* @param l the long value to be written
*/
public static void put(final ByteBuffer target, long l) {
if ( is64Bit )
target.putLong(l);
else
target.putInt((int)l);
}
/**
* Absolute <i>get</i> method. Reads the long at the given
* index. </p>
*
* @param index The index from which the long will be read
*
* @return The long at the given index
*
* @throws IndexOutOfBoundsException If <tt>index</tt> is negative
* or not smaller than the buffer's limit
*/
public long get(int index) {
if ( is64Bit )
return view64.get(index);
else
return view32.get(index) & 0x00000000FFFFFFFFL;
}
/**
* Absolute <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
* <p/>
* <p> Writes the given long into this buffer at the given
* index. </p>
*
* @param index The index at which the long will be written
* @param l The long value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException If <tt>index</tt> is negative
* or not smaller than the buffer's limit
* @throws ReadOnlyBufferException If this buffer is read-only
*/
public PointerBuffer put(int index, long l) {
if ( is64Bit )
view64.put(index, l);
else
view32.put(index, (int)l);
return this;
}
/**
* Convenience put that accepts PointerWrapper objects.
*
* @see #put(int, long)
*/
public PointerBuffer put(int index, PointerWrapper pointer) {
return put(index, pointer.getPointer());
}
/**
* Convenience put on a target ByteBuffer.
*
* @param target the target ByteBuffer
* @param index the index at which the long will be written
* @param l the long value to be written
*/
public static void put(final ByteBuffer target, int index, long l) {
if ( is64Bit )
target.putLong(index * 8, l);
else
target.putInt(index * 4, (int)l);
}
// -- Bulk get operations --
/**
* Relative bulk <i>get</i> method.
* <p/>
* <p> This method transfers longs from this buffer into the given
* destination array. If there are fewer longs remaining in the
* buffer than are required to satisfy the request, that is, if
* <tt>length</tt>&nbsp;<tt>&gt;</tt>&nbsp;<tt>remaining()</tt>, then no
* longs are transferred and a {@link BufferUnderflowException} is
* thrown.
* <p/>
* <p> Otherwise, this method copies <tt>length</tt> longs from this
* buffer into the given array, starting at the current position of this
* buffer and at the given offset in the array. The position of this
* buffer is then incremented by <tt>length</tt>.
* <p/>
* <p> In other words, an invocation of this method of the form
* <tt>src.get(dst,&nbsp;off,&nbsp;len)</tt> has exactly the same effect as
* the loop
* <p/>
* <pre>
* for (int i = off; i < off + len; i++)
* dst[i] = src.get(); </pre>
* <p/>
* except that it first checks that there are sufficient longs in
* this buffer and it is potentially much more efficient. </p>
*
* @param dst The array into which longs are to be written
* @param offset The offset within the array of the first long to be
* written; must be non-negative and no larger than
* <tt>dst.length</tt>
* @param length The maximum number of longs to be written to the given
* array; must be non-negative and no larger than
* <tt>dst.length - offset</tt>
*
* @return This buffer
*
* @throws BufferUnderflowException If there are fewer than <tt>length</tt> longs
* remaining in this buffer
* @throws IndexOutOfBoundsException If the preconditions on the <tt>offset</tt> and <tt>length</tt>
* parameters do not hold
*/
public PointerBuffer get(long[] dst, int offset, int length) {
if ( is64Bit )
view64.get(dst, offset, length);
else {
checkBounds(offset, length, dst.length);
if ( length > view32.remaining() )
throw new BufferUnderflowException();
int end = offset + length;
for ( int i = offset; i < end; i++ )
dst[i] = view32.get() & 0x00000000FFFFFFFFL;
}
return this;
}
/**
* Relative bulk <i>get</i> method.
* <p/>
* <p> This method transfers longs from this buffer into the given
* destination array. An invocation of this method of the form
* <tt>src.get(a)</tt> behaves in exactly the same way as the invocation
* <p/>
* <pre>
* src.get(a, 0, a.length) </pre>
*
* @return This buffer
*
* @throws BufferUnderflowException If there are fewer than <tt>length</tt> longs
* remaining in this buffer
*/
public PointerBuffer get(long[] dst) {
return get(dst, 0, dst.length);
}
/**
* Relative bulk <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
* <p/>
* <p> This method transfers the longs remaining in the given source
* buffer into this buffer. If there are more longs remaining in the
* source buffer than in this buffer, that is, if
* <tt>src.remaining()</tt>&nbsp;<tt>&gt;</tt>&nbsp;<tt>remaining()</tt>,
* then no longs are transferred and a {@link
* BufferOverflowException} is thrown.
* <p/>
* <p> Otherwise, this method copies
* <i>n</i>&nbsp;=&nbsp;<tt>src.remaining()</tt> longs from the given
* buffer into this buffer, starting at each buffer's current position.
* The positions of both buffers are then incremented by <i>n</i>.
* <p/>
* <p> In other words, an invocation of this method of the form
* <tt>dst.put(src)</tt> has exactly the same effect as the loop
* <p/>
* <pre>
* while (src.hasRemaining())
* dst.put(src.get()); </pre>
* <p/>
* except that it first checks that there is sufficient space in this
* buffer and it is potentially much more efficient. </p>
*
* @param src The source buffer from which longs are to be read;
* must not be this buffer
*
* @return This buffer
*
* @throws BufferOverflowException If there is insufficient space in this buffer
* for the remaining longs in the source buffer
* @throws IllegalArgumentException If the source buffer is this buffer
* @throws ReadOnlyBufferException If this buffer is read-only
*/
public PointerBuffer put(PointerBuffer src) {
if ( is64Bit )
view64.put(src.view64);
else
view32.put(src.view32);
return this;
}
/**
* Relative bulk <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
* <p/>
* <p> This method transfers longs into this buffer from the given
* source array. If there are more longs to be copied from the array
* than remain in this buffer, that is, if
* <tt>length</tt>&nbsp;<tt>&gt;</tt>&nbsp;<tt>remaining()</tt>, then no
* longs are transferred and a {@link BufferOverflowException} is
* thrown.
* <p/>
* <p> Otherwise, this method copies <tt>length</tt> longs from the
* given array into this buffer, starting at the given offset in the array
* and at the current position of this buffer. The position of this buffer
* is then incremented by <tt>length</tt>.
* <p/>
* <p> In other words, an invocation of this method of the form
* <tt>dst.put(src,&nbsp;off,&nbsp;len)</tt> has exactly the same effect as
* the loop
* <p/>
* <pre>
* for (int i = off; i < off + len; i++)
* dst.put(a[i]); </pre>
* <p/>
* except that it first checks that there is sufficient space in this
* buffer and it is potentially much more efficient. </p>
*
* @param src The array from which longs are to be read
* @param offset The offset within the array of the first long to be read;
* must be non-negative and no larger than <tt>array.length</tt>
* @param length The number of longs to be read from the given array;
* must be non-negative and no larger than
* <tt>array.length - offset</tt>
*
* @return This buffer
*
* @throws BufferOverflowException If there is insufficient space in this buffer
* @throws IndexOutOfBoundsException If the preconditions on the <tt>offset</tt> and <tt>length</tt>
* parameters do not hold
* @throws ReadOnlyBufferException If this buffer is read-only
*/
public PointerBuffer put(long[] src, int offset, int length) {
if ( is64Bit )
view64.put(src, offset, length);
else {
checkBounds(offset, length, src.length);
if ( length > view32.remaining() )
throw new BufferOverflowException();
int end = offset + length;
for ( int i = offset; i < end; i++ )
view32.put((int)src[i]);
}
return this;
}
/**
* Relative bulk <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
* <p/>
* <p> This method transfers the entire content of the given source
* long array into this buffer. An invocation of this method of the
* form <tt>dst.put(a)</tt> behaves in exactly the same way as the
* invocation
* <p/>
* <pre>
* dst.put(a, 0, a.length) </pre>
*
* @return This buffer
*
* @throws BufferOverflowException If there is insufficient space in this buffer
* @throws ReadOnlyBufferException If this buffer is read-only
*/
public final PointerBuffer put(long[] src) {
return put(src, 0, src.length);
}
/**
* Compacts this buffer&nbsp;&nbsp;<i>(optional operation)</i>.
* <p/>
* <p> The longs between the buffer's current position and its limit,
* if any, are copied to the beginning of the buffer. That is, the
* long at index <i>p</i>&nbsp;=&nbsp;<tt>position()</tt> is copied
* to index zero, the long at index <i>p</i>&nbsp;+&nbsp;1 is copied
* to index one, and so forth until the long at index
* <tt>limit()</tt>&nbsp;-&nbsp;1 is copied to index
* <i>n</i>&nbsp;=&nbsp;<tt>limit()</tt>&nbsp;-&nbsp;<tt>1</tt>&nbsp;-&nbsp;<i>p</i>.
* The buffer's position is then set to <i>n+1</i> and its limit is set to
* its capacity. The mark, if defined, is discarded.
* <p/>
* <p> The buffer's position is set to the number of longs copied,
* rather than to zero, so that an invocation of this method can be
* followed immediately by an invocation of another relative <i>put</i>
* method. </p>
*
* @return This buffer
*
* @throws ReadOnlyBufferException If this buffer is read-only
*/
public PointerBuffer compact() {
if ( is64Bit )
view64.compact();
else
view32.compact();
return this;
}
/**
* Retrieves this buffer's byte order.
* <p/>
* <p> The byte order of a pointer buffer created by allocation or by
* wrapping an existing <tt>long</tt> array is the {@link
* ByteOrder#nativeOrder </code>native order<code>} of the underlying
* hardware. The byte order of a pointer buffer created as a <a
* href="ByteBuffer.html#views">view</a> of a byte buffer is that of the
* byte buffer at the moment that the view is created. </p>
*
* @return This buffer's byte order
*/
public ByteOrder order() {
if ( is64Bit )
return view64.order();
else
return view32.order();
}
/**
* Returns a string summarizing the state of this buffer. </p>
*
* @return A summary string
*/
public String toString() {
StringBuffer sb = new StringBuffer(48);
sb.append(getClass().getName());
sb.append("[pos=");
sb.append(position());
sb.append(" lim=");
sb.append(limit());
sb.append(" cap=");
sb.append(capacity());
sb.append("]");
return sb.toString();
}
/**
* Returns the current hash code of this buffer.
* <p/>
* <p> The hash code of a pointer buffer depends only upon its remaining
* elements; that is, upon the elements from <tt>position()</tt> up to, and
* including, the element at <tt>limit()</tt>&nbsp;-&nbsp;<tt>1</tt>.
* <p/>
* <p> Because buffer hash codes are content-dependent, it is inadvisable
* to use buffers as keys in hash maps or similar data structures unless it
* is known that their contents will not change. </p>
*
* @return The current hash code of this buffer
*/
public int hashCode() {
int h = 1;
int p = position();
for ( int i = limit() - 1; i >= p; i-- )
h = 31 * h + (int)get(i);
return h;
}
/**
* Tells whether or not this buffer is equal to another object.
* <p/>
* <p> Two pointer buffers are equal if, and only if,
* <p/>
* <p><ol>
* <p/>
* <li><p> They have the same element type, </p></li>
* <p/>
* <li><p> They have the same number of remaining elements, and
* </p></li>
* <p/>
* <li><p> The two sequences of remaining elements, considered
* independently of their starting positions, are pointwise equal.
* </p></li>
* <p/>
* </ol>
* <p/>
* <p> A pointer buffer is not equal to any other type of object. </p>
*
* @param ob The object to which this buffer is to be compared
*
* @return <tt>true</tt> if, and only if, this buffer is equal to the
* given object
*/
public boolean equals(Object ob) {
if ( !(ob instanceof PointerBuffer) )
return false;
PointerBuffer that = (PointerBuffer)ob;
if ( this.remaining() != that.remaining() )
return false;
int p = this.position();
for ( int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j-- ) {
long v1 = this.get(i);
long v2 = that.get(j);
if ( v1 != v2 ) {
return false;
}
}
return true;
}
/**
* Compares this buffer to another.
* <p/>
* <p> Two pointer buffers are compared by comparing their sequences of
* remaining elements lexicographically, without regard to the starting
* position of each sequence within its corresponding buffer.
* <p/>
* <p> A pointer buffer is not comparable to any other type of object.
*
* @return A negative integer, zero, or a positive integer as this buffer
* is less than, equal to, or greater than the given buffer
*/
public int compareTo(Object o) {
final PointerBuffer that = (PointerBuffer)o;
int n = this.position() + Math.min(this.remaining(), that.remaining());
for ( int i = this.position(), j = that.position(); i < n; i++, j++ ) {
long v1 = this.get(i);
long v2 = that.get(j);
if ( v1 == v2 )
continue;
if ( v1 < v2 )
return -1;
return +1;
}
return this.remaining() - that.remaining();
}
private static void checkBounds(int off, int len, int size) {
if ( (off | len | (off + len) | (size - (off + len))) < 0 )
throw new IndexOutOfBoundsException();
}
/**
* Read-only version of PointerBuffer.
*
* @author Spasi
*/
private static final class PointerBufferR extends PointerBuffer {
PointerBufferR(final ByteBuffer source) {
super(source);
}
public boolean isReadOnly() {
return true;
}
protected PointerBuffer newInstance(final ByteBuffer source) {
return new PointerBufferR(source);
}
public PointerBuffer asReadOnlyBuffer() {
return duplicate();
}
public PointerBuffer put(final long l) {
throw new ReadOnlyBufferException();
}
public PointerBuffer put(final int index, final long l) {
throw new ReadOnlyBufferException();
}
public PointerBuffer put(final PointerBuffer src) {
throw new ReadOnlyBufferException();
}
public PointerBuffer put(final long[] src, final int offset, final int length) {
throw new ReadOnlyBufferException();
}
public PointerBuffer compact() {
throw new ReadOnlyBufferException();
}
}
}

View file

@ -29,9 +29,13 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
package org.lwjgl;
/** @author spasi <spasi@users.sourceforge.net> */
/**
* A common interface for classes that wrap pointer addresses.
*
* @author Spasi
*/
public interface PointerWrapper {
long getPointer();

View file

@ -0,0 +1,75 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl;
/**
* Base PointerWrapper implementation.
*
* @author Spasi
*/
public abstract class PointerWrapperAbstract implements PointerWrapper {
protected final long pointer;
protected PointerWrapperAbstract(final long pointer) {
this.pointer = pointer;
}
public final boolean isNull() {
return pointer == 0;
}
public final void checkNull() {
if ( LWJGLUtil.DEBUG && pointer == 0 )
throw new IllegalStateException("This pointer is null.");
}
public long getPointer() {
return pointer;
}
public boolean equals(final Object o) {
if ( this == o ) return true;
if ( !(o instanceof PointerWrapperAbstract) ) return false;
final PointerWrapperAbstract that = (PointerWrapperAbstract)o;
if ( pointer != that.pointer ) return false;
return true;
}
public int hashCode() {
return (int)(pointer ^ (pointer >>> 32));
}
}

View file

@ -56,17 +56,18 @@ public final class Sys {
/** Current version of library */
private static final String VERSION = "2.6";
/** The implementation instance to delegate platform specific behavior to */
private final static SysImplementation implementation;
private static final String POSTFIX64BIT = "64";
/** The implementation instance to delegate platform specific behavior to */
private static final SysImplementation implementation;
private static final boolean is64Bit;
private final static String POSTFIX64BIT = "64";
private static void doLoadLibrary(final String lib_name) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
String library_path = System.getProperty("org.lwjgl.librarypath");
if (library_path != null) {
System.load(library_path + File.separator +
System.load(library_path + File.separator +
System.mapLibraryName(lib_name));
} else {
System.loadLibrary(lib_name);
@ -76,14 +77,15 @@ public final class Sys {
});
}
private static void loadLibrary(final String lib_name) {
private static boolean loadLibrary(final String lib_name) {
try {
doLoadLibrary(lib_name);
return false;
} catch (UnsatisfiedLinkError e) {
if (implementation.has64Bit()) {
try {
doLoadLibrary(lib_name + POSTFIX64BIT);
return;
return true;
} catch (UnsatisfiedLinkError e2) {
LWJGLUtil.log("Failed to load 64 bit library: " + e2.getMessage());
}
@ -91,12 +93,12 @@ public final class Sys {
// Throw original error
throw e;
}
}
}
static {
implementation = createImplementation();
loadLibrary(JNI_LIBRARY_NAME);
is64Bit = loadLibrary(JNI_LIBRARY_NAME);
int native_jni_version = implementation.getJNIVersion();
int required_version = implementation.getRequiredJNIVersion();
if (native_jni_version != required_version)
@ -130,13 +132,18 @@ public final class Sys {
public static String getVersion() {
return VERSION;
}
/**
* Initialization. This is just a dummy method to trigger the static constructor.
*/
public static void initialize() {
}
/** Returns true if a 64bit implementation was loaded. */
public static boolean is64Bit() {
return is64Bit;
}
/**
* Obtains the number of ticks that the hires timer does in a second. This method is fast;
* it should be called as frequently as possible, as it recalibrates the timer.

View file

@ -0,0 +1,580 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.PointerBuffer;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.*;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.*;
/**
* Utility class for OpenCL API calls.
* TODO: Remove useless stuff
*
* @author spasi
*/
final class APIUtil {
private static final int INITIAL_BUFFER_SIZE = 256;
private static final int INITIAL_LENGTHS_SIZE = 4;
private static final int BUFFERS_SIZE = 32;
private static final ThreadLocal<char[]> arrayTL = new ThreadLocal<char[]>() {
protected char[] initialValue() { return new char[INITIAL_BUFFER_SIZE]; }
};
private static final ThreadLocal<ByteBuffer> bufferByteTL = new ThreadLocal<ByteBuffer>() {
protected ByteBuffer initialValue() { return BufferUtils.createByteBuffer(INITIAL_BUFFER_SIZE); }
};
private static final ThreadLocal<PointerBuffer> bufferPointerTL = new ThreadLocal<PointerBuffer>() {
protected PointerBuffer initialValue() { return BufferUtils.createPointerBuffer(INITIAL_BUFFER_SIZE); }
};
private static final ThreadLocal<PointerBuffer> lengthsTL = new ThreadLocal<PointerBuffer>() {
protected PointerBuffer initialValue() { return BufferUtils.createPointerBuffer(INITIAL_LENGTHS_SIZE); }
};
private static final ThreadLocal<InfiniteCharSequence> infiniteSeqTL = new ThreadLocal<InfiniteCharSequence>() {
protected InfiniteCharSequence initialValue() { return new InfiniteCharSequence(); }
};
private static final ThreadLocal<Buffers> buffersTL = new ThreadLocal<Buffers>() {
protected Buffers initialValue() { return new Buffers(); }
};
private static final CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
private static final ObjectDestructor<CLDevice> DESTRUCTOR_CLSubDevice = new ObjectDestructor<CLDevice>() {
public void release(final CLDevice object) { EXTDeviceFission.clReleaseDeviceEXT(object); }
};
private static final ObjectDestructor<CLMem> DESTRUCTOR_CLMem = new ObjectDestructor<CLMem>() {
public void release(final CLMem object) { CL10.clReleaseMemObject(object); }
};
private static final ObjectDestructor<CLCommandQueue> DESTRUCTOR_CLCommandQueue = new ObjectDestructor<CLCommandQueue>() {
public void release(final CLCommandQueue object) { CL10.clReleaseCommandQueue(object); }
};
private static final ObjectDestructor<CLSampler> DESTRUCTOR_CLSampler = new ObjectDestructor<CLSampler>() {
public void release(final CLSampler object) { CL10.clReleaseSampler(object); }
};
private static final ObjectDestructor<CLProgram> DESTRUCTOR_CLProgram = new ObjectDestructor<CLProgram>() {
public void release(final CLProgram object) { CL10.clReleaseProgram(object); }
};
private static final ObjectDestructor<CLKernel> DESTRUCTOR_CLKernel = new ObjectDestructor<CLKernel>() {
public void release(final CLKernel object) { CL10.clReleaseKernel(object); }
};
private static final ObjectDestructor<CLEvent> DESTRUCTOR_CLEvent = new ObjectDestructor<CLEvent>() {
public void release(final CLEvent object) { CL10.clReleaseEvent(object); }
};
private APIUtil() {
}
private static char[] getArray(final int size) {
char[] array = arrayTL.get();
if ( array.length < size ) {
int sizeNew = array.length << 1;
while ( sizeNew < size )
sizeNew <<= 1;
array = new char[size];
arrayTL.set(array);
}
return array;
}
static ByteBuffer getBufferByte(final int size) {
ByteBuffer buffer = bufferByteTL.get();
if ( buffer.capacity() < size ) {
int sizeNew = buffer.capacity() << 1;
while ( sizeNew < size )
sizeNew <<= 1;
buffer = BufferUtils.createByteBuffer(size);
bufferByteTL.set(buffer);
} else
buffer.clear();
return buffer;
}
private static ByteBuffer getBufferByteOffset(final int size) {
ByteBuffer buffer = bufferByteTL.get();
if ( buffer.capacity() < size ) {
int sizeNew = buffer.capacity() << 1;
while ( sizeNew < size )
sizeNew <<= 1;
final ByteBuffer bufferNew = BufferUtils.createByteBuffer(size);
bufferNew.put(buffer);
bufferByteTL.set(buffer = bufferNew);
} else {
buffer.position(buffer.limit());
buffer.limit(buffer.capacity());
}
return buffer;
}
static PointerBuffer getBufferPointer(final int size) {
PointerBuffer buffer = bufferPointerTL.get();
if ( buffer.capacity() < size ) {
int sizeNew = buffer.capacity() << 1;
while ( sizeNew < size )
sizeNew <<= 1;
buffer = BufferUtils.createPointerBuffer(size);
bufferPointerTL.set(buffer);
} else
buffer.clear();
return buffer;
}
static ShortBuffer getBufferShort() { return buffersTL.get().shorts; }
static IntBuffer getBufferInt() { return buffersTL.get().ints; }
static IntBuffer getBufferIntDebug() { return buffersTL.get().intsDebug; }
static LongBuffer getBufferLong() { return buffersTL.get().longs; }
static FloatBuffer getBufferFloat() { return buffersTL.get().floats; }
static DoubleBuffer getBufferDouble() { return buffersTL.get().doubles; }
static PointerBuffer getBufferPointer() { return buffersTL.get().pointers; }
static PointerBuffer getLengths() {
return getLengths(1);
}
static PointerBuffer getLengths(final int size) {
PointerBuffer lengths = lengthsTL.get();
if ( lengths.capacity() < size ) {
int sizeNew = lengths.capacity();
while ( sizeNew < size )
sizeNew <<= 1;
lengths = BufferUtils.createPointerBuffer(size);
lengthsTL.set(lengths);
} else
lengths.clear();
return lengths;
}
private static InfiniteCharSequence getInfiniteSeq() {
return infiniteSeqTL.get();
}
private static void encode(final ByteBuffer buffer, final CharSequence string) {
final InfiniteCharSequence infiniteSeq = getInfiniteSeq();
infiniteSeq.setString(string);
encoder.encode(infiniteSeq.buffer, buffer, true);
infiniteSeq.clear();
}
/**
* Reads a byte string from the specified buffer.
*
* @param buffer
*
* @return the buffer as a String.
*/
static String getString(final ByteBuffer buffer) {
final int length = buffer.remaining();
final char[] charArray = getArray(length);
for ( int i = buffer.position(); i < buffer.limit(); i++ )
charArray[i - buffer.position()] = (char)buffer.get(i);
return new String(charArray, 0, length);
}
/**
* Returns a buffer containing the specified string as bytes.
*
* @param string
*
* @return the String as a ByteBuffer
*/
static ByteBuffer getBuffer(final CharSequence string) {
final ByteBuffer buffer = getBufferByte(string.length());
encode(buffer, string);
buffer.flip();
return buffer;
}
/**
* Returns a buffer containing the specified string as bytes, starting at the specified offset.
*
* @param string
*
* @return the String as a ByteBuffer
*/
static ByteBuffer getBuffer(final CharSequence string, final int offset) {
final ByteBuffer buffer = getBufferByteOffset(offset + string.length());
encode(buffer, string);
buffer.flip();
return buffer;
}
/**
* Returns a buffer containing the specified string as bytes, including null-termination.
*
* @param string
*
* @return the String as a ByteBuffer
*/
static ByteBuffer getBufferNT(final CharSequence string) {
final ByteBuffer buffer = getBufferByte(string.length() + 1);
encode(buffer, string);
buffer.put((byte)0);
buffer.flip();
return buffer;
}
static int getTotalLength(final CharSequence[] strings) {
int length = 0;
for ( int i = 0; i < strings.length; i++ )
length += strings[i].length();
return length;
}
/**
* Returns a buffer containing the specified strings as bytes.
*
* @param strings
*
* @return the Strings as a ByteBuffer
*/
static ByteBuffer getBuffer(final CharSequence[] strings) {
final ByteBuffer buffer = getBufferByte(getTotalLength(strings));
final InfiniteCharSequence infiniteSeq = getInfiniteSeq();
for ( int i = 0; i < strings.length; i++ ) {
infiniteSeq.setString(strings[i]);
encoder.encode(infiniteSeq.buffer, buffer, true);
}
infiniteSeq.clear();
buffer.flip();
return buffer;
}
/**
* Returns a buffer containing the specified strings as bytes, including null-termination.
*
* @param strings
*
* @return the Strings as a ByteBuffer
*/
static ByteBuffer getBufferNT(final CharSequence[] strings) {
final ByteBuffer buffer = getBufferByte(getTotalLength(strings) + strings.length);
final InfiniteCharSequence infiniteSeq = getInfiniteSeq();
for ( int i = 0; i < strings.length; i++ ) {
infiniteSeq.setString(strings[i]);
encoder.encode(infiniteSeq.buffer, buffer, true);
buffer.put((byte)0);
}
infiniteSeq.clear();
buffer.flip();
return buffer;
}
/**
* Returns a buffer containing the lengths of the specified strings.
*
* @param strings
*
* @return the String lengths in a PointerBuffer
*/
static PointerBuffer getLengths(final CharSequence[] strings) {
PointerBuffer buffer = getLengths(strings.length);
for ( int i = 0; i < strings.length; i++ )
buffer.put(strings[i].length());
buffer.flip();
return buffer;
}
/**
* Returns a buffer containing the lengths of the specified buffers.
*
* @param buffers the buffer array
*
* @return the buffer lengths in a PointerBuffer
*/
static PointerBuffer getLengths(final ByteBuffer[] buffers) {
PointerBuffer buffer = getLengths(buffers.length);
for ( int i = 0; i < buffers.length; i++ )
buffer.put(buffers[i].remaining());
buffer.flip();
return buffer;
}
static int getSize(final PointerBuffer lengths) {
long size = 0;
for ( int i = lengths.position(); i < lengths.limit(); i++ )
size += lengths.get(i);
return (int)size;
}
static void getClassTokens(final Class[] tokenClasses, final Map<Integer, String> target, final TokenFilter filter) {
getClassTokens(Arrays.asList(tokenClasses), target, filter);
}
static void getClassTokens(final Iterable<Class> tokenClasses, final Map<Integer, String> target, final TokenFilter filter) {
final int TOKEN_MODIFIERS = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL;
for ( final Class tokenClass : tokenClasses ) {
for ( final Field field : tokenClass.getDeclaredFields() ) {
// Get only <public static final int> fields.
if ( (field.getModifiers() & TOKEN_MODIFIERS) == TOKEN_MODIFIERS && field.getType() == int.class ) {
try {
final int value = field.getInt(null);
if ( filter != null && !filter.accept(field, value) )
continue;
if ( target.containsKey(value) ) // Print colliding tokens in their hex representation.
target.put(value, "0x" + Integer.toHexString(value).toUpperCase());
else
target.put(value, field.getName());
} catch (IllegalAccessException e) {
// Ignore
}
}
}
}
}
static ByteBuffer getNativeKernelArgs(final long user_func_ref, final CLMem[] clMems, final long[] sizes) {
final ByteBuffer args = getBufferByte(8 + 4 + (clMems == null ? 0 : clMems.length * (4 + PointerBuffer.getPointerSize())));
args.putLong(0, user_func_ref);
if ( clMems == null )
args.putInt(8, 0);
else {
args.putInt(8, clMems.length);
int byteIndex = 12;
for ( int i = 0; i < clMems.length; i++ ) {
if ( LWJGLUtil.DEBUG && !clMems[i].isValid() )
throw new IllegalArgumentException("An invalid CLMem object was specified.");
args.putInt(byteIndex, (int)sizes[i]); // CLMem size
byteIndex += (4 + PointerBuffer.getPointerSize()); // Skip size and make room for the pointer
}
}
return args;
}
/**
* Releases all sub-devices created from the specified CLDevice.
*
* @param device the CLDevice to clear
*/
static void releaseObjects(final CLDevice device) {
// Release objects only if we're about to hit 0.
if ( device.getReferenceCount() > 1 )
return;
releaseObjects(device.getSubCLDeviceRegistry(), DESTRUCTOR_CLSubDevice);
}
/**
* Releases all objects contained in the specified CLContext.
*
* @param context the CLContext to clear
*/
static void releaseObjects(final CLContext context) {
// Release objects only if we're about to hit 0.
if ( context.getReferenceCount() > 1 )
return;
releaseObjects(context.getCLEventRegistry(), DESTRUCTOR_CLEvent);
releaseObjects(context.getCLProgramRegistry(), DESTRUCTOR_CLProgram);
releaseObjects(context.getCLSamplerRegistry(), DESTRUCTOR_CLSampler);
releaseObjects(context.getCLMemRegistry(), DESTRUCTOR_CLMem);
releaseObjects(context.getCLCommandQueueRegistry(), DESTRUCTOR_CLCommandQueue);
}
/**
* Releases all objects contained in the specified CLProgram.
*
* @param program the CLProgram to clear
*/
static void releaseObjects(final CLProgram program) {
// Release objects only if we're about to hit 0.
if ( program.getReferenceCount() > 1 )
return;
releaseObjects(program.getCLKernelRegistry(), DESTRUCTOR_CLKernel);
}
/**
* Releases all objects contained in the specified CLCommandQueue.
*
* @param queue the CLCommandQueue to clear
*/
static void releaseObjects(final CLCommandQueue queue) {
// Release objects only if we're about to hit 0.
if ( queue.getReferenceCount() > 1 )
return;
releaseObjects(queue.getCLEventRegistry(), DESTRUCTOR_CLEvent);
}
static Set<String> getExtensions(final String extensionList) {
final Set<String> extensions = new HashSet<String>();
final StringTokenizer tokenizer = new StringTokenizer(extensionList);
while ( tokenizer.hasMoreTokens() )
extensions.add(tokenizer.nextToken());
return extensions;
}
private static <T extends CLObjectChild> void releaseObjects(final CLObjectRegistry<T> registry, final ObjectDestructor<T> destructor) {
if ( registry.isEmpty() )
return;
for ( final T object : registry.getAll() ) {
while ( object.isValid() )
destructor.release(object);
}
}
private interface ObjectDestructor<T extends CLObjectChild> {
void release(T object);
}
/**
* A mutable CharSequence with very large initial length. We can wrap this in a re-usable CharBuffer for decoding.
* We cannot subclass CharBuffer because of {@link java.nio.CharBuffer#toString(int,int)}.
*/
private static class InfiniteCharSequence implements CharSequence {
final CharBuffer buffer;
CharSequence string;
InfiniteCharSequence() {
buffer = CharBuffer.wrap(this);
}
void setString(final CharSequence string) {
this.string = string;
this.buffer.position(0);
this.buffer.limit(string.length());
}
void clear() {
this.string = null;
}
public int length() {
return Integer.MAX_VALUE;
}
public char charAt(final int index) {
return string.charAt(index);
}
public CharSequence subSequence(final int start, final int end) {
return string.subSequence(start, end);
}
}
private static class Buffers {
final ShortBuffer shorts;
final IntBuffer ints;
final IntBuffer intsDebug;
final LongBuffer longs;
final FloatBuffer floats;
final DoubleBuffer doubles;
final PointerBuffer pointers;
Buffers() {
shorts = BufferUtils.createShortBuffer(BUFFERS_SIZE);
ints = BufferUtils.createIntBuffer(BUFFERS_SIZE);
intsDebug = BufferUtils.createIntBuffer(1);
longs = BufferUtils.createLongBuffer(BUFFERS_SIZE);
floats = BufferUtils.createFloatBuffer(BUFFERS_SIZE);
doubles = BufferUtils.createDoubleBuffer(BUFFERS_SIZE);
pointers = BufferUtils.createPointerBuffer(BUFFERS_SIZE);
}
}
/** Simple interface for Field filtering */
interface TokenFilter {
/** Should return true if the specified Field passes the filter. */
boolean accept(Field field, int value);
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import java.nio.ByteBuffer;
/**
* Utility class that provides CLContextCallback implementations that use
* the APPLE_ContextLoggingFunctions callback functions.
* <p/>
* TODO: Test this class
*
* @author Spasi
*/
public final class APPLEContextLoggingUtil {
/** Sends all log messages to the Apple System Logger. */
public static final CLContextCallback SYSTEM_LOG_CALLBACK;
/** Sends all log messages to the file descriptor stdout. */
public static final CLContextCallback STD_OUT_CALLBACK;
/** Sends all log messages to the file descriptor stderr. */
public static final CLContextCallback STD_ERR_CALLBACK;
static {
if ( CLCapabilities.isExtensionSupported("CL_APPLE_ContextLoggingFunctions") ) {
SYSTEM_LOG_CALLBACK = new CLContextCallback(CallbackUtil.getLogMessageToSystemLogAPPLE()) {
protected void handleMessage(final String errinfo, final ByteBuffer private_info) { throw new UnsupportedOperationException(); }
};
STD_OUT_CALLBACK = new CLContextCallback(CallbackUtil.getLogMessageToStdoutAPPLE()) {
protected void handleMessage(final String errinfo, final ByteBuffer private_info) { throw new UnsupportedOperationException(); }
};
STD_ERR_CALLBACK = new CLContextCallback(CallbackUtil.getLogMessageToStderrAPPLE()) {
protected void handleMessage(final String errinfo, final ByteBuffer private_info) { throw new UnsupportedOperationException(); }
};
} else {
SYSTEM_LOG_CALLBACK = null;
STD_OUT_CALLBACK = null;
STD_ERR_CALLBACK = null;
}
}
private APPLEContextLoggingUtil() {}
}

View file

@ -0,0 +1,148 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.Sys;
/**
* LWJGL users must use this class to initialize OpenCL
* before using any other class in the org.lwjgl.opencl package.
*
* @author Spasi
*/
public final class CL {
private static boolean created;
static {
Sys.initialize();
}
private CL() {
}
/**
* Native method to create CL instance
*
* @param oclPaths Array of strings containing paths to search for OpenCL library
*/
private static native void nCreate(String oclPaths) throws LWJGLException;
/**
* Native method to create CL instance from the Mac OS X 10.4 OpenCL framework.
* It is only defined in the Mac OS X native library.
*/
private static native void nCreateDefault() throws LWJGLException;
/** Native method the destroy the CL */
private static native void nDestroy();
/** @return true if CL has been created */
public static boolean isCreated() {
return created;
}
public static void create() throws LWJGLException {
if ( created )
return;
//throw new IllegalStateException("OpenCL has already been created.");
final String libname;
final String[] library_names;
switch ( LWJGLUtil.getPlatform() ) {
case LWJGLUtil.PLATFORM_WINDOWS:
libname = "OpenCL";
library_names = new String[] { "OpenCL.dll" };
break;
case LWJGLUtil.PLATFORM_LINUX:
libname = "OpenCL";
library_names = new String[] { "libOpenCL64.so", "libOpenCL.so" }; // TODO: Fix this
break;
case LWJGLUtil.PLATFORM_MACOSX:
libname = "OpenCL";
library_names = new String[] { "OpenCL.dylib" }; // TODO: Fix this
break;
default:
throw new LWJGLException("Unknown platform: " + LWJGLUtil.getPlatform());
}
final String[] oclPaths = LWJGLUtil.getLibraryPaths(libname, library_names, CL.class.getClassLoader());
LWJGLUtil.log("Found " + oclPaths.length + " OpenCL paths");
for ( int i = 0; i < oclPaths.length; i++ ) {
try {
nCreate(oclPaths[i]);
created = true;
break;
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to load " + oclPaths[i] + ": " + e.getMessage());
}
}
if ( !created && LWJGLUtil.getPlatform() == LWJGLUtil.PLATFORM_MACOSX ) {
// Try to load OpenCL from the framework instead
nCreateDefault();
created = true;
}
if ( !created )
throw new LWJGLException("Could not locate OpenCL library.");
if ( !CLCapabilities.isExtensionSupported("OpenCL10") )
throw new RuntimeException("OpenCL 1.0 not supported.");
}
public static void destroy() {
}
/**
* Helper method to get a pointer to a named function with aliases in the OpenCL library.
*
* @param aliases the function name aliases.
*
* @return the function pointer address
*/
static long getFunctionAddress(String[] aliases) {
for ( int i = 0; i < aliases.length; i++ ) {
long address = getFunctionAddress(aliases[i]);
if ( address != 0 )
return address;
}
return 0;
}
static native long getFunctionAddress(String name);
private static native void resetNativeStubs(Class clazz);
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerWrapperAbstract;
/**
* Instances of this class can be used to receive OpenCL program build notifications.
*
* @author Spasi
*/
public abstract class CLBuildProgramCallback extends CLCallback {
protected CLBuildProgramCallback() {
super(CallbackUtil.getBuildProgramCallback());
}
/**
* Called from native code.
*
* @param program_address the CLProgram object pointer
*/
private void handleMessage(long program_address) {
handleMessage(CLContext.getCLProgramGlobal(program_address));
}
/**
* The callback method.
*
* @param program the CLProgram object that was built
*/
protected abstract void handleMessage(CLProgram program);
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerWrapperAbstract;
/**
* Base class for OpenCL callback objects.
*
* @author Spasi
*/
abstract class CLCallback extends PointerWrapperAbstract {
private final boolean custom;
protected CLCallback(final long pointer) {
this(pointer, false);
}
protected CLCallback(final long pointer, final boolean custom) {
super(pointer);
this.custom = custom;
}
final boolean isCustom() {
return custom;
}
}

View file

@ -0,0 +1,259 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.PointerBuffer;
import java.nio.ByteBuffer;
/**
* Utility class that provides runtime checks for OpenCL method calls.
* TODO: Revisit this when Java 7.0 is released, there will be new Buffer API with 64bit indices/sizes.
*
* @author Spasi
*/
final class CLChecks {
private CLChecks() {
}
/**
* Calculates the number of bytes in the specified cl_mem buffer rectangle region.
*
* @param origin the host origin
* @param region the rectangle region
* @param row_pitch the host row pitch
* @param slice_pitch the host slice pitch
*
* @return the region size in bytes
*/
static int calculateBufferRectSize(final PointerBuffer origin, final PointerBuffer region, long row_pitch, long slice_pitch) {
if ( !LWJGLUtil.CHECKS )
return 0;
final long x = origin.get(0);
final long y = origin.get(1);
final long z = origin.get(2);
if ( x < 0 || y < 0 || z < 0 )
throw new IllegalArgumentException("Invalid cl_mem host origin: " + x + ", " + y + ", " + z);
final long w = region.get(0);
final long h = region.get(1);
final long d = region.get(2);
if ( w < 1 || h < 1 || d < 1 )
throw new IllegalArgumentException("Invalid cl_mem rectangle region dimensions: " + w + " x " + h + " x " + d);
if ( row_pitch == 0 )
row_pitch = w;
else if ( row_pitch < w )
throw new IllegalArgumentException("Invalid host row pitch specified: " + row_pitch);
if ( slice_pitch == 0 )
slice_pitch = row_pitch * h;
else if ( slice_pitch < (row_pitch * h) )
throw new IllegalArgumentException("Invalid host slice pitch specified: " + slice_pitch);
return (int)((z * slice_pitch + y * row_pitch + x) + (w * h * d));
}
/**
* Calculates the number of bytes in the specified cl_mem image region.
* This implementation assumes 1 byte per element, because we cannot the
* image type.
*
* @param region the image region
* @param row_pitch the row pitch
* @param slice_pitch the slice pitch
*
* @return the region size in bytes
*/
static int calculateImageSize(final PointerBuffer region, long row_pitch, long slice_pitch) {
if ( !LWJGLUtil.CHECKS )
return 0;
final long w = region.get(0);
final long h = region.get(1);
final long d = region.get(2);
if ( w < 1 || h < 1 || d < 1 )
throw new IllegalArgumentException("Invalid cl_mem image region dimensions: " + w + " x " + h + " x " + d);
if ( row_pitch == 0 )
row_pitch = w;
else if ( row_pitch < w )
throw new IllegalArgumentException("Invalid row pitch specified: " + row_pitch);
if ( slice_pitch == 0 )
slice_pitch = row_pitch * h;
else if ( slice_pitch < (row_pitch * h) )
throw new IllegalArgumentException("Invalid slice pitch specified: " + slice_pitch);
return (int)(slice_pitch * d);
}
/**
* Calculates the number of bytes in the specified 2D image.
*
* @param format the cl_image_format struct
* @param w the image width
* @param h the image height
* @param row_pitch the image row pitch
*
* @return the 2D image size in bytes
*/
static int calculateImage2DSize(final ByteBuffer format, final long w, final long h, long row_pitch) {
if ( LWJGLUtil.CHECKS && (w < 1 || h < 1) )
throw new IllegalArgumentException("Invalid 2D image dimensions: " + w + " x " + h);
final int elementSize = getElementSize(format);
if ( row_pitch == 0 )
row_pitch = w * elementSize;
else if ( LWJGLUtil.CHECKS && ((row_pitch < w * elementSize) || (row_pitch % elementSize != 0)) )
throw new IllegalArgumentException("Invalid image_row_pitch specified: " + row_pitch);
return (int)(row_pitch * h);
}
/**
* Calculates the number of bytes in the specified 3D image.
*
* @param format the cl_image_format struct
* @param w the image width
* @param h the image height
* @param d the image depth
* @param row_pitch the image row pitch
* @param slice_pitch the image slice pitch
*
* @return the 3D image size in bytes
*/
static int calculateImage3DSize(final ByteBuffer format, final long w, final long h, final long d, long row_pitch, long slice_pitch) {
if ( LWJGLUtil.CHECKS && (w < 1 || h < 1 || d < 2) )
throw new IllegalArgumentException("Invalid 3D image dimensions: " + w + " x " + h + " x " + d);
final int elementSize = getElementSize(format);
if ( row_pitch == 0 )
row_pitch = w * elementSize;
else if ( LWJGLUtil.CHECKS && ((row_pitch < w * elementSize) || (row_pitch % elementSize != 0)) )
throw new IllegalArgumentException("Invalid image_row_pitch specified: " + row_pitch);
if ( slice_pitch == 0 )
slice_pitch = row_pitch * h;
else if ( LWJGLUtil.CHECKS && ((row_pitch < row_pitch * h) || (slice_pitch % row_pitch != 0)) )
throw new IllegalArgumentException("Invalid image_slice_pitch specified: " + row_pitch);
return (int)(slice_pitch * d);
}
/**
* Returns the number of bytes per element for the specified image format.
*
* @param format a cl_image_format struct.
*
* @return the number of bytes per image element
*/
private static int getElementSize(final ByteBuffer format) {
final int channelOrder = format.getInt(format.position() + 0);
final int channelType = format.getInt(format.position() + 4);
return getChannelCount(channelOrder) * getChannelSize(channelType);
}
/**
* Returns the number of channels in the specified cl_channel_order.
*
* @param channelOrder the cl_channel_order
*
* @return the number of channels
*/
private static int getChannelCount(final int channelOrder) {
switch ( channelOrder ) {
case CL10.CL_R:
case CL10.CL_A:
case CL10.CL_INTENSITY:
case CL10.CL_LUMINANCE:
case CL11.CL_Rx:
return 1;
case CL10.CL_RG:
case CL10.CL_RA:
case CL11.CL_RGx:
return 2;
case CL10.CL_RGB:
case CL11.CL_RGBx:
return 3;
case CL10.CL_RGBA:
case CL10.CL_BGRA:
case CL10.CL_ARGB:
return 4;
default:
throw new IllegalArgumentException("Invalid cl_channel_order specified: 0x" + Integer.toHexString(channelOrder).toUpperCase());
}
}
/**
* Returns the number of bytes in the specified cl_channel_type.
*
* @param channelType the cl_channel_type
*
* @return the number of bytes
*/
private static int getChannelSize(final int channelType) {
switch ( channelType ) {
case CL10.CL_SNORM_INT8:
case CL10.CL_UNORM_INT8:
case CL10.CL_SIGNED_INT8:
case CL10.CL_UNSIGNED_INT8:
return 1;
case CL10.CL_SNORM_INT16:
case CL10.CL_UNORM_INT16:
case CL10.CL_UNORM_SHORT_565:
case CL10.CL_UNORM_SHORT_555:
case CL10.CL_SIGNED_INT16:
case CL10.CL_UNSIGNED_INT16:
case CL10.CL_HALF_FLOAT:
return 2;
case CL10.CL_UNORM_INT_101010:
case CL10.CL_SIGNED_INT32:
case CL10.CL_UNSIGNED_INT32:
case CL10.CL_FLOAT:
return 4;
default:
throw new IllegalArgumentException("Invalid cl_channel_type specified: 0x" + Integer.toHexString(channelType).toUpperCase());
}
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerBuffer;
/**
* This class is a wrapper around a cl_command_queue pointer.
*
* @author Spasi
*/
public final class CLCommandQueue extends CLObjectChild<CLContext> {
private final CLDevice device;
private final CLObjectRegistry<CLEvent> clEvents;
CLCommandQueue(final long pointer, final CLContext context, final CLDevice device) {
super(pointer, context);
if ( isValid() ) {
this.device = device;
this.clEvents = new CLObjectRegistryGlobal<CLEvent>(CLContext.clEventsGlobal);
context.getCLCommandQueueRegistry().registerObject(this);
} else {
this.device = null;
this.clEvents = null;
}
}
public CLDevice getCLDevice() {
return device;
}
/**
* Returns a CLEvent associated with this command-queue.
*
* @param id the event object id
*
* @return the CLEvent object
*/
public CLEvent getCLEvent(final long id) {
return clEvents.getObject(id);
}
// -------[ IMPLEMENTATION STUFF BELOW ]-------
CLObjectRegistry<CLEvent> getCLEventRegistry() { return clEvents; }
/**
* Called from OpenCL methods that generate CLEvents.
*
* @param event a buffer containing a CLEvent pointer.
*/
void registerCLEvent(final PointerBuffer event) {
if ( event != null )
new CLEvent(event.get(event.position()), this);
}
int release() {
try {
return super.release();
} finally {
if ( !isValid() )
getParent().getCLCommandQueueRegistry().unregisterObject(this);
}
}
}

View file

@ -0,0 +1,135 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import java.util.HashMap;
import java.util.Map;
/**
* This class is a wrapper around a cl_context pointer.
*
* @author Spasi
*/
public final class CLContext extends CLObject {
private final CLObjectRegistry<CLCommandQueue> clCommandQueues;
private final CLObjectRegistry<CLMem> clMems;
private final CLObjectRegistry<CLSampler> clSamplers;
private final CLObjectRegistry<CLProgram> clPrograms;
private final CLObjectRegistry<CLEvent> clEvents;
/** Global registry for build callbacks. */
static Map<Long, CLProgram> clProgramsGlobal = new HashMap<Long, CLProgram>();
/** Global registry for event callbacks. */
static Map<Long, CLEvent> clEventsGlobal = new HashMap<Long, CLEvent>();
CLContext(final long pointer) {
super(pointer);
if ( isValid() ) {
clCommandQueues = new CLObjectRegistry<CLCommandQueue>();
clMems = new CLObjectRegistry<CLMem>();
clSamplers = new CLObjectRegistry<CLSampler>();
clPrograms = new CLObjectRegistryGlobal<CLProgram>(clProgramsGlobal);
clEvents = new CLObjectRegistryGlobal<CLEvent>(clEventsGlobal);
} else {
clCommandQueues = null;
clMems = null;
clSamplers = null;
clPrograms = null;
clEvents = null;
}
}
/**
* Returns a CLCommandQueue associated with this context.
*
* @param id the command queue object id
*
* @return the CLCommandQueue object
*/
public CLCommandQueue getCLCommandQueue(final long id) { return clCommandQueues.getObject(id); }
/**
* Returns a CLMem associated with this context.
*
* @param id the memory object id
*
* @return the CLMem object
*/
public CLMem getCLMem(final long id) { return clMems.getObject(id); }
/**
* Returns a CLSampler associated with this context.
*
* @param id the sampler object id
*
* @return the CLSampler object
*/
public CLSampler getCLSampler(final long id) { return clSamplers.getObject(id); }
/**
* Returns a CLProgram associated with this context.
*
* @param id the program object id
*
* @return the CLProgram object
*/
public CLProgram getCLProgram(final long id) { return clPrograms.getObject(id); }
/**
* Returns a user CLEvent associated with this context.
*
* @param id the event object id
*
* @return the CLEvent object
*/
public CLEvent getCLEvent(final long id) { return clEvents.getObject(id); }
// -------[ IMPLEMENTATION STUFF BELOW ]-------
CLObjectRegistry<CLCommandQueue> getCLCommandQueueRegistry() { return clCommandQueues; }
CLObjectRegistry<CLMem> getCLMemRegistry() { return clMems; }
CLObjectRegistry<CLSampler> getCLSamplerRegistry() { return clSamplers; }
CLObjectRegistry<CLProgram> getCLProgramRegistry() { return clPrograms; }
CLObjectRegistry<CLEvent> getCLEventRegistry() { return clEvents; }
static CLProgram getCLProgramGlobal(final long id) { return clProgramsGlobal.get(id); }
static CLEvent getCLEventGlobal(final long id) { return clEventsGlobal.get(id); }
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerWrapperAbstract;
import java.nio.ByteBuffer;
/**
* Instances of this class can be used to receive OpenCL context error notifications.
*
* @author Spasi
*/
public abstract class CLContextCallback extends PointerWrapperAbstract {
private final boolean custom;
protected CLContextCallback() {
super(CallbackUtil.getContextCallback());
custom = false;
}
/**
* This constructor allows non-LWJGL implementations.
*
* @param pointer
*/
protected CLContextCallback(final long pointer) {
super(pointer);
if ( pointer == 0 )
throw new RuntimeException("Invalid callback function pointer specified.");
custom = true;
}
final boolean isCustom() {
return custom;
}
/**
* The callback method.
*
* @param errinfo the error description
* @param private_info optional error data (may be null)
*/
protected abstract void handleMessage(String errinfo, ByteBuffer private_info);
}

View file

@ -0,0 +1,191 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerBuffer;
/**
* This class is a wrapper around a cl_device_id pointer.
*
* @author Spasi
*/
public final class CLDevice extends CLObjectChild<CLDevice> {
private static final CLDeviceImpl impl = (CLDeviceImpl)CLPlatform.getClassInstance("org.lwjgl.opencl.CLDeviceImpl");
private final CLObjectRegistry<CLDevice> subCLDevices;
private Object caps;
public CLDevice(final long pointer) {
this(pointer, null);
}
/**
* EXT_device_fission constructor.
*
* @param pointer the sub-device pointer
* @param parent the parent CLDevice
*/
CLDevice(final long pointer, final CLDevice parent) {
super(pointer, parent);
if ( isValid() ) {
subCLDevices = new CLObjectRegistry<CLDevice>();
if ( parent != null )
parent.subCLDevices.registerObject(this);
} else
subCLDevices = null;
}
void setCapabilities(final Object caps) {
this.caps = caps;
}
Object getCapabilities() {
return caps;
}
/**
* Returns a sub-device of this device.
*
* @param id the sub-device object id
*
* @return the CLDevice object
*/
public CLDevice getSubCLDevice(final long id) { return subCLDevices.getObject(id); }
int retain() {
if ( getParent() == null )
return getReferenceCount(); // NO-OP, root devices cannot be retained
return super.retain();
}
int release() {
if ( getParent() == null )
return getReferenceCount(); // NO-OP, root devices cannot be released
try {
return super.release();
} finally {
if ( !isValid() )
getParent().subCLDevices.unregisterObject(this);
}
}
CLObjectRegistry<CLDevice> getSubCLDeviceRegistry() { return subCLDevices; }
/**
* Called from clCreateSubDevicesEXT to register new sub-devices.
*
* @param devices a buffer containing CLDevice pointers.
*/
void registerSubCLDevices(final PointerBuffer devices) {
for ( int i = devices.position(); i < devices.limit(); i++ ) {
final long pointer = devices.get(i);
if ( pointer != 0 )
new CLDevice(pointer, this);
}
}
// ---------------[ HELPER METHODS ]---------------
/**
* Returns the value of the specified String parameter.
*
* @param param_name the parameter
*
* @return the parameter value
*/
public String getInfoString(int param_name) {
return impl.getInfoString(this, param_name);
}
/**
* Returns the integer value of the specified parameter.
*
* @param param_name the parameter
*
* @return the parameter value
*/
public int getInfoInt(int param_name) {
return impl.getInfoInt(this, param_name);
}
/**
* Returns the boolean value of the specified parameter.
*
* @param param_name the parameter
*
* @return the parameter value
*/
public boolean getInfoBoolean(int param_name) {
return impl.getInfoInt(this, param_name) != 0;
}
/**
* Returns the size_t value of the specified parameter.
*
* @param param_name the parameter
*
* @return the parameter value
*/
public long getInfoSize(int param_name) {
return impl.getInfoSize(this, param_name);
}
/**
* Returns the long value of the specified parameter. Can be used
* for both cl_ulong and cl_bitfield parameters.
*
* @param param_name the parameter
*
* @return the parameter value
*/
public long getInfoLong(int param_name) {
return impl.getInfoLong(this, param_name);
}
/** CLDevice helper methods implementation interface. */
interface CLDeviceImpl {
String getInfoString(CLDevice device, int param_name);
int getInfoInt(CLDevice device, int param_name);
long getInfoSize(CLDevice device, int param_name);
long getInfoLong(CLDevice device, int param_name);
}
}

View file

@ -0,0 +1,104 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerBuffer;
import java.nio.ByteBuffer;
import static org.lwjgl.opencl.CL10.*;
/**
* Implementation of CLDevice helper methods.
*
* @author Spasi
*/
final class CLDeviceImpl implements CLDevice.CLDeviceImpl {
CLDeviceImpl() {
}
static CLDeviceCapabilities getCapabilities(final CLDevice device) {
device.checkValid();
CLDeviceCapabilities caps = (CLDeviceCapabilities)device.getCapabilities();
if ( caps == null )
device.setCapabilities(caps = new CLDeviceCapabilities(device));
return caps;
}
private static int getInfoBytes(final CLDevice device, final int param_name) {
final PointerBuffer bytes = APIUtil.getBufferPointer();
clGetDeviceInfo(device, param_name, null, bytes);
return (int)bytes.get(0);
}
public String getInfoString(final CLDevice device, final int param_name) {
device.checkValid();
final int bytes = getInfoBytes(device, param_name);
final ByteBuffer versionBuffer = APIUtil.getBufferByte(bytes);
clGetDeviceInfo(device, param_name, versionBuffer, null);
versionBuffer.limit(bytes - 1); // Exclude null-termination
return APIUtil.getString(versionBuffer);
}
public int getInfoInt(final CLDevice device, final int param_name) {
device.checkValid();
final ByteBuffer versionBuffer = APIUtil.getBufferByte(4);
clGetDeviceInfo(device, param_name, versionBuffer, null);
return versionBuffer.getInt(0);
}
public long getInfoSize(final CLDevice device, final int param_name) {
device.checkValid();
final PointerBuffer pointerBuffer = APIUtil.getBufferPointer();
clGetDeviceInfo(device, param_name, pointerBuffer.getBuffer(), null);
return pointerBuffer.get(0);
}
public long getInfoLong(final CLDevice device, final int param_name) {
device.checkValid();
final ByteBuffer versionBuffer = APIUtil.getBufferByte(8);
clGetDeviceInfo(device, param_name, versionBuffer, null);
return versionBuffer.getLong(0);
}
}

View file

@ -0,0 +1,86 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
/**
* This class is a wrapper around a cl_mem pointer.
*
* @author Spasi
*/
public final class CLEvent extends CLObjectChild<CLContext> {
private final CLCommandQueue queue;
CLEvent(final long pointer, final CLContext context) {
this(pointer, context, null);
}
CLEvent(final long pointer, final CLCommandQueue queue) {
this(pointer, queue.getParent(), queue);
}
CLEvent(final long pointer, final CLContext context, final CLCommandQueue queue) {
super(pointer, context);
if ( isValid() ) {
this.queue = queue;
if ( queue == null )
context.getCLEventRegistry().registerObject(this);
else
queue.getCLEventRegistry().registerObject(this);
} else
this.queue = null;
}
/**
* Returns the command-queue associated with this event. For
* user events this method returns null.
*
* @return the command-queue or null if this is a user event
*/
public CLCommandQueue getCLCommandQueue() {
return queue;
}
int release() {
try {
return super.release();
} finally {
if ( !isValid() ) {
if ( queue == null )
getParent().getCLEventRegistry().unregisterObject(this);
else
queue.getCLEventRegistry().unregisterObject(this);
}
}
}
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
/**
* Instances of this class can be used to receive OpenCL memory object destruction notifications.
*
* @author Spasi
*/
public abstract class CLEventCallback extends CLCallback {
protected CLEventCallback() {
super(CallbackUtil.getEventCallback());
}
/**
* Called from native code.
*
* @param event_address the CLEvent object pointer
*/
private void handleMessage(long event_address, int event_command_exec_status) {
handleMessage(CLContext.getCLEventGlobal(event_address), event_command_exec_status);
}
/**
* The callback method.
*
* @param event the CLEvent object
*/
protected abstract void handleMessage(CLEvent event, int event_command_exec_status);
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerWrapperAbstract;
/**
* This class is a wrapper around an OpenCL extension function pointer.
*
* @author Spasi
*/
final class CLFunctionAddress extends PointerWrapperAbstract {
CLFunctionAddress(final long pointer) {
super(pointer);
}
}

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerWrapper;
/**
* This class is a wrapper around a cl_kernel pointer.
*
* @author Spasi
*/
public final class CLKernel extends CLObjectChild<CLProgram> {
private static final CLKernelImpl impl = (CLKernelImpl)CLPlatform.getClassInstance("org.lwjgl.opencl.CLKernelImpl");
CLKernel(final long pointer, final CLProgram program) {
super(pointer, program);
if ( isValid() )
program.getCLKernelRegistry().registerObject(this);
}
int release() {
try {
return super.release();
} finally {
if ( !isValid() )
getParent().getCLKernelRegistry().unregisterObject(this);
}
}
public CLKernel setArg(final int index, final byte value) {
impl.setArg(this, index, value);
return this;
}
public CLKernel setArg(final int index, final short value) {
impl.setArg(this, index, value);
return this;
}
public CLKernel setArg(final int index, final int value) {
impl.setArg(this, index, value);
return this;
}
public CLKernel setArg(final int index, final long value) {
impl.setArg(this, index, value);
return this;
}
public CLKernel setArg(final int index, final float value) {
impl.setArg(this, index, value);
return this;
}
public CLKernel setArg(final int index, final double value) {
impl.setArg(this, index, value);
return this;
}
public CLKernel setArg(final int index, final PointerWrapper value) {
impl.setArg(this, index, value);
return this;
}
interface CLKernelImpl {
void setArg(CLKernel clKernel, int index, byte value);
void setArg(CLKernel clKernel, int index, short value);
void setArg(CLKernel clKernel, int index, int value);
void setArg(CLKernel clKernel, int index, long value);
void setArg(CLKernel clKernel, int index, float value);
void setArg(CLKernel clKernel, int index, double value);
void setArg(CLKernel clKernel, int index, PointerWrapper pointer);
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerBuffer;
import org.lwjgl.PointerWrapper;
import static org.lwjgl.opencl.CL10.*;
/**
* Implementation of CLKernel helper methods.
*
* @author Spasi
*/
final class CLKernelImpl implements CLKernel.CLKernelImpl {
CLKernelImpl() {
}
public void setArg(final CLKernel clKernel, final int index, final byte value) {
clSetKernelArg(clKernel, index, 1, APIUtil.getBufferByte(1).put(0, value));
}
public void setArg(final CLKernel clKernel, final int index, final short value) {
clSetKernelArg(clKernel, index, 2, APIUtil.getBufferShort().put(0, value));
}
public void setArg(final CLKernel clKernel, final int index, final int value) {
clSetKernelArg(clKernel, index, 4, APIUtil.getBufferInt().put(0, value));
}
public void setArg(final CLKernel clKernel, final int index, final long value) {
clSetKernelArg(clKernel, index, 8, APIUtil.getBufferLong().put(0, value));
}
public void setArg(final CLKernel clKernel, final int index, final float value) {
clSetKernelArg(clKernel, index, 4, APIUtil.getBufferFloat().put(0, value));
}
public void setArg(final CLKernel clKernel, final int index, final double value) {
clSetKernelArg(clKernel, index, 8, APIUtil.getBufferDouble().put(0, value));
}
public void setArg(final CLKernel clKernel, final int index, final PointerWrapper pointer) {
clSetKernelArg(clKernel, index, PointerBuffer.getPointerSize(), APIUtil.getBufferPointer().put(0, pointer).getBuffer());
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
/**
* This class is a wrapper around a cl_mem pointer.
*
* @author Spasi
*/
public final class CLMem extends CLObjectChild<CLContext> {
CLMem(final long pointer, final CLContext context) {
super(pointer, context);
if ( isValid() )
context.getCLMemRegistry().registerObject(this);
}
static CLMem create(final long pointer, final CLContext context) {
CLMem clMem = context.getCLMemRegistry().getObject(pointer);
if ( clMem == null )
clMem = new CLMem(pointer, context);
else
clMem.retain();
return clMem;
}
int release() {
try {
return super.release();
} finally {
if ( !isValid() )
getParent().getCLMemRegistry().unregisterObject(this);
}
}
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
/**
* Instances of this class can be used to receive OpenCL memory object destruction notifications.
*
* @author Spasi
*/
public abstract class CLMemObjectDestructorCallback extends CLCallback {
protected CLMemObjectDestructorCallback() {
super(CallbackUtil.getMemObjectDestructorCallback());
}
/**
* The callback method.
*
* @param memobj id of the CLMem object that was destroyed
*/
protected abstract void handleMessage(long memobj);
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import java.nio.ByteBuffer;
/**
* Instances of this class can be used to execute native kernels. clEnqueueNativeKernel will build
* the its arguments automatically, in a way that allows <code>execute</code> to receive an array
* of ByteBuffers, pointing to cl_mem objects in global memory. The ByteBuffer objects should not
* be used outside the handleMessage method.
*
* @author Spasi
* @see CL10#clEnqueueNativeKernel
* @see #execute(java.nio.ByteBuffer[])
*/
public abstract class CLNativeKernel extends CLCallback {
protected CLNativeKernel() {
super(CallbackUtil.getNativeKernelCallback());
}
/**
* Implement this method to execute an action on cl_mem objects in global memory.
*
* @param memobjs an array of ByteBuffers pointing to cl_mem global memory.
*/
protected abstract void execute(ByteBuffer[] memobjs);
}

View file

@ -0,0 +1,88 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.PointerWrapperAbstract;
/**
* Base class for all retainable OpenCL objects.
*
* @author Spasi
*/
abstract class CLObject extends PointerWrapperAbstract {
private int refCount;
CLObject(final long pointer) {
super(pointer);
if ( pointer != 0 )
this.refCount = 1;
}
public final int getReferenceCount() {
return refCount;
}
public final boolean isValid() {
return refCount > 0;
}
public final long getPointer() {
checkValid();
return super.getPointer();
}
final long getPointerUnsafe() {
return super.getPointer();
}
int retain() {
checkValid();
//System.out.println(getClass().getSimpleName() + " REF COUNT: " + pointer + " - " + (refCount + 1));
return ++refCount;
}
int release() {
checkValid();
//System.out.println(getClass().getSimpleName() + " REF COUNT: " + pointer + " - " + (refCount - 1));
return --refCount;
}
final void checkValid() {
checkNull();
if ( LWJGLUtil.DEBUG && refCount == 0 )
throw new IllegalStateException("This CL object is invalid.");
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.LWJGLUtil;
/**
* Base class for all CLObjects that are associated with a parent CLObject.
*
* @author Spasi
*/
abstract class CLObjectChild<P extends CLObject> extends CLObject {
private final P parent;
CLObjectChild(final long pointer, final P parent) {
super(pointer);
if ( LWJGLUtil.DEBUG && parent != null && !parent.isValid() )
throw new IllegalStateException("The parent specified is not a valid CL object.");
this.parent = parent;
}
public P getParent() {
return parent;
}
}

View file

@ -0,0 +1,55 @@
package org.lwjgl.opencl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A CLContextObject container.
*
* @author Spasi
*/
class CLObjectRegistry<T extends CLObjectChild> {
private Map<Long, T> registry;
CLObjectRegistry() {
}
final boolean isEmpty() {
return registry == null || registry.isEmpty();
}
final T getObject(final long id) {
return registry == null ? null : registry.get(id);
}
final boolean hasObject(final long id) {
return registry != null && registry.containsKey(id);
}
final List<T> getAll() {
return registry == null ? null : new ArrayList<T>(registry.values());
}
void registerObject(final T object) {
final Map<Long, T> map = getMap();
final Long key = object.getPointer();
if ( !map.containsKey(key) )
getMap().put(object.getPointer(), object);
}
void unregisterObject(final T object) {
getMap().remove(object.getPointerUnsafe());
}
private Map<Long, T> getMap() {
if ( registry == null )
registry = new HashMap<Long, T>();
return registry;
}
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import java.util.Map;
/**
* A CLObject registry that also registers/unregisters objects to/from a global registry.
*
* @author Spasi
*/
final class CLObjectRegistryGlobal<T extends CLObjectChild> extends CLObjectRegistry<T> {
private final Map<Long, T> globalRegistry;
CLObjectRegistryGlobal(final Map<Long, T> globalRegistry) {
this.globalRegistry = globalRegistry;
}
void registerObject(final T object) {
super.registerObject(object);
globalRegistry.put(object.getPointer(), object);
}
void unregisterObject(final T object) {
super.unregisterObject(object);
globalRegistry.remove(object.getPointerUnsafe());
}
}

View file

@ -0,0 +1,104 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerWrapperAbstract;
import org.lwjgl.opencl.api.Filter;
import java.util.List;
/**
* This class is a wrapper around a cl_platform_id pointer.
*
* @author Spasi
*/
public final class CLPlatform extends PointerWrapperAbstract {
private static final CLPlatformImpl impl = (CLPlatformImpl)getClassInstance("org.lwjgl.opencl.CLPlatformImpl");
private Object caps;
public CLPlatform(final long pointer) {
super(pointer);
}
void setCapabilities(final Object caps) {
this.caps = caps;
}
Object getCapabilities() {
return caps;
}
// ---------------[ HELPER METHODS ]---------------
static Object getClassInstance(final String className) {
Object instance = null;
try {
instance = Class.forName(className).newInstance();
} finally {
return instance;
}
}
public static List<CLPlatform> getPlatforms() {
return getPlatforms(null);
}
public static List<CLPlatform> getPlatforms(final Filter<CLPlatform> filter) {
return impl.getPlatforms(filter);
}
public String getInfoString(int param_name) {
return impl.getInfoString(this, param_name);
}
public List<CLDevice> getDevices(final int device_type) {
return getDevices(device_type, null);
}
public List<CLDevice> getDevices(final int device_type, final Filter<CLDevice> filter) {
return impl.getDevices(this, device_type, filter);
}
/** CLPlatform helper methods implementation interface. */
interface CLPlatformImpl {
List<CLPlatform> getPlatforms(Filter<CLPlatform> filter);
String getInfoString(CLPlatform platform, int param_name);
List<CLDevice> getDevices(CLPlatform platform, int device_type, final Filter<CLDevice> filter);
}
}

View file

@ -0,0 +1,121 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerBuffer;
import org.lwjgl.opencl.api.Filter;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import static org.lwjgl.opencl.CL10.*;
/**
* Implementation of CLPlatform helper methods.
*
* @author Spasi
*/
final class CLPlatformImpl implements CLPlatform.CLPlatformImpl {
CLPlatformImpl() {
}
static CLPlatformCapabilities getCapabilities(final CLPlatform platform) {
platform.checkNull();
CLPlatformCapabilities caps = (CLPlatformCapabilities)platform.getCapabilities();
if ( caps == null )
platform.setCapabilities(caps = new CLPlatformCapabilities(platform));
return caps;
}
public List<CLPlatform> getPlatforms(final Filter<CLPlatform> filter) {
final IntBuffer numBuffer = APIUtil.getBufferInt();
clGetPlatformIDs(null, numBuffer);
final int num_platforms = numBuffer.get(0);
if ( num_platforms == 0 )
return null;
final PointerBuffer platformIDs = APIUtil.getBufferPointer(num_platforms);
clGetPlatformIDs(platformIDs, null);
final List<CLPlatform> platforms = new ArrayList<CLPlatform>(num_platforms);
for ( int i = 0; i < num_platforms; i++ ) {
final CLPlatform platform = new CLPlatform(platformIDs.get(i));
if ( filter == null || filter.accept(platform) )
platforms.add(platform);
}
return platforms.size() == 0 ? null : platforms;
}
public String getInfoString(final CLPlatform platform, final int param_name) {
platform.checkNull();
final PointerBuffer bytes = APIUtil.getBufferPointer();
clGetPlatformInfo(platform, param_name, null, bytes);
final ByteBuffer versionBuffer = APIUtil.getBufferByte((int)bytes.get(0));
clGetPlatformInfo(platform, param_name, versionBuffer, null);
versionBuffer.limit((int)bytes.get(0) - 1); // Exclude null-termination
return APIUtil.getString(versionBuffer);
}
public List<CLDevice> getDevices(final CLPlatform platform, final int device_type, final Filter<CLDevice> filter) {
platform.checkNull();
final IntBuffer numBuffer = APIUtil.getBufferInt();
clGetDeviceIDs(platform, device_type, null, numBuffer);
final int num_devices = numBuffer.get(0);
if ( num_devices == 0 )
return null;
final PointerBuffer deviceIDs = APIUtil.getBufferPointer(num_devices);
clGetDeviceIDs(platform, device_type, deviceIDs, null);
final List<CLDevice> devices = new ArrayList<CLDevice>(num_devices);
for ( int i = 0; i < num_devices; i++ ) {
final CLDevice device = new CLDevice(deviceIDs.get(i));
if ( filter == null || filter.accept(device) )
devices.add(device);
}
return devices.size() == 0 ? null : devices;
}
}

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.PointerBuffer;
import java.io.Serializable;
/**
* This class is a wrapper around a cl_program pointer.
*
* @author Spasi
*/
public final class CLProgram extends CLObjectChild<CLContext> {
private final CLObjectRegistry<CLKernel> clKernels;
CLProgram(final long pointer, final CLContext context) {
super(pointer, context);
if ( isValid() ) {
context.getCLProgramRegistry().registerObject(this);
clKernels = new CLObjectRegistry<CLKernel>();
} else
clKernels = null;
}
/**
* Returns a CLKernel associated with this program.
*
* @param id the kernel id
*
* @return the CLKernel object
*/
public CLKernel getCLKernel(final long id) {
return clKernels.getObject(id);
}
// -------[ IMPLEMENTATION STUFF BELOW ]-------
CLObjectRegistry<CLKernel> getCLKernelRegistry() { return clKernels; }
/**
* Called from clCreateKernelsInProgram to register new CLKernels.
*
* @param kernels a buffer containing CLKernel pointers.
*/
void registerCLKernels(final PointerBuffer kernels) {
for ( int i = kernels.position(); i < kernels.limit(); i++ ) {
final long pointer = kernels.get(i);
if ( pointer != 0 )
new CLKernel(pointer, this);
}
}
int release() {
try {
return super.release();
} finally {
if ( !isValid() )
getParent().getCLProgramRegistry().unregisterObject(this);
}
}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
/**
* This class is a wrapper around a cl_sampler pointer.
*
* @author Spasi
*/
public final class CLSampler extends CLObjectChild<CLContext> {
CLSampler(final long pointer, final CLContext context) {
super(pointer, context);
if ( isValid() )
context.getCLSamplerRegistry().registerObject(this);
}
int release() {
try {
return super.release();
} finally {
if ( !isValid() )
getParent().getCLSamplerRegistry().unregisterObject(this);
}
}
}

View file

@ -0,0 +1,200 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import java.util.HashMap;
import java.util.Map;
/**
* Utility class that handles OpenCL API callbacks.
*
* @author Spasi
*/
final class CallbackUtil {
private static final Map<CLContext, Long> contextUserData = new HashMap<CLContext, Long>();
private CallbackUtil() {}
/**
* Creates a new global reference to the specified Object.
*
* @param obj the Object
*
* @return the GlobalRef memory address or 0 if the Object is null.
*/
static long createGlobalRef(final Object obj) {
return obj == null ? 0 : ncreateGlobalRef(obj);
}
/**
* Creates a new global reference to the specified Object.
*
* @param obj the Object
*
* @return the GlobalRef memory address.
*/
private static native long ncreateGlobalRef(Object obj);
/**
* Deletes a global reference.
*
* @param ref the GlobalRef memory address.
*/
private static native void deleteGlobalRef(long ref);
/**
* Deletes the global reference represented by user_data if an OpenCL error occured.
*
* @param errcode the error code
* @param user_data the GlobalRef memory address
*/
static void checkCallback(final int errcode, final long user_data) {
if ( errcode != 0x0 && user_data != 0 )
deleteGlobalRef(user_data);
}
/* [ Context callback functionality ]
This is a little weird, so here's an explanation of what's happening for future reference:
Before making the clCreateContext call we create a global reference to the CLContextCallback object (using JNI's NewGlobalRef function).
We pass that global reference to the user_data parameter of clCreateContext. If clCreateContext returns anything but CL_SUCCESS, we
immediately destroy the global reference to avoid the memory leak. If the new context was created successfully, we associate the context
with the global reference in the contextUserData HashMap. On a future call to clReleaseContext, we clear that association and destroy the
global reference (if the reference count is 0).
*/
/**
* Returns the memory address of the native function we pass to clCreateContext(FromType).
*
* @return the callback function address
*/
static native long getContextCallback();
/**
* Associates the specified CLContext with the specified global reference. If the context
* is invalid, the global reference is deleted. NO-OP if user_data is 0.
*
* @param context the CLContext to register
* @param user_data the global reference pointer
*/
static void registerCallback(final CLContext context, final long user_data) {
if ( context.getPointer() == 0 ) {
if ( user_data != 0 )
deleteGlobalRef(user_data);
return;
}
if ( user_data != 0 )
contextUserData.put(context, user_data);
}
/**
* Decrements the specified context's reference count, clears its association
* with a CLContextCallback object if it exists and deletes the corresponding
* global reference.
*
* @param context the CLContext to unregister
*/
static void unregisterCallback(final CLContext context) {
if ( context.release() > 0 )
return;
final Long user_data = contextUserData.remove(context);
if ( user_data != null )
deleteGlobalRef(user_data);
}
/* [ Other callback functionality ]
The other callbacks are simpler. We create the GlobalRef before passing the callback,
we delete it when we receive the callback call.
*/
/**
* Returns the memory address of the native function we pass to clSetMemObjectDestructorCallback.
*
* @return the callback function address
*/
static native long getMemObjectDestructorCallback();
/**
* Returns the memory address of the native function we pass to clBuildProgram.
*
* @return the callback function address
*/
static native long getBuildProgramCallback();
/**
* Returns the memory address of the native function we pass to clEnqueueNativeKernel.
*
* @return the callback function address
*/
static native long getNativeKernelCallback();
/**
* Returns the memory address of the native function we pass to clSetEventCallback.
*
* @return the callback function address
*/
static native long getEventCallback();
/**
* Returns the memory address of the native function we pass to clCreateContext(FromType),
* when <code>APPLEContextLoggingUtil.SYSTEM_LOG_CALLBACK</code> is used.
*
* @return the callback function address
*
* @see APPLEContextLoggingUtil#SYSTEM_LOG_CALLBACK
*/
static native long getLogMessageToSystemLogAPPLE();
/**
* Returns the memory address of the native function we pass to clCreateContext(FromType),
* when <code>APPLEContextLoggingUtil.STD_OUT_CALLBACK</code> is used.
*
* @return the callback function address
*
* @see APPLEContextLoggingUtil#STD_OUT_CALLBACK
*/
static native long getLogMessageToStdoutAPPLE();
/**
* Returns the memory address of the native function we pass to clCreateContext(FromType),
* when <code>APPLEContextLoggingUtil.STD_ERR_CALLBACK</code> is used.
*
* @return the callback function address
*
* @see APPLEContextLoggingUtil#STD_ERR_CALLBACK
*/
static native long getLogMessageToStderrAPPLE();
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
public class OpenCLException extends RuntimeException {
private static final long serialVersionUID = 1L;
public OpenCLException() {
super();
}
public OpenCLException(final String message) {
super(message);
}
public OpenCLException(final String message, final Throwable cause) {
super(message, cause);
}
public OpenCLException(final Throwable cause) {
super(cause);
}
}

View file

@ -0,0 +1,76 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* Utility methods for OpenCL
*
* @author Spasi
*/
public final class Util {
/** Maps OpenCL error token values to their String representations. */
private static final Map<Integer, String> CL_ERROR_TOKENS = new HashMap<Integer, String>(64);
static {
APIUtil.getClassTokens(new Class[] {
CL10.class, CL11.class,
KHRGLSharing.class, KHRICD.class,
APPLEGLSharing.class,
EXTDeviceFission.class,
}, CL_ERROR_TOKENS, new APIUtil.TokenFilter() {
public boolean accept(final Field field, final int value) {
return value < 0; // Currently, all OpenCL errors have negative values.
}
});
}
private Util() {
}
public static void checkCLError(final int errcode) {
if ( errcode != CL10.CL_SUCCESS )
throwCLError(errcode);
}
private static void throwCLError(final int errcode) {
String errname = CL_ERROR_TOKENS.get(errcode);
if ( errname == null )
errname = "UNKNOWN";
throw new OpenCLException("Error Code: " + errname + " (0x" + Integer.toHexString(errcode).toUpperCase() + ")");
}
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl.api;
/**
* Simple filter interface.
*
* @author Spasi
*/
public interface Filter<T> {
/**
* Returns true if the specified object passes the filter.
*
* @param object the object to test
*
* @return true if the object is accepted
*/
boolean accept(T object);
}

View file

@ -31,6 +31,8 @@
*/
package org.lwjgl.opengl;
import org.lwjgl.PointerWrapperAbstract;
/**
* Instances of this class are needed to use the callback functionality of the AMD_debug_output extension.
* A debug context must be current before creating instances of this class. Users of this class may provide
@ -39,7 +41,7 @@ package org.lwjgl.opengl;
*
* @author Spasi
*/
public final class AMDDebugOutputCallback implements PointerWrapper {
public final class AMDDebugOutputCallback extends PointerWrapperAbstract {
/** Severity levels. */
private static final int GL_DEBUG_SEVERITY_HIGH_AMD = 0x9146,
@ -56,7 +58,7 @@ public final class AMDDebugOutputCallback implements PointerWrapper {
GL_DEBUG_CATEGORY_APPLICATION_AMD = 0x914F,
GL_DEBUG_CATEGORY_OTHER_AMD = 0x9150;
private final long pointer;
private final Handler handler;
/**
* Creates an AMDDebugOutputCallback with a default callback handler.
@ -120,30 +122,31 @@ public final class AMDDebugOutputCallback implements PointerWrapper {
}
/**
* Creates an AMDDebugOutputCallback with the specified callback handlers.
* Creates an AMDDebugOutputCallback with the specified callback handler.
* The handler's {@code handleMessage} method will be called whenever
* debug output is generated by the GL.
*
* @param handler the callback handler
*/
public AMDDebugOutputCallback(final Handler handler) {
super(getFunctionPointer());
this.handler = handler;
}
Handler getHandler() {
return handler;
}
private static long getFunctionPointer() {
try {
// We have to call registerHandler reflectively because we need this class to compile before we run the Generator.
// The registerHandler method depends on org.lwjgl.opengl.Context, if we touched that we would need to compile
// the whole library (which is not possible).
Class.forName("org.lwjgl.opengl.AMDDebugOutputUtil").getMethod("registerHandler", new Class[] { Handler.class }).invoke(null, new Object[] { handler });
// Call reflectively so that we can compile this class for the Generator.
return ((Long)Class.forName("org.lwjgl.opengl.CallbackUtil").getDeclaredMethod("getDebugOutputCallbackAMD", null).invoke(null, null)).longValue();
} catch (Exception e) {
throw new RuntimeException(e.getCause() != null ? e.getCause() : e);
}
this.pointer = getFunctionPointer();
}
public long getPointer() {
return pointer;
}
private static native long getFunctionPointer();
/** Implementations of this interface can be used to receive AMD_debug_output notifications. */
public interface Handler {

View file

@ -1,59 +0,0 @@
package org.lwjgl.opengl;
import org.lwjgl.opengl.AMDDebugOutputCallback.Handler;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.WeakHashMap;
/**
* This class handles AMDDebugOutputCallback.Handler registration and notification.
* We could have put this in AMDDebugOutputCallback, but we need to compile it for
* the generator. Registration is done reflectively in the AMDDebugOutputCallback
* constructor.
*
* @author Spasi
*/
final class AMDDebugOutputUtil {
private static final Map handlers = new WeakHashMap();
private AMDDebugOutputUtil() {}
public static void registerHandler(final Handler handler) {
final Context ctx = Context.getCurrentContext();
if ( ctx == null )
throw new IllegalStateException("No context is current.");
if ( !ctx.getContextAttribs().isDebug() )
throw new IllegalStateException("The current context is not a debug context.");
if ( !GLContext.getCapabilities().GL_AMD_debug_output )
throw new IllegalStateException("AMD_debug_output is not supported.");
handlers.put(ctx, handler);
}
/**
* This method is called by native code. If finds the callback handler associated
* with the current Thread and calls its {@code handleMessage} method.
*
* @param id the message ID
* @param category the message category
* @param severity the message severity
* @param message the string representation of the message.
* @param userParam the user-specified data specified in glDebugMessageCallbackAMD. For the current implementation this is always null and we ignore it.
*/
private static void messageCallback(final int id, final int category, final int severity, final String message, final ByteBuffer userParam) {
synchronized ( GlobalLock.lock ) {
final Context ctx = Context.getCurrentContext();
if ( ctx == null )
return;
final Handler handler = (Handler)handlers.get(ctx);
if ( handler != null )
handler.handleMessage(id, category, severity, message);
}
}
}

View file

@ -38,7 +38,7 @@ import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
/** @author spasi */
final class APIUtils {
final class APIUtil {
private static final int INITIAL_BUFFER_SIZE = 256;
private static final int INITIAL_LENGTHS_SIZE = 4;
@ -67,7 +67,7 @@ final class APIUtils {
private static CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
private APIUtils() {
private APIUtil() {
}
private static char[] getArray(final int size) {

View file

@ -31,6 +31,8 @@
*/
package org.lwjgl.opengl;
import org.lwjgl.PointerWrapperAbstract;
/**
* Instances of this class are needed to use the callback functionality of the ARB_debug_output extension.
* A debug context must be current before creating instances of this class. Users of this class may provide
@ -39,7 +41,7 @@ package org.lwjgl.opengl;
*
* @author Spasi
*/
public final class ARBDebugOutputCallback implements PointerWrapper {
public final class ARBDebugOutputCallback extends PointerWrapperAbstract {
/** Severity levels. */
private static final int
@ -65,7 +67,7 @@ public final class ARBDebugOutputCallback implements PointerWrapper {
GL_DEBUG_TYPE_PERFORMANCE_ARB = 0x8250,
GL_DEBUG_TYPE_OTHER_ARB = 0x8251;
private final long pointer;
private final Handler handler;
/**
* Creates an ARBDebugOutputCallback with a default callback handler.
@ -147,35 +149,36 @@ public final class ARBDebugOutputCallback implements PointerWrapper {
}
/**
* Creates an ARBDebugOutputCallback with the specified callback handlers.
* Creates an ARBDebugOutputCallback with the specified callback handler.
* The handler's {@code handleMessage} method will be called whenever
* debug output is generated by the GL.
*
* @param handler the callback handler
*/
public ARBDebugOutputCallback(final Handler handler) {
super(getFunctionPointer());
this.handler = handler;
}
Handler getHandler() {
return handler;
}
private static long getFunctionPointer() {
try {
// We have to call registerHandler reflectively because we need this class to compile before we run the Generator.
// The registerHandler method depends on org.lwjgl.opengl.Context, if we touched that we would need to compile
// the whole library (which is not possible).
Class.forName("org.lwjgl.opengl.ARBDebugOutputUtil").getMethod("registerHandler", new Class[] { Handler.class }).invoke(null, new Object[] { handler });
// Call reflectively so that we can compile this class for the Generator.
return ((Long)Class.forName("org.lwjgl.opengl.CallbackUtil").getDeclaredMethod("getDebugOutputCallbackARB", null).invoke(null, null)).longValue();
} catch (Exception e) {
throw new RuntimeException(e.getCause() != null ? e.getCause() : e);
}
this.pointer = getFunctionPointer();
}
public long getPointer() {
return pointer;
}
private static native long getFunctionPointer();
/** Implementations of this interface can be used to receive ARB_debug_output notifications. */
public interface Handler {
/**
* This method will be called when an AMD_debug_output message is generated.
* This method will be called when an ARB_debug_output message is generated.
*
* @param id the message ID
* @param source the message source

View file

@ -1,60 +0,0 @@
package org.lwjgl.opengl;
import org.lwjgl.opengl.ARBDebugOutputCallback.Handler;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.WeakHashMap;
/**
* This class handles ARBDebugOutputCallback.Handler registration and notification.
* We could have put this in ARBDebugOutputCallback, but we need to compile it for
* the generator. Registration is done reflectively in the ARBDebugOutputCallback
* constructor.
*
* @author Spasi
*/
final class ARBDebugOutputUtil {
private static final Map handlers = new WeakHashMap();
private ARBDebugOutputUtil() {}
public static void registerHandler(final Handler handler) {
final Context ctx = Context.getCurrentContext();
if ( ctx == null )
throw new IllegalStateException("No context is current.");
if ( !ctx.getContextAttribs().isDebug() )
throw new IllegalStateException("The current context is not a debug context.");
if ( !GLContext.getCapabilities().GL_ARB_debug_output )
throw new IllegalStateException("ARB_debug_output is not supported.");
handlers.put(ctx, handler);
}
/**
* This method is called by native code. If finds the callback handler associated
* with the current Thread and calls its {@code handleMessage} method.
*
* @param source the message source
* @param type the message type
* @param id the message ID
* @param severity the message severity
* @param message the string representation of the message.
* @param userParam the user-specified data specified in glDebugMessageCallbackAMD. For the current implementation this is always null and we ignore it.
*/
private static void messageCallback(final int source, final int type, final int id, final int severity, final String message, final ByteBuffer userParam) {
synchronized ( GlobalLock.lock ) {
final Context ctx = Context.getCurrentContext();
if ( ctx == null )
return;
final Handler handler = (Handler)handlers.get(ctx);
if ( handler != null )
handler.handleMessage(source, type, id, severity, message);
}
}
}

View file

@ -33,6 +33,7 @@ package org.lwjgl.opengl;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.PointerBuffer;
import org.lwjgl.Sys;
import java.awt.*;
@ -258,6 +259,14 @@ public class AWTGLCanvas extends Canvas implements DrawableLWJGL, ComponentListe
}
}
public final void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {
synchronized ( SYNC_LOCK ) {
if ( context == null )
throw new IllegalStateException("Canvas not yet displayable");
context.setCLSharingProperties(properties);
}
}
/**
* Override this to do initialising of the context.
* It will be called once from paint(), immediately after

View file

@ -2,6 +2,7 @@ package org.lwjgl.opengl;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.PointerBuffer;
/**
* @author Spasi
@ -73,6 +74,13 @@ abstract class AbstractDrawable implements DrawableLWJGL {
}
}
public void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {
synchronized ( GlobalLock.lock ) {
checkDestroyed();
context.setCLSharingProperties(properties);
}
}
protected final void checkDestroyed() {
if ( context == null )
throw new IllegalStateException("The Drawable has no context available.");

View file

@ -0,0 +1,157 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
import java.util.HashMap;
import java.util.Map;
/**
* Utility class that handles OpenGL API callbacks.
*
* @author Spasi
*/
final class CallbackUtil {
/** Context -> Long */
private static final Map contextUserParamsARB = new HashMap();
/** Context -> Long */
private static final Map contextUserParamsAMD = new HashMap();
private CallbackUtil() {}
/**
* Creates a new global reference to the specified Object.
*
* @param obj the Object
*
* @return the GlobalRef memory address or 0 if the Object is null.
*/
static long createGlobalRef(final Object obj) {
return obj == null ? 0 : ncreateGlobalRef(obj);
}
/**
* Creates a new global reference to the specified Object.
*
* @param obj the Object
*
* @return the GlobalRef memory address.
*/
private static native long ncreateGlobalRef(Object obj);
/**
* Deletes a global reference.
*
* @param ref the GlobalRef memory address.
*/
private static native void deleteGlobalRef(long ref);
// --------- [ XXX_debug_output ] ---------
/**
* Associates the current OpenGL context with the specified global reference. If there
* is no context current, the global reference is deleted and an exception is thrown.
* Any previous callback registrations will be cleared.
*
* @param userParam the global reference pointer
*/
private static void registerContextCallback(final long userParam, final Map contextUserData) {
Context context = Context.getCurrentContext();
if ( context == null ) {
deleteGlobalRef(userParam);
throw new IllegalStateException("No context is current.");
}
final Long userParam_old = (Long)contextUserData.remove(context);
if ( userParam_old != null )
deleteGlobalRef(userParam_old.longValue());
if ( userParam != 0 )
contextUserData.put(context, new Long(userParam));
}
/**
* Releases references to any callbacks associated with the specified GL context.
*
* @param context the Context to unregister
*/
static void unregisterCallbacks(final Context context) {
Long userParam = (Long)contextUserParamsARB.remove(context);
if ( userParam != null )
deleteGlobalRef(userParam.longValue());
userParam = (Long)contextUserParamsAMD.remove(context);
if ( userParam != null )
deleteGlobalRef(userParam.longValue());
}
// --------- [ ARB_debug_output ] ---------
/**
* Returns the memory address of the native function we pass to glDebugMessageCallbackARB.
*
* @return the callback function address
*/
static native long getDebugOutputCallbackARB();
/**
* Associates the current OpenGL context with the specified global reference. If there
* is no context current, the global reference is deleted and an exception is thrown.
* Any previous callback registrations will be cleared.
*
* @param userParam the global reference pointer
*/
static void registerContextCallbackARB(final long userParam) {
registerContextCallback(userParam, contextUserParamsARB);
}
// --------- [ AMD_debug_output ] ---------
/**
* Returns the memory address of the native function we pass to glDebugMessageCallbackAMD.
*
* @return the callback function address
*/
static native long getDebugOutputCallbackAMD();
/**
* Associates the current OpenGL context with the specified global reference. If there
* is no context current, the global reference is deleted and an exception is thrown.
* Any previous callback registrations will be cleared.
*
* @param userParam the global reference pointer
*/
static void registerContextCallbackAMD(final long userParam) {
registerContextCallback(userParam, contextUserParamsAMD);
}
}

View file

@ -33,7 +33,9 @@ package org.lwjgl.opengl;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.PointerBuffer;
import org.lwjgl.Sys;
import org.lwjgl.opencl.KHRGLSharing;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
@ -52,10 +54,10 @@ import java.nio.IntBuffer;
final class Context {
/** The platform specific implementation of context methods */
private final static ContextImplementation implementation;
private static final ContextImplementation implementation;
/** The current Context */
private final static ThreadLocal current_context_local = new ThreadLocal();
private static final ThreadLocal current_context_local = new ThreadLocal();
/** Handle to the native GL rendering context */
private final ByteBuffer handle;
@ -206,6 +208,7 @@ final class Context {
try {
releaseDrawable();
implementation.destroy(peer_info, handle);
CallbackUtil.unregisterCallbacks(this);
destroyed = true;
thread = null;
GLContext.unloadOpenGLLibrary();
@ -256,4 +259,26 @@ final class Context {
throw new OpenGLException(error);
}
public synchronized void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {
final ByteBuffer peer_handle = peer_info.lockAndGetHandle();
try {
switch ( LWJGLUtil.getPlatform() ) {
case LWJGLUtil.PLATFORM_WINDOWS:
final WindowsContextImplementation implWindows = (WindowsContextImplementation)implementation;
properties.put(KHRGLSharing.CL_GL_CONTEXT_KHR).put(implWindows.getHGLRC(handle));
properties.put(KHRGLSharing.CL_WGL_HDC_KHR).put(implWindows.getHDC(peer_handle));
break;
case LWJGLUtil.PLATFORM_LINUX:
final LinuxContextImplementation implLinux = (LinuxContextImplementation)implementation;
properties.put(KHRGLSharing.CL_GL_CONTEXT_KHR).put(implLinux.getGLXContext(handle));
properties.put(KHRGLSharing.CL_GLX_DISPLAY_KHR).put(implLinux.getDisplay(peer_handle));
break;
default:
throw new UnsupportedOperationException("CL/GL context sharing is not supposed on this platform.");
}
} finally {
peer_info.unlock();
}
}
}

View file

@ -57,6 +57,8 @@ import java.nio.IntBuffer;
public final class ContextAttribs {
// Same values for GLX & WGL
private static final int CONTEXT_ES2_PROFILE_BIT_EXT = 0x00000004;
private static final int CONTEXT_ROBUST_ACCESS_BIT_ARB = 0x00000004;
private static final int CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB = 0x8256;
private static final int
@ -74,6 +76,7 @@ public final class ContextAttribs {
private boolean profileCore;
private boolean profileCompatibility;
private boolean profileES;
private boolean loseContextOnReset;
@ -106,6 +109,7 @@ public final class ContextAttribs {
this.profileCore = attribs.profileCore;
this.profileCompatibility = attribs.profileCompatibility;
this.profileES = attribs.profileES;
this.loseContextOnReset = attribs.loseContextOnReset;
}
@ -138,6 +142,10 @@ public final class ContextAttribs {
return profileCompatibility;
}
public boolean isProfileES() {
return profileES;
}
public ContextAttribs withLayer(final int layerPlane) {
if ( layerPlane < 0 )
throw new IllegalArgumentException("Invalid layer plane specified: " + layerPlane);
@ -198,6 +206,19 @@ public final class ContextAttribs {
return attribs;
}
public ContextAttribs withProfileES(final boolean profileES) {
if ( !(majorVersion == 2 && minorVersion == 0) )
throw new IllegalArgumentException("The OpenGL ES profiles is only supported for OpenGL version 2.0.");
if ( profileES == this.profileES )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.profileES = profileES;
return attribs;
}
/**
* Returns a ContextAttribs instance with CONTEXT_RESET_NOTIFICATION_STRATEGY set
* to LOSE_CONTEXT_ON_RESET if the parameter is true or to NO_RESET_NOTIFICATION
@ -254,6 +275,8 @@ public final class ContextAttribs {
profileMask |= implementation.getProfileCoreBit();
else if ( profileCompatibility )
profileMask |= implementation.getProfileCompatibilityBit();
else if ( profileES )
profileMask |= CONTEXT_ES2_PROFILE_BIT_EXT;
if ( 0 < profileMask )
attribCount++;

View file

@ -32,6 +32,7 @@
package org.lwjgl.opengl;
import org.lwjgl.LWJGLException;
import org.lwjgl.PointerBuffer;
/**
* The Drawable interface describes an OpenGL drawable with an associated
@ -62,4 +63,15 @@ public interface Drawable {
/** Destroys the Drawable. */
void destroy();
/**
* Sets the appropriate khr_gl_sharing properties in the target <code>PointerBuffer</code>,
* so that if it is used in a <code>clCreateContext(FromType)</code> call, the created CL
* context will be sharing objects with this <code>Drawable</code>'s GL context. After a
* call to this method, the target buffer position will have advanced by 2 to 4 positions,
* depending on the implementation.
*
* @param properties The target properties buffer. It must have at least 4 positions remaining.
*/
void setCLSharingProperties(PointerBuffer properties) throws LWJGLException;
}

View file

@ -31,19 +31,17 @@
*/
package org.lwjgl.opengl;
import org.lwjgl.PointerWrapperAbstract;
/**
* This class is a wrapper around a GLsync pointer.
*
* @author spasi <spasi@users.sourceforge.net>
*/
public final class GLSync implements PointerWrapper {
private final long sync;
public final class GLSync extends PointerWrapperAbstract {
GLSync(final long sync) {
this.sync = sync;
}
public long getPointer() {
return sync;
super(sync);
}
}

View file

@ -59,6 +59,10 @@ final class LinuxContextImplementation implements ContextImplementation {
private static native ByteBuffer nCreate(ByteBuffer peer_handle, IntBuffer attribs, ByteBuffer shared_context_handle) throws LWJGLException;
native long getGLXContext(ByteBuffer context_handle);
native long getDisplay(ByteBuffer peer_info_handle);
public void releaseDrawable(ByteBuffer context_handle) throws LWJGLException {
}

View file

@ -55,6 +55,10 @@ final class WindowsContextImplementation implements ContextImplementation {
private static native ByteBuffer nCreate(ByteBuffer peer_handle, IntBuffer attribs_handle, ByteBuffer shared_context_handle) throws LWJGLException;
native long getHGLRC(ByteBuffer context_handle);
native long getHDC(ByteBuffer peer_info_handle);
public void swapBuffers() throws LWJGLException {
Context current_context = Context.getCurrentContext();
if ( current_context == null )

View file

@ -0,0 +1,185 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.test.opencl;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.PointerBuffer;
import org.lwjgl.opencl.*;
import java.nio.ByteBuffer;
import java.util.List;
import static org.lwjgl.opencl.CL10.*;
import static org.lwjgl.opencl.CL11.*;
/** Basic OpenCL test. */
public class HelloOpenCL {
public HelloOpenCL() {
}
protected void execute() {
try {
CL.create();
final List<CLPlatform> platforms = CLPlatform.getPlatforms();
for ( CLPlatform platform : platforms ) {
System.out.println("\n-------------------------");
System.out.println("NEW PLATFORM: " + platform.getPointer());
System.out.println(CLCapabilities.getPlatformCapabilities(platform));
System.out.println("-------------------------");
printPlatformInfo(platform, "CL_PLATFORM_PROFILE", CL_PLATFORM_PROFILE);
printPlatformInfo(platform, "CL_PLATFORM_VERSION", CL_PLATFORM_VERSION);
printPlatformInfo(platform, "CL_PLATFORM_NAME", CL_PLATFORM_NAME);
printPlatformInfo(platform, "CL_PLATFORM_VENDOR", CL_PLATFORM_VENDOR);
System.out.println("");
final PointerBuffer ctxProps = BufferUtils.createPointerBuffer(3);
ctxProps.put(CL_CONTEXT_PLATFORM).put(platform.getPointer()).put(0).flip();
final List<CLDevice> devices = platform.getDevices(CL_DEVICE_TYPE_ALL);
for ( CLDevice device : devices ) {
System.out.println("\n\tNEW DEVICE: " + device.getPointer());
System.out.println(CLCapabilities.getDeviceCapabilities(device));
System.out.println("\t-------------------------");
System.out.println("\tCL_DEVICE_TYPE = " + device.getInfoInt(CL_DEVICE_TYPE));
System.out.println("\tCL_DEVICE_VENDOR_ID = " + device.getInfoInt(CL_DEVICE_VENDOR_ID));
System.out.println("\tCL_DEVICE_MAX_COMPUTE_UNITS = " + device.getInfoInt(CL_DEVICE_MAX_COMPUTE_UNITS));
System.out.println("\tCL_DEVICE_MAX_WORK_ITEM_DIMENSIONS = " + device.getInfoInt(CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS));
//CL10.clGetDeviceInfo(device, CL10.CL_DEVICE_MAX_WORK_ITEM_SIZES, info, size_ret);
//System.out.println("\tCL_DEVICE_MAX_WORK_ITEM_SIZES = " + info.getInt(0));
System.out.println("\tCL_DEVICE_MAX_WORK_GROUP_SIZE = " + device.getInfoSize(CL_DEVICE_MAX_WORK_GROUP_SIZE));
System.out.println("\tCL_DEVICE_MAX_CLOCK_FREQUENCY = " + device.getInfoInt(CL_DEVICE_MAX_CLOCK_FREQUENCY));
System.out.println("\tCL_DEVICE_ADDRESS_BITS = " + device.getInfoInt(CL_DEVICE_ADDRESS_BITS));
System.out.println("\tCL_DEVICE_AVAILABLE = " + device.getInfoBoolean(CL_DEVICE_AVAILABLE));
System.out.println("\tCL_DEVICE_COMPILER_AVAILABLE = " + device.getInfoBoolean(CL_DEVICE_COMPILER_AVAILABLE));
printDeviceInfo(device, "CL_DEVICE_NAME", CL_DEVICE_NAME);
printDeviceInfo(device, "CL_DEVICE_VENDOR", CL_DEVICE_VENDOR);
printDeviceInfo(device, "CL_DRIVER_VERSION", CL_DRIVER_VERSION);
printDeviceInfo(device, "CL_DEVICE_PROFILE", CL_DEVICE_PROFILE);
printDeviceInfo(device, "CL_DEVICE_VERSION", CL_DEVICE_VERSION);
printDeviceInfo(device, "CL_DEVICE_OPENCL_C_VERSION", CL_DEVICE_OPENCL_C_VERSION);
CLContext context = clCreateContext(ctxProps, device, new CLContextCallback() {
protected void handleMessage(final String errinfo, final ByteBuffer private_info) {
System.out.println("IN CLContextCallback :: " + errinfo);
}
}, null);
CLMem buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, 128, null);
clSetMemObjectDestructorCallback(buffer, new CLMemObjectDestructorCallback() {
protected void handleMessage(final long memobj) {
System.out.println("FIRST Buffer destructed: " + memobj);
}
});
clSetMemObjectDestructorCallback(buffer, new CLMemObjectDestructorCallback() {
protected void handleMessage(final long memobj) {
System.out.println("SECOND Buffer destructed: " + memobj);
}
});
ByteBuffer bufferCreateInfo = BufferUtils.createByteBuffer(2 * PointerBuffer.getPointerSize());
PointerBuffer.put(bufferCreateInfo, 0);
PointerBuffer.put(bufferCreateInfo, 64);
bufferCreateInfo.flip();
CLMem subbuffer = clCreateSubBuffer(buffer, CL10.CL_MEM_READ_ONLY, CL11.CL_BUFFER_CREATE_TYPE_REGION, bufferCreateInfo, null);
clSetMemObjectDestructorCallback(subbuffer, new CLMemObjectDestructorCallback() {
protected void handleMessage(final long memobj) {
System.out.println("Sub Buffer destructed: " + memobj);
}
});
clRetainMemObject(buffer);
final long exec_caps = device.getInfoLong(CL_DEVICE_EXECUTION_CAPABILITIES);
if ( (exec_caps & CL_EXEC_NATIVE_KERNEL) == CL_EXEC_NATIVE_KERNEL ) {
System.out.println("-TRYING TO EXEC NATIVE KERNEL-");
final CLCommandQueue queue = clCreateCommandQueue(context, device, 0, null);
clEnqueueNativeKernel(queue, new CLNativeKernel() {
protected void execute(final ByteBuffer[] memobjs) {
if ( memobjs == null )
System.out.println("OK, it's null");
else {
System.out.println("memobjs = " + memobjs.length);
for ( int k = 0; k < memobjs.length; k++ ) {
System.out.println("memobjs[" + k + "].remaining() = " + memobjs[k].remaining());
for ( int l = memobjs[k].position(); l < memobjs[k].limit(); l++ ) {
memobjs[k].put(l, (byte)l);
}
}
}
}
}, new CLMem[] { buffer }, new long[] { 128 }, null, null);
clFinish(queue);
}
clReleaseMemObject(buffer);
clReleaseContext(context);
}
}
} catch (LWJGLException le) {
die("Init", le.getMessage());
}
CL.destroy();
}
private static void printPlatformInfo(final CLPlatform platform, final String param_name, final int param) {
System.out.println("\t" + param_name + " = " + platform.getInfoString(param));
}
private static void printDeviceInfo(final CLDevice device, final String param_name, final int param) {
System.out.println("\t" + param_name + " = " + device.getInfoString(param));
}
private static void die(String kind, String description) {
System.out.println(kind + " error " + description + " occured");
}
/**
* main entry point
*
* @param args String array containing arguments
*/
public static void main(String[] args) {
new HelloOpenCL().execute();
}
}

View file

@ -0,0 +1,675 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.test.opencl.gl;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.PointerBuffer;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opencl.*;
import org.lwjgl.opencl.api.Filter;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.Drawable;
import org.lwjgl.util.Color;
import org.lwjgl.util.ReadableColor;
import java.io.*;
import java.nio.IntBuffer;
import java.util.List;
import static java.lang.Math.*;
import static org.lwjgl.opencl.CL10.*;
import static org.lwjgl.opencl.CL10GL.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL21.*;
/*
THIS DEMO USES CODE PORTED FROM JogAmp.org
Original code: http://github.com/mbien/jocl-demos
Original author: Michael Bien
___ ___ ___
/ /\ / /\ ___ / /\ http://jocl.jogamp.org/
/ /:/ / /::\ /__/\ / /::\ a http://jogamp.org/ project.
/__/::\ / /:/\:\ \ \:\ / /:/\:\
\__\/\:\ / /:/~/::\ \ \:\ / /:/~/::\
\ \:\ /__/:/ /:/\:\ ___ \__\:\/__/:/ /:/\:\
\__\:\\ \:\/:/__\//__/\ | |:|\ \:\/:/__\/
/ /:/ \ \::/ \ \:\| |:| \ \::/
/__/:/ \ \:\ \ \:\__|:| \ \:\
\__\/ \ \:\ \__\::::/ \ \:\
\__\/ ~~~~ \__\/
___ ___ ___ ___ ___
/ /\ / /\ / /\ /__/\ / /\
/ /::\ / /::\ / /:/_ \ \:\ / /:/
/ /:/\:\ / /:/\:\ / /:/ /\ \ \:\ / /:/ ___ ___
/ /:/ \:\ / /:/~/:// /:/ /:/_ _____\__\:\ / /:/ ___ /__/\ / /\
/__/:/ \__\:\/__/:/ /://__/:/ /:/ /\/__/::::::::\/__/:/ / /\\ \:\ / /:/
\ \:\ / /:/\ \:\/:/ \ \:\/:/ /:/\ \:\~~\~~\/\ \:\ / /:/ \ \:\ /:/
\ \:\ /:/ \ \::/ \ \::/ /:/ \ \:\ ~~~ \ \:\ /:/ \ \:\/:/
\ \:\/:/ \ \:\ \ \:\/:/ \ \:\ \ \:\/:/ \ \::/
\ \::/ \ \:\ \ \::/ \ \:\ \ \::/ \__\/
\__\/ \__\/ \__\/ \__\/ \__\/
_____ ___ ___ ___ ___
/ /::\ / /\ /__/\ / /\ / /\
/ /:/\:\ / /:/_ | |::\ / /::\ / /:/_
/ /:/ \:\ / /:/ /\ | |:|:\ / /:/\:\ / /:/ /\
/__/:/ \__\:| / /:/ /:/_ __|__|:|\:\ / /:/ \:\ / /:/ /::\
\ \:\ / /:/ /__/:/ /:/ /\ /__/::::| \:\ /__/:/ \__\:\ /__/:/ /:/\:\
\ \:\ /:/ \ \:\/:/ /:/ \ \:\~~\__\/ \ \:\ / /:/ \ \:\/:/~/:/
\ \:\/:/ \ \::/ /:/ \ \:\ \ \:\ /:/ \ \::/ /:/
\ \::/ \ \:\/:/ \ \:\ \ \:\/:/ \__\/ /:/
\__\/ \ \::/ \ \:\ \ \::/ /__/:/
\__\/ \__\/ \__\/ \__\/
*/
/**
* Computes the Mandelbrot set with OpenCL using multiple GPUs and renders the result with OpenGL.
* A shared PBO is used as storage for the fractal image.<br/>
* http://en.wikipedia.org/wiki/Mandelbrot_set
* <p>
* controls:<br/>
* keys 1-9 control parallelism level<br/>
* space enables/disables slice seperator<br/>
* 'd' toggles between 32/64bit floatingpoint precision<br/>
* mouse/mousewheel to drag and zoom<br/>
* 'Home' to reset the viewport<br/>
* </p>
*
* @author Michael Bien, Spasi
*/
public class DemoFractal {
// max number of used GPUs
private static final int MAX_PARALLELISM_LEVEL = 8;
// max per pixel iterations to compute the fractal
private static final int MAX_ITERATIONS = 500;
private CLContext clContext;
private CLCommandQueue[] queues;
private CLKernel[] kernels;
private CLProgram[] programs;
private CLMem[] pboBuffers;
private IntBuffer pboIDs;
private CLMem[] colorMap;
private IntBuffer[] colorMapBuffer;
private final PointerBuffer kernel2DGlobalWorkSize;
private int width = 0;
private int height = 0;
private double minX = -2f;
private double minY = -1.2f;
private double maxX = 0.6f;
private double maxY = 1.3f;
private boolean dragging;
private double dragX;
private double dragY;
private double dragMinX;
private double dragMinY;
private double dragMaxX;
private double dragMaxY;
private int mouseX;
private int mouseY;
private int slices;
private boolean drawSeparator;
private boolean doublePrecision = true;
private boolean buffersInitialized;
private boolean rebuild;
private boolean run = true;
public DemoFractal(int width, int height) {
kernel2DGlobalWorkSize = BufferUtils.createPointerBuffer(2);
this.width = width;
this.height = height;
}
private void run() {
long startTime = System.currentTimeMillis() + 5000;
long fps = 0;
while ( run ) {
if ( !Display.isVisible() )
Thread.yield();
handleIO();
display();
Display.update();
if ( Display.isCloseRequested() )
break;
if ( startTime > System.currentTimeMillis() ) {
fps++;
} else {
long timeUsed = 5000 + (startTime - System.currentTimeMillis());
startTime = System.currentTimeMillis() + 5000;
System.out.println(fps + " frames in 5 seconds = " + (fps / (timeUsed / 1000f)));
fps = 0;
}
}
CL.destroy();
Display.destroy();
}
private void handleIO() {
if ( Keyboard.getNumKeyboardEvents() != 0 ) {
while ( Keyboard.next() ) {
if ( Keyboard.getEventKeyState() )
continue;
final int key = Keyboard.getEventKey();
if ( Keyboard.KEY_1 <= key && key <= Keyboard.KEY_8 ) {
int number = key - Keyboard.KEY_1 + 1;
slices = min(number, min(queues.length, MAX_PARALLELISM_LEVEL));
System.out.println("NEW PARALLELISM LEVEL: " + slices);
buffersInitialized = false;
} else {
switch ( Keyboard.getEventKey() ) {
case Keyboard.KEY_SPACE:
drawSeparator = !drawSeparator;
System.out.println("SEPARATOR DRAWING IS NOW: " + (drawSeparator ? "ON" : "OFF"));
break;
case Keyboard.KEY_D:
doublePrecision = !doublePrecision;
System.out.println("DOUBLE PRECISION IS NOW: " + (doublePrecision ? "ON" : "OFF"));
rebuild = true;
break;
case Keyboard.KEY_HOME:
minX = -2f;
minY = -1.2f;
maxX = 0.6f;
maxY = 1.3f;
break;
case Keyboard.KEY_ESCAPE:
run = false;
break;
}
}
}
}
while ( Mouse.next() ) {
final int eventBtn = Mouse.getEventButton();
final int x = Mouse.getX();
final int y = Mouse.getY();
if ( Mouse.isButtonDown(0) && (x != mouseX || y != mouseY) ) {
if ( !dragging ) {
dragging = true;
dragX = mouseX;
dragY = mouseY;
dragMinX = minX;
dragMinY = minY;
dragMaxX = maxX;
dragMaxY = maxY;
}
double offsetX = (x - dragX) * (maxX - minX) / width;
double offsetY = (y - dragY) * (maxY - minY) / height;
minX = dragMinX - offsetX;
minY = dragMinY - offsetY;
maxX = dragMaxX - offsetX;
maxY = dragMaxY - offsetY;
} else {
if ( dragging )
dragging = false;
if ( eventBtn == -1 ) {
final int dwheel = Mouse.getEventDWheel();
if ( dwheel != 0 ) {
double scale = dwheel > 0 ? 0.05 : -0.05;
double deltaX = scale * (maxX - minX);
double deltaY = scale * (maxY - minY);
// offset for "zoom to cursor"
double offsetX = (x / (double)width - 0.5) * deltaX * 2.0;
double offsetY = (y / (double)height - 0.5) * deltaY * 2.0;
minX += deltaX + offsetX;
minY += deltaY - offsetY;
maxX += -deltaX + offsetX;
maxY += -deltaY - offsetY;
}
}
}
mouseX = x;
mouseY = y;
}
}
public void init() {
try {
Display.setDisplayMode(new DisplayMode(width, height));
Display.setTitle("OpenCL Fractal Demo");
Display.create();
CL.create();
} catch (LWJGLException e) {
throw new RuntimeException(e);
}
try {
initCL(Display.getDrawable());
} catch (Exception e) {
if ( clContext != null )
clReleaseContext(clContext);
Display.destroy();
throw new RuntimeException(e);
}
Display.setSwapInterval(0);
glDisable(GL_DEPTH_TEST);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
initView(Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());
initPBO();
glFinish();
setKernelConstants();
}
private void initCL(Drawable drawable) throws Exception {
// Find a platform
List<CLPlatform> platforms = CLPlatform.getPlatforms();
if ( platforms == null )
throw new RuntimeException("No OpenCL platforms found.");
final CLPlatform platform = platforms.get(0); // just grab the first one
// Find devices with GL sharing support
final Filter<CLDevice> glSharingFilter = new Filter<CLDevice>() {
public boolean accept(final CLDevice device) {
final CLDeviceCapabilities caps = CLCapabilities.getDeviceCapabilities(device);
return caps.CL_KHR_gl_sharing;
}
};
List<CLDevice> devices = platform.getDevices(CL_DEVICE_TYPE_GPU, glSharingFilter);
if ( devices == null ) {
devices = platform.getDevices(CL_DEVICE_TYPE_CPU, glSharingFilter);
if ( devices == null )
throw new RuntimeException("No OpenCL devices found.");
}
// Create the context
final PointerBuffer deviceIDs = BufferUtils.createPointerBuffer(devices.size());
for ( CLDevice device : devices )
deviceIDs.put(device);
deviceIDs.flip();
final PointerBuffer contextProps = BufferUtils.createPointerBuffer(2 + 4 + 1);
contextProps.put(CL_CONTEXT_PLATFORM).put(platform);
drawable.setCLSharingProperties(contextProps); // Enable GL sharing
contextProps.put(0);
contextProps.flip();
clContext = clCreateContext(contextProps, deviceIDs, null, null);
slices = min(devices.size(), MAX_PARALLELISM_LEVEL);
// create command queues for every GPU, setup colormap and init kernels
queues = new CLCommandQueue[slices];
kernels = new CLKernel[slices];
colorMap = new CLMem[slices];
colorMapBuffer = new IntBuffer[slices];
for ( int i = 0; i < slices; i++ ) {
colorMapBuffer[i] = BufferUtils.createIntBuffer(32 * 2);
colorMap[i] = clCreateBuffer(clContext, CL_MEM_READ_ONLY, colorMapBuffer[i].capacity() * 4, null);
colorMap[i].checkNull();
initColorMap(colorMapBuffer[i], 32, Color.BLUE, Color.GREEN, Color.RED);
// create command queue and upload color map buffer on each used device
queues[i] = clCreateCommandQueue(clContext, devices.get(i), CL_QUEUE_PROFILING_ENABLE, null);
queues[i].checkNull();
clEnqueueWriteBuffer(queues[i], colorMap[i], CL_TRUE, 0, colorMapBuffer[i], null, null); // blocking upload
}
// check if we have 64bit FP support on all devices
// if yes we can use only one program for all devices + one kernel per device.
// if not we will have to create (at least) one program for 32 and one for 64bit devices.
// since there are different vendor extensions for double FP we use one program per device.
// (OpenCL spec is not very clear about this usecases)
boolean all64bit = true;
for ( CLDevice device : devices ) {
if ( !isDoubleFPAvailable(device) ) {
all64bit = false;
break;
}
}
// load program(s)
programs = new CLProgram[all64bit ? 1 : slices];
buildPrograms();
}
private void createPrograms() throws IOException {
final String source = getProgramSource("Mandelbrot.cl");
for ( int i = 0; i < programs.length; i++ )
programs[i] = clCreateProgramWithSource(clContext, source, null);
}
private String getProgramSource(final String file) throws IOException {
InputStream source = getClass().getResourceAsStream(file);
if ( source == null ) // dev-mode
source = new FileInputStream("src/java/org/lwjgl/test/opencl/gl/" + file);
final BufferedReader reader = new BufferedReader(new InputStreamReader(source));
final StringBuilder sb = new StringBuilder();
String line;
try {
while ( (line = reader.readLine()) != null )
sb.append(line).append("\n");
} finally {
source.close();
}
return sb.toString();
}
private static void initColorMap(IntBuffer colorMap, int stepSize, ReadableColor... colors) {
for ( int n = 0; n < colors.length - 1; n++ ) {
ReadableColor color = colors[n];
int r0 = color.getRed();
int g0 = color.getGreen();
int b0 = color.getBlue();
color = colors[n + 1];
int r1 = color.getRed();
int g1 = color.getGreen();
int b1 = color.getBlue();
int deltaR = r1 - r0;
int deltaG = g1 - g0;
int deltaB = b1 - b0;
for ( int step = 0; step < stepSize; step++ ) {
float alpha = (float)step / (stepSize - 1);
int r = (int)(r0 + alpha * deltaR);
int g = (int)(g0 + alpha * deltaG);
int b = (int)(b0 + alpha * deltaB);
colorMap.put((r << 16) | (g << 8) | (b << 0));
}
}
colorMap.rewind();
}
private static void initView(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, 0.0, height, 0.0, 1.0);
}
private void initPBO() {
if ( pboBuffers == null ) {
pboBuffers = new CLMem[slices];
pboIDs = BufferUtils.createIntBuffer(slices);
} else {
for ( CLMem pboBuffer : pboBuffers )
clReleaseMemObject(pboBuffer);
glDeleteBuffers(pboIDs);
}
glGenBuffers(pboIDs);
// setup one empty PBO per slice
for ( int i = 0; i < slices; i++ ) {
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIDs.get(i));
glBufferData(GL_PIXEL_UNPACK_BUFFER, width * height * 4 / slices, GL_STREAM_DRAW);
pboBuffers[i] = clCreateFromGLBuffer(clContext, CL_MEM_WRITE_ONLY, pboIDs.get(i), null);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
buffersInitialized = true;
}
private void buildPrograms() {
/*
* workaround: The driver keeps using the old binaries for some reason.
* to solve this we simple create a new program and release the old.
* however rebuilding programs should be possible -> remove when drivers are fixed.
* (again: the spec is not very clear about this kind of usages)
*/
if ( programs[0] != null ) {
for ( CLProgram program : programs )
clReleaseProgram(program);
}
try {
createPrograms();
} catch (IOException e) {
throw new RuntimeException(e);
}
// disable 64bit floating point math if not available
for ( int i = 0; i < programs.length; i++ ) {
final CLDevice device = queues[i].getCLDevice();
final StringBuilder options = new StringBuilder("-cl-fast-relaxed-math");
final CLDeviceCapabilities caps = CLCapabilities.getDeviceCapabilities(device);
if ( doublePrecision && isDoubleFPAvailable(device) ) {
//cl_khr_fp64
options.append(" -D DOUBLE_FP");
//amd's verson of double precision floating point math
if ( !caps.CL_KHR_fp64 && caps.CL_AMD_fp64 )
options.append(" -D AMD_FP");
}
System.out.println("COMPILER OPTIONS: " + options);
clBuildProgram(programs[i], device, options, null);
}
rebuild = false;
for ( int i = 0; i < kernels.length; i++ ) {
// init kernel with constants
kernels[i] = clCreateKernel(programs[min(i, programs.length)], "mandelbrot", null);
}
}
// init kernels with constants
private void setKernelConstants() {
for ( int i = 0; i < slices; i++ ) {
kernels[i]
.setArg(6, pboBuffers[i])
.setArg(7, colorMap[i])
.setArg(8, colorMapBuffer[i].capacity())
.setArg(9, MAX_ITERATIONS);
}
}
// rendering cycle
public void display() {
// make sure GL does not use our objects before we start computeing
glFinish();
if ( !buffersInitialized ) {
initPBO();
setKernelConstants();
}
if ( rebuild ) {
buildPrograms();
setKernelConstants();
}
compute(doublePrecision);
render();
}
// OpenCL
private void compute(final boolean is64bit) {
int sliceWidth = (int)(width / (float)slices);
double rangeX = (maxX - minX) / slices;
double rangeY = (maxY - minY);
kernel2DGlobalWorkSize.put(0, sliceWidth).put(1, height);
// start computation
for ( int i = 0; i < slices; i++ ) {
kernels[i].setArg(0, sliceWidth).setArg(1, height);
if ( !is64bit || !isDoubleFPAvailable(queues[i].getCLDevice()) ) {
kernels[i]
.setArg(2, (float)(minX + rangeX * i)).setArg(3, (float)minY)
.setArg(4, (float)rangeX).setArg(5, (float)rangeY);
} else {
kernels[i]
.setArg(2, minX + rangeX * i).setArg(3, minY)
.setArg(4, rangeX).setArg(5, rangeY);
}
// aquire GL objects, and enqueue a kernel with a probe from the list
clEnqueueAcquireGLObjects(queues[i], pboBuffers[i], null, null);
clEnqueueNDRangeKernel(queues[i], kernels[i], 2,
null,
kernel2DGlobalWorkSize,
null,
null, null);
clEnqueueReleaseGLObjects(queues[i], pboBuffers[i], null, null);
}
// block until done (important: finish before doing further gl work)
for ( int i = 0; i < slices; i++ ) {
clFinish(queues[i]);
}
}
// OpenGL
private void render() {
glClear(GL_COLOR_BUFFER_BIT);
//draw slices
int sliceWidth = width / slices;
for ( int i = 0; i < slices; i++ ) {
int seperatorOffset = drawSeparator ? i : 0;
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIDs.get(i));
glRasterPos2i(sliceWidth * i + seperatorOffset, 0);
glDrawPixels(sliceWidth, height, GL_BGRA, GL_UNSIGNED_BYTE, 0);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
//draw info text
/*
textRenderer.beginRendering(width, height, false);
textRenderer.draw("device/time/precision", 10, height - 15);
for ( int i = 0; i < slices; i++ ) {
CLDevice device = queues[i].getDevice();
boolean doubleFP = doublePrecision && isDoubleFPAvailable(device);
CLEvent event = probes.getEvent(i);
long start = event.getProfilingInfo(START);
long end = event.getProfilingInfo(END);
textRenderer.draw(device.getType().toString() + i + " "
+ (int)((end - start) / 1000000.0f) + "ms @"
+ (doubleFP ? "64bit" : "32bit"), 10, height - (20 + 16 * (slices - i)));
}
textRenderer.endRendering();
*/
}
public void reshape(int x, int y, int width, int height) {
if ( this.width == width && this.height == height )
return;
this.width = width;
this.height = height;
initPBO();
setKernelConstants();
initView(width, height);
}
private static boolean isDoubleFPAvailable(CLDevice device) {
final CLDeviceCapabilities caps = CLCapabilities.getDeviceCapabilities(device);
return caps.CL_KHR_fp64 || caps.CL_AMD_fp64;
}
public static void main(String args[]) {
DemoFractal demo = new DemoFractal(512, 512);
demo.init();
demo.run();
}
}

View file

@ -0,0 +1,55 @@
#ifdef DOUBLE_FP
#ifdef AMD_FP
#pragma OPENCL EXTENSION cl_amd_fp64 : enable
#else
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
#endif
typedef double varfloat;
#else
typedef float varfloat;
#endif
/**
* For a description of this algorithm please refer to
* http://en.wikipedia.org/wiki/Mandelbrot_set
* @author Michael Bien
*/
kernel void mandelbrot(
const int width, const int height,
const varfloat x0, const varfloat y0,
const varfloat rangeX, const varfloat rangeY,
global uint *output, global uint *colorMap,
const int colorMapSize, const int maxIterations) {
unsigned int ix = get_global_id(0);
unsigned int iy = get_global_id(1);
varfloat r = x0 + ix * rangeX / width;
varfloat i = y0 + iy * rangeY / height;
varfloat x = 0;
varfloat y = 0;
varfloat magnitudeSquared = 0;
int iteration = 0;
while (magnitudeSquared < 4 && iteration < maxIterations) {
varfloat x2 = x*x;
varfloat y2 = y*y;
y = 2 * x * y + i;
x = x2 - y2 + r;
magnitudeSquared = x2+y2;
iteration++;
}
if (iteration == maxIterations) {
output[iy * width + ix] = 0;
}else {
varfloat alpha = (varfloat)iteration / maxIterations;
int colorIndex = (int)(alpha * colorMapSize);
output[iy * width + ix] = colorMap[colorIndex];
// monochrom
// output[iy * width + ix] = 255*iteration/maxIterations;
}
}

View file

@ -81,6 +81,8 @@ public final class VersionTest {
ca = ca.withProfileCore(true);
else if ( "compatibility".equalsIgnoreCase(args[i]) )
ca = ca.withProfileCompatibility(true);
else if ( "es".equalsIgnoreCase(args[i]) )
ca = ca.withProfileES(true);
else
argsError("Unknown argument: \'" + args[i] + "\'");
}
@ -236,6 +238,7 @@ public final class VersionTest {
System.out.println("majorVersion\t- Minor OpenGL version.");
System.out.println("core\t- Sets the Core Profile bit (optional, requires 3.2+).");
System.out.println("compatibility\t- Sets the Compatibility Profile bit (optional, requires 3.2+).");
System.out.println("ws\t- Sets the OpenGL ES Profile bit (optional, requires 2.0).");
System.out.println("layer\t- Layer plane (optional).");
System.out.println("debug\t- Enables debug mode (optional).");
System.out.println("fc\t- Enables forward compatibility mode (optional, requires 3.0+).");

View file

@ -49,6 +49,9 @@ public @interface Alternate {
/** If true, an alternate Java->native call will be created. Useful when the alternate implementation uses different types. */
boolean nativeAlt() default false;
/** Applicable when nativeAlt is true. If true, no extra native call will be generated. Useful when there's another nativeAlt already defined. */
boolean skipNative() default false;
/** If true, the alternate method's name will be used for the Java call. */
boolean javaAlt() default false;
}

View file

@ -45,9 +45,10 @@ import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Auto
@Target(ElementType.PARAMETER)
@Target({ElementType.METHOD,ElementType.PARAMETER})
public @interface AutoSize {
String value(); // The name of the Buffer parameter
String expression() default ""; // This value is added after the argument
boolean canBeNull() default false; // When this is true and the Buffer parameter is null, 0 will be used.
boolean isNative() default false; // When this is true, auto-sizing will be performed in native code.
}

View file

@ -41,7 +41,7 @@ package org.lwjgl.util.generator;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target(ElementType.PARAMETER)
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface Check {
String value() default "";
boolean canBeNull() default false;

View file

@ -38,10 +38,22 @@ package org.lwjgl.util.generator;
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
public @interface Code {
String value();
String value() default ""; // Java, before everything
boolean tryBlock() default false; // Add a try/finally block around the native call and return statement
String javaBeforeNative() default ""; // Before the native call
String javaAfterNative() default ""; // After the native call
String javaFinally() default ""; // In the finally block
String nativeAfterVars() default ""; // After variable declaration
String nativeBeforeCall() default ""; // Before the API call
String nativeAfterCall() default ""; // After the API call
}

View file

@ -46,4 +46,6 @@ public @interface Constant {
String value();
/** If true, the original parameter will not be removed from the method. */
boolean keepParam() default false;
/** If true, this is a native code constant. */
boolean isNative() default false;
}

View file

@ -1,50 +1,46 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* AutoResultSize specifies the size of a returned Buffer
* as an expression.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target(ElementType.METHOD)
public @interface AutoResultSize {
String value(); // The size as a java expression
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Functions marked with <code>@Extern</code> will not be declared as <code>static</code> in the C implementation.
* This allows other source files to call them.
*
* @author Spasi
*/
@Target(ElementType.METHOD)
public @interface Extern {
}

View file

@ -43,4 +43,6 @@ import java.lang.annotation.ElementType;
@Target(ElementType.METHOD)
public @interface GenerateAutos {
/** If true, a size variable will be generated. */
String[] sizeVariables() default {};
}

View file

@ -32,29 +32,32 @@
package org.lwjgl.util.generator;
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import java.io.File;
import java.io.FileFilter;
import java.util.Collection;
import java.util.Set;
import java.util.Map;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;
import com.sun.mirror.declaration.TypeDeclaration;
import static java.util.Collections.*;
import static com.sun.mirror.util.DeclarationVisitors.*;
import static java.util.Collections.*;
/**
*
* Generator tool for creating the java classes and native code
* from an annotated template java interface.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
* $Id$
*/
public class GeneratorProcessorFactory implements AnnotationProcessorFactory, RoundCompleteListener {
private static boolean first_round = true;
// Process any set of annotations
@ -78,7 +81,7 @@ public class GeneratorProcessorFactory implements AnnotationProcessorFactory, Ro
public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds, AnnotationProcessorEnvironment env) {
// Only process the initial types, not the generated ones
if (first_round) {
if ( first_round ) {
env.addListener(this);
return new GeneratorProcessor(env);
} else
@ -86,6 +89,7 @@ public class GeneratorProcessorFactory implements AnnotationProcessorFactory, Ro
}
private static class GeneratorProcessor implements AnnotationProcessor {
private final AnnotationProcessorEnvironment env;
GeneratorProcessor(AnnotationProcessorEnvironment env) {
@ -97,22 +101,22 @@ public class GeneratorProcessorFactory implements AnnotationProcessorFactory, Ro
String typemap_classname = null;
boolean generate_error_checks = options.containsKey("-Ageneratechecks");
boolean context_specific = options.containsKey("-Acontextspecific");
for (String k : options.keySet()) {
for ( String k : options.keySet() ) {
int delimiter = k.indexOf('=');
if (delimiter != -1) {
if (k.startsWith("-Atypemap")) {
if ( delimiter != -1 ) {
if ( k.startsWith("-Atypemap") ) {
typemap_classname = k.substring(delimiter + 1);
}
}
}
if (typemap_classname == null)
if ( typemap_classname == null )
throw new RuntimeException("No TypeMap class name specified with -Atypemap=<class-name>");
TypeDeclaration lastFile = null;
try {
long generatorLM = getGeneratorLastModified();
TypeMap type_map = (TypeMap)(Class.forName(typemap_classname).newInstance());
for (TypeDeclaration typedecl : env.getSpecifiedTypeDeclarations()) {
for ( TypeDeclaration typedecl : env.getSpecifiedTypeDeclarations() ) {
lastFile = typedecl;
typedecl.accept(getDeclarationScanner(new GeneratorVisitor(env, type_map, generate_error_checks, context_specific, generatorLM), NO_OP));
}
@ -130,7 +134,16 @@ public class GeneratorProcessorFactory implements AnnotationProcessorFactory, Ro
* @return time of the latest change
*/
private static long getGeneratorLastModified() {
final File pck = new File(System.getProperty("user.dir") + "/bin/org/lwjgl/util/generator");
long lastModified = getDirectoryLastModified("/bin/org/lwjgl/util/generator");
lastModified = Math.max(lastModified, getDirectoryLastModified("/bin/org/lwjgl/util/generator/openal"));
lastModified = Math.max(lastModified, getDirectoryLastModified("/bin/org/lwjgl/util/generator/opengl"));
lastModified = Math.max(lastModified, getDirectoryLastModified("/bin/org/lwjgl/util/generator/opencl"));
return lastModified;
}
private static long getDirectoryLastModified(final String path) {
final File pck = new File(System.getProperty("user.dir") + path);
if ( !pck.exists() || !pck.isDirectory() )
return Long.MAX_VALUE;

View file

@ -37,12 +37,11 @@ import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import java.io.*;
import java.lang.annotation.Annotation;
import java.nio.channels.FileChannel;
import java.util.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.File;
import java.nio.*;
/**
@ -68,11 +67,6 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
this.generatorLM = generatorLM;
}
private void validateMethods(InterfaceDeclaration d) {
for (MethodDeclaration method : d.getMethods())
validateMethod(method);
}
private void validateMethod(MethodDeclaration method) {
if (method.isVarArgs())
throw new RuntimeException("Method " + method.getSimpleName() + " is variadic");
@ -96,13 +90,13 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
if (method.getAnnotation(CachedResult.class) != null) {
if (Utils.getNIOBufferType(Utils.getMethodReturnType(method)) == null)
throw new RuntimeException(method + " return type is not a Buffer, but is annotated with CachedResult");
if (method.getAnnotation(AutoResultSize.class) == null)
throw new RuntimeException(method + " is annotated with CachedResult but misses an AutoResultSize annotation");
if (method.getAnnotation(AutoSize.class) == null)
throw new RuntimeException(method + " is annotated with CachedResult but misses an AutoSize annotation");
}
validateTypes(method, method.getAnnotationMirrors(), method.getReturnType());
}
private void validateType(MethodDeclaration method, Class annotation_type, Class type) {
private void validateType(MethodDeclaration method, Class<?extends Annotation> annotation_type, Class type) {
Class[] valid_types = type_map.getValidAnnotationTypes(type);
for (int i = 0; i < valid_types.length; i++)
if (valid_types[i].equals(annotation_type))
@ -115,7 +109,11 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
for (AnnotationMirror annotation : annotations) {
NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type_annotation != null) {
Class annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
Class<? extends Annotation> annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
/*System.out.println("\nYO:");
System.out.println("annotation = " + annotation);
System.out.println("native_type_annotation = " + native_type_annotation);
System.out.println("annotation_type = " + annotation_type);*/
Class type = Utils.getJavaType(type_mirror);
if (Buffer.class.equals(type))
continue;
@ -172,7 +170,9 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
}
private static void generateMethodNativePointers(PrintWriter writer, MethodDeclaration method) {
writer.println("static " + Utils.getTypedefName(method) + " " + method.getSimpleName() + ";");
if ( method.getAnnotation(Extern.class) == null )
writer.print("static ");
writer.println(Utils.getTypedefName(method) + " " + method.getSimpleName() + ";");
}
private void generateJavaSource(InterfaceDeclaration d, PrintWriter java_writer) throws IOException {
@ -182,9 +182,15 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
java_writer.println();
java_writer.println("import org.lwjgl.*;");
java_writer.println("import java.nio.*;");
Imports imports = d.getAnnotation(Imports.class);
if ( imports != null ) {
for ( String i : imports.value() )
java_writer.println("import " + i + ";");
}
java_writer.println();
Utils.printDocComment(java_writer, d);
java_writer.print("public ");
if ( d.getAnnotation(Private.class) == null )
java_writer.print("public ");
boolean is_final = Utils.isFinal(d);
if (is_final)
java_writer.write("final ");
@ -223,8 +229,10 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
native_writer.println("#include <jni.h>");
type_map.printNativeIncludes(native_writer);
native_writer.println();
//if ( d.getAnnotation(NoTypeDefs.class) == null ) {
TypedefsGenerator.generateNativeTypedefs(type_map, native_writer, d.getMethods());
native_writer.println();
//}
if (!context_specific) {
generateMethodsNativePointers(native_writer, d.getMethods());
native_writer.println();
@ -247,29 +255,98 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
}
public void visitInterfaceDeclaration(InterfaceDeclaration d) {
File input = d.getPosition().file();
File output = new File(env.getOptions().get("-s") + '/' + d.getPackage().getQualifiedName().replace('.', '/'), Utils.getSimpleClassName(d) + ".java");
final File input = d.getPosition().file();
final File outputJava = new File(env.getOptions().get("-s") + '/' + d.getPackage().getQualifiedName().replace('.', '/'), Utils.getSimpleClassName(d) + ".java");
PrintWriter java_writer = null;
try {
// Skip this class if the output exists and the input has not been modified.
if ( output.exists() && Math.max(input.lastModified(), generatorLM) < output.lastModified() )
final Collection<? extends MethodDeclaration> methods = d.getMethods();
if ( methods.size() == 0 && d.getFields().size() == 0 )
return;
if (d.getMethods().size() > 0 || d.getFields().size() > 0) {
validateMethods(d);
java_writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, d.getPackage().getQualifiedName(), new File(Utils.getSimpleClassName(d) + ".java"), null);
generateJavaSource(d, java_writer);
// Skip this class if the output exists and the input has not been modified.
if ( outputJava.exists() && Math.max(input.lastModified(), generatorLM) < outputJava.lastModified() )
return;
for ( final MethodDeclaration method : methods )
validateMethod(method);
java_writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, d.getPackage().getQualifiedName(), new File(Utils.getSimpleClassName(d) + ".java"), null);
generateJavaSource(d, java_writer);
if ( methods.size() > 0 ) {
boolean hasNative = false;
for ( final MethodDeclaration method : methods ) {
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if ( (alt_annotation == null || alt_annotation.nativeAlt()) && method.getAnnotation(Reuse.class) == null ) {
hasNative = true;
break;
}
}
if ( !hasNative )
return;
final String outputPath = env.getOptions().get("-d") + '/' + Utils.getNativeQualifiedName(Utils.getQualifiedClassName(d));
final File outputNative = new File(outputPath + ".c");
final File outputBackup = new File(outputPath + "_backup.c");
// If the native file exists, rename.
final ByteBuffer nativeBefore;
if ( outputNative.exists() ) {
nativeBefore = readFile(outputNative);
outputNative.renameTo(outputBackup);
} else
nativeBefore = null;
try {
generateNativeSource(d);
// If the native file did exist, compare with the new file. If they're the same,
// reset the last modified time to avoid ridiculous C compilation times.
if ( nativeBefore != null && outputNative.length() == nativeBefore.capacity() ) {
final ByteBuffer nativeAfter = readFile(outputNative);
boolean same = true;
for ( int i = nativeBefore.position(); i < nativeBefore.limit(); i++ ) {
if ( nativeBefore.get(i) != nativeAfter.get(i) ) {
same = false;
break;
}
}
if ( same ) {
outputNative.delete();
outputBackup.renameTo(outputNative);
}
}
} finally {
if ( outputBackup.exists() )
outputBackup.delete();
}
}
if (d.getMethods().size() > 0)
generateNativeSource(d);
} catch (Exception e) {
// If anything goes wrong mid-gen, delete output to allow regen next time we run.
if ( java_writer != null ) java_writer.close();
if ( output.exists() ) output.delete();
if ( outputJava.exists() ) outputJava.delete();
throw new RuntimeException(e);
}
}
private static ByteBuffer readFile(final File file) throws IOException {
final FileChannel channel = new FileInputStream(file).getChannel();
final long bytesTotal = channel.size();
final ByteBuffer buffer = ByteBuffer.allocateDirect((int)bytesTotal);
long bytesRead = 0;
do {
bytesRead += channel.read(buffer);
} while ( bytesRead < bytesTotal );
buffer.flip();
channel.close();
return buffer;
}
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
* Method parameters marked with <code>@Helper</code> will be considered Java-API
* parameters and will be ignored when generating native stubs/code.
*
* @author Spasi
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
public @interface Helper {
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* This annotation can be used when an extension template needs
* extra imports in its generated class.
*
* @author Spasi
*/
@Target(ElementType.TYPE)
public @interface Imports {
String[] value();
}

View file

@ -56,8 +56,13 @@ public class JNITypeTranslator implements TypeVisitor {
}
public void visitArrayType(ArrayType t) {
if ( "java.lang.CharSequence".equals(t.getComponentType().toString()) )
final String className = t.getComponentType().toString();
if ( "java.lang.CharSequence".equals(className) )
signature.append("jobject");
else if ( "java.nio.ByteBuffer".equals(className) )
signature.append("jobjectArray");
else if ( "org.lwjgl.opencl.CLMem".equals(className) )
signature.append("jobjectArray");
else
throw new RuntimeException(t + " is not allowed");
}

View file

@ -41,6 +41,9 @@ package org.lwjgl.util.generator;
* $Id$
*/
import org.lwjgl.PointerBuffer;
import org.lwjgl.util.generator.opengl.GLreturn;
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
@ -50,7 +53,7 @@ import java.util.*;
import java.nio.*;
public class JavaMethodsGenerator {
private final static String SAVED_PARAMETER_POSTFIX = "_saved";
private static final String SAVED_PARAMETER_POSTFIX = "_saved";
public static void generateMethodsJava(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, InterfaceDeclaration interface_decl, boolean generate_error_checks, boolean context_specific) {
for (MethodDeclaration method : interface_decl.getMethods())
@ -71,8 +74,14 @@ public class JavaMethodsGenerator {
if ( method.getAnnotation(CachedResult.class) != null && !method.getAnnotation(CachedResult.class).isRange() ) {
printMethodWithMultiType(env, type_map, writer, interface_decl, method, TypeInfo.getDefaultTypeInfoMap(method), Mode.CACHEDRESULT, generate_error_checks, context_specific);
}
// Skip the native function if we're re-using.
Reuse reuse_annotation = method.getAnnotation(Reuse.class);
if ( reuse_annotation != null )
return;
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if ( alt_annotation == null || alt_annotation.nativeAlt() ) {
if ( alt_annotation == null || (alt_annotation.nativeAlt() && !alt_annotation.skipNative()) ) {
if ( alt_annotation != null && method.getSimpleName().equals(alt_annotation.value()) )
throw new RuntimeException("An alternate function with native code should have a different name than the main function.");
printJavaNativeStub(writer, method, Mode.NORMAL, generate_error_checks, context_specific);
@ -90,12 +99,12 @@ public class JavaMethodsGenerator {
Utils.printDocComment(writer, method);
writer.print("\tpublic static native ");
}
printResultType(writer, method, true);
writer.print(getResultType(method, true));
writer.print(" " + Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific));
if (mode == Mode.BUFFEROBJECT)
writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
writer.print("(");
boolean first_parameter = generateParametersJava(writer, method, TypeInfo.getDefaultTypeInfoMap(method), true, mode);
boolean first_parameter = generateParametersJava(writer, method, TypeInfo.getDefaultTypeInfoMap(method), true, true, mode);
if (context_specific) {
if (!first_parameter)
writer.print(", ");
@ -104,10 +113,14 @@ public class JavaMethodsGenerator {
writer.println(");");
}
private static boolean generateParametersJava(PrintWriter writer, MethodDeclaration method, Map<ParameterDeclaration, TypeInfo> typeinfos_instance,
boolean native_stub, Mode mode) {
private static boolean generateParametersJava(PrintWriter writer, MethodDeclaration method, Map<ParameterDeclaration, TypeInfo> typeinfos_instance, boolean native_stub, final boolean printTypes, Mode mode) {
boolean first_parameter = true;
for (ParameterDeclaration param : method.getParameters()) {
if ( native_stub && param.getAnnotation(Helper.class) != null )
continue;
final Constant constant_annotation = param.getAnnotation(Constant.class);
if ( constant_annotation != null && constant_annotation.isNative() )
continue;
AnnotationMirror auto_annotation_mirror = Utils.getParameterAutoAnnotation(param);
boolean hide_auto_parameter = mode == Mode.NORMAL && !native_stub && auto_annotation_mirror != null;
if (hide_auto_parameter) {
@ -119,44 +132,53 @@ public class JavaMethodsGenerator {
if (!first_parameter)
writer.print(", ");
first_parameter = false;
writer.print("boolean " + TypeInfo.UNSIGNED_PARAMETER_NAME);
if ( printTypes )
writer.print("boolean ");
writer.print( TypeInfo.UNSIGNED_PARAMETER_NAME);
}
}
} else if (
param.getAnnotation(Result.class) == null
&& (native_stub || ((param.getAnnotation(Constant.class) == null || param.getAnnotation(Constant.class).keepParam()) && !Utils.isReturnParameter(method, param)))
&& (getAutoTypeParameter(method, param) == null || mode != Mode.AUTOS)
)
{
TypeInfo type_info = typeinfos_instance.get(param);
first_parameter = generateParameterJava(writer, param, type_info, native_stub, first_parameter, mode);
&& (mode != Mode.AUTOS || getAutoTypeParameter(method, param) == null)
) {
first_parameter = generateParameterJava(writer, param, typeinfos_instance.get(param), native_stub, printTypes, first_parameter, mode);
}
}
CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class);
TypeMirror result_type = Utils.getMethodReturnType(method);
if ((native_stub && Utils.getNIOBufferType(result_type) != null) || Utils.needResultSize(method)) {
if (cached_result_annotation == null || !cached_result_annotation.isRange()) {
if (!first_parameter)
writer.print(", ");
first_parameter = false;
writer.print("long " + Utils.RESULT_SIZE_NAME);
AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class);
if ( auto_size_annotation == null || !auto_size_annotation.isNative() ) {
if (cached_result_annotation == null || !cached_result_annotation.isRange()) {
if (!first_parameter)
writer.print(", ");
first_parameter = false;
if ( printTypes )
writer.print("long ");
writer.print(Utils.RESULT_SIZE_NAME);
}
}
}
if (cached_result_annotation != null) {
if (!first_parameter)
writer.print(", ");
if ( mode == Mode.CACHEDRESULT )
writer.print("long " + Utils.CACHED_BUFFER_LENGTH_NAME + ", ");
if ( mode == Mode.CACHEDRESULT ) {
if ( printTypes )
writer.print("long ");
writer.print(Utils.CACHED_BUFFER_LENGTH_NAME + ", ");
}
first_parameter = false;
printResultType(writer, method, native_stub);
if ( printTypes )
writer.print(getResultType(method, native_stub));
writer.print(" " + Utils.CACHED_BUFFER_NAME);
}
return first_parameter;
}
private static boolean generateParameterJava(PrintWriter writer, ParameterDeclaration param, TypeInfo type_info, boolean native_stub, boolean first_parameter, Mode mode) {
private static boolean generateParameterJava(PrintWriter writer, ParameterDeclaration param, TypeInfo type_info, boolean native_stub, final boolean printTypes, boolean first_parameter, Mode mode) {
Class buffer_type = Utils.getNIOBufferType(param.getType());
if (!first_parameter)
writer.print(", ");
@ -164,18 +186,23 @@ public class JavaMethodsGenerator {
if (bo_annotation != null && mode == Mode.BUFFEROBJECT) {
if (buffer_type == null)
throw new RuntimeException("type of " + param + " is not a nio Buffer parameter but is annotated as buffer object");
writer.print("long " + param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX);
if ( printTypes )
writer.print("long ");
writer.print(param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX);
} else {
if ( native_stub && param.getAnnotation(GLpointer.class) != null )
writer.print("long");
if ( native_stub && param.getAnnotation(PointerWrapper.class) != null )
writer.print("long ");
else {
Class type = type_info.getType();
if ( native_stub && (type == CharSequence.class || type == CharSequence[].class) )
writer.print("ByteBuffer");
else
writer.print(type_info.getType().getSimpleName());
if ( native_stub && (type == CharSequence.class || type == CharSequence[].class || type == PointerBuffer.class) )
writer.print("ByteBuffer ");
else if ( printTypes )
writer.print(type_info.getType().getSimpleName() + " ");
}
writer.print(" " + param.getSimpleName());
AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class);
if ( auto_size_annotation != null )
writer.print(auto_size_annotation.value() + "_");
writer.print(param.getSimpleName());
if ( native_stub && buffer_type != null )
writer.print(", int " + param.getSimpleName() + NativeMethodStubsGenerator.BUFFER_POSITION_POSTFIX);
}
@ -205,8 +232,11 @@ public class JavaMethodsGenerator {
private static void printMethodWithMultiType(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, InterfaceDeclaration interface_decl, MethodDeclaration method, Map<ParameterDeclaration, TypeInfo> typeinfos_instance, Mode mode, boolean generate_error_checks, boolean context_specific) {
Utils.printDocComment(writer, method);
writer.print("\tpublic static ");
printResultType(writer, method, false);
if ( interface_decl.getAnnotation(Private.class) == null && method.getAnnotation(Private.class) == null )
writer.print("\tpublic static ");
else
writer.print("\tstatic ");
writer.print(getResultType(method, false));
StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class);
String method_name;
Alternate alt_annotation = method.getAnnotation(Alternate.class);
@ -214,32 +244,60 @@ public class JavaMethodsGenerator {
if (strip_annotation != null && mode == Mode.NORMAL)
method_name = getPostfixStrippedName(type_map, interface_decl, method);
writer.print(" " + method_name + "(");
generateParametersJava(writer, method, typeinfos_instance, false, mode);
TypeMirror result_type = Utils.getMethodReturnType(method);
generateParametersJava(writer, method, typeinfos_instance, false, true, mode);
writer.println(") {");
final TypeMirror result_type = Utils.getMethodReturnType(method);
boolean has_result = !result_type.equals(env.getTypeUtils().getVoidType());
final Reuse reuse_annotation = method.getAnnotation(Reuse.class);
if ( reuse_annotation != null ) {
writer.print("\t\t");
if ( has_result || method.getAnnotation(GLreturn.class) != null )
writer.print("return ");
writer.print(reuse_annotation.value() + "." + method_name + "(");
generateParametersJava(writer, method, typeinfos_instance, false, false, mode);
writer.println(");\n\t}");
return;
}
if (context_specific) {
writer.println("\t\tContextCapabilities caps = GLContext.getCapabilities();");
writer.print("\t\tlong " + Utils.FUNCTION_POINTER_VAR_NAME + " = caps.");
type_map.printCapabilitiesInit(writer);
writer.print("\t\tlong " + Utils.FUNCTION_POINTER_VAR_NAME + " = " + type_map.getCapabilities() + ".");
writer.println(Utils.getFunctionAddressName(interface_decl, method, true) + ";");
writer.print("\t\tBufferChecks.checkFunctionAddress(");
writer.println(Utils.FUNCTION_POINTER_VAR_NAME + ");");
}
Code code_annotation = method.getAnnotation(Code.class);
if (code_annotation != null)
final Code code_annotation = method.getAnnotation(Code.class);
if (code_annotation != null && code_annotation.value().length() > 0)
writer.println(code_annotation.value());
printBufferObjectChecks(writer, method, mode);
printParameterChecks(writer, method, typeinfos_instance, mode);
printParameterChecks(writer, method, typeinfos_instance, mode, generate_error_checks);
printParameterCaching(writer, interface_decl, method, mode);
writer.print("\t\t");
boolean has_result = !result_type.equals(env.getTypeUtils().getVoidType());
if (has_result) {
printResultType(writer, method, false);
writer.print(" " + Utils.RESULT_VAR_NAME + " = ");
if ( method.getAnnotation(GLpointer.class) != null )
writer.print("new " + method.getReturnType() + "(");
}
if ( method.getAnnotation(GLreturn.class) != null ) {
if ( code_annotation != null && code_annotation.javaBeforeNative().length() > 0 )
writer.println(code_annotation.javaBeforeNative());
writer.print("\t\t");
final PointerWrapper pointer_wrapper_annotation = method.getAnnotation(PointerWrapper.class);
if (has_result) {
writer.print(getResultType(method, false) + " " + Utils.RESULT_VAR_NAME);
if ( code_annotation != null && code_annotation.tryBlock() ) {
writer.print(" = " + getDefaultResultValue(method));
writer.println(";\n\t\ttry {");
writer.print("\t\t\t" + Utils.RESULT_VAR_NAME);
}
writer.print(" = ");
if ( pointer_wrapper_annotation != null ) {
if ( pointer_wrapper_annotation.factory().length() > 0 )
writer.print(pointer_wrapper_annotation.factory() + "(");
else
writer.print("new " + getResultType(method, false) + "(");
}
} else if ( method.getAnnotation(GLreturn.class) != null ) {
has_result = true;
Utils.printGLReturnPre(writer, method, method.getAnnotation(GLreturn.class));
}
@ -253,22 +311,36 @@ public class JavaMethodsGenerator {
writer.print(", ");
writer.print(Utils.FUNCTION_POINTER_VAR_NAME);
}
if ( has_result && method.getAnnotation(GLpointer.class) != null )
if ( has_result && pointer_wrapper_annotation != null ) {
writer.print(")");
if ( pointer_wrapper_annotation.params().length() > 0 )
writer.print(", " + pointer_wrapper_annotation.params());
}
writer.println(");");
if ( code_annotation != null && code_annotation.javaAfterNative().length() > 0 )
writer.println(code_annotation.javaAfterNative());
final String tabs = code_annotation != null && code_annotation.tryBlock() ? "\t\t\t" : "\t\t";
if (generate_error_checks && method.getAnnotation(NoErrorCheck.class) == null)
writer.println("\t\t" + type_map.getErrorCheckMethodName() + ";");
type_map.printErrorCheckMethod(writer, method, tabs);
// DISABLED: indirect buffer support
//printNondirectParameterCopies(writer, method, mode);
if (has_result) {
if ( method.getAnnotation(GLreturn.class) == null ) {
if ( ByteBuffer.class.equals(Utils.getJavaType(result_type)) )
writer.println("\t\treturn LWJGLUtil.CHECKS && " + Utils.RESULT_VAR_NAME + " == null ? null : " + Utils.RESULT_VAR_NAME + ".order(ByteOrder.nativeOrder());"); // safeNewBuffer returns a direct ByteBuffer with BIG_ENDIAN order.
writer.println(tabs + "return LWJGLUtil.CHECKS && " + Utils.RESULT_VAR_NAME + " == null ? null : " + Utils.RESULT_VAR_NAME + ".order(ByteOrder.nativeOrder());"); // safeNewBuffer returns a direct ByteBuffer with BIG_ENDIAN order.
else
writer.println("\t\treturn " + Utils.RESULT_VAR_NAME + ";");
writer.println(tabs + "return " + Utils.RESULT_VAR_NAME + ";");
} else
Utils.printGLReturnPost(writer, method, method.getAnnotation(GLreturn.class));
}
if ( code_annotation != null && code_annotation.tryBlock() ) {
writer.println("\t\t} finally {");
writer.println(code_annotation.javaFinally());
writer.println("\t\t}");
}
writer.println("\t}");
}
@ -296,7 +368,7 @@ public class JavaMethodsGenerator {
else if (annotation_type.equals(AutoSize.class))
parameter_name = param.getAnnotation(AutoSize.class).value();
else
throw new RuntimeException("Unkown annotation type " + annotation_type);
throw new RuntimeException("Unknown annotation type " + annotation_type);
if (target_parameter.getSimpleName().equals(parameter_name))
return param;
}
@ -368,6 +440,7 @@ public class JavaMethodsGenerator {
private static boolean printMethodCallArgument(PrintWriter writer, MethodDeclaration method, ParameterDeclaration param, Map<ParameterDeclaration, TypeInfo> typeinfos_instance, Mode mode, boolean first_parameter) {
if (!first_parameter)
writer.print(", ");
AnnotationMirror auto_annotation = Utils.getParameterAutoAnnotation(param);
Constant constant_annotation = param.getAnnotation(Constant.class);
if (constant_annotation != null) {
@ -375,31 +448,34 @@ public class JavaMethodsGenerator {
} else if (auto_annotation != null && mode == Mode.NORMAL) {
Class param_type = NativeTypeTranslator.getClassFromType(auto_annotation.getAnnotationType());
if (AutoType.class.equals(param_type)) {
AutoType auto_type_annotation = param.getAnnotation(AutoType.class);
String auto_parameter_name = auto_type_annotation.value();
ParameterDeclaration auto_parameter = Utils.findParameter(method, auto_parameter_name);
String auto_type = typeinfos_instance.get(auto_parameter).getAutoType();
if (auto_type == null)
final AutoType auto_type_annotation = param.getAnnotation(AutoType.class);
final ParameterDeclaration auto_parameter = Utils.findParameter(method, auto_type_annotation.value());
final String auto_type = typeinfos_instance.get(auto_parameter).getAutoType();
if ( auto_type == null )
throw new RuntimeException("No auto type for parameter " + param.getSimpleName() + " in method " + method);
writer.print(auto_type);
} else if (AutoSize.class.equals(param_type)) {
AutoSize auto_type_annotation = param.getAnnotation(AutoSize.class);
String auto_parameter_name = auto_type_annotation.value();
ParameterDeclaration auto_target_param = Utils.findParameter(method, auto_parameter_name);
TypeInfo auto_target_type_info = typeinfos_instance.get(auto_target_param);
if ( auto_type_annotation.canBeNull() )
writer.print("((" + auto_parameter_name + " == null ? 0 : " + auto_parameter_name + ".remaining())");
else
writer.print("(" + auto_parameter_name + ".remaining()");
// Shift the remaining if the target parameter is multityped and there's no AutoType to track type
boolean shift_remaining = !hasAnyParameterAutoTypeAnnotation(method, auto_target_param) && Utils.isParameterMultiTyped(auto_target_param);
if (shift_remaining) {
int shifting = getBufferElementSizeExponent(auto_target_type_info.getType());
if (shifting > 0)
writer.print(" << " + shifting);
final AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class);
final String auto_parameter_name = auto_size_annotation.value();
final ParameterDeclaration auto_target_param = Utils.findParameter(method, auto_parameter_name);
final TypeInfo auto_target_type_info = typeinfos_instance.get(auto_target_param);
final boolean shift_remaining = !hasAnyParameterAutoTypeAnnotation(method, auto_target_param) && Utils.isParameterMultiTyped(auto_target_param);
int shifting = 0;
if ( shift_remaining ) {
shifting = getBufferElementSizeExponent(auto_target_type_info.getType());
if ( shifting > 0 )
writer.print("(");
}
writer.print(")");
writer.print(auto_type_annotation.expression());
if ( auto_size_annotation.canBeNull() )
writer.print("(" + auto_parameter_name + " == null ? 0 : " + auto_parameter_name + ".remaining())");
else
writer.print(auto_parameter_name + ".remaining()");
// Shift the remaining if the target parameter is multityped and there's no AutoType to track type
if (shift_remaining && shifting > 0) {
writer.print(" << " + shifting);
writer.print(")");
}
writer.print(auto_size_annotation.expression());
} else
throw new RuntimeException("Unknown auto annotation " + param_type);
} else {
@ -407,14 +483,15 @@ public class JavaMethodsGenerator {
writer.print(param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX);
} else {
Class type = typeinfos_instance.get(param).getType();
Check check_annotation = param.getAnnotation(Check.class);
boolean hide_buffer = mode == Mode.AUTOS && getAutoTypeParameter(method, param) != null;
if (hide_buffer)
if (hide_buffer) {
writer.print("null");
else {
} else {
if ( type == CharSequence.class || type == CharSequence[].class ) {
final String offset = Utils.getStringOffset(method, param);
writer.print("APIUtils.getBuffer");
writer.print("APIUtil.getBuffer");
if ( param.getAnnotation(NullTerminated.class) != null )
writer.print("NT");
writer.print("(" + param.getSimpleName());
@ -422,24 +499,37 @@ public class JavaMethodsGenerator {
writer.print(", " + offset);
writer.print(")");
hide_buffer = true;
} else
} else {
final AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class);
if ( auto_size_annotation != null )
writer.print(auto_size_annotation.value() + "_");
writer.print(param.getSimpleName());
if ( PointerBuffer.class.isAssignableFrom(type) ) {
if ( check_annotation != null && check_annotation.canBeNull() )
writer.print(" != null ? " + param.getSimpleName());
writer.print(".getBuffer()");
if ( check_annotation != null && check_annotation.canBeNull() )
writer.print(" : null");
}
}
}
Class buffer_type = Utils.getNIOBufferType(param.getType());
if (buffer_type != null) {
writer.print(", ");
if (!hide_buffer) {
TypeInfo type_info = typeinfos_instance.get(param);
Check check_annotation = param.getAnnotation(Check.class);
int shifting;
if (Utils.getNIOBufferType(param.getType()).equals(Buffer.class))
shifting = getBufferElementSizeExponent(type_info.getType());
else
if (Utils.getNIOBufferType(param.getType()).equals(Buffer.class)) {
shifting = getBufferElementSizeExponent(type == Buffer.class ? ByteBuffer.class : type); // TODO: This will always throw an exception
//shifting = 0;
} else
shifting = 0;
writer.print(param.getSimpleName());
if (check_annotation != null && check_annotation.canBeNull())
writer.print(" != null ? " + param.getSimpleName());
writer.print(".position()");
if ( type == PointerBuffer.class )
writer.print(".positionByte()");
else
writer.print(".position()");
if (shifting > 0)
writer.print(" << " + shifting);
if (check_annotation != null && check_annotation.canBeNull())
@ -449,8 +539,8 @@ public class JavaMethodsGenerator {
writer.print(offset == null ? "0" : offset);
} else
writer.print("0");
} else {
GLpointer pointer_annotation = param.getAnnotation(GLpointer.class);
} else if ( type != long.class ) {
PointerWrapper pointer_annotation = param.getAnnotation(PointerWrapper.class);
if ( pointer_annotation != null ) {
if ( pointer_annotation.canBeNull() )
writer.print(" == null ? 0 : " + param.getSimpleName());
@ -464,30 +554,35 @@ public class JavaMethodsGenerator {
private static boolean printMethodCallArguments(PrintWriter writer, MethodDeclaration method, Map<ParameterDeclaration, TypeInfo> typeinfos_instance, Mode mode) {
boolean first_parameter = true;
for (ParameterDeclaration param : method.getParameters())
if (param.getAnnotation(Result.class) == null) {
for ( ParameterDeclaration param : method.getParameters() ) {
if ( param.getAnnotation(Result.class) != null || param.getAnnotation(Helper.class) != null )
continue;
final Constant constant_annotation = param.getAnnotation(Constant.class);
if ( constant_annotation== null || !constant_annotation.isNative() )
first_parameter = printMethodCallArgument(writer, method, param, typeinfos_instance, mode, first_parameter);
}
}
if (Utils.getNIOBufferType(Utils.getMethodReturnType(method)) != null) {
if (method.getAnnotation(CachedResult.class) != null && method.getAnnotation(CachedResult.class).isRange()) {
first_parameter = false;
Utils.printExtraCallArguments(writer, method, "");
} else {
if (!first_parameter)
writer.print(", ");
first_parameter = false;
AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class);
if ( auto_size_annotation == null || !auto_size_annotation.isNative() ) {
if (!first_parameter)
writer.print(", ");
first_parameter = false;
String result_size_expression;
if ( mode == Mode.CACHEDRESULT )
result_size_expression = Utils.CACHED_BUFFER_LENGTH_NAME;
else {
AutoResultSize auto_result_size_annotation = method.getAnnotation(AutoResultSize.class);
if (auto_result_size_annotation == null)
String result_size_expression;
if ( mode == Mode.CACHEDRESULT )
result_size_expression = Utils.CACHED_BUFFER_LENGTH_NAME;
else if ( auto_size_annotation == null )
result_size_expression = Utils.RESULT_SIZE_NAME;
else
result_size_expression = auto_result_size_annotation.value();
result_size_expression = auto_size_annotation.value();
Utils.printExtraCallArguments(writer, method, result_size_expression);
}
Utils.printExtraCallArguments(writer, method, result_size_expression);
}
}
return first_parameter;
@ -531,14 +626,33 @@ public class JavaMethodsGenerator {
}
}
private static void printParameterChecks(PrintWriter writer, MethodDeclaration method, Map<ParameterDeclaration, TypeInfo> typeinfos, Mode mode) {
private static void printParameterChecks(PrintWriter writer, MethodDeclaration method, Map<ParameterDeclaration, TypeInfo> typeinfos, Mode mode, final boolean generate_error_checks) {
if ( mode == Mode.NORMAL ) {
final GenerateAutos gen_autos_annotation = method.getAnnotation(GenerateAutos.class);
if ( gen_autos_annotation != null && gen_autos_annotation.sizeVariables().length > 0 ) {
// For the auto-generated parameters, declare and init a size variable (that can be reused by @Code)
for ( final ParameterDeclaration param : method.getParameters() ) {
if ( Arrays.binarySearch(gen_autos_annotation.sizeVariables(), param.getSimpleName()) >= 0 ) {
final int shifting = getBufferElementSizeExponent(typeinfos.get(param).getType());
final Check check_annotation = param.getAnnotation(Check.class);
writer.print("\t\tlong " + param.getSimpleName() + "_size = ");
if ( check_annotation == null || !check_annotation.canBeNull() )
writer.println(param.getSimpleName() + ".remaining() << " + shifting + ";");
else
writer.println(param.getSimpleName() + " == null ? 0 : " + param.getSimpleName() + ".remaining() << " + shifting + ";");
}
}
}
}
for (ParameterDeclaration param : method.getParameters()) {
Class java_type = Utils.getJavaType(param.getType());
if (Utils.isAddressableType(java_type) &&
if ( java_type.isArray() || (Utils.isAddressableType(java_type) &&
(mode != Mode.BUFFEROBJECT || param.getAnnotation(BufferObject.class) == null) &&
(mode != Mode.AUTOS || getAutoTypeParameter(method, param) == null) &&
param.getAnnotation(Result.class) == null &&
!Utils.isReturnParameter(method, param) ) {
!Utils.isReturnParameter(method, param)) ) {
String check_value = null;
boolean can_be_null = false;
Check check_annotation = param.getAnnotation(Check.class);
@ -546,59 +660,115 @@ public class JavaMethodsGenerator {
check_value = check_annotation.value();
can_be_null = check_annotation.canBeNull();
}
NullTerminated null_terminated = param.getAnnotation(NullTerminated.class);
if (Buffer.class.isAssignableFrom(java_type) && param.getAnnotation(Constant.class) == null) {
if ((Buffer.class.isAssignableFrom(java_type) || PointerBuffer.class.isAssignableFrom(java_type)) && param.getAnnotation(Constant.class) == null) {
boolean indirect_buffer_allowed = false && param.getAnnotation(CachedReference.class) == null; // DISABLED: indirect buffer support
boolean out_parameter = param.getAnnotation(OutParameter.class) != null;
TypeInfo typeinfo = typeinfos.get(param);
printParameterCheck(writer, param.getSimpleName(), typeinfo.getType().getSimpleName(), check_value, can_be_null, null_terminated, indirect_buffer_allowed, out_parameter);
printParameterCheck(writer, method, param.getSimpleName(), typeinfo.getType().getSimpleName(), check_value, can_be_null, param.getAnnotation(NullTerminated.class), indirect_buffer_allowed, out_parameter, generate_error_checks);
} else if ( String.class.equals(java_type)) {
if (!can_be_null)
writer.println("\t\tBufferChecks.checkNotNull(" + param.getSimpleName() + ");");
} else if ( java_type.isArray() ) {
final TypeInfo typeinfo = typeinfos.get(param);
printArrayParameterCheck(writer, param.getSimpleName(), typeinfo.getType().getSimpleName(), check_value, can_be_null);
}
}
}
if (method.getAnnotation(CachedResult.class) != null)
printParameterCheck(writer, Utils.CACHED_BUFFER_NAME, null, null, true, null, false, false);
printParameterCheck(writer, method, Utils.CACHED_BUFFER_NAME, null, null, true, null, false, false, generate_error_checks);
}
private static void printParameterCheck(PrintWriter writer, String name, String type, String check_value, boolean can_be_null, NullTerminated null_terminated, boolean indirect_buffer_allowed, boolean out_parameter) {
private static void printParameterCheck(PrintWriter writer, MethodDeclaration method, String name, String type, String check_value, boolean can_be_null, NullTerminated null_terminated, boolean indirect_buffer_allowed, boolean out_parameter, final boolean generate_error_checks) {
if (indirect_buffer_allowed && out_parameter) {
writer.println("\t\t" + type + " " + name + SAVED_PARAMETER_POSTFIX + " = " + name + ";");
}
String tabs;
if (can_be_null) {
writer.println("\t\tif (" + name + " != null)");
writer.print("\t");
}
writer.print("\t\tif (" + name + " != null)");
if ( null_terminated != null )
writer.println(" {");
else
writer.println();
tabs = "\t\t\t";
} else
tabs = "\t\t";
if (indirect_buffer_allowed) {
writer.print("\t\t" + name + " = NondirectBufferWrapper.wrap");
writer.print(tabs + name + " = NondirectBufferWrapper.wrap");
if (out_parameter)
writer.print("NoCopy");
} else
writer.print("\t\tBufferChecks.check");
if (check_value != null && !"".equals(check_value) ) {
writer.print("Buffer(" + name + ", " + check_value);
writer.print(tabs + "BufferChecks.check");
if (check_value != null && check_value.length() > 0) {
writer.print("Buffer");
if ( "Buffer".equals(type) )
writer.print("Size"); // Check size only, Buffer.isDirect() was added in 1.6, cannot use yet. TODO: Remove?
writer.print("(" + name + ", " + check_value);
} else {
writer.print("Direct(" + name);
}
writer.println(");");
if ( can_be_null && generate_error_checks ) {
final Check check_annotation = method.getAnnotation(Check.class);
if ( check_annotation != null && check_annotation.value().equals(name) ) {
writer.println("\t\telse");
writer.println("\t\t\t" + name + " = APIUtil.getBufferIntDebug();"); // Use an exclusive buffer here
}
}
if (null_terminated != null) {
writer.print("\t\tBufferChecks.checkNullTerminated(");
writer.print(tabs + "BufferChecks.checkNullTerminated(");
writer.print(name);
if ( null_terminated.value().length() > 0 ) {
writer.print(", ");
writer.print(null_terminated.value());
}
writer.println(");");
if ( can_be_null )
writer.println("\t\t}");
}
}
private static void printResultType(PrintWriter writer, MethodDeclaration method, boolean native_stub) {
if ( native_stub && method.getAnnotation(GLpointer.class) != null )
writer.print("long");
else if ( !native_stub && method.getAnnotation(GLreturn.class) != null )
writer.print(Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false));
else
writer.print(Utils.getMethodReturnType(method).toString());
private static void printArrayParameterCheck(PrintWriter writer, String name, String type, String check_value, boolean can_be_null) {
String tabs;
if ( can_be_null ) {
writer.println("\t\tif (" + name + " != null)");
tabs = "\t\t\t";
} else
tabs = "\t\t";
writer.print(tabs + "BufferChecks.checkArray(" + name);
if ( check_value != null && check_value.length() > 0)
writer.print(", " + check_value);
writer.println(");");
}
private static String getResultType(MethodDeclaration method, boolean native_stub) {
if ( native_stub && method.getAnnotation(PointerWrapper.class) != null )
return "long";
else if ( !native_stub && method.getAnnotation(GLreturn.class) != null )
return Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false);
else
return Utils.getJavaType(Utils.getMethodReturnType(method)).getSimpleName();
}
private static String getDefaultResultValue(MethodDeclaration method) {
if ( method.getAnnotation(GLreturn.class) != null ) {
final String type = Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false);
if ( "boolean".equals(type) )
return "false";
else if ( Character.isLowerCase(type.charAt(0)) )
return "0";
else
return "null";
} else {
final Class type = Utils.getJavaType(Utils.getMethodReturnType(method));
if ( type.isPrimitive() ) {
if ( type == boolean.class )
return "false";
else
return "0";
} else
return "null";
}
}
}

View file

@ -32,11 +32,14 @@
package org.lwjgl.util.generator;
import org.lwjgl.opencl.CLMem;
import java.nio.ByteBuffer;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
/**
*
* A TypeVisitor that translates (annotated) TypeMirrors to
* java types (represented by a Class)
*
@ -56,10 +59,42 @@ public class JavaTypeTranslator implements TypeVisitor {
}
public void visitArrayType(ArrayType t) {
if ( "java.lang.CharSequence".equals(t.getComponentType().toString()) )
final TypeMirror componentType = t.getComponentType();
if ( componentType instanceof PrimitiveType ) {
type = getPrimitiveArrayClassFromKind(((PrimitiveType)componentType).getKind());
} else {
try {
final Class c = Class.forName(t.getComponentType().toString());
if ( CharSequence.class.isAssignableFrom(c) || ByteBuffer.class.isAssignableFrom(c) || org.lwjgl.PointerWrapper.class.isAssignableFrom(c) )
type = Class.forName("[L" + t.getComponentType() + ";");
else {
throw new RuntimeException(t + " is not allowed");
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/*
final String className = t.getComponentType().toString();
if ( "java.lang.CharSequence".equals(className) )
type = CharSequence[].class;
else if ( "java.nio.ByteBuffer".equals(className) )
type = ByteBuffer[].class;
else if ( "org.lwjgl.opencl.CLMem".equals(className) )
type = CLMem[].class;
else
throw new RuntimeException(t + " is not allowed");
//*/
/*
try {
System.out.println("t = " + t);
System.out.println("t.getClass() = " + t.getClass());
System.out.println("t.getComponentType() = " + t.getComponentType());
type = Class.forName(t.toString());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}*/
}
public static Class getPrimitiveClassFromKind(PrimitiveType.Kind kind) {
@ -83,6 +118,27 @@ public class JavaTypeTranslator implements TypeVisitor {
}
}
private static Class getPrimitiveArrayClassFromKind(PrimitiveType.Kind kind) {
switch ( kind ) {
case LONG:
return long[].class;
case INT:
return int[].class;
case DOUBLE:
return double[].class;
case FLOAT:
return float[].class;
case SHORT:
return short[].class;
case BYTE:
return byte[].class;
case BOOLEAN:
return boolean[].class;
default:
throw new RuntimeException(kind + " is not allowed");
}
}
public void visitPrimitiveType(PrimitiveType t) {
type = getPrimitiveClassFromKind(t.getKind());
}

View file

@ -41,6 +41,8 @@ package org.lwjgl.util.generator;
* $Id$
*/
import org.lwjgl.PointerBuffer;
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
@ -52,12 +54,13 @@ import java.nio.*;
public class NativeMethodStubsGenerator {
private static final String BUFFER_ADDRESS_POSTFIX = "_address";
public static final String BUFFER_POSITION_POSTFIX = "_position";
private static final String STRING_LIST_POSTFIX = "_str";
private static final String STRING_LIST_NAME = "_str";
private static final String POINTER_LIST_NAME = "_ptr";
public static void generateNativeMethodStubs(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, InterfaceDeclaration d, boolean generate_error_checks, boolean context_specific) {
for (MethodDeclaration method : d.getMethods()) {
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if ( alt_annotation != null && !alt_annotation.nativeAlt() )
if ( (alt_annotation != null && (!alt_annotation.nativeAlt() || alt_annotation.skipNative())) || method.getAnnotation(Reuse.class) != null )
continue;
generateMethodStub(env, type_map, writer, Utils.getQualifiedClassName(d), method, Mode.NORMAL, generate_error_checks, context_specific);
if (Utils.hasMethodBufferObjectParameter(method))
@ -66,16 +69,20 @@ public class NativeMethodStubsGenerator {
}
private static void generateParameters(PrintWriter writer, Collection<ParameterDeclaration> params, Mode mode) {
for (ParameterDeclaration param : params)
if (param.getAnnotation(Result.class) == null)
for (ParameterDeclaration param : params) {
if ( param.getAnnotation(Helper.class) != null || param.getAnnotation(Result.class) != null )
continue;
final Constant constant_annotation = param.getAnnotation(Constant.class);
if ( constant_annotation == null || !constant_annotation.isNative() )
generateParameter(writer, param, mode);
}
}
private static void generateParameter(PrintWriter writer, ParameterDeclaration param, Mode mode) {
writer.print(", ");
if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
writer.print("jlong " + param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX);
} else if ( param.getAnnotation(GLpointer.class) != null ) {
} else if ( param.getAnnotation(PointerWrapper.class) != null ) {
writer.print("jlong " + param.getSimpleName());
} else {
JNITypeTranslator translator = new JNITypeTranslator();
@ -92,9 +99,11 @@ public class NativeMethodStubsGenerator {
else
writer.print("JNIEXPORT ");
TypeMirror result_type = Utils.getMethodReturnType(method);
final TypeMirror result_type = Utils.getMethodReturnType(method);
final CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class);
final AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class);
if ( method.getAnnotation(GLpointer.class) != null ) {
if ( method.getAnnotation(PointerWrapper.class) != null ) {
writer.print("jlong");
} else {
JNITypeTranslator translator = new JNITypeTranslator();
@ -109,8 +118,7 @@ public class NativeMethodStubsGenerator {
writer.print("(JNIEnv *env, jclass clazz");
generateParameters(writer, method.getParameters(), mode);
if (Utils.getNIOBufferType(result_type) != null) {
CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class);
if (cached_result_annotation == null || !cached_result_annotation.isRange())
if ( (cached_result_annotation == null || !cached_result_annotation.isRange()) && (auto_size_annotation == null || !auto_size_annotation.isNative()) )
writer.print(", jlong " + Utils.RESULT_SIZE_NAME);
if (cached_result_annotation != null)
writer.print(", jobject " + Utils.CACHED_BUFFER_NAME);
@ -119,6 +127,7 @@ public class NativeMethodStubsGenerator {
writer.print(", jlong " + Utils.FUNCTION_POINTER_VAR_NAME);
}
writer.println(") {");
generateBufferParameterAddresses(type_map, writer, method, mode);
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if (context_specific) {
@ -127,49 +136,59 @@ public class NativeMethodStubsGenerator {
writer.print(" = (" + typedef_name + ")((intptr_t)");
writer.println(Utils.FUNCTION_POINTER_VAR_NAME + ");");
}
generateStringListInits(writer, method.getParameters());
final Code code_annotation = method.getAnnotation(Code.class);
final boolean hasResult = !result_type.equals(env.getTypeUtils().getVoidType());
final boolean resultPreDeclare = hasResult && (hasPointerArrayInits(method.getParameters()) || (code_annotation != null && (code_annotation.nativeAfterVars().length() > 0 || code_annotation.nativeBeforeCall().length() > 0)));
if ( resultPreDeclare )
printResultParam(type_map, writer, method, result_type, true);
if ( code_annotation != null && code_annotation.nativeAfterVars().length() > 0 )
writer.println(code_annotation.nativeAfterVars());
generatePointerArrayInits(type_map, writer, method.getParameters());
if ( code_annotation != null && code_annotation.nativeBeforeCall().length() > 0 )
writer.println(code_annotation.nativeBeforeCall());
writer.print("\t");
if (!result_type.equals(env.getTypeUtils().getVoidType())) {
Declaration return_declaration;
ParameterDeclaration result_param = Utils.getResultParameter(method);
if (result_param != null)
return_declaration = result_param;
else
return_declaration = method;
NativeTypeTranslator native_translator = new NativeTypeTranslator(type_map, return_declaration);
result_type.accept(native_translator);
writer.print(native_translator.getSignature() + " " + Utils.RESULT_VAR_NAME);
if (result_param != null) {
writer.println(";");
writer.print("\t");
} else
writer.print(" = ");
}
if ( resultPreDeclare )
writer.print(Utils.RESULT_VAR_NAME + " = ");
else if ( hasResult )
printResultParam(type_map, writer, method, result_type, false);
writer.print((alt_annotation == null ? method.getSimpleName() : alt_annotation.value()) + "(");
generateCallParameters(writer, type_map, method.getParameters());
writer.print(")");
writer.println(";");
if ( code_annotation != null && code_annotation.nativeAfterCall().length() > 0 )
writer.println(code_annotation.nativeAfterCall());
generateStringDeallocations(writer, method.getParameters());
if (!result_type.equals(env.getTypeUtils().getVoidType())) {
writer.print("\treturn ");
Class java_result_type = Utils.getJavaType(result_type);
if (Buffer.class.isAssignableFrom(java_result_type)) {
if (method.getAnnotation(CachedResult.class) != null)
if (cached_result_annotation != null)
writer.print("safeNewBufferCached(env, ");
else
writer.print("safeNewBuffer(env, ");
} else if (String.class.equals(java_result_type)) {
writer.print("NewStringNativeUnsigned(env, ");
} else if ( method.getAnnotation(GLpointer.class) != null ) {
} else if ( method.getAnnotation(PointerWrapper.class) != null ) {
writer.print("(intptr_t)");
}
writer.print(Utils.RESULT_VAR_NAME);
if (Buffer.class.isAssignableFrom(java_result_type)) {
writer.print(", ");
if (method.getAnnotation(CachedResult.class) != null && method.getAnnotation(CachedResult.class).isRange())
Utils.printExtraCallArguments(writer, method, method.getAnnotation(AutoResultSize.class).value());
final String size_parameter_name;
if ( auto_size_annotation != null && (auto_size_annotation.isNative() || (cached_result_annotation != null && cached_result_annotation.isRange())) )
size_parameter_name = auto_size_annotation.value();
else
Utils.printExtraCallArguments(writer, method, Utils.RESULT_SIZE_NAME);
size_parameter_name = Utils.RESULT_SIZE_NAME;
writer.print(", ");
Utils.printExtraCallArguments(writer, method, size_parameter_name);
}
if (Buffer.class.isAssignableFrom(java_result_type) ||
String.class.equals(java_result_type))
@ -180,133 +199,226 @@ public class NativeMethodStubsGenerator {
writer.println();
}
private static void printResultParam(final TypeMap type_map, final PrintWriter writer, final MethodDeclaration method, final TypeMirror result_type, final boolean preDeclare) {
final ParameterDeclaration result_param = Utils.getResultParameter(method);
final Declaration return_declaration = result_param == null ? method : result_param;
final NativeTypeTranslator result_translator = new NativeTypeTranslator(type_map, return_declaration);
result_type.accept(result_translator);
if ( preDeclare )
writer.print("\t");
writer.print(result_translator.getSignature() + " " + Utils.RESULT_VAR_NAME);
if ( preDeclare)
writer.println(";");
else
writer.print(result_param == null ? " = " : ";\n\t");
}
private static void generateCallParameters(PrintWriter writer, TypeMap type_map, Collection<ParameterDeclaration> params) {
if (params.size() > 0) {
Iterator<ParameterDeclaration> it = params.iterator();
generateCallParameter(writer, type_map, it.next());
while (it.hasNext()) {
writer.print(", ");
generateCallParameter(writer, type_map, it.next());
boolean first = true;
for ( ParameterDeclaration param : params ) {
if ( param.getAnnotation(Helper.class) != null )
continue;
if ( first )
first = false;
else
writer.print(", ");
generateCallParameter(writer, type_map, param);
}
}
}
private static void generateCallParameter(PrintWriter writer, TypeMap type_map, ParameterDeclaration param) {
if ( param.getAnnotation(Helper.class) != null )
return;
final Constant constant_annotation = param.getAnnotation(Constant.class);
if ( constant_annotation != null && constant_annotation.isNative() ) {
writer.print(constant_annotation.value());
return;
}
boolean is_indirect = param.getAnnotation(Indirect.class) != null;
if (is_indirect || param.getAnnotation(StringList.class) != null) {
if (is_indirect || param.getAnnotation(PointerArray.class) != null) {
writer.print("(");
NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
param.getType().accept(translator);
writer.print(translator.getSignature());
writer.print("*)");
}
if ( param.getAnnotation(GLpointer.class) != null )
writer.print("(" + param.getAnnotation(GLpointer.class).value() + ")(intptr_t)");
if ( param.getAnnotation(PointerWrapper.class) != null )
writer.print("(" + param.getAnnotation(PointerWrapper.class).value() + ")(intptr_t)");
if (param.getAnnotation(Result.class) != null || is_indirect)
writer.print("&");
if (param.getAnnotation(Result.class) != null) {
if ( param.getAnnotation(Result.class) != null ) {
writer.print(Utils.RESULT_VAR_NAME);
} else {
writer.print(param.getSimpleName());
if ( param.getAnnotation(StringList.class) != null )
writer.print(STRING_LIST_POSTFIX);
else if (Utils.isAddressableType(param.getType()))
if ( param.getAnnotation(PointerArray.class) != null )
writer.print(getPointerArrayName(Utils.getJavaType(param.getType())));
else if ( Utils.isAddressableType(param.getType()) )
writer.print(BUFFER_ADDRESS_POSTFIX);
}
}
private static void generateStringDeallocations(PrintWriter writer, Collection<ParameterDeclaration> params) {
for (ParameterDeclaration param : params) {
if (Utils.getJavaType(param.getType()).equals(String.class) &&
param.getAnnotation(Result.class) == null)
final Class java_type = Utils.getJavaType(param.getType());
if ( java_type.equals(String.class) && param.getAnnotation(Result.class) == null )
writer.println("\tfree(" + param.getSimpleName() + BUFFER_ADDRESS_POSTFIX + ");");
else if (param.getAnnotation(StringList.class) != null ) // Free the string array mem
writer.println("\tfree(" + param.getSimpleName() + STRING_LIST_POSTFIX + ");");
else if (param.getAnnotation(PointerArray.class) != null ) // Free the string array mem
writer.println("\tfree(" + param.getSimpleName() + getPointerArrayName(java_type) + ");");
}
}
private static void generateBufferParameterAddresses(TypeMap type_map, PrintWriter writer, MethodDeclaration method, Mode mode) {
boolean loopDeclared = false;
for (ParameterDeclaration param : method.getParameters())
if (Utils.isAddressableType(param.getType()) && param.getAnnotation(Result.class) == null)
loopDeclared = generateBufferParameterAddress(type_map, writer, method, param, mode, loopDeclared);
strLoopDeclared = false;
ptrLoopDeclared = false;
for ( ParameterDeclaration param : method.getParameters() ) {
final Constant constant_annotation = param.getAnnotation(Constant.class);
if ( param.getAnnotation(Result.class) == null && (constant_annotation == null || !constant_annotation.isNative()) && Utils.isAddressableType(param.getType()))
generateBufferParameterAddress(type_map, writer, method, param, mode);
}
}
private static boolean generateBufferParameterAddress(TypeMap type_map, PrintWriter writer, MethodDeclaration method, ParameterDeclaration param, Mode mode, boolean loopDeclared) {
NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
private static boolean strLoopDeclared;
private static boolean ptrLoopDeclared;
private static void generateBufferParameterAddress(TypeMap type_map, PrintWriter writer, MethodDeclaration method, ParameterDeclaration param, Mode mode) {
final Check check_annotation = param.getAnnotation(Check.class);
final PointerArray array_annotation = param.getAnnotation(PointerArray.class);
final Class java_type = Utils.getJavaType(param.getType());
final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
param.getType().accept(translator);
writer.print("\t" + translator.getSignature() + param.getSimpleName());
writer.print(BUFFER_ADDRESS_POSTFIX + " = ((");
writer.print(translator.getSignature());
Check check_annotation = param.getAnnotation(Check.class);
writer.print(")");
if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
writer.print("offsetToPointer(" + param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX + "))");
} else {
Class java_type = Utils.getJavaType(param.getType());
if (Buffer.class.isAssignableFrom(java_type) || java_type.equals(CharSequence.class) || java_type.equals(CharSequence[].class)) {
boolean explicitly_byte_sized = java_type.equals(Buffer.class) ||
translator.getAnnotationType().equals(type_map.getVoidType());
if (explicitly_byte_sized)
writer.print("(((char *)");
if (method.getAnnotation(GenerateAutos.class) != null || (check_annotation != null && check_annotation.canBeNull())) {
writer.print("safeGetBufferAddress(env, " + param.getSimpleName());
} else {
writer.print("(*env)->GetDirectBufferAddress(env, " + param.getSimpleName());
}
writer.print("))");
writer.print(" + " + param.getSimpleName() + BUFFER_POSITION_POSTFIX);
if (explicitly_byte_sized)
final String native_type = translator.getSignature();
if ( !java_type.isArray() || CharSequence.class.isAssignableFrom(java_type.getComponentType()) ) {
writer.print("\t" + native_type + param.getSimpleName());
writer.print(BUFFER_ADDRESS_POSTFIX + " = ((");
writer.print(native_type);
writer.print(")");
if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
writer.print("offsetToPointer(" + param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX + "))");
} else {
if (Buffer.class.isAssignableFrom(java_type) || java_type.equals(CharSequence.class) || java_type.equals(CharSequence[].class) || PointerBuffer.class.isAssignableFrom(java_type) ) {
boolean explicitly_byte_sized = java_type.equals(Buffer.class) ||
translator.getAnnotationType().equals(type_map.getVoidType()) ||
param.getAnnotation(NativeType.class) != null;
if (explicitly_byte_sized)
writer.print("(((char *)");
if (method.getAnnotation(GenerateAutos.class) != null || (check_annotation != null && check_annotation.canBeNull())) {
writer.print("safeGetBufferAddress(env, " + param.getSimpleName());
} else {
writer.print("(*env)->GetDirectBufferAddress(env, " + param.getSimpleName());
}
writer.print("))");
} else if (java_type.equals(String.class)) {
writer.print("GetStringNativeChars(env, " + param.getSimpleName() + "))");
} else
throw new RuntimeException("Illegal type " + java_type);
}
writer.println(";");
if ( param.getAnnotation(StringList.class) != null ) {
if ( Utils.getJavaType(param.getType()) != CharSequence[].class && (
param.getAnnotation(GLchar.class) == null ||
param.getAnnotation(NullTerminated.class) == null ||
param.getAnnotation(NullTerminated.class).value().length() == 0
)
)
throw new RuntimeException("StringList annotation can only be applied on null-terminated GLchar buffers.");
if ( "_str".equals(param.getSimpleName()) )
throw new RuntimeException("The name '_str' is not valid for arguments annotated with StringList");
// Declare loop counters and allocate string array
if ( !loopDeclared ) {
writer.println("\tunsigned int _str_i;");
writer.println("\tGLchar *_str_address;");
loopDeclared = true;
writer.print(" + " + param.getSimpleName() + BUFFER_POSITION_POSTFIX);
if (explicitly_byte_sized)
writer.print("))");
} else if (java_type.equals(String.class)) {
writer.print("GetStringNativeChars(env, " + param.getSimpleName() + "))");
} else if ( array_annotation == null )
throw new RuntimeException("Illegal type " + java_type);
}
writer.println("\tGLchar **" + param.getSimpleName() + STRING_LIST_POSTFIX + " = (GLchar **) malloc(" + param.getAnnotation(StringList.class).value() + "*sizeof(GLchar*));");
writer.println(";");
}
if ( array_annotation != null ) {
final String n = getPointerArrayName(java_type);
final String arrayType;
if ( POINTER_LIST_NAME.equals(n) ) {
if ( n.equals(param.getSimpleName()) )
throw new RuntimeException("The name '" + n + "' is not valid for object array arguments annotated with PointerArray");
arrayType = translator.getSignature(true) + (org.lwjgl.PointerWrapper.class.isAssignableFrom(java_type.getComponentType()) ? " " : "");
// Declare loop counters and allocate object array
if ( !ptrLoopDeclared ) {
writer.println("\tunsigned int " + n + "_i;");
writer.println("\tjobject " + n + "_object;");
ptrLoopDeclared = true;
}
} else {
if ( n.equals(param.getSimpleName()) )
throw new RuntimeException("The name '" + n + "' is not valid for arguments annotated with PointerArray");
arrayType = translator.getSignature(true);
// Declare loop counters and allocate string array
if ( !strLoopDeclared ) {
writer.println("\tunsigned int " + n + "_i;");
writer.println("\t" + arrayType + n + "_address;");
strLoopDeclared = true;
}
}
writer.print("\t" + arrayType + "*" + param.getSimpleName() + n + " = ");
if ( check_annotation != null && check_annotation.canBeNull() )
writer.print(array_annotation.value() + " == 0 ? NULL : ");
writer.println("(" + arrayType + "*) malloc(" + array_annotation.value() + " * sizeof(" + arrayType + "));");
}
return loopDeclared;
}
private static void generateStringListInits(PrintWriter writer, Collection<ParameterDeclaration> params) {
for ( ParameterDeclaration param : params ) {
StringList stringList_annotation = param.getAnnotation(StringList.class);
if ( stringList_annotation != null ) {
String lengths = stringList_annotation.lengths();
private static String getPointerArrayName(final Class java_type) {
final Class<?> component_type = java_type.getComponentType();
if ( component_type != null && (Buffer.class.isAssignableFrom(component_type) || org.lwjgl.PointerWrapper.class.isAssignableFrom(component_type)) )
return POINTER_LIST_NAME;
else
return STRING_LIST_NAME;
}
// Init vars
writer.println("\t_str_i = 0;");
writer.println("\t_str_address = (GLchar *)" + param.getSimpleName() + BUFFER_ADDRESS_POSTFIX + ";");
// Fill string array with the string pointers
writer.println("\twhile ( _str_i < " + stringList_annotation.value() + " ) {");
if ( lengths.length() == 0 ) {
writer.println("\t\t" + param.getSimpleName() + STRING_LIST_POSTFIX + "[_str_i++] = _str_address;");
writer.println("\t\t_str_address += strlen(_str_address) + 1;");
private static boolean hasPointerArrayInits(Collection<ParameterDeclaration> params) {
for ( ParameterDeclaration param : params ) {
PointerArray pointerArray_annotation = param.getAnnotation(PointerArray.class);
if ( pointerArray_annotation != null )
return true;
}
return false;
}
private static void generatePointerArrayInits(TypeMap type_map, PrintWriter writer, Collection<ParameterDeclaration> params) {
for ( ParameterDeclaration param : params ) {
PointerArray pointerArray_annotation = param.getAnnotation(PointerArray.class);
if ( pointerArray_annotation != null ) {
final Class java_type = Utils.getJavaType(param.getType());
final Class<?> component_type = java_type.isArray() ? java_type.getComponentType() : null;
final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
param.getType().accept(translator);
final String n = getPointerArrayName(java_type);
if ( POINTER_LIST_NAME.equals(n) ) {
// Init vars
writer.println("\t" + n + "_i = 0;");
// Fill pointer array with the buffer pointers
writer.println("\twhile ( " + n + "_i < " + pointerArray_annotation.value() + " ) {");
if ( component_type.isAssignableFrom(Buffer.class) )
writer.println("\t\t" + n + "_object = (*env)->GetObjectArrayElement(env, " + param.getSimpleName() + ", " + n + "_i);");
else
writer.println("\t\t" + n + "_object = (*env)->GetObjectArrayElement(env, " + param.getSimpleName() + ", " + n + "_i);");
writer.println("\t\t" + param.getSimpleName() + n + "[" + n + "_i++] = (" + translator.getSignature(true) + ")(intptr_t)getPointerWrapperAddress(env, " + n + "_object);");
writer.println("\t}");
} else {
writer.println("\t\t" + param.getSimpleName() + STRING_LIST_POSTFIX + "[_str_i] = _str_address;");
writer.println("\t\t_str_address += " + lengths + BUFFER_ADDRESS_POSTFIX + "[_str_i++];");
final String lengths = pointerArray_annotation.lengths();
// Init vars
writer.println("\t" + n + "_i = 0;");
writer.println("\t" + n + "_address = (" + translator.getSignature(true) + ")" + param.getSimpleName() + BUFFER_ADDRESS_POSTFIX + ";");
// Fill string array with the string pointers
writer.println("\twhile ( " + n + "_i < " + pointerArray_annotation.value() + " ) {");
if ( lengths.length() == 0 ) {
writer.println("\t\t" + param.getSimpleName() + n + "[" + n + "_i++] = " + n + "_address;");
writer.println("\t\t" + n + "_address += strlen(" + n + "_address) + 1;");
} else {
writer.println("\t\t" + param.getSimpleName() + n + "[" + n + "_i] = " + n + "_address;");
writer.println("\t\t" + n + "_address += " + lengths + BUFFER_ADDRESS_POSTFIX + "[" + n + "_i++];");
}
writer.println("\t}");
}
writer.println("\t}");
}
}
}

View file

@ -44,6 +44,7 @@ package org.lwjgl.util.generator;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target(ElementType.ANNOTATION_TYPE)
@Target({ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
public @interface NativeType {
String value() default "";
}

View file

@ -42,22 +42,21 @@ package org.lwjgl.util.generator;
* $Id$
*/
import org.lwjgl.opengl.PointerWrapper;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import java.util.Collection;
import java.util.ArrayList;
import java.nio.*;
import org.lwjgl.PointerBuffer;
import java.lang.annotation.Annotation;
import java.nio.*;
import java.util.ArrayList;
import java.util.Collection;
import com.sun.mirror.declaration.AnnotationMirror;
import com.sun.mirror.declaration.Declaration;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
/**
* $Id$
*
* <p/>
* A TypeVisitor that translates (annotated) TypeMirrors to
* native types
*
@ -65,6 +64,7 @@ import java.lang.annotation.Annotation;
* @version $Revision$
*/
public class NativeTypeTranslator implements TypeVisitor {
private Collection<Class> native_types;
private boolean is_indirect;
private final Declaration declaration;
@ -76,26 +76,32 @@ public class NativeTypeTranslator implements TypeVisitor {
}
public String getSignature() {
return getSignature(false);
}
public String getSignature(final boolean skipConst) {
StringBuilder signature = new StringBuilder();
if (declaration.getAnnotation(Const.class) != null)
if ( !skipConst && declaration.getAnnotation(Const.class) != null )
signature.append("const ");
if ( declaration.getAnnotation(GLpointer.class) != null ) {
signature.append(declaration.getAnnotation(GLpointer.class).value());
if ( declaration.getAnnotation(PointerWrapper.class) != null ) {
signature.append(declaration.getAnnotation(PointerWrapper.class).value());
} else if ( declaration.getAnnotation(NativeType.class) != null ) {
signature.append(declaration.getAnnotation(NativeType.class).value());
} else {
// Use the name of the native type annotation as the C type name
signature.append(getAnnotationType().getSimpleName());
}
if (is_indirect)
if ( is_indirect )
signature.append(" *");
return signature.toString();
}
public Class getAnnotationType() {
if (native_types.size() != 1)
if ( native_types.size() != 1 )
throw new RuntimeException("Expected only one native type for declaration " + declaration +
", but got " + native_types.size());
", but got " + native_types.size());
return native_types.iterator().next();
}
@ -104,34 +110,43 @@ public class NativeTypeTranslator implements TypeVisitor {
}
public void visitArrayType(ArrayType t) {
if ( "java.lang.CharSequence".equals(t.getComponentType().toString()) ) {
final Class<?> type = Utils.getJavaType(t).getComponentType();
if ( CharSequence.class.isAssignableFrom(type) ) {
is_indirect = true;
native_types = new ArrayList<Class>();
native_types.add(GLchar.class);
native_types.add(type_map.getStringArrayType());
} else if ( Buffer.class.isAssignableFrom(type) ) {
is_indirect = true;
native_types = new ArrayList<Class>();
native_types.add(type_map.getByteBufferArrayType());
} else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) ) {
is_indirect = false;
} else
throw new RuntimeException(t + " is not allowed");
}
public static PrimitiveType.Kind getPrimitiveKindFromBufferClass(Class c) {
if (IntBuffer.class.equals(c))
if ( IntBuffer.class.equals(c) )
return PrimitiveType.Kind.INT;
else if (DoubleBuffer.class.equals(c))
else if ( DoubleBuffer.class.equals(c) )
return PrimitiveType.Kind.DOUBLE;
else if (ShortBuffer.class.equals(c))
else if ( ShortBuffer.class.equals(c) )
return PrimitiveType.Kind.SHORT;
else if (ByteBuffer.class.equals(c))
else if ( ByteBuffer.class.equals(c) || PointerBuffer.class.equals(c) )
return PrimitiveType.Kind.BYTE;
else if (FloatBuffer.class.equals(c))
else if ( FloatBuffer.class.equals(c) )
return PrimitiveType.Kind.FLOAT;
else if (LongBuffer.class.equals(c))
else if ( LongBuffer.class.equals(c) )
return PrimitiveType.Kind.LONG;
else
throw new RuntimeException(c + " is not allowed");
}
public static Class<?> getClassFromType(DeclaredType t) {
@SuppressWarnings("unchecked")
public static Class<? extends Annotation> getClassFromType(DeclaredType t) {
try {
return Class.forName(t.getDeclaration().getQualifiedName());
return (Class<? extends Annotation>)Class.forName(t.getDeclaration().getQualifiedName());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
@ -139,7 +154,7 @@ public class NativeTypeTranslator implements TypeVisitor {
private void getNativeTypeFromAnnotatedPrimitiveType(PrimitiveType.Kind kind) {
native_types = translateAnnotations();
if (native_types.size() == 0)
if ( native_types.size() == 0 )
native_types.add(type_map.getNativeTypeFromPrimitiveType(kind));
}
@ -147,18 +162,21 @@ public class NativeTypeTranslator implements TypeVisitor {
is_indirect = true;
Class<?> c = getClassFromType(t);
if (String.class.equals(c)) {
if ( String.class.equals(c) ) {
native_types = new ArrayList<Class>();
native_types.add(type_map.getStringElementType());
} else if (Buffer.class.equals(c)) {
} else if ( Buffer.class.equals(c) ) {
native_types = new ArrayList<Class>();
native_types.add(type_map.getVoidType());
} else if (Buffer.class.isAssignableFrom(c)) {
} else if ( Buffer.class.isAssignableFrom(c) ) {
PrimitiveType.Kind kind = getPrimitiveKindFromBufferClass(c);
getNativeTypeFromAnnotatedPrimitiveType(kind);
} else if ( PointerWrapper.class.isAssignableFrom(c) ) {
} else if ( PointerBuffer.class.isAssignableFrom(c) ) {
native_types = new ArrayList<Class>();
native_types.add(GLpointer.class);
native_types.add(PointerBuffer.class);
} else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(c) ) {
native_types = new ArrayList<Class>();
native_types.add(PointerWrapper.class);
is_indirect = false;
} else
@ -182,13 +200,14 @@ public class NativeTypeTranslator implements TypeVisitor {
}
// Check if the annotation is itself annotated with a certain annotation type
public static <T extends Annotation> T getAnnotation(AnnotationMirror annotation, Class<T> type) {
return annotation.getAnnotationType().getDeclaration().getAnnotation(type);
}
private static Class translateAnnotation(AnnotationMirror annotation) {
NativeType native_type = getAnnotation(annotation, NativeType.class);
if (native_type != null) {
if ( native_type != null ) {
return getClassFromType(annotation.getAnnotationType());
} else
return null;
@ -196,9 +215,9 @@ public class NativeTypeTranslator implements TypeVisitor {
private Collection<Class> translateAnnotations() {
Collection<Class> result = new ArrayList<Class>();
for (AnnotationMirror annotation : Utils.getSortedAnnotations(declaration.getAnnotationMirrors())) {
for ( AnnotationMirror annotation : Utils.getSortedAnnotations(declaration.getAnnotationMirrors()) ) {
Class translated_result = translateAnnotation(annotation);
if (translated_result != null) {
if ( translated_result != null ) {
result.add(translated_result);
}
}
@ -219,7 +238,7 @@ public class NativeTypeTranslator implements TypeVisitor {
public void visitVoidType(VoidType t) {
native_types = translateAnnotations();
if (native_types.size() == 0)
if ( native_types.size() == 0 )
native_types.add(void.class);
}

View file

@ -40,7 +40,7 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface StringList {
public @interface PointerArray {
/** Number of values in the string list (name of native-side parameter) */
String value();
/** List of string lengths (name of native-side parameter) */

View file

@ -38,7 +38,9 @@ import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface GLpointer {
public @interface PointerWrapper {
String value(); // The native pointer type.
boolean canBeNull() default false; // Whether the pointer may be null.
String params() default ""; // Pass these extra parameters when constructing PointerWrapper objects.
String factory() default ""; // Use this factory method call instead of normal object construction.
}

View file

@ -46,6 +46,7 @@ import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import java.lang.annotation.Annotation;
import java.nio.*;
public class PostfixTranslator implements TypeVisitor {
@ -108,7 +109,7 @@ public class PostfixTranslator implements TypeVisitor {
private boolean translateAnnotation(AnnotationMirror annotation) {
NativeType native_type = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type != null) {
Class annotation_class = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
Class<? extends Annotation> annotation_class = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
signature.append(type_map.translateAnnotation(annotation_class));
return true;
} else

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2002-2010 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
* Extension templates marked with <code>@Private</code> will result in classes without the <code>public</code> keyword.
*
* @author Spasi
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Private {
}

View file

@ -41,6 +41,8 @@ package org.lwjgl.util.generator;
* $Id$
*/
import org.lwjgl.opencl.CLMem;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
@ -52,7 +54,8 @@ public class RegisterStubsGenerator {
Iterator<? extends MethodDeclaration> it = d.getMethods().iterator();
while (it.hasNext()) {
MethodDeclaration method = it.next();
if ( method.getAnnotation(Alternate.class) != null )
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if ( (alt_annotation != null && (!alt_annotation.nativeAlt() || alt_annotation.skipNative())) || method.getAnnotation(Reuse.class) != null )
continue;
EnumSet<Platform> platforms;
PlatformDependent platform_annotation = method.getAnnotation(PlatformDependent.class);
@ -83,20 +86,30 @@ public class RegisterStubsGenerator {
Collection<ParameterDeclaration> params = method.getParameters();
String signature = "(";
for (ParameterDeclaration param : params) {
if (param.getAnnotation(Result.class) != null)
if ( param.getAnnotation(Helper.class) != null || param.getAnnotation(Result.class) != null )
continue;
if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
final Constant constant_annotation = param.getAnnotation(Constant.class);
if ( constant_annotation != null && constant_annotation.isNative() )
continue;
if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null)
signature += "I";
} else {
else
signature += getTypeSignature(param.getType(), true);
}
}
TypeMirror result_type = Utils.getMethodReturnType(method);
if (Utils.getNIOBufferType(result_type) != null)
signature += "I";
final TypeMirror result_type = Utils.getMethodReturnType(method);
final CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class);
final AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class);
if ( Utils.getNIOBufferType(result_type) != null && (auto_size_annotation == null || !auto_size_annotation.isNative()) )
signature += "J";
String result_type_signature = getTypeSignature(result_type, false);
if (method.getAnnotation(CachedResult.class) != null)
if ( cached_result_annotation != null )
signature += result_type_signature;
signature += ")";
signature += result_type_signature;
return signature;
@ -110,8 +123,11 @@ public class RegisterStubsGenerator {
writer.print(Utils.getQualifiedNativeMethodName(Utils.getQualifiedClassName(d), method, generate_error_checks, context_specific));
if (mode == Mode.BUFFEROBJECT)
writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
String opengl_handle_name = method.getSimpleName().replaceFirst("gl", platform.getPrefix());
writer.print(", \"" + opengl_handle_name + "\", (void *)&" + method.getSimpleName() + "}");
final Alternate alt_annotation = method.getAnnotation(Alternate.class);
final String methodName = alt_annotation == null ? method.getSimpleName() : alt_annotation.value();
String opengl_handle_name = methodName.replaceFirst("gl", platform.getPrefix());
writer.print(", \"" + opengl_handle_name + "\", (void *)&" + methodName + "}");
if (has_more)
writer.println(",");
}

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Reuse can be used to annotate methods that duplicate functionality that has been already
* defined somewhere else. For example, this can be applied to OpenGL core functionality that
* exists as an ARB extension as well, but with the exact same entry points.
*
* @author Spasi
*/
@Target(ElementType.METHOD)
public @interface Reuse {
/** The extension Class that defines the method. */
String value();
}

View file

@ -41,6 +41,8 @@ package org.lwjgl.util.generator;
* $Id$
*/
import org.lwjgl.PointerBuffer;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
@ -67,17 +69,33 @@ class SignatureTranslator implements TypeVisitor {
}
public void visitArrayType(ArrayType t) {
throw new RuntimeException(t + " is not allowed");
final Class type = Utils.getJavaType(t.getComponentType());
if ( CharSequence.class.isAssignableFrom(type) )
signature.append("Ljava/nio/ByteBuffer;I");
else if ( Buffer.class.isAssignableFrom(type) )
signature.append("[Ljava/nio/ByteBuffer;");
else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) )
signature.append("[L" + getNativeNameFromClassName(type.getName()) + ";");
else
throw new RuntimeException(t + " is not allowed");
}
public void visitClassType(ClassType t) {
String type_name = getNativeNameFromClassName(t.getDeclaration().getQualifiedName());
Class type = NativeTypeTranslator.getClassFromType(t);
String type_name;
if ( CharSequence.class.isAssignableFrom(type) || CharSequence[].class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) )
type_name = ByteBuffer.class.getName();
else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) ) {
signature.append("J");
return;
} else
type_name = t.getDeclaration().getQualifiedName();
signature.append("L");
signature.append(type_name);
signature.append(getNativeNameFromClassName(type_name));
signature.append(";");
if (add_position_signature && Buffer.class.isAssignableFrom(NativeTypeTranslator.getClassFromType(t))) {
if ( add_position_signature && Utils.isAddressableType(type) )
signature.append("I");
}
}
public void visitDeclaredType(DeclaredType t) {

View file

@ -41,9 +41,12 @@ package org.lwjgl.util.generator;
* $Id$
*/
import org.lwjgl.util.generator.opengl.GLvoid;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.lang.annotation.Annotation;
import java.util.*;
import java.nio.*;
@ -95,6 +98,9 @@ public class TypeInfo {
case BYTE:
type = byte.class;
break;
case BOOLEAN:
type = boolean.class;
break;
default:
throw new RuntimeException(kind + " is not allowed");
}
@ -151,7 +157,7 @@ public class TypeInfo {
for (AnnotationMirror annotation : annotations) {
NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type_annotation != null) {
Class annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
Class<? extends Annotation> annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
Signedness signedness = type_map.getSignednessFromType(annotation_type);
Class inverse_type = type_map.getInverseType(annotation_type);
String auto_type = type_map.getAutoTypeFromAnnotation(annotation);

View file

@ -45,19 +45,25 @@ import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.io.*;
import java.lang.annotation.Annotation;
public interface TypeMap {
String getErrorCheckMethodName();
void printCapabilitiesInit(PrintWriter writer);
String getCapabilities();
void printErrorCheckMethod(PrintWriter writer, MethodDeclaration method, String tabs);
String getRegisterNativesFunctionName();
PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class native_type);
String getTypedefPrefix();
PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class<? extends Annotation> native_type);
String getTypedefPostfix();
String getFunctionPrefix();
void printNativeIncludes(PrintWriter writer);
Class getStringElementType();
Class<? extends Annotation> getStringElementType();
Class<? extends Annotation> getStringArrayType();
Class<? extends Annotation> getByteBufferArrayType();
Class[] getValidAnnotationTypes(Class type);
Class getVoidType();
String translateAnnotation(Class annotation_type);
Class<? extends Annotation> getVoidType();
String translateAnnotation(Class<? extends Annotation> annotation_type);
Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind);
String getAutoTypeFromAnnotation(AnnotationMirror annotation);
Class getInverseType(Class type);
Signedness getSignednessFromType(Class type);
Class<? extends Annotation> getInverseType(Class<? extends Annotation> type);
Signedness getSignednessFromType(Class<? extends Annotation> type);
}

View file

@ -51,11 +51,12 @@ public class TypedefsGenerator {
private static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, MethodDeclaration method) {
TypeMirror return_type = method.getReturnType();
writer.print("typedef ");
writer.print(type_map.getTypedefPostfix());
NativeTypeTranslator translator = new NativeTypeTranslator(type_map, method);
return_type.accept(translator);
writer.print(translator.getSignature());
writer.print(" (");
writer.print(type_map.getTypedefPrefix());
writer.print(type_map.getFunctionPrefix());
writer.print(" *" + Utils.getTypedefName(method) + ") (");
generateNativeTypedefsParameters(type_map, writer, method.getParameters());
writer.println(");");
@ -63,11 +64,17 @@ public class TypedefsGenerator {
private static void generateNativeTypedefsParameters(TypeMap type_map, PrintWriter writer, Collection<ParameterDeclaration> params) {
if (params.size() > 0) {
Iterator<ParameterDeclaration> it = params.iterator();
generateNativeTypedefsParameter(type_map, writer, it.next());
while (it.hasNext()) {
writer.print(", ");
generateNativeTypedefsParameter(type_map, writer, it.next());
boolean first = true;
for ( ParameterDeclaration param : params ) {
if ( param.getAnnotation(Helper.class) != null )
continue;
if ( first )
first = false;
else
writer.print(", ");
generateNativeTypedefsParameter(type_map, writer, param);
}
}
}
@ -76,14 +83,14 @@ public class TypedefsGenerator {
NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
param.getType().accept(translator);
writer.print(translator.getSignature());
if (param.getAnnotation(Result.class) != null || param.getAnnotation(Indirect.class) != null || param.getAnnotation(StringList.class) != null)
if (param.getAnnotation(Result.class) != null || param.getAnnotation(Indirect.class) != null || param.getAnnotation(PointerArray.class) != null)
writer.print("*");
writer.print(" " + param.getSimpleName());
}
public static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, Collection<? extends MethodDeclaration> methods) {
for (MethodDeclaration method : methods) {
if ( method.getAnnotation(Alternate.class) == null )
if ( method.getAnnotation(Alternate.class) == null && method.getAnnotation(Reuse.class) == null )
generateNativeTypedefs(type_map, writer, method);
}
}

View file

@ -40,6 +40,12 @@ package org.lwjgl.util.generator;
* $Id$
*/
import org.lwjgl.PointerBuffer;
import org.lwjgl.util.generator.opengl.GLboolean;
import org.lwjgl.util.generator.opengl.GLchar;
import org.lwjgl.util.generator.opengl.GLcharARB;
import org.lwjgl.util.generator.opengl.GLreturn;
import java.io.PrintWriter;
import java.nio.Buffer;
import java.nio.ByteBuffer;
@ -75,11 +81,19 @@ public class Utils {
}
public static String getFunctionAddressName(InterfaceDeclaration interface_decl, MethodDeclaration method, boolean forceAlt) {
Alternate alt_annotation = method.getAnnotation(Alternate.class);
final Alternate alt_annotation = method.getAnnotation(Alternate.class);
/* Removed prefix so that we can identify reusable entry points, removed postfix because it's not needed and looks nicer.
String interfaceName = interface_decl.getSimpleName(); // If we add this back, we need to fix @Reuse (add a param for the template name)
if ( alt_annotation == null || (alt_annotation.nativeAlt() && !forceAlt) )
return interface_decl.getSimpleName() + "_" + method.getSimpleName() + FUNCTION_POINTER_POSTFIX;
return interfaceName + "_" + method.getSimpleName() + FUNCTION_POINTER_POSTFIX;
else
return interface_decl.getSimpleName() + "_" + alt_annotation.value() + FUNCTION_POINTER_POSTFIX;
return interfaceName + "_" + alt_annotation.value() + FUNCTION_POINTER_POSTFIX;
*/
if ( alt_annotation == null || (alt_annotation.nativeAlt() && !forceAlt) )
return method.getSimpleName();
else
return alt_annotation.value();
}
public static boolean isFinal(InterfaceDeclaration d) {
@ -115,7 +129,15 @@ public class Utils {
}
public static boolean isAddressableType(Class type) {
return Buffer.class.isAssignableFrom(type) || String.class.equals(type) || CharSequence.class.equals(type) || CharSequence[].class.equals(type);
if ( type.isArray() ) {
final Class component_type = type.getComponentType();
return isAddressableTypeImpl(component_type) || org.lwjgl.PointerWrapper.class.isAssignableFrom(component_type);
}
return isAddressableTypeImpl(type);
}
private static boolean isAddressableTypeImpl(Class type) {
return Buffer.class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) || CharSequence.class.isAssignableFrom(type);
}
public static Class getJavaType(TypeMirror type_mirror) {
@ -149,11 +171,23 @@ public class Utils {
public static void printDocComment(PrintWriter writer, Declaration decl) {
String doc_comment = decl.getDocComment();
if (doc_comment != null) {
String tab = decl instanceof InterfaceDeclaration ? "" : "\t";
final String tab = decl instanceof InterfaceDeclaration ? "" : "\t";
writer.println(tab + "/**");
StringTokenizer doc_lines = new StringTokenizer(doc_comment, "\n");
while (doc_lines.hasMoreTokens())
writer.println(tab + " * " + doc_lines.nextToken());
final StringTokenizer doc_lines = new StringTokenizer(doc_comment, "\n", true);
boolean lastWasNL = false;
while (doc_lines.hasMoreTokens()) {
final String t = doc_lines.nextToken();
if ( "\n".equals(t) ) {
if ( lastWasNL )
writer.println(tab + " *");
lastWasNL = true;
} else {
writer.println(tab + " * " + t);
lastWasNL = false;
}
}
writer.println(tab + " */");
} else if ( (decl instanceof MethodDeclaration) && decl.getAnnotation(Alternate.class) != null )
writer.println("\t/** Overloads " + decl.getAnnotation(Alternate.class).value() + " */");
@ -241,7 +275,7 @@ public class Utils {
}
public static boolean needResultSize(MethodDeclaration method) {
return getNIOBufferType(getMethodReturnType(method)) != null && method.getAnnotation(AutoResultSize.class) == null;
return getNIOBufferType(getMethodReturnType(method)) != null && method.getAnnotation(AutoSize.class) == null;
}
public static void printExtraCallArguments(PrintWriter writer, MethodDeclaration method, String size_parameter_name) {
@ -289,7 +323,7 @@ public class Utils {
Class<?> param_type = getJavaType(t);
if (Buffer.class.isAssignableFrom(param_type))
return param_type;
else if ( param_type == CharSequence.class || param_type == CharSequence[].class )
else if ( param_type == CharSequence.class || param_type == CharSequence[].class || param_type == PointerBuffer.class )
return ByteBuffer.class;
else
return null;
@ -337,9 +371,9 @@ public class Utils {
} else if ( type.equals(CharSequence[].class) ) {
if ( offset == null )
offset = "APIUtils.getTotalLength(" + p.getSimpleName() + ")";
offset = "APIUtil.getTotalLength(" + p.getSimpleName() + ")";
else
offset += " + APIUtils.getTotalLength(" + p.getSimpleName() + ")";
offset += " + APIUtil.getTotalLength(" + p.getSimpleName() + ")";
if ( p.getAnnotation(NullTerminated.class) != null ) offset += " + " + p.getSimpleName() + ".length";
}
@ -352,10 +386,10 @@ public class Utils {
if ( "String".equals(return_type) ) {
if ( !return_annotation.forceMaxLength() ) {
writer.println("IntBuffer " + return_annotation.value() + "_length = APIUtils.getLengths();");
writer.println("IntBuffer " + return_annotation.value() + "_length = APIUtil.getLengths();");
writer.print("\t\t");
}
writer.print("ByteBuffer " + return_annotation.value() + " = APIUtils.getBufferByte(" + return_annotation.maxLength());
writer.print("ByteBuffer " + return_annotation.value() + " = APIUtil.getBufferByte(" + return_annotation.maxLength());
/*
Params that use the return buffer will advance its position while filling it. When we return, the position will be
at the right spot for grabbing the returned string bytes. We only have to make sure that the original buffer was
@ -367,13 +401,18 @@ public class Utils {
writer.println(");");
} else {
final String buffer_type = "Boolean".equals(return_type) ? "Byte" : return_type;
writer.print(buffer_type + "Buffer " + return_annotation.value() + " = APIUtils.getBuffer" + buffer_type + "(");
writer.print(buffer_type + "Buffer " + return_annotation.value() + " = APIUtil.getBuffer" + buffer_type + "(");
if ( "Byte".equals(buffer_type) )
writer.print('1');
writer.println(");");
}
writer.print("\t\t");
final Code code_annotation = method.getAnnotation(Code.class);
if ( code_annotation != null && code_annotation.tryBlock() ) {
writer.println("\t\ttry {");
writer.print("\t\t\t");
} else
writer.print("\t\t");
}
static void printGLReturnPost(PrintWriter writer, MethodDeclaration method, GLreturn return_annotation) {
@ -389,7 +428,7 @@ public class Utils {
else
writer.print(return_annotation.value() + "_length.get(0)");
writer.println(");");
writer.println("\t\treturn APIUtils.getString(" + return_annotation.value() + ");");
writer.println("\t\treturn APIUtil.getString(" + return_annotation.value() + ");");
} else {
writer.print("\t\treturn " + return_annotation.value() + ".get(0)");
if ( "Boolean".equals(return_type) )

View file

@ -1,218 +1,242 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* The OpenAL specific generator behaviour
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.io.*;
import java.util.*;
import java.nio.*;
public class ALTypeMap implements TypeMap {
private static final Map<Class, PrimitiveType.Kind> native_types_to_primitive;
static {
native_types_to_primitive = new HashMap<Class, PrimitiveType.Kind>();
native_types_to_primitive.put(ALboolean.class, PrimitiveType.Kind.BOOLEAN);
native_types_to_primitive.put(ALbyte.class, PrimitiveType.Kind.BYTE);
native_types_to_primitive.put(ALenum.class, PrimitiveType.Kind.INT);
native_types_to_primitive.put(ALfloat.class, PrimitiveType.Kind.FLOAT);
native_types_to_primitive.put(ALdouble.class, PrimitiveType.Kind.DOUBLE);
native_types_to_primitive.put(ALint.class, PrimitiveType.Kind.INT);
native_types_to_primitive.put(ALshort.class, PrimitiveType.Kind.SHORT);
native_types_to_primitive.put(ALsizei.class, PrimitiveType.Kind.INT);
native_types_to_primitive.put(ALubyte.class, PrimitiveType.Kind.BYTE);
native_types_to_primitive.put(ALuint.class, PrimitiveType.Kind.INT);
native_types_to_primitive.put(ALvoid.class, PrimitiveType.Kind.BYTE);
}
public PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class native_type) {
PrimitiveType.Kind kind = native_types_to_primitive.get(native_type);
if (kind == null)
throw new RuntimeException("Unsupported type " + native_type);
return kind;
}
public Signedness getSignednessFromType(Class type) {
if (ALuint.class.equals(type))
return Signedness.UNSIGNED;
else if (ALint.class.equals(type))
return Signedness.SIGNED;
else if (ALshort.class.equals(type))
return Signedness.SIGNED;
else if (ALbyte.class.equals(type))
return Signedness.SIGNED;
else
return Signedness.NONE;
}
public String translateAnnotation(Class annotation_type) {
if (annotation_type.equals(ALuint.class))
return "i";
else if (annotation_type.equals(ALint.class))
return "i";
else if (annotation_type.equals(ALshort.class))
return "s";
else if (annotation_type.equals(ALbyte.class))
return "b";
else if (annotation_type.equals(ALfloat.class))
return "f";
else if (annotation_type.equals(ALdouble.class))
return "d";
else if (annotation_type.equals(ALboolean.class) || annotation_type.equals(ALvoid.class))
return "";
else
throw new RuntimeException(annotation_type + " is not allowed");
}
public Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind) {
Class type;
switch (kind) {
case INT:
type = ALint.class;
break;
case FLOAT:
type = ALfloat.class;
break;
case DOUBLE:
type = ALdouble.class;
break;
case SHORT:
type = ALshort.class;
break;
case BYTE:
type = ALbyte.class;
break;
case BOOLEAN:
type = ALboolean.class;
break;
default:
throw new RuntimeException(kind + " is not allowed");
}
return type;
}
private static Class[] getValidBufferTypes(Class type) {
if (type.equals(IntBuffer.class))
return new Class[]{ALenum.class, ALint.class, ALsizei.class, ALuint.class};
else if (type.equals(FloatBuffer.class))
return new Class[]{ALfloat.class};
else if (type.equals(ByteBuffer.class))
return new Class[]{ALboolean.class, ALbyte.class, ALvoid.class};
else if (type.equals(ShortBuffer.class))
return new Class[]{ALshort.class};
else if (type.equals(DoubleBuffer.class))
return new Class[]{ALdouble.class};
else
return new Class[]{};
}
private static Class[] getValidPrimitiveTypes(Class type) {
if (type.equals(int.class))
return new Class[]{ALenum.class, ALint.class, ALsizei.class, ALuint.class};
else if (type.equals(double.class))
return new Class[]{ALdouble.class};
else if (type.equals(float.class))
return new Class[]{ALfloat.class};
else if (type.equals(short.class))
return new Class[]{ALshort.class};
else if (type.equals(byte.class))
return new Class[]{ALbyte.class};
else if (type.equals(boolean.class))
return new Class[]{ALboolean.class};
else if (type.equals(void.class))
return new Class[]{ALvoid.class};
else
return new Class[]{};
}
public String getErrorCheckMethodName() {
return "Util.checkALError()";
}
public String getRegisterNativesFunctionName() {
return "extal_InitializeClass";
}
public String getTypedefPrefix() {
return "ALAPIENTRY";
}
public void printNativeIncludes(PrintWriter writer) {
writer.println("#include \"extal.h\"");
}
public Class getStringElementType() {
return ALubyte.class;
}
public Class[] getValidAnnotationTypes(Class type) {
Class[] valid_types;
if (Buffer.class.isAssignableFrom(type))
valid_types = getValidBufferTypes(type);
else if (type.isPrimitive())
valid_types = getValidPrimitiveTypes(type);
else if (type.equals(String.class))
valid_types = new Class[]{ALubyte.class};
else
valid_types = new Class[]{};
return valid_types;
}
public Class getVoidType() {
return ALvoid.class;
}
public Class getInverseType(Class type) {
if (ALuint.class.equals(type))
return ALint.class;
else if (ALint.class.equals(type))
return ALuint.class;
else
return null;
}
public String getAutoTypeFromAnnotation(AnnotationMirror annotation) {
return null;
}
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* The OpenAL specific generator behaviour
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALTypeMap.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.Signedness;
import org.lwjgl.util.generator.TypeMap;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.io.*;
import java.lang.annotation.Annotation;
import java.util.*;
import java.nio.*;
public class ALTypeMap implements TypeMap {
private static final Map<Class, PrimitiveType.Kind> native_types_to_primitive;
static {
native_types_to_primitive = new HashMap<Class, PrimitiveType.Kind>();
native_types_to_primitive.put(ALboolean.class, PrimitiveType.Kind.BOOLEAN);
native_types_to_primitive.put(ALbyte.class, PrimitiveType.Kind.BYTE);
native_types_to_primitive.put(ALenum.class, PrimitiveType.Kind.INT);
native_types_to_primitive.put(ALfloat.class, PrimitiveType.Kind.FLOAT);
native_types_to_primitive.put(ALdouble.class, PrimitiveType.Kind.DOUBLE);
native_types_to_primitive.put(ALint.class, PrimitiveType.Kind.INT);
native_types_to_primitive.put(ALshort.class, PrimitiveType.Kind.SHORT);
native_types_to_primitive.put(ALsizei.class, PrimitiveType.Kind.INT);
native_types_to_primitive.put(ALubyte.class, PrimitiveType.Kind.BYTE);
native_types_to_primitive.put(ALuint.class, PrimitiveType.Kind.INT);
native_types_to_primitive.put(ALvoid.class, PrimitiveType.Kind.BYTE);
}
public PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class native_type) {
PrimitiveType.Kind kind = native_types_to_primitive.get(native_type);
if (kind == null)
throw new RuntimeException("Unsupported type " + native_type);
return kind;
}
public Signedness getSignednessFromType(Class type) {
if (ALuint.class.equals(type))
return Signedness.UNSIGNED;
else if (ALint.class.equals(type))
return Signedness.SIGNED;
else if (ALshort.class.equals(type))
return Signedness.SIGNED;
else if (ALbyte.class.equals(type))
return Signedness.SIGNED;
else
return Signedness.NONE;
}
public String translateAnnotation(Class annotation_type) {
if (annotation_type.equals(ALuint.class))
return "i";
else if (annotation_type.equals(ALint.class))
return "i";
else if (annotation_type.equals(ALshort.class))
return "s";
else if (annotation_type.equals(ALbyte.class))
return "b";
else if (annotation_type.equals(ALfloat.class))
return "f";
else if (annotation_type.equals(ALdouble.class))
return "d";
else if (annotation_type.equals(ALboolean.class) || annotation_type.equals(ALvoid.class))
return "";
else
throw new RuntimeException(annotation_type + " is not allowed");
}
public Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind) {
Class type;
switch (kind) {
case INT:
type = ALint.class;
break;
case FLOAT:
type = ALfloat.class;
break;
case DOUBLE:
type = ALdouble.class;
break;
case SHORT:
type = ALshort.class;
break;
case BYTE:
type = ALbyte.class;
break;
case BOOLEAN:
type = ALboolean.class;
break;
default:
throw new RuntimeException(kind + " is not allowed");
}
return type;
}
private static Class[] getValidBufferTypes(Class type) {
if (type.equals(IntBuffer.class))
return new Class[]{ALenum.class, ALint.class, ALsizei.class, ALuint.class};
else if (type.equals(FloatBuffer.class))
return new Class[]{ALfloat.class};
else if (type.equals(ByteBuffer.class))
return new Class[]{ALboolean.class, ALbyte.class, ALvoid.class};
else if (type.equals(ShortBuffer.class))
return new Class[]{ALshort.class};
else if (type.equals(DoubleBuffer.class))
return new Class[]{ALdouble.class};
else
return new Class[]{};
}
private static Class[] getValidPrimitiveTypes(Class type) {
if (type.equals(int.class))
return new Class[]{ALenum.class, ALint.class, ALsizei.class, ALuint.class};
else if (type.equals(double.class))
return new Class[]{ALdouble.class};
else if (type.equals(float.class))
return new Class[]{ALfloat.class};
else if (type.equals(short.class))
return new Class[]{ALshort.class};
else if (type.equals(byte.class))
return new Class[]{ALbyte.class};
else if (type.equals(boolean.class))
return new Class[]{ALboolean.class};
else if (type.equals(void.class))
return new Class[]{ALvoid.class};
else
return new Class[]{};
}
public void printCapabilitiesInit(final PrintWriter writer) {
throw new UnsupportedOperationException();
}
public String getCapabilities() {
throw new UnsupportedOperationException();
}
public void printErrorCheckMethod(final PrintWriter writer, final MethodDeclaration method, final String tabs) {
writer.println(tabs + "Util.checkALError();");
}
public String getRegisterNativesFunctionName() {
return "extal_InitializeClass";
}
public String getTypedefPostfix() {
return "";
}
public String getFunctionPrefix() {
return "ALAPIENTRY";
}
public void printNativeIncludes(PrintWriter writer) {
writer.println("#include \"extal.h\"");
}
public Class<? extends Annotation> getStringElementType() {
return ALubyte.class;
}
public Class<? extends Annotation> getStringArrayType() {
return ALubyte.class;
}
public Class<? extends Annotation> getByteBufferArrayType() {
return ALubyte.class;
}
public Class[] getValidAnnotationTypes(Class type) {
Class[] valid_types;
if (Buffer.class.isAssignableFrom(type))
valid_types = getValidBufferTypes(type);
else if (type.isPrimitive())
valid_types = getValidPrimitiveTypes(type);
else if (type.equals(String.class))
valid_types = new Class[]{ALubyte.class};
else
valid_types = new Class[]{};
return valid_types;
}
public Class<? extends Annotation> getVoidType() {
return ALvoid.class;
}
public Class<? extends Annotation> getInverseType(Class type) {
if (ALuint.class.equals(type))
return ALint.class;
else if (ALint.class.equals(type))
return ALuint.class;
else
return null;
}
public String getAutoTypeFromAnnotation(AnnotationMirror annotation) {
return null;
}
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALboolean {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALboolean.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALboolean {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALbyte {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALbyte.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALbyte {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALdouble {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALdouble.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALdouble {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALenum {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALenum.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALenum {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALfloat {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALfloat.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALfloat {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALint {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALint.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALint {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALshort {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALshort.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALshort {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALsizei {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALsizei.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALsizei {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALubyte {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALubyte.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALubyte {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALuint {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALuint.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALuint {
}

View file

@ -1,47 +1,49 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALvoid {
}
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator.openal;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2983 $
* $Id: ALvoid.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface ALvoid {
}

Some files were not shown because too many files have changed in this diff Show more