diff options
Diffstat (limited to 'src/classes/com')
8 files changed, 1361 insertions, 3 deletions
diff --git a/src/classes/com/sun/opengl/impl/GLFixedArrayHandler.java b/src/classes/com/sun/opengl/impl/GLFixedArrayHandler.java index 333a75aa0..868385447 100644 --- a/src/classes/com/sun/opengl/impl/GLFixedArrayHandler.java +++ b/src/classes/com/sun/opengl/impl/GLFixedArrayHandler.java @@ -2,7 +2,6 @@ package com.sun.opengl.impl; import javax.media.opengl.*; -import javax.media.opengl.glsl.ShaderState; import java.nio.*; public class GLFixedArrayHandler implements GLArrayHandler { diff --git a/src/classes/com/sun/opengl/impl/glsl/GLSLArrayHandler.java b/src/classes/com/sun/opengl/impl/glsl/GLSLArrayHandler.java index 3d48f2014..d74298a7c 100644 --- a/src/classes/com/sun/opengl/impl/glsl/GLSLArrayHandler.java +++ b/src/classes/com/sun/opengl/impl/glsl/GLSLArrayHandler.java @@ -4,7 +4,7 @@ package com.sun.opengl.impl.glsl; import com.sun.opengl.impl.*; import javax.media.opengl.*; -import javax.media.opengl.glsl.ShaderState; +import com.sun.opengl.util.glsl.ShaderState; import java.nio.*; public class GLSLArrayHandler implements GLArrayHandler { diff --git a/src/classes/com/sun/opengl/impl/glsl/fixed/FixedFuncPipeline.java b/src/classes/com/sun/opengl/impl/glsl/fixed/FixedFuncPipeline.java index 53f1046c0..7cd3d7bbb 100644 --- a/src/classes/com/sun/opengl/impl/glsl/fixed/FixedFuncPipeline.java +++ b/src/classes/com/sun/opengl/impl/glsl/fixed/FixedFuncPipeline.java @@ -3,7 +3,7 @@ package com.sun.opengl.impl.glsl.fixed; import javax.media.opengl.*; import javax.media.opengl.util.*; -import javax.media.opengl.glsl.*; +import com.sun.opengl.util.glsl.*; import java.nio.*; public class FixedFuncPipeline { diff --git a/src/classes/com/sun/opengl/util/glsl/ShaderCode.java b/src/classes/com/sun/opengl/util/glsl/ShaderCode.java new file mode 100644 index 000000000..8addf339c --- /dev/null +++ b/src/classes/com/sun/opengl/util/glsl/ShaderCode.java @@ -0,0 +1,302 @@ + +package com.sun.opengl.util.glsl; + +import javax.media.opengl.*; +import javax.media.opengl.util.*; +import com.sun.opengl.util.StreamUtil; +import com.sun.opengl.impl.io.Locator; + +import java.util.*; +import java.nio.*; +import java.io.*; +import java.net.*; + +public class ShaderCode { + public static final String SUFFIX_VERTEX_SOURCE = "vp" ; + public static final String SUFFIX_VERTEX_BINARY = "bvp" ; + public static final String SUFFIX_FRAGMENT_SOURCE = "fp" ; + public static final String SUFFIX_FRAGMENT_BINARY = "bfp" ; + + public static final String SUB_PATH_NVIDIA = "nvidia" ; + + public ShaderCode(int type, int number, String[][] source) { + switch (type) { + case GL2ES2.GL_VERTEX_SHADER: + case GL2ES2.GL_FRAGMENT_SHADER: + break; + default: + throw new GLException("Unknown shader type: "+type); + } + shaderSource = source; + shaderBinaryFormat = -1; + shaderBinary = null; + shaderType = type; + shader = BufferUtil.newIntBuffer(number); + id = getNextID(); + } + + public ShaderCode(int type, int number, int binFormat, Buffer binary) { + switch (type) { + case GL2ES2.GL_VERTEX_SHADER: + case GL2ES2.GL_FRAGMENT_SHADER: + break; + default: + throw new GLException("Unknown shader type: "+type); + } + shaderSource = null; + shaderBinaryFormat = binFormat; + shaderBinary = binary; + shaderType = type; + shader = BufferUtil.newIntBuffer(number); + id = getNextID(); + } + + public static ShaderCode create(int type, int number, Class context, String[] sourceFiles) { + String[][] shaderSources = null; + if(null!=sourceFiles) { + shaderSources = new String[sourceFiles.length][1]; + for(int i=0; null!=shaderSources && i<sourceFiles.length; i++) { + shaderSources[i][0] = readShaderSource(context, sourceFiles[i]); + if(null == shaderSources[i][0]) { + shaderSources = null; + } + } + } + if(null==shaderSources) { + return null; + } + return new ShaderCode(type, number, shaderSources); + } + + public static ShaderCode create(int type, int number, Class context, int binFormat, String binaryFile) { + ByteBuffer shaderBinary = null; + if(null!=binaryFile && 0<=binFormat) { + shaderBinary = readShaderBinary(context, binaryFile); + if(null == shaderBinary) { + binFormat = -1; + } + } + if(null==shaderBinary) { + return null; + } + return new ShaderCode(type, number, binFormat, shaderBinary); + } + + public static String getFileSuffix(boolean binary, int type) { + switch (type) { + case GL2ES2.GL_VERTEX_SHADER: + return binary?SUFFIX_VERTEX_BINARY:SUFFIX_VERTEX_SOURCE; + case GL2ES2.GL_FRAGMENT_SHADER: + return binary?SUFFIX_FRAGMENT_BINARY:SUFFIX_FRAGMENT_SOURCE; + default: + throw new GLException("illegal shader type: "+type); + } + } + + public static String getBinarySubPath(int binFormat) { + switch (binFormat) { + case GLES2.GL_NVIDIA_PLATFORM_BINARY_NV: + return SUB_PATH_NVIDIA; + default: + throw new GLException("unsupported binary format: "+binFormat); + } + } + + public static ShaderCode create(GL2ES2 gl, int type, int number, Class context, + String srcRoot, String binRoot, String basename) { + ShaderCode res = null; + String srcFileName = null; + String binFileName = null; + + if(gl.glShaderCompilerAvailable()) { + String srcPath[] = new String[1]; + srcFileName = srcRoot + '/' + basename + "." + getFileSuffix(false, type); + srcPath[0] = srcFileName; + res = create(type, number, context, srcPath); + if(null!=res) { + return res; + } + } + Set binFmts = gl.glGetShaderBinaryFormats(); + for(Iterator iter=binFmts.iterator(); null==res && iter.hasNext(); ) { + int bFmt = ((Integer)(iter.next())).intValue(); + String bFmtPath = getBinarySubPath(bFmt); + if(null==bFmtPath) continue; + binFileName = binRoot + '/' + bFmtPath + '/' + basename + "." + getFileSuffix(true, type); + res = create(type, number, context, bFmt, binFileName); + } + + if(null==res) { + throw new GLException("No shader code found (source nor binary) for src: "+srcFileName+ + ", bin: "+binFileName); + } + + return res; + } + + /** + * returns the uniq shader id as an integer + * @see #key() + */ + public int id() { return id.intValue(); } + + /** + * returns the uniq shader id as an Integer + * + * @see #id() + */ + public Integer key() { return id; } + + public int shaderType() { return shaderType; } + public String shaderTypeStr() { return shaderTypeStr(shaderType); } + + public static String shaderTypeStr(int type) { + switch (type) { + case GL2ES2.GL_VERTEX_SHADER: + return "VERTEX_SHADER"; + case GL2ES2.GL_FRAGMENT_SHADER: + return "FRAGMENT_SHADER"; + } + return "UNKNOWN_SHADER"; + } + + public int shaderBinaryFormat() { return shaderBinaryFormat; } + public Buffer shaderBinary() { return shaderBinary; } + public String[][] shaderSource() { return shaderSource; } + + public boolean isValid() { return valid; } + + public IntBuffer shader() { return shader; } + + public boolean compile(GL2ES2 gl) { + return compile(gl, null); + } + public boolean compile(GL2ES2 gl, PrintStream verboseOut) { + if(isValid()) return true; + + // Create & Compile the vertex/fragment shader objects + if(null!=shaderSource) { + valid=gl.glCreateCompileShader(shader, shaderType, + shaderSource, verboseOut); + } else if(null!=shaderBinary) { + valid=gl.glCreateLoadShader(shader, shaderType, + shaderBinaryFormat, shaderBinary, verboseOut); + } else { + throw new GLException("no code (source or binary)"); + } + return valid; + } + + public void release(GL2ES2 gl) { + if(isValid()) { + gl.glDeleteShader(shader()); + valid=false; + } + } + + public boolean equals(Object obj) { + if(this==obj) return true; + if(obj instanceof ShaderCode) { + return id()==((ShaderCode)obj).id(); + } + return false; + } + public int hashCode() { + return id.intValue(); + } + public String toString() { + StringBuffer buf = new StringBuffer("ShaderCode [id="+id+", type="+shaderTypeStr()+", valid="+valid+", shader: "); + for(int i=0; i<shader.remaining(); i++) { + buf.append(" "+shader.get(i)); + } + if(null!=shaderSource) { + buf.append(", source]"); + } else if(null!=shaderBinary) { + buf.append(", binary "+shaderBinary+"]"); + } + return buf.toString(); + } + + public static void readShaderSource(ClassLoader context, String path, URL url, StringBuffer result) { + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); + String line = null; + while ((line = reader.readLine()) != null) { + if (line.startsWith("#include ")) { + String includeFile = line.substring(9).trim(); + // Try relative path first + String next = Locator.getRelativeOf(path, includeFile); + URL nextURL = Locator.getResource(next, context); + if (nextURL == null) { + // Try absolute path + next = includeFile; + nextURL = Locator.getResource(next, context); + } + if (nextURL == null) { + // Fail + throw new FileNotFoundException("Can't find include file " + includeFile); + } + readShaderSource(context, next, nextURL, result); + } else { + result.append(line + "\n"); + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static String readShaderSource(Class context, String path) { + ClassLoader contextCL = (null!=context)?context.getClassLoader():null; + URL url = Locator.getResource(path, contextCL); + if (url == null && null!=context) { + // Try again by scoping the path within the class's package + String className = context.getName().replace('.', '/'); + int lastSlash = className.lastIndexOf('/'); + if (lastSlash >= 0) { + String tmpPath = className.substring(0, lastSlash + 1) + path; + url = Locator.getResource(tmpPath, contextCL); + if (url != null) { + path = tmpPath; + } + } + } + if (url == null) { + return null; + } + StringBuffer result = new StringBuffer(); + readShaderSource(contextCL, path, url, result); + return result.toString(); + } + + public static ByteBuffer readShaderBinary(Class context, String path) { + try { + URL url = Locator.getResource(context, path); + if (url == null) { + return null; + } + return StreamUtil.readAll2Buffer(new BufferedInputStream(url.openStream())); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + //---------------------------------------------------------------------- + // Internals only below this point + // + + protected String[][] shaderSource = null; + protected Buffer shaderBinary = null; + protected int shaderBinaryFormat = -1; + protected IntBuffer shader = null; + protected int shaderType = -1; + protected Integer id = null; + + protected boolean valid=false; + + private static synchronized Integer getNextID() { + return new Integer(nextID++); + } + protected static int nextID = 1; +} + diff --git a/src/classes/com/sun/opengl/util/glsl/ShaderProgram.java b/src/classes/com/sun/opengl/util/glsl/ShaderProgram.java new file mode 100644 index 000000000..066244fa6 --- /dev/null +++ b/src/classes/com/sun/opengl/util/glsl/ShaderProgram.java @@ -0,0 +1,197 @@ + +package com.sun.opengl.util.glsl; + +import javax.media.opengl.*; + +import java.util.HashMap; +import java.util.Iterator; +import java.nio.*; +import java.io.PrintStream; + +public class ShaderProgram { + public ShaderProgram() { + id = getNextID(); + } + + public boolean linked() { + return programLinked; + } + + public boolean inUse() { + return programInUse; + } + + public int program() { return shaderProgram; } + + /** + * returns the uniq shader id as an integer + * @see #key() + */ + public int id() { return id.intValue(); } + + /** + * returns the uniq shader id as an Integer + * + * @see #id() + */ + public Integer key() { return id; } + + /** + * @see #glReleaseAllVertexAttributes + */ + public synchronized void release(GL2ES2 gl) { + release(gl, false); + } + + /** + * @see #glReleaseAllVertexAttributes + */ + public synchronized void release(GL2ES2 gl, boolean releaseShaderToo) { + glUseProgram(gl, false); + for(Iterator iter=shaderMap.values().iterator(); iter.hasNext(); ) { + ShaderCode shaderCode = (ShaderCode) iter.next(); + gl.glDetachShader(shaderProgram, shaderCode.shader()); + if(releaseShaderToo) { + shaderCode.release(gl); + } + } + shaderMap.clear(); + gl.glDeleteProgram(shaderProgram); + shaderProgram=-1; + } + + // + // ShaderCode handling + // + + /** + * Adds a new shader to a this non running program. + * + * @return false if the program is in use, or the shader already exist, + * otherwise true. + */ + public synchronized boolean add(ShaderCode shaderCode) { + if(shaderMap.containsKey(shaderCode.key())) return false; + shaderMap.put(shaderCode.key(), shaderCode); + return true; + } + + public synchronized ShaderCode getShader(int id) { + return (ShaderCode) shaderMap.get(new Integer(id)); + } + + // + // Program handling + // + + /** + * Replace a shader in a 'running' program. + * Refetches all previously bin/get attribute names + * and resets all attribute data as well + * + * @see getAttribLocation + * @param gl + * @param oldShaderID the to be replace Shader + * @param newShader the new ShaderCode + * @param verboseOut the optional verbose outputstream + * @throws GLException is the program is not linked + * + * @see #glRefetchAttribLocations + * @see #glResetAllVertexAttributes + * @see #glReplaceShader + */ + public synchronized boolean glReplaceShader(GL2ES2 gl, int oldShaderID, ShaderCode newShader, PrintStream verboseOut) { + if(!programLinked) throw new GLException("Program is not linked"); + boolean shaderWasInUse = programInUse; + glUseProgram(gl, false); + if(!newShader.compile(gl, verboseOut)) { + return false; + } + if(oldShaderID>=0) { + ShaderCode oldShader = (ShaderCode) shaderMap.remove(new Integer(oldShaderID)); + if(null!=oldShader) { + gl.glDetachShader(shaderProgram, oldShader.shader()); + } + } + add(newShader); + + gl.glAttachShader(shaderProgram, newShader.shader()); + gl.glLinkProgram(shaderProgram); + if ( ! gl.glIsProgramValid(shaderProgram, System.err) ) { + return false; + } + + if(shaderWasInUse) { + glUseProgram(gl, true); + } + return true; + } + + public synchronized boolean link(GL2ES2 gl, PrintStream verboseOut) { + if(programLinked) throw new GLException("Program is already linked"); + + if(0>shaderProgram) { + shaderProgram = gl.glCreateProgram(); + } + + for(Iterator iter=shaderMap.values().iterator(); iter.hasNext(); ) { + ShaderCode shaderCode = (ShaderCode) iter.next(); + if(!shaderCode.compile(gl, verboseOut)) { + return false; + } + gl.glAttachShader(shaderProgram, shaderCode.shader()); + } + + // Link the program + gl.glLinkProgram(shaderProgram); + + programLinked = gl.glIsProgramValid(shaderProgram, System.err); + + return programLinked; + } + + public boolean equals(Object obj) { + if(this==obj) return true; + if(obj instanceof ShaderCode) { + return id()==((ShaderCode)obj).id(); + } + return false; + } + public int hashCode() { + return id.intValue(); + } + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append("ShaderProgram[id="+id); + buf.append(", linked="+programLinked+", inUse="+programInUse+", program: "+shaderProgram+", ["); + for(Iterator iter=shaderMap.values().iterator(); iter.hasNext(); ) { + buf.append((ShaderCode) iter.next()); + buf.append(" "); + } + buf.append("]"); + return buf.toString(); + } + + protected synchronized void glUseProgram(GL2ES2 gl, boolean on) { + if(!programLinked) throw new GLException("Program is not linked"); + if(programInUse==on) return; + gl.glUseProgram(on?shaderProgram:0); + programInUse = on; + + //Throwable tX = new Throwable("Info: ShaderProgram.glUseProgram: "+on); + //tX.printStackTrace(); + + } + + protected boolean programLinked = false; + protected boolean programInUse = false; + protected int shaderProgram=-1; + protected HashMap shaderMap = new HashMap(); + protected Integer id = null; + + private static synchronized Integer getNextID() { + return new Integer(nextID++); + } + protected static int nextID = 1; +} + diff --git a/src/classes/com/sun/opengl/util/glsl/ShaderState.java b/src/classes/com/sun/opengl/util/glsl/ShaderState.java new file mode 100644 index 000000000..6320f9c6a --- /dev/null +++ b/src/classes/com/sun/opengl/util/glsl/ShaderState.java @@ -0,0 +1,623 @@ + +package com.sun.opengl.util.glsl; + +import javax.media.opengl.*; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.nio.*; +import java.io.PrintStream; + +public class ShaderState { + + public ShaderState() { + } + + public boolean verbose() { return verbose; } + + public void setVerbose(boolean v) { verbose=v; } + + /** + * Fetches the current shader state + * + * @see javax.media.opengl.glsl.ShaderState#glUseProgram(GL2ES2, boolean) + * @see javax.media.opengl.glsl.ShaderState#getCurrent() + */ + public static synchronized ShaderState getCurrent() { return currentShaderState; } + + /** + * Turns the shader program on + * and set this ShaderState to current if on equals true + * + * @see javax.media.opengl.glsl.ShaderState#glUseProgram(GL2ES2, boolean) + * @see javax.media.opengl.glsl.ShaderState#getCurrent() + */ + public synchronized void glUseProgram(GL2ES2 gl, boolean on) { + if(on) { + if(null!=shaderProgram) { + shaderProgram.glUseProgram(gl, true); + } else { + throw new GLException("No program is attached"); + } + if(currentShaderState!=this) { + currentShaderState = this; + } + } else if(null!=shaderProgram) { + shaderProgram.glUseProgram(gl, false); + } + } + + public boolean linked() { + return (null!=shaderProgram)?shaderProgram.linked():false; + } + + public boolean inUse() { + return (null!=shaderProgram)?shaderProgram.inUse():false; + } + + /** + * Attach or switch a shader program + * + * Attaching a shader program the first time, + * as well as switching to another program on the fly, + * while managing all attribute and uniform data. + */ + public synchronized void attachShaderProgram(GL2ES2 gl, ShaderProgram prog) { + boolean prgInUse = false; // earmarked state + + if(DEBUG) { + int curId = (null!=shaderProgram)?shaderProgram.id():-1; + int newId = (null!=prog)?prog.id():-1; + System.err.println("Info: attachShaderProgram: "+curId+" -> "+newId+"\n\t"+shaderProgram+"\n\t"+prog); + Throwable tX = new Throwable("Info: attachShaderProgram: Trace"); + tX.printStackTrace(); + } + if(null!=shaderProgram) { + if(shaderProgram.equals(prog)) { + // nothing to do .. + if(DEBUG) { + System.err.println("Info: attachShaderProgram: NOP: equal id: "+shaderProgram.id()); + } + return; + } + prgInUse = shaderProgram.inUse(); + shaderProgram.glUseProgram(gl, false); + } + + // register new one + shaderProgram = prog; + + if(null!=shaderProgram) { + // reinstall all data .. + shaderProgram.glUseProgram(gl, true); + glResetAllVertexAttributes(gl); + glResetAllUniforms(gl); + if(!prgInUse) { + shaderProgram.glUseProgram(gl, false); + } + } + if(DEBUG) { + System.err.println("Info: attachShaderProgram: END"); + } + } + + public ShaderProgram shaderProgram() { return shaderProgram; } + + /** + * @see #glReleaseAllVertexAttributes + * @see #glReleaseAllUniforms + */ + public synchronized void release(GL2ES2 gl) { + release(gl, false, false); + } + + public synchronized void release(GL2ES2 gl, boolean releaseProgramToo, boolean releaseShaderToo) { + boolean prgInUse = false; + if(null!=shaderProgram) { + prgInUse = shaderProgram.inUse(); + if(!prgInUse) { + shaderProgram.glUseProgram(gl, true); + } + } + glReleaseAllVertexAttributes(gl); + glReleaseAllUniforms(gl); + if(null!=shaderProgram) { + if(releaseProgramToo) { + shaderProgram.release(gl, releaseShaderToo); + } else if(!prgInUse) { + shaderProgram.glUseProgram(gl, false); + } + } + } + + // + // Shader attribute handling + // + + /** + * Binds an attribute to the shader. + * This must be done before the program is linked ! + * n name - 1 idx, where name is a uniq key + * + * @throws GLException is the program is already linked + * + * @see #glBindAttribLocation + * @see javax.media.opengl.GL2ES2#glBindAttribLocation + * @see #glGetAttribLocation + * @see javax.media.opengl.GL2ES2#glGetAttribLocation + * @see #getAttribLocation + * @see #glReplaceShader + */ + public void glBindAttribLocation(GL2ES2 gl, int index, String name) { + if(null==shaderProgram) throw new GLException("No program is attached"); + if(shaderProgram.linked()) throw new GLException("Program is already linked"); + Integer idx = new Integer(index); + if(!attribMap2Idx.containsKey(name)) { + attribMap2Idx.put(name, idx); + gl.glBindAttribLocation(shaderProgram.program(), index, name); + } + } + + /** + * Gets the index of a shader attribute. + * This must be done after the program is linked ! + * + * @return -1 if there is no such attribute available, + * otherwise >= 0 + * @throws GLException is the program is not linked + * + * @see #glBindAttribLocation + * @see javax.media.opengl.GL2ES2#glBindAttribLocation + * @see #glGetAttribLocation + * @see javax.media.opengl.GL2ES2#glGetAttribLocation + * @see #getAttribLocation + * @see #glReplaceShader + */ + public int glGetAttribLocation(GL2ES2 gl, String name) { + if(!shaderProgram.linked()) throw new GLException("Program is not linked"); + int index = getAttribLocation(name); + if(0>index) { + index = gl.glGetAttribLocation(shaderProgram.program(), name); + if(0<=index) { + Integer idx = new Integer(index); + attribMap2Idx.put(name, idx); + if(DEBUG) { + System.err.println("Info: glGetAttribLocation: "+name+", loc: "+index); + } + } else if(verbose) { + Throwable tX = new Throwable("Info: glGetAttribLocation failed, no location for: "+name+", index: "+index); + tX.printStackTrace(); + } + } + return index; + } + + protected int getAttribLocation(String name) { + Integer idx = (Integer) attribMap2Idx.get(name); + return (null!=idx)?idx.intValue():-1; + } + + + // + // Enabled Vertex Arrays and its data + // + + /** + * Enable a vertex attribute array + * + * Even if the attribute is not found in the current shader, + * it is stored in this state. + * + * @returns false, if the name is not found, otherwise true + * + * @throws GLException if the program is not in use + * + * @see #glEnableVertexAttribArray + * @see #glDisableVertexAttribArray + * @see #glVertexAttribPointer + * @see #getVertexAttributePointer + * @see #glReleaseAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glReplaceShader + */ + public boolean glEnableVertexAttribArray(GL2ES2 gl, String name) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + enabledVertexAttribArraySet.add(name); + int index = glGetAttribLocation(gl, name); + if(0>index) { + if(verbose) { + Throwable tX = new Throwable("Info: glEnableVertexAttribArray failed, no index for: "+name); + tX.printStackTrace(); + } + return false; + } + if(DEBUG) { + System.err.println("Info: glEnableVertexAttribArray: "+name+", loc: "+index); + } + gl.glEnableVertexAttribArray(index); + return true; + } + + public boolean isVertexAttribArrayEnabled(String name) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + return enabledVertexAttribArraySet.contains(name); + } + + /** + * Disables a vertex attribute array + * + * Even if the attribute is not found in the current shader, + * it is removed from this state. + * + * @returns false, if the name is not found, otherwise true + * + * @throws GLException if the program is not in use + * + * @see #glEnableVertexAttribArray + * @see #glDisableVertexAttribArray + * @see #glVertexAttribPointer + * @see #getVertexAttributePointer + * @see #glReleaseAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glReplaceShader + */ + public boolean glDisableVertexAttribArray(GL2ES2 gl, String name) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + enabledVertexAttribArraySet.remove(name); + int index = glGetAttribLocation(gl, name); + if(0>index) { + if(verbose) { + Throwable tX = new Throwable("Info: glDisableVertexAttribArray failed, no index for: "+name); + tX.printStackTrace(); + } + return false; + } + if(DEBUG) { + System.err.println("Info: glDisableVertexAttribArray: "+name); + } + gl.glDisableVertexAttribArray(index); + return true; + } + + /** + * Set the vertex attribute data. + * Enable the attribute, if it is not enabled yet. + * + * Even if the attribute is not found in the current shader, + * it is stored in this state. + * + * @arg data the GLArrayData's name must match the attributes one, + * it's index will be set with the attribute's location, + * if found. + * + * @returns false, if the name is not found, otherwise true + * + * @throws GLException if the program is not in use + * + * @see #glEnableVertexAttribArray + * @see #glDisableVertexAttribArray + * @see #glVertexAttribPointer + * @see #getVertexAttributePointer + * @see #glReleaseAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glReplaceShader + */ + public boolean glVertexAttribPointer(GL2ES2 gl, GLArrayData data) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + if(!enabledVertexAttribArraySet.contains(data.getName())) { + if(!glEnableVertexAttribArray(gl, data.getName())) { + if(verbose) { + Throwable tX = new Throwable("Info: glVertexAttribPointer: couldn't enable: "+data); + tX.printStackTrace(); + } + } + } + int index = getAttribLocation(data.getName()); + if(0>index) { + if(verbose) { + Throwable tX = new Throwable("Info: glVertexAttribPointer failed, no index for: "+data); + tX.printStackTrace(); + } + } + data.setLocation(index); + vertexAttribMap2Data.put(data.getName(), data); + if(0<=index) { + // only pass the data, if the attribute exists in the current shader + if(DEBUG) { + System.err.println("Info: glVertexAttribPointer: "+data); + } + gl.glVertexAttribPointer(data); + return true; + } + return false; + } + + /** + * Get the vertex attribute data, previously set. + * + * @returns the GLArrayData object, null if not previously set. + * + * @see #glEnableVertexAttribArray + * @see #glDisableVertexAttribArray + * @see #glVertexAttribPointer + * @see #getVertexAttributePointer + * @see #glReleaseAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glReplaceShader + */ + public GLArrayData getVertexAttribPointer(String name) { + return (GLArrayData) vertexAttribMap2Data.get(name); + } + + /** + * Releases all mapped vertex attribute data, + * disables all enabled attributes and loses all indices + * + * @throws GLException is the program is not in use but the shaderProgram is set + * + * @see #glEnableVertexAttribArray + * @see #glDisableVertexAttribArray + * @see #glVertexAttribPointer + * @see #getVertexAttributePointer + * @see #glReleaseAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glReplaceShader + */ + public void glReleaseAllVertexAttributes(GL2ES2 gl) { + if(null!=shaderProgram) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + for(Iterator iter = vertexAttribMap2Data.keySet().iterator(); iter.hasNext(); ) { + if(!glDisableVertexAttribArray(gl, (String) iter.next())) { + throw new GLException("Internal Error: mapped vertex attribute couldn't be disabled"); + } + } + for(Iterator iter = enabledVertexAttribArraySet.iterator(); iter.hasNext(); ) { + if(!glDisableVertexAttribArray(gl, (String) iter.next())) { + throw new GLException("Internal Error: prev enabled vertex attribute couldn't be disabled"); + } + } + } + vertexAttribMap2Data.clear(); + enabledVertexAttribArraySet.clear(); + attribMap2Idx.clear(); + } + + /** + * Disables all vertex attribute arrays. + * + * Their enabled stated will be removed from this state only + * if 'removeFromState' is true. + * + * This method purpose is more for debugging. + * + * @throws GLException is the program is not in use but the shaderProgram is set + * + * @see #glEnableVertexAttribArray + * @see #glDisableVertexAttribArray + * @see #glVertexAttribPointer + * @see #getVertexAttributePointer + * @see #glReleaseAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glReplaceShader + */ + public void glDisableAllVertexAttributeArrays(GL2ES2 gl, boolean removeFromState) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + + for(Iterator iter = enabledVertexAttribArraySet.iterator(); iter.hasNext(); ) { + String name = (String) iter.next(); + if(removeFromState) { + enabledVertexAttribArraySet.remove(name); + } + int index = glGetAttribLocation(gl, name); + if(0<=index) { + gl.glDisableVertexAttribArray(index); + } + } + } + + /** + * Reset all previously enabled mapped vertex attribute data, + * incl enabling them + * + * @throws GLException is the program is not in use + * + * @see #glEnableVertexAttribArray + * @see #glDisableVertexAttribArray + * @see #glVertexAttribPointer + * @see #getVertexAttributePointer + * @see #glReleaseAllVertexAttributes + * @see #glResetAllVertexAttributes + * @see #glReplaceShader + */ + public void glResetAllVertexAttributes(GL2ES2 gl) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + attribMap2Idx.clear(); + + /** + * + for(Iterator iter = enabledVertexAttribArraySet.iterator(); iter.hasNext(); ) { + glEnableVertexAttribArray(gl, (String) iter.next()); + } + for(Iterator iter = vertexAttribMap2Data.values().iterator(); iter.hasNext(); ) { + GLArrayData data = (GLArrayData) iter.next(); + + ... + } */ + + for(Iterator iter = enabledVertexAttribArraySet.iterator(); iter.hasNext(); ) { + // get new location .. + String name = (String) iter.next(); + int loc = glGetAttribLocation(gl, name); + + // get & update data .. + GLArrayData data = getVertexAttribPointer(name); + data.setLocation(loc); + vertexAttribMap2Data.put(name, data); + + if(0>loc) { + // not used in shader + continue; + } + + // enable attrib, VBO and pass location/data + gl.glEnableVertexAttribArray(loc); + + if( data.isVBO() ) { + gl.glBindBuffer(GL.GL_ARRAY_BUFFER, data.getVBOName()); + } + + gl.glVertexAttribPointer(data); + } + } + + // + // Shader Uniform handling + // + + /** + * Gets the index of a shader uniform. + * This must be done when the program is in use ! + * + * @return -1 if there is no such attribute available, + * otherwise >= 0 + + * @throws GLException is the program is not linked + * + * @see #glGetUniformLocation + * @see javax.media.opengl.GL2ES2#glGetUniformLocation + * @see #getUniformLocation + * @see #glReplaceShader + */ + protected int glGetUniformLocation(GL2ES2 gl, String name) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + int index = getUniformLocation(name); + if(0>index) { + index = gl.glGetUniformLocation(shaderProgram.program(), name); + if(0<=index) { + Integer idx = new Integer(index); + uniformMap2Idx.put(name, idx); + } else if(verbose) { + Throwable tX = new Throwable("Info: glUniform failed, no location for: "+name+", index: "+index); + tX.printStackTrace(); + } + } + return index; + } + + protected int getUniformLocation(String name) { + Integer idx = (Integer) uniformMap2Idx.get(name); + return (null!=idx)?idx.intValue():-1; + } + + /** + * Set the uniform data. + * + * Even if the uniform is not found in the current shader, + * it is stored in this state. + * + * @arg data the GLUniforms's name must match the uniform one, + * it's index will be set with the uniforms's location, + * if found. + * + * + * @returns false, if the name is not found, otherwise true + * + * @throws GLException if the program is not in use + * + * @see #glGetUniformLocation + * @see javax.media.opengl.GL2ES2#glGetUniformLocation + * @see #getUniformLocation + * @see #glReplaceShader + */ + public boolean glUniform(GL2ES2 gl, GLUniformData data) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + int location = glGetUniformLocation(gl, data.getName()); + data.setLocation(location); + uniformMap2Data.put(data.getName(), data); + if(0<=location) { + // only pass the data, if the uniform exists in the current shader + if(DEBUG) { + System.err.println("Info: glUniform: "+data); + } + gl.glUniform(data); + } + return true; + } + + /** + * Get the uniform data, previously set. + * + * @returns the GLUniformData object, null if not previously set. + */ + public GLUniformData getUniform(String name) { + return (GLUniformData) uniformMap2Data.get(name); + } + + /** + * Releases all mapped uniform data + * and loses all indices + * + * @throws GLException is the program is not in use + */ + public void glReleaseAllUniforms(GL2ES2 gl) { + uniformMap2Data.clear(); + uniformMap2Idx.clear(); + } + + /** + * Reset all previously mapped uniform data + * + * @throws GLException is the program is not in use + */ + public void glResetAllUniforms(GL2ES2 gl) { + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + uniformMap2Idx.clear(); + for(Iterator iter = uniformMap2Data.values().iterator(); iter.hasNext(); ) { + glUniform(gl, (GLUniformData) iter.next()); + } + } + + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append("ShaderState["); + buf.append(shaderProgram.toString()); + buf.append(",EnabledStates: ["); + for(Iterator iter = enabledVertexAttribArraySet.iterator(); iter.hasNext(); ) { + buf.append("\n "); + buf.append((String)iter.next()); + } + buf.append("], ["); + for(Iterator iter = vertexAttribMap2Data.values().iterator(); iter.hasNext(); ) { + GLArrayData data = (GLArrayData) iter.next(); + if(data.getLocation()>=0) { + buf.append("\n "); + buf.append(data); + } + } + buf.append("], ["); + for(Iterator iter=uniformMap2Data.values().iterator(); iter.hasNext(); ) { + GLUniformData data = (GLUniformData) iter.next(); + if(data.getLocation()>=0) { + buf.append("\n "); + buf.append(data); + } + } + buf.append("]"); + return buf.toString(); + } + + protected static final boolean DEBUG = false; + protected boolean verbose = false; + protected ShaderProgram shaderProgram=null; + protected HashMap attribMap2Idx = new HashMap(); + protected HashSet enabledVertexAttribArraySet = new HashSet(); + protected HashMap vertexAttribMap2Data = new HashMap(); + protected HashMap uniformMap2Idx = new HashMap(); + protected HashMap uniformMap2Data = new HashMap(); + protected static ShaderState currentShaderState = null; + +} + diff --git a/src/classes/com/sun/opengl/util/glsl/sdk/CompileShader.java b/src/classes/com/sun/opengl/util/glsl/sdk/CompileShader.java new file mode 100755 index 000000000..9b3a48780 --- /dev/null +++ b/src/classes/com/sun/opengl/util/glsl/sdk/CompileShader.java @@ -0,0 +1,184 @@ +package com.sun.opengl.util.glsl.sdk; + +import javax.media.opengl.*; +import com.sun.opengl.impl.io.Locator; +import com.sun.opengl.util.glsl.*; + +import java.io.*; +import java.net.*; + +/** Precompiles a shader into a vendor binary format. Input is the + resource name of the shader, such as + "com/sun/opengl/impl/glsl/fixed/shader/a.fp". + Output is "com/sun/opengl/impl/glsl/fixed/shader/bin/nvidia/a.bfp". + + All path and suffixes are determined by the ShaderCode class, + which ensures runtime compatibility. + + @see javax.media.opengl.glsl.ShaderCode + */ + +public abstract class CompileShader { + + public abstract int getBinaryFormat(); + + public abstract File getSDKCompilerDir(); + + public abstract String getVertexShaderCompiler(); + + public abstract String getFragmentShaderCompiler(); + + public void processOneShader(String resourceName) + throws IOException, UnsupportedEncodingException, InterruptedException + { + int type = -1; + String outName=null; + int suffixLen = -1; + if(resourceName.endsWith(ShaderCode.getFileSuffix(false, GL2ES2.GL_FRAGMENT_SHADER))) { + suffixLen = 2; + type = GL2ES2.GL_FRAGMENT_SHADER; + } else if(resourceName.endsWith(".frag")) { + suffixLen = 4; + type = GL2ES2.GL_FRAGMENT_SHADER; + } else if(resourceName.endsWith(ShaderCode.getFileSuffix(false, GL2ES2.GL_VERTEX_SHADER))) { + suffixLen = 2; + type = GL2ES2.GL_VERTEX_SHADER; + } else if(resourceName.endsWith(".vert")) { + suffixLen = 4; + type = GL2ES2.GL_VERTEX_SHADER; + } + String justName = basename(resourceName); + outName = justName.substring(0, justName.length() - suffixLen) + + ShaderCode.getFileSuffix(true, type); + URL resourceURL = Locator.getResource(null, resourceName); + String dirName = dirname(resourceURL.getPath()); + + outName = dirName + File.separator + "bin" + File.separator + + ShaderCode.getBinarySubPath(getBinaryFormat()) + File.separator + + outName; + processOneShader(resourceName, outName, type); + } + + public void processOneShader(String resourceName, String outName, int type) + throws IOException, UnsupportedEncodingException, InterruptedException + { + URL resourceURL = Locator.getResource(null, resourceName); + String dirName = dirname(resourceURL.getPath()); + + String shader = ShaderCode.readShaderSource(null, resourceName); + if(null==shader) { + System.err.println("Can't find shader source " + resourceName + " - ignored"); + return; + } + System.err.println("Preprocessing: "+ resourceName+", in dir: "+dirName); + String justName = basename(resourceName); + String processor; + switch (type) { + case GL2ES2.GL_VERTEX_SHADER: + processor = getVertexShaderCompiler(); + break; + case GL2ES2.GL_FRAGMENT_SHADER: + processor = getFragmentShaderCompiler(); + break; + default: + throw new GLException("Unknown shader type: "+type); + } + File outputFile = new File(outName); + + // Write shader to a file in java.io.tmpdir + File tmpDir = new File(dirName+File.separator+"tmp"); + tmpDir.mkdirs(); + File tmpFile = new File(tmpDir, justName); + Writer writer = new BufferedWriter(new FileWriter(tmpFile)); + writer.write(shader, 0, shader.length()); + writer.flush(); + writer.close(); + System.err.println("Preprocessed: "+ tmpFile.getAbsolutePath()); + + File processorDir = getSDKCompilerDir(); + + System.err.println("SDK: "+ processorDir.getAbsolutePath() + ", compiler: "+processor); + + System.err.println("Output: "+ outputFile.getAbsolutePath()); + + // Run the tool + Process process = Runtime.getRuntime().exec(new String[] { + processorDir.getAbsolutePath() + File.separator + processor, + tmpFile.getAbsolutePath(), + outputFile.getAbsolutePath() + }); // , null, processorDir); + new StreamMonitor(process.getInputStream()); + new StreamMonitor(process.getErrorStream()); + process.waitFor(); + // Delete the temporary file + // tmpFile.delete(); + } + + protected static String basename(String path) { + int lastSlash = path.lastIndexOf("/"); + if (lastSlash < 0) { + lastSlash = path.lastIndexOf("\\"); + } + String basename; + if (lastSlash < 0) { + basename = path; + } else { + basename = path.substring(lastSlash + 1); + } + return basename; + } + + protected static String dirname(String path) { + int lastSlash = path.lastIndexOf("/"); + if (lastSlash < 0) { + lastSlash = path.lastIndexOf("\\"); + } + String dirname; + if (lastSlash < 0) { + dirname = new String(); + } else { + dirname = path.substring(0, lastSlash + 1); + } + return dirname; + } + + public void run(String[] args) { + try { + for (int i = 0; i < args.length; i++) { + processOneShader(args[i]); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static class StreamMonitor implements Runnable { + private InputStream istream; + public StreamMonitor(InputStream stream) { + istream = stream; + new Thread(this, "Output Reader Thread").start(); + } + + public void run() + { + byte[] buffer = new byte[4096]; + try { + int numRead = 0; + do { + numRead = istream.read(buffer); + if (numRead > 0) { + System.out.write(buffer, 0, numRead); + System.out.flush(); + } + } while (numRead >= 0); + } + catch (IOException e) { + try { + istream.close(); + } catch (IOException e2) { + } + // Should allow clean exit when process shuts down + } + } + } +} diff --git a/src/classes/com/sun/opengl/util/glsl/sdk/CompileShaderNVidia.java b/src/classes/com/sun/opengl/util/glsl/sdk/CompileShaderNVidia.java new file mode 100755 index 000000000..387ccf732 --- /dev/null +++ b/src/classes/com/sun/opengl/util/glsl/sdk/CompileShaderNVidia.java @@ -0,0 +1,53 @@ +package com.sun.opengl.util.glsl.sdk; + +import javax.media.opengl.*; + +import java.io.*; + +/** Precompiles a shader into NVidia binary format. Input is the + resource name of the shader, such as + "com/sun/opengl/impl/glsl/fixed/shader/a.fp". + Output is "com/sun/opengl/impl/glsl/fixed/shader/bin/nvidia/a.bfp". */ + +public class CompileShaderNVidia extends CompileShader { + private static final String NVAPSDK; + + static { + String nvapSDKProp = System.getProperty("NVAPSDK"); + if (nvapSDKProp != null) { + NVAPSDK = nvapSDKProp; + } else { + NVAPSDK = "C:\\nvap_sdk_0_3_x"; + } + } + + public int getBinaryFormat() { + return GLES2.GL_NVIDIA_PLATFORM_BINARY_NV; + } + + public File getSDKCompilerDir() { + File compilerDir = new File( NVAPSDK + File.separator + "tools" + File.separator ); + File compilerFile = new File( compilerDir, getVertexShaderCompiler()); + if(!compilerFile.exists()) { + compilerDir = new File( NVAPSDK ); + compilerFile = new File( compilerDir, getVertexShaderCompiler()); + } + if(!compilerFile.exists()) { + throw new GLException("Can't find compiler: "+getVertexShaderCompiler() + " in : " + + NVAPSDK+", "+NVAPSDK + File.separator + "tools"); + } + return compilerDir; + } + + public String getVertexShaderCompiler() { + return "glslv.bat"; + } + + public String getFragmentShaderCompiler() { + return "glslf.bat"; + } + + public static void main(String[] args) { + new CompileShaderNVidia().run(args); + } +} |