diff options
author | phil <[email protected]> | 2016-10-11 12:59:29 +1300 |
---|---|---|
committer | phil <[email protected]> | 2016-10-11 12:59:29 +1300 |
commit | 6e59ac5f89bcd8cbb0b05653c56a0454963984c8 (patch) | |
tree | b5b7612861f7f22b812ef66d85e710b79c5b593d /src/classes/org/jdesktop/j3d/examples/gl2es2pipeline | |
parent | 78924b53370ef6fd874f858e683b226a18bb82c5 (diff) |
New gl2es2 pipeline examples showing usage
Imports organized
Cg shader examples removed
pom.xml added
Resources now has brute force fall back
Diffstat (limited to 'src/classes/org/jdesktop/j3d/examples/gl2es2pipeline')
36 files changed, 5363 insertions, 0 deletions
diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/EnvironmentMappingGLSL.form b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/EnvironmentMappingGLSL.form new file mode 100644 index 0000000..b6a3e94 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/EnvironmentMappingGLSL.form @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.0" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> + <Properties> + <Property name="defaultCloseOperation" type="int" value="3"/> + <Property name="title" type="java.lang.String" value="EnvironmentMappingGLSL"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + </SyntheticProperties> + <AuxValues> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="drawingPanel"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[500, 500]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + </Container> + </SubComponents> +</Form> diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/EnvironmentMappingGLSL.java b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/EnvironmentMappingGLSL.java new file mode 100644 index 0000000..5eba8df --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/EnvironmentMappingGLSL.java @@ -0,0 +1,265 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +package org.jdesktop.j3d.examples.gl2es2pipeline; + +import java.awt.GraphicsConfiguration; +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import javax.swing.JOptionPane; + +import org.jdesktop.j3d.examples.Resources; +import org.jogamp.java3d.Alpha; +import org.jogamp.java3d.BoundingSphere; +import org.jogamp.java3d.BranchGroup; +import org.jogamp.java3d.Canvas3D; +import org.jogamp.java3d.GLSLShaderProgram; +import org.jogamp.java3d.GeometryArray; +import org.jogamp.java3d.J3DBuffer; +import org.jogamp.java3d.RotationInterpolator; +import org.jogamp.java3d.Shader; +import org.jogamp.java3d.ShaderAppearance; +import org.jogamp.java3d.ShaderAttribute; +import org.jogamp.java3d.ShaderAttributeSet; +import org.jogamp.java3d.ShaderAttributeValue; +import org.jogamp.java3d.ShaderError; +import org.jogamp.java3d.ShaderErrorListener; +import org.jogamp.java3d.ShaderProgram; +import org.jogamp.java3d.SourceCodeShader; +import org.jogamp.java3d.Texture; +import org.jogamp.java3d.TextureUnitState; +import org.jogamp.java3d.Transform3D; +import org.jogamp.java3d.TransformGroup; +import org.jogamp.java3d.TriangleStripArray; +import org.jogamp.java3d.utils.geometry.Sphere; +import org.jogamp.java3d.utils.image.TextureLoader; +import org.jogamp.java3d.utils.shader.StringIO; +import org.jogamp.java3d.utils.universe.SimpleUniverse; +import org.jogamp.java3d.utils.universe.ViewingPlatform; +import org.jogamp.vecmath.Color3f; +import org.jogamp.vecmath.Point3d; +import org.jogamp.vecmath.Point3f; + +public class EnvironmentMappingGLSL extends javax.swing.JFrame +{ + + private URL textureURL = null; + private static final int NUM_TEX_UNITS = 1; + private static final int TEX_UNIT = 0; + + SimpleUniverse univ = null; + + public BranchGroup createSceneGraph() + { + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + + // Create the TransformGroup node and initialize it to the + // identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at run time. Add it to + // the root of the subgraph. + TransformGroup objTrans = new TransformGroup(); + objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objRoot.addChild(objTrans); + + // Create texture object + textureURL = Resources.getResource("resources/images/duke-gears.jpg"); + Texture tex = new TextureLoader(textureURL, this).getTexture(); + // Create the shader program + String vertexProgram = null; + String fragmentProgram = null; + try + { + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/envmap.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/envmap.frag")); + } + catch (IOException e) + { + System.err.println(e); + } + Shader[] shaders = new Shader[2]; + shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); + shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); + final String[] shaderAttrNames = { "LightPos", "BaseColor", "MixRatio", "EnvMap", }; + final Object[] shaderAttrValues = { new Point3f(1.0f, -1.0f, 2.0f), new Color3f(0.2f, 0.9f, 0.5f), new Float(0.4f), + new Integer(TEX_UNIT), }; + ShaderProgram shaderProgram = new GLSLShaderProgram(); + shaderProgram.setShaders(shaders); + shaderProgram.setShaderAttrNames(shaderAttrNames); + + // Create the shader attribute set + ShaderAttributeSet shaderAttributeSet = new ShaderAttributeSet(); + for (int i = 0; i < shaderAttrNames.length; i++) + { + ShaderAttribute shaderAttribute = new ShaderAttributeValue(shaderAttrNames[i], shaderAttrValues[i]); + shaderAttributeSet.put(shaderAttribute); + } + + // Create shader appearance to hold the shader program and + // shader attributes + ShaderAppearance app = new ShaderAppearance(); + app.setShaderProgram(shaderProgram); + app.setShaderAttributeSet(shaderAttributeSet); + + // Put the texture in specified texture unit + TextureUnitState[] tus = new TextureUnitState[NUM_TEX_UNITS]; + tus[TEX_UNIT] = new TextureUnitState(); + tus[TEX_UNIT].setTexture(tex); + app.setTextureUnitState(tus); + + // Create a Sphere object using the shader appearance, + // and add it into the scene graph. + Sphere sph = new Sphere(0.4f, Sphere.GENERATE_NORMALS, 20, app); + SphereGLSL.makeNIO(sph); + objTrans.addChild(sph); + + // Create a new Behavior object that will perform the + // desired operation on the specified transform and add + // it into the scene graph. + Transform3D yAxis = new Transform3D(); + Alpha rotationAlpha = new Alpha(-1, 4000); + + RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, objTrans, yAxis, 0.0f, (float) Math.PI * 2.0f); + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + rotator.setSchedulingBounds(bounds); + objRoot.addChild(rotator); + + // Have Java 3D perform optimizations on this scene graph. + //objRoot.compile(); + + return objRoot; + } + + + + private Canvas3D initScene() + { + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + Canvas3D c = new Canvas3D(config); + + BranchGroup scene = createSceneGraph(); + univ = new SimpleUniverse(c); + + // Add a ShaderErrorListener + univ.addShaderErrorListener(new ShaderErrorListener() { + public void errorOccurred(ShaderError error) + { + error.printVerbose(); + JOptionPane.showMessageDialog(EnvironmentMappingGLSL.this, error.toString(), "ShaderError", JOptionPane.ERROR_MESSAGE); + } + }); + + ViewingPlatform viewingPlatform = univ.getViewingPlatform(); + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + viewingPlatform.setNominalViewingTransform(); + + univ.addBranchGraph(scene); + + return c; + } + + /** + * Creates new form EnvironmentMappingGLSL + */ + public EnvironmentMappingGLSL() + { + // Initialize the GUI components + initComponents(); + + // Create the scene and add the Canvas3D to the drawing panel + Canvas3D c = initScene(); + drawingPanel.add(c, java.awt.BorderLayout.CENTER); + } + + // ---------------------------------------------------------------- + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents + private void initComponents() + { + drawingPanel = new javax.swing.JPanel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setTitle("EnvironmentMappingGLSL"); + drawingPanel.setLayout(new java.awt.BorderLayout()); + + drawingPanel.setPreferredSize(new java.awt.Dimension(500, 500)); + getContentPane().add(drawingPanel, java.awt.BorderLayout.CENTER); + + pack(); + }// </editor-fold>//GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) + { + System.setProperty("sun.awt.noerasebackground", "true"); + System.setProperty("j3d.rend", "jogl2es2"); + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() + { + new EnvironmentMappingGLSL().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel drawingPanel; + // End of variables declaration//GEN-END:variables + +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ObjLoadGLSL.form b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ObjLoadGLSL.form new file mode 100644 index 0000000..343b6d5 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ObjLoadGLSL.form @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.0" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> + <Properties> + <Property name="defaultCloseOperation" type="int" value="3"/> + <Property name="title" type="java.lang.String" value="ObjLoadGLSL"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + </SyntheticProperties> + <AuxValues> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="drawingPanel"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[700, 700]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + </Container> + </SubComponents> +</Form> diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ObjLoadGLSL.java b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ObjLoadGLSL.java new file mode 100644 index 0000000..709ff47 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ObjLoadGLSL.java @@ -0,0 +1,444 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +package org.jdesktop.j3d.examples.gl2es2pipeline; + +import java.awt.GraphicsConfiguration; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Enumeration; + +import javax.swing.JOptionPane; + +import org.jdesktop.j3d.examples.Resources; +import org.jogamp.java3d.Alpha; +import org.jogamp.java3d.AmbientLight; +import org.jogamp.java3d.Background; +import org.jogamp.java3d.BoundingSphere; +import org.jogamp.java3d.BranchGroup; +import org.jogamp.java3d.Canvas3D; +import org.jogamp.java3d.DirectionalLight; +import org.jogamp.java3d.GLSLShaderProgram; +import org.jogamp.java3d.Group; +import org.jogamp.java3d.Material; +import org.jogamp.java3d.Node; +import org.jogamp.java3d.RotationInterpolator; +import org.jogamp.java3d.Shader; +import org.jogamp.java3d.ShaderAppearance; +import org.jogamp.java3d.ShaderError; +import org.jogamp.java3d.ShaderErrorListener; +import org.jogamp.java3d.ShaderProgram; +import org.jogamp.java3d.Shape3D; +import org.jogamp.java3d.SourceCodeShader; +import org.jogamp.java3d.Transform3D; +import org.jogamp.java3d.TransformGroup; +import org.jogamp.java3d.loaders.IncorrectFormatException; +import org.jogamp.java3d.loaders.ParsingErrorException; +import org.jogamp.java3d.loaders.Scene; +import org.jogamp.java3d.loaders.objectfile.ObjectFile; +import org.jogamp.java3d.utils.behaviors.vp.OrbitBehavior; +import org.jogamp.java3d.utils.shader.StringIO; +import org.jogamp.java3d.utils.universe.PlatformGeometry; +import org.jogamp.java3d.utils.universe.SimpleUniverse; +import org.jogamp.java3d.utils.universe.ViewingPlatform; +import org.jogamp.vecmath.Color3f; +import org.jogamp.vecmath.Point3d; +import org.jogamp.vecmath.Vector3f; + +/** + * Simple Java 3D example program to display an .obj object with shader programs. + */ +public class ObjLoadGLSL extends javax.swing.JFrame +{ + + private String shaderName = "polkadot3d"; + private boolean spin = false; + private boolean noTriangulate = false; + private boolean noStripify = false; + private double creaseAngle = 60.0; + private URL filename = null; + + private SimpleUniverse univ = null; + private BranchGroup scene = null; + + public BranchGroup createSceneGraph() + { + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + + // Create a Transformgroup to scale all objects so they + // appear in the scene. + TransformGroup objScale = new TransformGroup(); + Transform3D t3d = new Transform3D(); + t3d.setScale(0.7); + objScale.setTransform(t3d); + objRoot.addChild(objScale); + + // Create the transform group node and initialize it to the + // identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at runtime. Add it to the + // root of the subgraph. + TransformGroup objTrans = new TransformGroup(); + objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); + objScale.addChild(objTrans); + + int flags = ObjectFile.RESIZE; + if (!noTriangulate) + flags |= ObjectFile.TRIANGULATE; + if (!noStripify) + flags |= ObjectFile.STRIPIFY; + ObjectFile f = new ObjectFile(flags, (float) (creaseAngle * Math.PI / 180.0)); + Scene s = null; + try + { + s = f.load(filename); + } + catch (FileNotFoundException e) + { + System.err.println(e); + System.exit(1); + } + catch (ParsingErrorException e) + { + System.err.println(e); + System.exit(1); + } + catch (IncorrectFormatException e) + { + System.err.println(e); + System.exit(1); + } + + // Set vertex and fragment shader program for all Shape3D nodes in scene + String vertexProgram = null; + String fragmentProgram = null; + try + { + vertexProgram = StringIO.readFully(new File( + System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/" + shaderName + ".vert")); + fragmentProgram = StringIO.readFully(new File( + System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/" + shaderName + ".frag")); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + Shader[] shaders = new Shader[2]; + shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); + shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); + ShaderProgram shaderProgram = new GLSLShaderProgram(); + shaderProgram.setShaders(shaders); + setShaderProgram(s.getSceneGroup(), shaderProgram); + + objTrans.addChild(s.getSceneGroup()); + + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + + if (spin) + { + Transform3D yAxis = new Transform3D(); + Alpha rotationAlpha = new Alpha(-1, Alpha.INCREASING_ENABLE, 0, 0, 4000, 0, 0, 0, 0, 0); + + RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, objTrans, yAxis, 0.0f, (float) Math.PI * 2.0f); + rotator.setSchedulingBounds(bounds); + objTrans.addChild(rotator); + } + + // Set up the background + Color3f bgColor = new Color3f(0.05f, 0.05f, 0.5f); + Background bgNode = new Background(bgColor); + bgNode.setApplicationBounds(bounds); + objRoot.addChild(bgNode); + + return objRoot; + } + + private Canvas3D createUniverse() + { + // Get the preferred graphics configuration for the default screen + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + // Create a Canvas3D using the preferred configuration + Canvas3D canvas3d = new Canvas3D(config); + + // Create simple universe with view branch + univ = new SimpleUniverse(canvas3d); + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + + // Add a ShaderErrorListener + univ.addShaderErrorListener(new ShaderErrorListener() { + public void errorOccurred(ShaderError error) + { + error.printVerbose(); + JOptionPane.showMessageDialog(ObjLoadGLSL.this, error.toString(), "ShaderError", JOptionPane.ERROR_MESSAGE); + } + }); + + // add mouse behaviors to the ViewingPlatform + ViewingPlatform viewingPlatform = univ.getViewingPlatform(); + + PlatformGeometry pg = new PlatformGeometry(); + + // Set up the ambient light + Color3f ambientColor = new Color3f(0.1f, 0.1f, 0.1f); + AmbientLight ambientLightNode = new AmbientLight(ambientColor); + ambientLightNode.setInfluencingBounds(bounds); + pg.addChild(ambientLightNode); + + // Set up the directional lights + Color3f light1Color = new Color3f(1.0f, 1.0f, 0.9f); + Vector3f light1Direction = new Vector3f(1.0f, 1.0f, 1.0f); + Color3f light2Color = new Color3f(1.0f, 1.0f, 1.0f); + Vector3f light2Direction = new Vector3f(-1.0f, -1.0f, -1.0f); + + DirectionalLight light1 = new DirectionalLight(light1Color, light1Direction); + light1.setInfluencingBounds(bounds); + pg.addChild(light1); + + DirectionalLight light2 = new DirectionalLight(light2Color, light2Direction); + light2.setInfluencingBounds(bounds); + pg.addChild(light2); + + viewingPlatform.setPlatformGeometry(pg); + + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + viewingPlatform.setNominalViewingTransform(); + + if (!spin) + { + OrbitBehavior orbit = new OrbitBehavior(canvas3d, OrbitBehavior.REVERSE_ALL); + orbit.setSchedulingBounds(bounds); + viewingPlatform.setViewPlatformBehavior(orbit); + } + + // Ensure at least 5 msec per frame (i.e., < 200Hz) + univ.getViewer().getView().setMinimumFrameCycleTime(5); + + return canvas3d; + } + + private void usage() + { + System.out.println("Usage: java ObjLoadGLSL [-s] [-S shaderName] [-n] [-t] [-c degrees] <.obj file>"); + System.out.println(" -s Spin (no user interaction)"); + System.out.println(" -S Set shader name (default is 'simple')"); + System.out.println(" -n No triangulation"); + System.out.println(" -t No stripification"); + System.out.println(" -c Set crease angle for normal generation (default is 60 without"); + System.out.println(" smoothing group info, otherwise 180 within smoothing groups)"); + System.exit(0); + } // End of usage + + // Set shader program for all nodes in specified branch graph + private void setShaderProgram(BranchGroup g, ShaderProgram shaderProgram) + { + ShaderAppearance myApp = new ShaderAppearance(); + Material mat = new Material(); + myApp.setShaderProgram(shaderProgram); + myApp.setMaterial(mat); + setShaderProgram(g, myApp); + } + + // Recursively set shader program for all children of specified group + private void setShaderProgram(Group g, ShaderAppearance myApp) + { + + Enumeration e = g.getAllChildren(); + while (e.hasMoreElements()) + { + Node n = (Node) (e.nextElement()); + if (n instanceof Group) + { + setShaderProgram((Group) n, myApp); + } + else if (n instanceof Shape3D) + { + Shape3D s = (Shape3D) n; + s.setAppearance(myApp); + } + } + } + + /** + * Creates new form ObjLoadGLSL + */ + public ObjLoadGLSL(String args[]) + { + if (args.length != 0) + { + for (int i = 0; i < args.length; i++) + { + if (args[i].startsWith("-")) + { + if (args[i].equals("-s")) + { + spin = true; + } + else if (args[i].equals("-n")) + { + noTriangulate = true; + } + else if (args[i].equals("-t")) + { + noStripify = true; + } + else if (args[i].equals("-c")) + { + if (i < args.length - 1) + { + creaseAngle = (new Double(args[++i])).doubleValue(); + } + else + usage(); + } + else if (args[i].equals("-S")) + { + if (i < args.length - 1) + { + shaderName = args[++i]; + } + else + usage(); + } + else + { + usage(); + } + } + else + { + try + { + if ((args[i].indexOf("file:") == 0) || (args[i].indexOf("http") == 0)) + { + filename = new URL(args[i]); + } + else if (args[i].charAt(0) != '/') + { + filename = new URL("file:./" + args[i]); + } + else + { + filename = new URL("file:" + args[i]); + } + } + catch (MalformedURLException e) + { + System.err.println(e); + System.exit(1); + } + } + } + } + + if (filename == null) + { + filename = Resources.getResource("resources/geometry/galleon.obj"); + if (filename == null) + { + System.err.println("resources/geometry/galleon.obj not found"); + System.exit(1); + } + } + + // Initialize the GUI components + initComponents(); + + // Create Canvas3D and SimpleUniverse; add canvas to drawing panel + Canvas3D c = createUniverse(); + drawingPanel.add(c, java.awt.BorderLayout.CENTER); + + // Create the content branch and add it to the universe + scene = createSceneGraph(); + univ.addBranchGraph(scene); + } + + // ---------------------------------------------------------------- + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents + private void initComponents() + { + drawingPanel = new javax.swing.JPanel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setTitle("ObjLoadGLSL"); + drawingPanel.setLayout(new java.awt.BorderLayout()); + + drawingPanel.setPreferredSize(new java.awt.Dimension(700, 700)); + getContentPane().add(drawingPanel, java.awt.BorderLayout.CENTER); + + pack(); + }// </editor-fold>//GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(final String args[]) + { + System.setProperty("sun.awt.noerasebackground", "true"); + System.setProperty("j3d.rend","jogl2es2"); + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() + { + ObjLoadGLSL objLoadGLSL = new ObjLoadGLSL(args); + objLoadGLSL.setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel drawingPanel; + // End of variables declaration//GEN-END:variables + +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/PhongShadingGLSL.form b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/PhongShadingGLSL.form new file mode 100644 index 0000000..dcccf73 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/PhongShadingGLSL.form @@ -0,0 +1,138 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.0" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> + <NonVisualComponents> + <Component class="javax.swing.ButtonGroup" name="shaderButtonGroup"> + </Component> + <Menu class="javax.swing.JMenuBar" name="jMenuBar1"> + <SubComponents> + <Menu class="javax.swing.JMenu" name="fileMenu"> + <Properties> + <Property name="text" type="java.lang.String" value="File"/> + </Properties> + <SubComponents> + <MenuItem class="javax.swing.JMenuItem" name="exitMenuItem"> + <Properties> + <Property name="text" type="java.lang.String" value="Exit"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="exitMenuItemActionPerformed"/> + </Events> + </MenuItem> + </SubComponents> + </Menu> + </SubComponents> + </Menu> + </NonVisualComponents> + <Properties> + <Property name="defaultCloseOperation" type="int" value="3"/> + <Property name="title" type="java.lang.String" value="Phong Shading Test"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="menuBar" type="java.lang.String" value="jMenuBar1"/> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + </SyntheticProperties> + <AuxValues> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="guiPanel"> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="North"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="jPanel1"> + <Properties> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo"> + <TitledBorder title="Shader"/> + </Border> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="4" insetsLeft="4" insetsBottom="4" insetsRight="4" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Component class="javax.swing.JRadioButton" name="gouraudButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="shaderButtonGroup"/> + </Property> + <Property name="selected" type="boolean" value="true"/> + <Property name="text" type="java.lang.String" value="Per-Vertex Lighting (Gouraud)"/> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo"> + <EmptyBorder bottom="0" left="0" right="0" top="0"/> + </Border> + </Property> + <Property name="margin" type="java.awt.Insets" editor="org.netbeans.beaninfo.editors.InsetsEditor"> + <Insets value="[0, 0, 0, 0]"/> + </Property> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="gouraudButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="2" insetsLeft="2" insetsBottom="2" insetsRight="2" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + <Component class="javax.swing.JRadioButton" name="phongButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="shaderButtonGroup"/> + </Property> + <Property name="text" type="java.lang.String" value="Per-Pixel Lighting (Phong)"/> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo"> + <EmptyBorder bottom="0" left="0" right="0" top="0"/> + </Border> + </Property> + <Property name="margin" type="java.awt.Insets" editor="org.netbeans.beaninfo.editors.InsetsEditor"> + <Insets value="[0, 0, 0, 0]"/> + </Property> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="phongButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="2" insetsLeft="2" insetsBottom="2" insetsRight="2" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + </SubComponents> + </Container> + </SubComponents> + </Container> + <Container class="javax.swing.JPanel" name="drawingPanel"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[500, 500]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + </Container> + </SubComponents> +</Form> diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/PhongShadingGLSL.java b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/PhongShadingGLSL.java new file mode 100644 index 0000000..03fbd3d --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/PhongShadingGLSL.java @@ -0,0 +1,501 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +package org.jdesktop.j3d.examples.gl2es2pipeline; + +import java.awt.GraphicsConfiguration; +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import javax.swing.JOptionPane; + +import org.jogamp.java3d.Alpha; +import org.jogamp.java3d.AmbientLight; +import org.jogamp.java3d.Appearance; +import org.jogamp.java3d.Background; +import org.jogamp.java3d.BoundingSphere; +import org.jogamp.java3d.BranchGroup; +import org.jogamp.java3d.Canvas3D; +import org.jogamp.java3d.ColoringAttributes; +import org.jogamp.java3d.DirectionalLight; +import org.jogamp.java3d.GLSLShaderProgram; +import org.jogamp.java3d.GeometryArray; +import org.jogamp.java3d.J3DBuffer; +import org.jogamp.java3d.Light; +import org.jogamp.java3d.Material; +import org.jogamp.java3d.PointLight; +import org.jogamp.java3d.RotationInterpolator; +import org.jogamp.java3d.Shader; +import org.jogamp.java3d.ShaderAppearance; +import org.jogamp.java3d.ShaderError; +import org.jogamp.java3d.ShaderErrorListener; +import org.jogamp.java3d.ShaderProgram; +import org.jogamp.java3d.SourceCodeShader; +import org.jogamp.java3d.SpotLight; +import org.jogamp.java3d.Transform3D; +import org.jogamp.java3d.TransformGroup; +import org.jogamp.java3d.TriangleStripArray; +import org.jogamp.java3d.utils.geometry.Sphere; +import org.jogamp.java3d.utils.shader.StringIO; +import org.jogamp.java3d.utils.universe.SimpleUniverse; +import org.jogamp.vecmath.Color3f; +import org.jogamp.vecmath.Point3d; +import org.jogamp.vecmath.Point3f; +import org.jogamp.vecmath.Vector3d; +import org.jogamp.vecmath.Vector3f; + +/** + * + * @author kcr + */ +public class PhongShadingGLSL extends javax.swing.JFrame +{ + + // Constants for type of light to use + private static final int DIRECTIONAL_LIGHT = 0; + private static final int POINT_LIGHT = 1; + private static final int SPOT_LIGHT = 2; + + // Flag indicates type of lights: directional, point, or spot lights. + private static int lightType = DIRECTIONAL_LIGHT; + + private SimpleUniverse univ = null; + + private ShaderAppearance sApp = null; + private ShaderProgram gouraudSP = null; + private ShaderProgram phongSP = null; + + public BranchGroup createSceneGraph() + { + Color3f eColor = new Color3f(0.0f, 0.0f, 0.0f); + Color3f sColor = new Color3f(1.0f, 1.0f, 1.0f); + Color3f objColor = new Color3f(0.6f, 0.6f, 0.6f); + // Color3f lColor1 = new Color3f(1.0f, 0.0f, 0.0f); + // Color3f lColor2 = new Color3f(0.0f, 1.0f, 0.0f); + Color3f lColor1 = new Color3f(1.0f, 1.0f, 0.5f); + Color3f alColor = new Color3f(0.2f, 0.2f, 0.2f); + Color3f bgColor = new Color3f(0.05f, 0.05f, 0.2f); + + Transform3D t; + + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + + // Create a Transformgroup to scale all objects so they + // appear in the scene. + TransformGroup objScale = new TransformGroup(); + Transform3D t3d = new Transform3D(); + t3d.setScale(0.5); + objScale.setTransform(t3d); + objRoot.addChild(objScale); + + // Create a bounds for the background and lights + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + + // Set up the background + Background bg = new Background(bgColor); + bg.setApplicationBounds(bounds); + objRoot.addChild(bg); + + // Create the TransformGroup node and initialize it to the + // identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at run time. Add it to + // the root of the subgraph. + TransformGroup objTrans = new TransformGroup(); + objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objScale.addChild(objTrans); + + // Create a Sphere object, generate one copy of the sphere, + // and add it into the scene graph. + sApp = new ShaderAppearance(); + sApp.setCapability(ShaderAppearance.ALLOW_SHADER_PROGRAM_WRITE); + Material m = new Material(objColor, eColor, objColor, sColor, 100.0f); + sApp.setMaterial(m); + + // Create Gouraud and Phong shader programs + String vertexProgram = null; + String fragmentProgram = null; + Shader[] shaders = new Shader[2]; + String[] attrNames = { "numLights" }; + + try + { + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/gouraud.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/gouraud.frag")); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); + shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); + gouraudSP = new GLSLShaderProgram(); + gouraudSP.setShaders(shaders); + + try + { + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/phong.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/phong.frag")); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); + shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); + phongSP = new GLSLShaderProgram(); + phongSP.setShaders(shaders); + + if (gouraudButton.isSelected()) + { + sApp.setShaderProgram(gouraudSP); + } + else if (phongButton.isSelected()) + { + sApp.setShaderProgram(phongSP); + } + Sphere sph = new Sphere(1.0f, Sphere.GENERATE_NORMALS, 30, sApp); + SphereGLSL.makeNIO(sph); + objTrans.addChild(sph); + + // Create a new Behavior object that will perform the + // desired operation on the specified transform and add + // it into the scene graph. + Transform3D yAxis = new Transform3D(); + yAxis.rotZ(Math.PI); + Alpha rotationAlpha = new Alpha(-1, 10000); + + RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, objTrans, yAxis, 0.0f, (float) Math.PI * 2.0f); + rotator.setSchedulingBounds(bounds); + objRoot.addChild(rotator); + + // Create the transform group node for the each light and initialize + // it to the identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at runtime. Add them to the root + // of the subgraph. + TransformGroup l1RotTrans = new TransformGroup(); + l1RotTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objScale.addChild(l1RotTrans); + + TransformGroup l2RotTrans = new TransformGroup(); + l2RotTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objScale.addChild(l2RotTrans); + + // Create transformations for the positional lights + t = new Transform3D(); + Vector3d lPos1 = new Vector3d(0.0, 0.0, 2.0); + t.set(lPos1); + TransformGroup l1Trans = new TransformGroup(t); + l1RotTrans.addChild(l1Trans); + + // t = new Transform3D(); + // Vector3d lPos2 = new Vector3d(0.5, 0.8, 2.0); + // t.set(lPos2); + // TransformGroup l2Trans = new TransformGroup(t); + // l2RotTrans.addChild(l2Trans); + + // Create Geometry for point lights + ColoringAttributes caL1 = new ColoringAttributes(); + // ColoringAttributes caL2 = new ColoringAttributes(); + caL1.setColor(lColor1); + // caL2.setColor(lColor2); + Appearance appL1 = new Appearance(); + // Appearance appL2 = new Appearance(); + appL1.setColoringAttributes(caL1); + // appL2.setColoringAttributes(caL2); + + Sphere sph2 = new Sphere(0.05f, appL1); + SphereGLSL.makeNIO(sph2); + l1Trans.addChild(sph2); + // l2Trans.addChild(new Sphere(0.05f, appL2)); + + // Create lights + AmbientLight aLgt = new AmbientLight(alColor); + + Light lgt1 = null; + // Light lgt2 = null; + + Point3f lPoint = new Point3f(0.0f, 0.0f, 0.0f); + Point3f atten = new Point3f(1.0f, 0.0f, 0.0f); + Vector3f lDirect1 = new Vector3f(lPos1); + // Vector3f lDirect2 = new Vector3f(lPos2); + lDirect1.negate(); + // lDirect2.negate(); + + switch (lightType) + { + case DIRECTIONAL_LIGHT: + lgt1 = new DirectionalLight(lColor1, lDirect1); + // lgt2 = new DirectionalLight(lColor2, lDirect2); + break; + case POINT_LIGHT: + assert false : "can't get here"; + lgt1 = new PointLight(lColor1, lPoint, atten); + // lgt2 = new PointLight(lColor2, lPoint, atten); + break; + case SPOT_LIGHT: + assert false : "can't get here"; + lgt1 = new SpotLight(lColor1, lPoint, atten, lDirect1, 25.0f * (float) Math.PI / 180.0f, 10.0f); + // lgt2 = new SpotLight(lColor2, lPoint, atten, lDirect2, + // 25.0f * (float)Math.PI / 180.0f, 10.0f); + break; + } + + // Set the influencing bounds + aLgt.setInfluencingBounds(bounds); + lgt1.setInfluencingBounds(bounds); + // lgt2.setInfluencingBounds(bounds); + + // Add the lights into the scene graph + objScale.addChild(aLgt); + l1Trans.addChild(lgt1); + // l2Trans.addChild(lgt2); + + // Create a new Behavior object that will perform the desired + // operation on the specified transform object and add it into the + // scene graph. + yAxis = new Transform3D(); + Alpha rotor1Alpha = new Alpha(-1, Alpha.INCREASING_ENABLE, 0, 0, 4000, 0, 0, 0, 0, 0); + RotationInterpolator rotator1 = new RotationInterpolator(rotor1Alpha, l1RotTrans, yAxis, 0.0f, (float) Math.PI * 2.0f); + rotator1.setSchedulingBounds(bounds); + l1RotTrans.addChild(rotator1); + + // Create a new Behavior object that will perform the desired + // operation on the specified transform object and add it into the + // scene graph. + Alpha rotor2Alpha = new Alpha(-1, Alpha.INCREASING_ENABLE, 0, 0, 1000, 0, 0, 0, 0, 0); + RotationInterpolator rotator2 = new RotationInterpolator(rotor2Alpha, l2RotTrans, yAxis, 0.0f, 0.0f); + bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + rotator2.setSchedulingBounds(bounds); + l2RotTrans.addChild(rotator2); + + return objRoot; + } + + + + private Canvas3D initScene() + { + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + Canvas3D c = new Canvas3D(config); + + univ = new SimpleUniverse(c); + + // Add a ShaderErrorListener + univ.addShaderErrorListener(new ShaderErrorListener() { + public void errorOccurred(ShaderError error) + { + error.printVerbose(); + JOptionPane.showMessageDialog(PhongShadingGLSL.this, error.toString(), "ShaderError", JOptionPane.ERROR_MESSAGE); + } + }); + + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + univ.getViewingPlatform().setNominalViewingTransform(); + + BranchGroup scene = createSceneGraph(); + univ.addBranchGraph(scene); + + return c; + } + + /** + * Creates new form PhongShadingGLSL + */ + public PhongShadingGLSL() + { + // Initialize the GUI components + initComponents(); + + // Create the scene and add the Canvas3D to the drawing panel + Canvas3D c = initScene(); + drawingPanel.add(c, java.awt.BorderLayout.CENTER); + } + + // ---------------------------------------------------------------- + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents + private void initComponents() + { + java.awt.GridBagConstraints gridBagConstraints; + + shaderButtonGroup = new javax.swing.ButtonGroup(); + guiPanel = new javax.swing.JPanel(); + jPanel1 = new javax.swing.JPanel(); + gouraudButton = new javax.swing.JRadioButton(); + phongButton = new javax.swing.JRadioButton(); + drawingPanel = new javax.swing.JPanel(); + jMenuBar1 = new javax.swing.JMenuBar(); + fileMenu = new javax.swing.JMenu(); + exitMenuItem = new javax.swing.JMenuItem(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setTitle("Phong Shading Test"); + guiPanel.setLayout(new java.awt.GridBagLayout()); + + jPanel1.setLayout(new java.awt.GridBagLayout()); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Shader")); + shaderButtonGroup.add(gouraudButton); + gouraudButton.setSelected(true); + gouraudButton.setText("Per-Vertex Lighting (Gouraud)"); + gouraudButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + gouraudButton.setMargin(new java.awt.Insets(0, 0, 0, 0)); + gouraudButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + gouraudButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); + jPanel1.add(gouraudButton, gridBagConstraints); + + shaderButtonGroup.add(phongButton); + phongButton.setText("Per-Pixel Lighting (Phong)"); + phongButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + phongButton.setMargin(new java.awt.Insets(0, 0, 0, 0)); + phongButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + phongButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 1; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); + jPanel1.add(phongButton, gridBagConstraints); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); + guiPanel.add(jPanel1, gridBagConstraints); + + getContentPane().add(guiPanel, java.awt.BorderLayout.NORTH); + + drawingPanel.setLayout(new java.awt.BorderLayout()); + + drawingPanel.setPreferredSize(new java.awt.Dimension(500, 500)); + getContentPane().add(drawingPanel, java.awt.BorderLayout.CENTER); + + fileMenu.setText("File"); + exitMenuItem.setText("Exit"); + exitMenuItem.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + exitMenuItemActionPerformed(evt); + } + }); + + fileMenu.add(exitMenuItem); + + jMenuBar1.add(fileMenu); + + setJMenuBar(jMenuBar1); + + pack(); + }// </editor-fold>//GEN-END:initComponents + + private void phongButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_phongButtonActionPerformed + sApp.setShaderProgram(phongSP); + }//GEN-LAST:event_phongButtonActionPerformed + + private void gouraudButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_gouraudButtonActionPerformed + sApp.setShaderProgram(gouraudSP); + }//GEN-LAST:event_gouraudButtonActionPerformed + + private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_exitMenuItemActionPerformed + System.exit(0); + }//GEN-LAST:event_exitMenuItemActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) + { + System.setProperty("sun.awt.noerasebackground", "true"); + System.setProperty("j3d.rend", "jogl2es2"); + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() + { + new PhongShadingGLSL().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel drawingPanel; + private javax.swing.JMenuItem exitMenuItem; + private javax.swing.JMenu fileMenu; + private javax.swing.JRadioButton gouraudButton; + private javax.swing.JPanel guiPanel; + private javax.swing.JMenuBar jMenuBar1; + private javax.swing.JPanel jPanel1; + private javax.swing.JRadioButton phongButton; + private javax.swing.ButtonGroup shaderButtonGroup; + // End of variables declaration//GEN-END:variables + +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SamplerTestGLSL.form b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SamplerTestGLSL.form new file mode 100644 index 0000000..6a1a031 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SamplerTestGLSL.form @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.0" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> + <Properties> + <Property name="defaultCloseOperation" type="int" value="3"/> + <Property name="title" type="java.lang.String" value="SamplerTestGLSL"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + </SyntheticProperties> + <AuxValues> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="drawingPanel"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[500, 500]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + </Container> + </SubComponents> +</Form> diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SamplerTestGLSL.java b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SamplerTestGLSL.java new file mode 100644 index 0000000..c641095 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SamplerTestGLSL.java @@ -0,0 +1,289 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +package org.jdesktop.j3d.examples.gl2es2pipeline; + +import java.awt.GraphicsConfiguration; +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import javax.swing.JOptionPane; + +import org.jdesktop.j3d.examples.Resources; +import org.jogamp.java3d.Alpha; +import org.jogamp.java3d.BoundingSphere; +import org.jogamp.java3d.BranchGroup; +import org.jogamp.java3d.Canvas3D; +import org.jogamp.java3d.GLSLShaderProgram; +import org.jogamp.java3d.GeometryArray; +import org.jogamp.java3d.J3DBuffer; +import org.jogamp.java3d.RotationInterpolator; +import org.jogamp.java3d.Shader; +import org.jogamp.java3d.ShaderAppearance; +import org.jogamp.java3d.ShaderAttribute; +import org.jogamp.java3d.ShaderAttributeSet; +import org.jogamp.java3d.ShaderAttributeValue; +import org.jogamp.java3d.ShaderError; +import org.jogamp.java3d.ShaderErrorListener; +import org.jogamp.java3d.ShaderProgram; +import org.jogamp.java3d.SourceCodeShader; +import org.jogamp.java3d.TexCoordGeneration; +import org.jogamp.java3d.Texture; +import org.jogamp.java3d.TextureUnitState; +import org.jogamp.java3d.Transform3D; +import org.jogamp.java3d.TransformGroup; +import org.jogamp.java3d.TriangleStripArray; +import org.jogamp.java3d.utils.geometry.Sphere; +import org.jogamp.java3d.utils.image.TextureLoader; +import org.jogamp.java3d.utils.shader.StringIO; +import org.jogamp.java3d.utils.universe.SimpleUniverse; +import org.jogamp.java3d.utils.universe.ViewingPlatform; +import org.jogamp.vecmath.Point3d; +import org.jogamp.vecmath.Vector4f; + +public class SamplerTestGLSL extends javax.swing.JFrame +{ + + private static String cloudTexName = "resources/images/bg.jpg"; + private static String earthTexName = "resources/images/earth.jpg"; + + private URL cloudURL = null; + private URL earthURL = null; + private static final int CLOUD = 0; + private static final int EARTH = 1; + + SimpleUniverse univ = null; + + public BranchGroup createSceneGraph() + { + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + + // Create the TransformGroup node and initialize it to the + // identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at run time. Add it to + // the root of the subgraph. + TransformGroup objTrans = new TransformGroup(); + objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objRoot.addChild(objTrans); + + // Create texture objects + cloudURL = Resources.getResource(cloudTexName); + Texture cloudTex = new TextureLoader(cloudURL, this).getTexture(); + earthURL = Resources.getResource(earthTexName); + Texture earthTex = new TextureLoader(earthURL, this).getTexture(); + + // Create the shader program + String vertexProgram = null; + String fragmentProgram = null; + try + { + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/multitex.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/multitex.frag")); + } + catch (IOException e) + { + System.err.println(e); + } + Shader[] shaders = new Shader[2]; + shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); + shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); + final String[] shaderAttrNames = { "cloudFactor", "cloudTex", "earthTex", }; + final Object[] shaderAttrValues = { new Float(0.6f), new Integer(0), new Integer(1), }; + ShaderProgram shaderProgram = new GLSLShaderProgram(); + shaderProgram.setShaders(shaders); + shaderProgram.setShaderAttrNames(shaderAttrNames); + + // Create the shader attribute set + ShaderAttributeSet shaderAttributeSet = new ShaderAttributeSet(); + for (int i = 0; i < shaderAttrNames.length; i++) + { + ShaderAttribute shaderAttribute = new ShaderAttributeValue(shaderAttrNames[i], shaderAttrValues[i]); + shaderAttributeSet.put(shaderAttribute); + } + + // Create shader appearance to hold the shader program and + // shader attributes + ShaderAppearance app = new ShaderAppearance(); + app.setShaderProgram(shaderProgram); + app.setShaderAttributeSet(shaderAttributeSet); + + // GL2ES2: Tex coord gen done in shader now + //Vector4f plane0S = new Vector4f(3.0f, 1.5f, 0.3f, 0.0f); + //Vector4f plane0T = new Vector4f(1.0f, 2.5f, 0.24f, 0.0f); + //TexCoordGeneration tcg0 = new TexCoordGeneration(TexCoordGeneration.OBJECT_LINEAR, TexCoordGeneration.TEXTURE_COORDINATE_2, plane0S, + // plane0T); + //TexCoordGeneration tcg1 = new TexCoordGeneration(TexCoordGeneration.SPHERE_MAP, TexCoordGeneration.TEXTURE_COORDINATE_2); + + // Put the textures in unit 0,1 + TextureUnitState[] tus = new TextureUnitState[2]; + tus[CLOUD] = new TextureUnitState(); + tus[CLOUD].setTexture(cloudTex); + + // GL2ES2: Tex coord gen done in shader now + //tus[CLOUD].setTexCoordGeneration(tcg0); + + tus[EARTH] = new TextureUnitState(); + tus[EARTH].setTexture(earthTex); + + // GL2ES2: Tex coord gen done in shader now + //tus[EARTH].setTexCoordGeneration(tcg1); + + app.setTextureUnitState(tus); + + // Create a Sphere object using the shader appearance, + // and add it into the scene graph. + Sphere sph = new Sphere(0.4f, Sphere.GENERATE_NORMALS, 30, app); + + SphereGLSL.makeNIO(sph); + objTrans.addChild(sph); + + + // Create a new Behavior object that will perform the + // desired operation on the specified transform and add + // it into the scene graph. + Transform3D yAxis = new Transform3D(); + Alpha rotationAlpha = new Alpha(-1, 4000); + + RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, objTrans, yAxis, 0.0f, (float) Math.PI * 2.0f); + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + rotator.setSchedulingBounds(bounds); + objRoot.addChild(rotator); + + // Have Java 3D perform optimizations on this scene graph. + //objRoot.compile(); + + return objRoot; + } + + + private Canvas3D initScene() + { + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + Canvas3D c = new Canvas3D(config); + + BranchGroup scene = createSceneGraph(); + univ = new SimpleUniverse(c); + + // Add a ShaderErrorListener + univ.addShaderErrorListener(new ShaderErrorListener() { + public void errorOccurred(ShaderError error) + { + error.printVerbose(); + JOptionPane.showMessageDialog(SamplerTestGLSL.this, error.toString(), "ShaderError", JOptionPane.ERROR_MESSAGE); + } + }); + + ViewingPlatform viewingPlatform = univ.getViewingPlatform(); + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + viewingPlatform.setNominalViewingTransform(); + + univ.addBranchGraph(scene); + + return c; + } + + /** + * Creates new form SamplerTestGLSL + */ + public SamplerTestGLSL() + { + // Initialize the GUI components + initComponents(); + + // Create the scene and add the Canvas3D to the drawing panel + Canvas3D c = initScene(); + drawingPanel.add(c, java.awt.BorderLayout.CENTER); + } + + // ---------------------------------------------------------------- + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents + private void initComponents() + { + drawingPanel = new javax.swing.JPanel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setTitle("SamplerTestGLSL"); + drawingPanel.setLayout(new java.awt.BorderLayout()); + + drawingPanel.setPreferredSize(new java.awt.Dimension(500, 500)); + getContentPane().add(drawingPanel, java.awt.BorderLayout.CENTER); + + pack(); + }// </editor-fold>//GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) + { + System.setProperty("sun.awt.noerasebackground", "true"); + System.setProperty("j3d.rend","jogl2es2"); + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() + { + new SamplerTestGLSL().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel drawingPanel; + // End of variables declaration//GEN-END:variables + +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ShaderTestGLSL.form b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ShaderTestGLSL.form new file mode 100644 index 0000000..714273d --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ShaderTestGLSL.form @@ -0,0 +1,266 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.2" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> + <NonVisualComponents> + <Component class="javax.swing.ButtonGroup" name="densityButtonGroup"> + </Component> + <Component class="javax.swing.ButtonGroup" name="colorButtonGroup"> + </Component> + <Component class="javax.swing.ButtonGroup" name="sceneGraphButtonGroup"> + </Component> + <Menu class="javax.swing.JMenuBar" name="jMenuBar1"> + <SubComponents> + <Menu class="javax.swing.JMenu" name="fileMenu"> + <Properties> + <Property name="text" type="java.lang.String" value="File"/> + </Properties> + <SubComponents> + <MenuItem class="javax.swing.JMenuItem" name="exitMenuItem"> + <Properties> + <Property name="text" type="java.lang.String" value="Exit"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="exitMenuItemActionPerformed"/> + </Events> + </MenuItem> + </SubComponents> + </Menu> + </SubComponents> + </Menu> + </NonVisualComponents> + <Properties> + <Property name="title" type="java.lang.String" value="Window Title"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="menuBar" type="java.lang.String" value="jMenuBar1"/> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + </SyntheticProperties> + <Events> + <EventHandler event="windowClosing" listener="java.awt.event.WindowListener" parameters="java.awt.event.WindowEvent" handler="exitForm"/> + </Events> + <AuxValues> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,-85,0,0,2,0"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="mainPanel"> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="guiPanel"> + <Properties> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.LineBorderInfo"> + <LineBorder/> + </Border> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="North"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBoxLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="densityPanel"> + <Properties> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo"> + <TitledBorder title="Density"/> + </Border> + </Property> + </Properties> + <AccessibilityProperties> + <Property name="AccessibleContext.accessibleName" type="java.lang.String" value="ShaderAttributeValue 
"/> + </AccessibilityProperties> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Component class="javax.swing.JRadioButton" name="zeroButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="densityButtonGroup"/> + </Property> + <Property name="text" type="java.lang.String" value="Zero"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="zeroButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + <Component class="javax.swing.JRadioButton" name="halfButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="densityButtonGroup"/> + </Property> + <Property name="text" type="java.lang.String" value="Half"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="halfButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + <Component class="javax.swing.JRadioButton" name="fullButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="densityButtonGroup"/> + </Property> + <Property name="selected" type="boolean" value="true"/> + <Property name="text" type="java.lang.String" value="Full"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="fullButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="2" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + </SubComponents> + </Container> + <Container class="javax.swing.JPanel" name="colorPanel"> + <Properties> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo"> + <TitledBorder title="Color"/> + </Border> + </Property> + </Properties> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Component class="javax.swing.JRadioButton" name="goldButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="colorButtonGroup"/> + </Property> + <Property name="selected" type="boolean" value="true"/> + <Property name="text" type="java.lang.String" value="Gold"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="goldButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + <Component class="javax.swing.JRadioButton" name="silverButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="colorButtonGroup"/> + </Property> + <Property name="text" type="java.lang.String" value="Silver"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="silverButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + </SubComponents> + </Container> + <Container class="javax.swing.JPanel" name="sceneGraphPanel"> + <Properties> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo"> + <TitledBorder title="Scene Graph"/> + </Border> + </Property> + </Properties> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Component class="javax.swing.JToggleButton" name="DetachButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="sceneGraphButtonGroup"/> + </Property> + <Property name="selected" type="boolean" value="true"/> + <Property name="text" type="java.lang.String" value="Detach"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="DetachButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + <Component class="javax.swing.JToggleButton" name="AttachButton"> + <Properties> + <Property name="buttonGroup" type="javax.swing.ButtonGroup" editor="org.netbeans.modules.form.RADComponent$ButtonGroupPropertyEditor"> + <ComponentRef name="sceneGraphButtonGroup"/> + </Property> + <Property name="text" type="java.lang.String" value="Create"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="AttachButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + <Component class="javax.swing.JButton" name="replaceSPButton"> + <Properties> + <Property name="text" type="java.lang.String" value="Replace Shader"/> + <Property name="enabled" type="boolean" value="false"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="replaceSPButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="2" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + </SubComponents> + </Container> + </SubComponents> + </Container> + <Container class="javax.swing.JPanel" name="drawingPanel"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[500, 500]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + </Container> + </SubComponents> + </Container> + </SubComponents> +</Form> diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ShaderTestGLSL.java b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ShaderTestGLSL.java new file mode 100644 index 0000000..65f40bb --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/ShaderTestGLSL.java @@ -0,0 +1,745 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +package org.jdesktop.j3d.examples.gl2es2pipeline; + +import java.awt.GraphicsConfiguration; +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import javax.swing.JOptionPane; + +import org.jogamp.java3d.Alpha; +import org.jogamp.java3d.Background; +import org.jogamp.java3d.BoundingSphere; +import org.jogamp.java3d.BranchGroup; +import org.jogamp.java3d.Canvas3D; +import org.jogamp.java3d.GLSLShaderProgram; +import org.jogamp.java3d.GeometryArray; +import org.jogamp.java3d.J3DBuffer; +import org.jogamp.java3d.Material; +import org.jogamp.java3d.PositionInterpolator; +import org.jogamp.java3d.Shader; +import org.jogamp.java3d.ShaderAppearance; +import org.jogamp.java3d.ShaderAttributeObject; +import org.jogamp.java3d.ShaderAttributeSet; +import org.jogamp.java3d.ShaderAttributeValue; +import org.jogamp.java3d.ShaderError; +import org.jogamp.java3d.ShaderErrorListener; +import org.jogamp.java3d.ShaderProgram; +import org.jogamp.java3d.Shape3D; +import org.jogamp.java3d.SourceCodeShader; +import org.jogamp.java3d.Transform3D; +import org.jogamp.java3d.TransformGroup; +import org.jogamp.java3d.TriangleStripArray; +import org.jogamp.java3d.View; +import org.jogamp.java3d.utils.geometry.Sphere; +import org.jogamp.java3d.utils.shader.StringIO; +import org.jogamp.java3d.utils.universe.SimpleUniverse; +import org.jogamp.java3d.utils.universe.ViewingPlatform; +import org.jogamp.vecmath.Color3f; +import org.jogamp.vecmath.Point3d; +import org.jogamp.vecmath.Point3f; +import org.jogamp.vecmath.Vector3d; + +public class ShaderTestGLSL extends javax.swing.JFrame +{ + + static final int GOLD = 1; + static final int SILVER = 2; + + static final int DIMPLE_SHADER = 1; + static final int BRICK_SHADER = 2; + static final int WOOD_SHADER = 3; + static final int POLKADOT3D_SHADER = 4; + + static final String[] shaderAttrNames1 = { "Density", "Size", "LightPosition", "Color" }; + + static final String[] shaderAttrNames2 = { "BrickColor", "LightPosition" }; + + private SimpleUniverse univ = null; + private View view; + private BranchGroup transpObj; + private BranchGroup scene = null; + private int shaderSelected = DIMPLE_SHADER; + private float density = 16.0f; + private int color = GOLD; + + private Color3f eColor = new Color3f(0.2f, 0.2f, 0.2f); + private Color3f sColor = new Color3f(0.8f, 0.8f, 0.8f); + private Color3f objColor = new Color3f(0.6f, 0.6f, 0.6f); + private Color3f bgColor = new Color3f(0.05f, 0.05f, 0.2f); + private Color3f gold = new Color3f(0.7f, 0.6f, 0.18f); + private Color3f silver = new Color3f(0.75f, 0.75f, 0.75f); + + // Handlers for doing update + private ShaderAppearance sApp1 = null; + private ShaderAppearance sApp2 = null; + private ShaderAppearance sApp3 = null; + private ShaderAppearance sApp4 = null; + private ShaderProgram sp1 = null; + private ShaderProgram sp2 = null; + private ShaderProgram sp3 = null; + private ShaderProgram sp4 = null; + private ShaderAttributeSet sas1 = null; + private ShaderAttributeSet sas2 = null; + private ShaderAttributeObject sao1 = null; + private ShaderAttributeObject sao2 = null; + private Sphere sphere = null; + private Shape3D s3d = null; + + private Material createMaterial() + { + Material m; + m = new Material(objColor, eColor, objColor, sColor, 100.0f); + m.setLightingEnable(true); + return m; + } + + private ShaderProgram createGLSLShaderProgram(int index) + { + String vertexProgram = null; + String fragmentProgram = null; + + try + { + switch (index) + { + case DIMPLE_SHADER: + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/dimple.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/dimple.frag")); + break; + case BRICK_SHADER: + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/aabrick.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/aabrick.frag")); + break; + case WOOD_SHADER: + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/wood.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/wood.frag")); + break; + case POLKADOT3D_SHADER: + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/polkadot3d.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/polkadot3d.frag")); + break; + default: + } + } + catch (IOException e) + { + throw new RuntimeException(e); + } + Shader[] shaders = new Shader[2]; + shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); + shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); + ShaderProgram shaderProgram = new GLSLShaderProgram(); + shaderProgram.setShaders(shaders); + return shaderProgram; + } + + private ShaderAttributeSet createShaderAttributeSet(int index) + { + ShaderAttributeSet shaderAttributeSet = new ShaderAttributeSet(); + ShaderAttributeObject shaderAttribute = null; + + switch (index) + { + case DIMPLE_SHADER: + // "Density", "Size", "Scale", "Color", "LightPosition" + shaderAttribute = new ShaderAttributeValue("Size", new Float(0.25)); + shaderAttributeSet.put(shaderAttribute); + shaderAttribute = new ShaderAttributeValue("LightPosition", new Point3f(0.0f, 0.0f, 0.5f)); + shaderAttributeSet.put(shaderAttribute); + + sao1 = new ShaderAttributeValue("Density", new Float(density)); + sao1.setCapability(ShaderAttributeObject.ALLOW_VALUE_READ); + sao1.setCapability(ShaderAttributeObject.ALLOW_VALUE_WRITE); + shaderAttributeSet.put(sao1); + + if (color == GOLD) + { + sao2 = new ShaderAttributeValue("Color", gold); + } + else if (color == SILVER) + { + sao2 = new ShaderAttributeValue("Color", silver); + } + sao2.setCapability(ShaderAttributeObject.ALLOW_VALUE_READ); + sao2.setCapability(ShaderAttributeObject.ALLOW_VALUE_WRITE); + shaderAttributeSet.put(sao2); + break; + + case BRICK_SHADER: + // "BrickColor", "LightPosition" + shaderAttribute = new ShaderAttributeValue("BrickColor", new Color3f(1.0f, 0.3f, 0.2f)); + shaderAttributeSet.put(shaderAttribute); + shaderAttribute = new ShaderAttributeValue("LightPosition", new Point3f(0.0f, 0.0f, 0.5f)); + shaderAttributeSet.put(shaderAttribute); + break; + default: + assert false; + } + return shaderAttributeSet; + } + + private ShaderAppearance createShaderAppearance() + { + ShaderAppearance sApp = new ShaderAppearance(); + sApp.setMaterial(createMaterial()); + return sApp; + } + + private BranchGroup createSubSceneGraph() + { + // Create the sub-root of the branch graph + BranchGroup subRoot = new BranchGroup(); + + // + // Create 1 spheres with a GLSLShader and add it into the scene graph. + // + sApp1 = createShaderAppearance(); + sApp1.setCapability(ShaderAppearance.ALLOW_SHADER_PROGRAM_READ); + sApp1.setCapability(ShaderAppearance.ALLOW_SHADER_PROGRAM_WRITE); + sApp1.setCapability(ShaderAppearance.ALLOW_SHADER_ATTRIBUTE_SET_READ); + sApp1.setCapability(ShaderAppearance.ALLOW_SHADER_ATTRIBUTE_SET_WRITE); + + sp1 = createGLSLShaderProgram(1); + sp1.setShaderAttrNames(shaderAttrNames1); + sas1 = createShaderAttributeSet(1); + sas1.setCapability(ShaderAttributeSet.ALLOW_ATTRIBUTES_READ); + sas1.setCapability(ShaderAttributeSet.ALLOW_ATTRIBUTES_WRITE); + sApp1.setShaderProgram(sp1); + sApp1.setShaderAttributeSet(sas1); + + // Setup Brick shader + sp2 = createGLSLShaderProgram(2); + sp2.setShaderAttrNames(shaderAttrNames2); + sas2 = createShaderAttributeSet(2); + sApp2 = createShaderAppearance(); + sApp2.setShaderProgram(sp2); + sApp2.setShaderAttributeSet(sas2); + + // Setup Wood shader + sp3 = createGLSLShaderProgram(3); + sApp3 = createShaderAppearance(); + sApp3.setShaderProgram(sp3); + + // Setup Polkadot3d shader + sp4 = createGLSLShaderProgram(4); + sApp4 = createShaderAppearance(); + sApp4.setShaderProgram(sp4); + + sphere = new Sphere(1.5f, Sphere.GENERATE_NORMALS, 200, null); + SphereGLSL.makeNIO(sphere); + s3d = sphere.getShape(); + s3d.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + s3d.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + s3d.setAppearance(sApp1); + + TransformGroup objTG; + Transform3D t = new Transform3D(); + t.set(new Vector3d(0.0, 0.0, 0.0)); + objTG = new TransformGroup(t); + objTG.addChild(sphere); + subRoot.addChild(objTG); + + return subRoot; + } + + + private BranchGroup createSceneGraph(int selectedScene) + { + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + objRoot.setCapability(BranchGroup.ALLOW_DETACH); + + // Create a Transformgroup to scale all objects so they + // appear in the scene. + TransformGroup objScale = new TransformGroup(); + Transform3D t3d = new Transform3D(); + t3d.setScale(0.4); + objScale.setTransform(t3d); + objRoot.addChild(objScale); + + // Create a bounds for the background and lights + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + + // Set up the background + Background bg = new Background(bgColor); + bg.setApplicationBounds(bounds); + objScale.addChild(bg); + + objScale.addChild(createSubSceneGraph()); + + // Create a position interpolator and attach it to the view + // platform + TransformGroup vpTrans = univ.getViewingPlatform().getViewPlatformTransform(); + Transform3D axisOfTranslation = new Transform3D(); + Alpha transAlpha = new Alpha(-1, Alpha.INCREASING_ENABLE | Alpha.DECREASING_ENABLE, 0, 0, 5000, 0, 0, 5000, 0, 0); + axisOfTranslation.rotY(-Math.PI / 2.0); + PositionInterpolator translator = new PositionInterpolator(transAlpha, vpTrans, axisOfTranslation, 2.0f, 3.5f); + translator.setSchedulingBounds(bounds); + objScale.addChild(translator); + + // Let Java 3D perform optimizations on this scene graph. + objRoot.compile(); + + return objRoot; + } + + private Canvas3D initScene() + { + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + Canvas3D c = new Canvas3D(config); + + univ = new SimpleUniverse(c); + + // Add a ShaderErrorListener + univ.addShaderErrorListener(new ShaderErrorListener() { + public void errorOccurred(ShaderError error) + { + error.printVerbose(); + JOptionPane.showMessageDialog(ShaderTestGLSL.this, error.toString(), "ShaderError", JOptionPane.ERROR_MESSAGE); + } + }); + + ViewingPlatform viewingPlatform = univ.getViewingPlatform(); + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + viewingPlatform.setNominalViewingTransform(); + + view = univ.getViewer().getView(); + + return c; + } + + /** + * Creates new form ShaderTestGLSL + */ + public ShaderTestGLSL() + { + // Initialize the GUI components + initComponents(); + + // Create the scene and add the Canvas3D to the drawing panel + Canvas3D c = initScene(); + drawingPanel.add(c, java.awt.BorderLayout.CENTER); + } + + // ---------------------------------------------------------------- + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents + private void initComponents() + { + java.awt.GridBagConstraints gridBagConstraints; + + densityButtonGroup = new javax.swing.ButtonGroup(); + colorButtonGroup = new javax.swing.ButtonGroup(); + sceneGraphButtonGroup = new javax.swing.ButtonGroup(); + mainPanel = new javax.swing.JPanel(); + guiPanel = new javax.swing.JPanel(); + densityPanel = new javax.swing.JPanel(); + zeroButton = new javax.swing.JRadioButton(); + halfButton = new javax.swing.JRadioButton(); + fullButton = new javax.swing.JRadioButton(); + colorPanel = new javax.swing.JPanel(); + goldButton = new javax.swing.JRadioButton(); + silverButton = new javax.swing.JRadioButton(); + sceneGraphPanel = new javax.swing.JPanel(); + DetachButton = new javax.swing.JToggleButton(); + AttachButton = new javax.swing.JToggleButton(); + replaceSPButton = new javax.swing.JButton(); + drawingPanel = new javax.swing.JPanel(); + jMenuBar1 = new javax.swing.JMenuBar(); + fileMenu = new javax.swing.JMenu(); + exitMenuItem = new javax.swing.JMenuItem(); + + setTitle("Window Title"); + addWindowListener(new java.awt.event.WindowAdapter() { + public void windowClosing(java.awt.event.WindowEvent evt) + { + exitForm(evt); + } + }); + + mainPanel.setLayout(new java.awt.BorderLayout()); + + guiPanel.setLayout(new javax.swing.BoxLayout(guiPanel, javax.swing.BoxLayout.X_AXIS)); + + guiPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0))); + densityPanel.setLayout(new java.awt.GridBagLayout()); + + densityPanel.setBorder(new javax.swing.border.TitledBorder("Density")); + densityButtonGroup.add(zeroButton); + zeroButton.setText("Zero"); + zeroButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + zeroButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + densityPanel.add(zeroButton, gridBagConstraints); + + densityButtonGroup.add(halfButton); + halfButton.setText("Half"); + halfButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + halfButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 1; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + densityPanel.add(halfButton, gridBagConstraints); + + densityButtonGroup.add(fullButton); + fullButton.setSelected(true); + fullButton.setText("Full"); + fullButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + fullButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 2; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + densityPanel.add(fullButton, gridBagConstraints); + + guiPanel.add(densityPanel); + densityPanel.getAccessibleContext().setAccessibleName("ShaderAttributeValue \n"); + + colorPanel.setLayout(new java.awt.GridBagLayout()); + + colorPanel.setBorder(new javax.swing.border.TitledBorder("Color")); + colorButtonGroup.add(goldButton); + goldButton.setSelected(true); + goldButton.setText("Gold"); + goldButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + goldButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + colorPanel.add(goldButton, gridBagConstraints); + + colorButtonGroup.add(silverButton); + silverButton.setText("Silver"); + silverButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + silverButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 1; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + colorPanel.add(silverButton, gridBagConstraints); + + guiPanel.add(colorPanel); + + sceneGraphPanel.setLayout(new java.awt.GridBagLayout()); + + sceneGraphPanel.setBorder(new javax.swing.border.TitledBorder("Scene Graph")); + sceneGraphButtonGroup.add(DetachButton); + DetachButton.setSelected(true); + DetachButton.setText("Detach"); + DetachButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + DetachButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + sceneGraphPanel.add(DetachButton, gridBagConstraints); + + sceneGraphButtonGroup.add(AttachButton); + AttachButton.setText("Create"); + AttachButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + AttachButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 1; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + sceneGraphPanel.add(AttachButton, gridBagConstraints); + + replaceSPButton.setText("Replace Shader"); + replaceSPButton.setEnabled(false); + replaceSPButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + replaceSPButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 2; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + sceneGraphPanel.add(replaceSPButton, gridBagConstraints); + + guiPanel.add(sceneGraphPanel); + + mainPanel.add(guiPanel, java.awt.BorderLayout.NORTH); + + drawingPanel.setLayout(new java.awt.BorderLayout()); + + drawingPanel.setPreferredSize(new java.awt.Dimension(500, 500)); + mainPanel.add(drawingPanel, java.awt.BorderLayout.CENTER); + + getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER); + + fileMenu.setText("File"); + exitMenuItem.setText("Exit"); + exitMenuItem.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + exitMenuItemActionPerformed(evt); + } + }); + + fileMenu.add(exitMenuItem); + + jMenuBar1.add(fileMenu); + + setJMenuBar(jMenuBar1); + + pack(); + } + // </editor-fold>//GEN-END:initComponents + + private void silverButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_silverButtonActionPerformed + color = SILVER; + if (scene != null) + { + sao2.setValue(silver); + } + }//GEN-LAST:event_silverButtonActionPerformed + + private void goldButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_goldButtonActionPerformed + color = GOLD; + if (scene != null) + { + sao2.setValue(gold); + } + }//GEN-LAST:event_goldButtonActionPerformed + + private void replaceSPButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_replaceSPButtonActionPerformed + if (shaderSelected != DIMPLE_SHADER) + { + goldButton.setEnabled(false); + silverButton.setEnabled(false); + zeroButton.setEnabled(false); + halfButton.setEnabled(false); + fullButton.setEnabled(false); + } + + switch (shaderSelected) + { + case DIMPLE_SHADER: + s3d.setAppearance(sApp1); + goldButton.setEnabled(true); + silverButton.setEnabled(true); + zeroButton.setEnabled(true); + halfButton.setEnabled(true); + fullButton.setEnabled(true); + shaderSelected = BRICK_SHADER; + break; + case BRICK_SHADER: + s3d.setAppearance(sApp2); + shaderSelected = WOOD_SHADER; + break; + case WOOD_SHADER: + s3d.setAppearance(sApp3); + shaderSelected = POLKADOT3D_SHADER; + break; + case POLKADOT3D_SHADER: + s3d.setAppearance(sApp4); + shaderSelected = DIMPLE_SHADER; + break; + default: + assert false; + } + + }//GEN-LAST:event_replaceSPButtonActionPerformed + + private void fullButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_fullButtonActionPerformed + density = 16.0f; + if (scene != null) + { + sao1.setValue(new Float(density)); + } + }//GEN-LAST:event_fullButtonActionPerformed + + private void DetachButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_DetachButtonActionPerformed + if (scene != null) + { + scene.detach(); + scene = null; + replaceSPButton.setEnabled(false); + goldButton.setEnabled(true); + silverButton.setEnabled(true); + zeroButton.setEnabled(true); + halfButton.setEnabled(true); + fullButton.setEnabled(true); + shaderSelected = DIMPLE_SHADER; + } + }//GEN-LAST:event_DetachButtonActionPerformed + + private void AttachButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_AttachButtonActionPerformed + if (scene == null) + { + scene = createSceneGraph(1); + univ.addBranchGraph(scene); + replaceSPButton.setEnabled(true); + shaderSelected = BRICK_SHADER; + } + }//GEN-LAST:event_AttachButtonActionPerformed + + private void halfButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_halfButtonActionPerformed + density = 8.0f; + if (scene != null) + { + sao1.setValue(new Float(density)); + } + }//GEN-LAST:event_halfButtonActionPerformed + + private void zeroButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_zeroButtonActionPerformed + density = 0.0f; + if (scene != null) + { + sao1.setValue(new Float(density)); + } + + }//GEN-LAST:event_zeroButtonActionPerformed + + private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_exitMenuItemActionPerformed + System.exit(0); + }//GEN-LAST:event_exitMenuItemActionPerformed + + /** Exit the Application */ + private void exitForm(java.awt.event.WindowEvent evt) + {//GEN-FIRST:event_exitForm + System.exit(0); + }//GEN-LAST:event_exitForm + + /** + * @param args the command line arguments + */ + public static void main(String args[]) + { + System.setProperty("sun.awt.noerasebackground", "true"); + System.setProperty("j3d.rend","jogl2es2"); + new ShaderTestGLSL().setVisible(true); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JToggleButton AttachButton; + private javax.swing.JToggleButton DetachButton; + private javax.swing.ButtonGroup colorButtonGroup; + private javax.swing.JPanel colorPanel; + private javax.swing.ButtonGroup densityButtonGroup; + private javax.swing.JPanel densityPanel; + private javax.swing.JPanel drawingPanel; + private javax.swing.JMenuItem exitMenuItem; + private javax.swing.JMenu fileMenu; + private javax.swing.JRadioButton fullButton; + private javax.swing.JRadioButton goldButton; + private javax.swing.JPanel guiPanel; + private javax.swing.JRadioButton halfButton; + private javax.swing.JMenuBar jMenuBar1; + private javax.swing.JPanel mainPanel; + private javax.swing.JButton replaceSPButton; + private javax.swing.ButtonGroup sceneGraphButtonGroup; + private javax.swing.JPanel sceneGraphPanel; + private javax.swing.JRadioButton silverButton; + private javax.swing.JRadioButton zeroButton; + // End of variables declaration//GEN-END:variables + +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SphereGLSL.form b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SphereGLSL.form new file mode 100644 index 0000000..26e9b32 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SphereGLSL.form @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.0" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> + <Properties> + <Property name="defaultCloseOperation" type="int" value="3"/> + <Property name="title" type="java.lang.String" value="SphereGLSL"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + </SyntheticProperties> + <AuxValues> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="drawingPanel"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[700, 700]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + </Container> + </SubComponents> +</Form> diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SphereGLSL.java b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SphereGLSL.java new file mode 100644 index 0000000..f49c42a --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/SphereGLSL.java @@ -0,0 +1,410 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +package org.jdesktop.j3d.examples.gl2es2pipeline; + +import java.awt.GraphicsConfiguration; +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import javax.swing.JOptionPane; + +import org.jogamp.java3d.Alpha; +import org.jogamp.java3d.AmbientLight; +import org.jogamp.java3d.Appearance; +import org.jogamp.java3d.Background; +import org.jogamp.java3d.BoundingSphere; +import org.jogamp.java3d.BranchGroup; +import org.jogamp.java3d.Canvas3D; +import org.jogamp.java3d.ColoringAttributes; +import org.jogamp.java3d.DirectionalLight; +import org.jogamp.java3d.GLSLShaderProgram; +import org.jogamp.java3d.GeometryArray; +import org.jogamp.java3d.J3DBuffer; +import org.jogamp.java3d.Light; +import org.jogamp.java3d.Material; +import org.jogamp.java3d.PointLight; +import org.jogamp.java3d.PositionInterpolator; +import org.jogamp.java3d.RotationInterpolator; +import org.jogamp.java3d.Shader; +import org.jogamp.java3d.ShaderAppearance; +import org.jogamp.java3d.ShaderError; +import org.jogamp.java3d.ShaderErrorListener; +import org.jogamp.java3d.ShaderProgram; +import org.jogamp.java3d.SourceCodeShader; +import org.jogamp.java3d.SpotLight; +import org.jogamp.java3d.Transform3D; +import org.jogamp.java3d.TransformGroup; +import org.jogamp.java3d.TriangleStripArray; +import org.jogamp.java3d.utils.geometry.Sphere; +//import org.jogamp.java3d.utils.geometry.Sphere; +import org.jogamp.java3d.utils.shader.StringIO; +import org.jogamp.java3d.utils.universe.SimpleUniverse; +import org.jogamp.vecmath.Color3f; +import org.jogamp.vecmath.Point3d; +import org.jogamp.vecmath.Point3f; +import org.jogamp.vecmath.Vector3d; +import org.jogamp.vecmath.Vector3f; + +/** + * Simple Java 3D example program with programmable shader. + */ +public class SphereGLSL extends javax.swing.JFrame +{ + + // Constants for type of light to use + private static final int DIRECTIONAL_LIGHT = 0; + private static final int POINT_LIGHT = 1; + private static final int SPOT_LIGHT = 2; + + // Flag indicates type of lights: directional, point, or spot + // lights. This flag is set based on command line argument + private static int lightType = DIRECTIONAL_LIGHT; + private SimpleUniverse univ = null; + private BranchGroup scene = null; + + public BranchGroup createSceneGraph() + { + Color3f eColor = new Color3f(0.0f, 0.0f, 0.0f); + Color3f sColor = new Color3f(1.0f, 1.0f, 1.0f); + Color3f objColor = new Color3f(0.6f, 0.6f, 0.6f); + Color3f lColor1 = new Color3f(1.0f, 0.0f, 0.0f); + Color3f lColor2 = new Color3f(0.0f, 1.0f, 0.0f); + Color3f alColor = new Color3f(0.2f, 0.2f, 0.2f); + Color3f bgColor = new Color3f(0.05f, 0.05f, 0.2f); + + Transform3D t; + + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + + // Create a Transformgroup to scale all objects so they + // appear in the scene. + TransformGroup objScale = new TransformGroup(); + Transform3D t3d = new Transform3D(); + t3d.setScale(0.4); + objScale.setTransform(t3d); + objRoot.addChild(objScale); + + // Create a bounds for the background and lights + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + + // Set up the background + Background bg = new Background(bgColor); + bg.setApplicationBounds(bounds); + objScale.addChild(bg); + + // Create a Sphere object, generate one copy of the sphere, + // and add it into the scene graph. + ShaderAppearance a = new ShaderAppearance(); + Material m = new Material(objColor, eColor, objColor, sColor, 100.0f); + m.setLightingEnable(true); + String vertexProgram = null; + String fragmentProgram = null; + try + { + vertexProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/simple.vert")); + fragmentProgram = StringIO.readFully( + new File(System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/simple.frag")); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + Shader[] shaders = new Shader[2]; + shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); + shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); + ShaderProgram shaderProgram = new GLSLShaderProgram(); + shaderProgram.setShaders(shaders); + + a.setShaderProgram(shaderProgram); + a.setMaterial(m); + Sphere sph = new Sphere(1.0f, Sphere.GENERATE_NORMALS, 200, a); + makeNIO(sph); + objScale.addChild(sph); + + // Create the transform group node for the each light and initialize + // it to the identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at runtime. Add them to the root + // of the subgraph. + TransformGroup l1RotTrans = new TransformGroup(); + l1RotTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objScale.addChild(l1RotTrans); + + TransformGroup l2RotTrans = new TransformGroup(); + l2RotTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objScale.addChild(l2RotTrans); + + // Create transformations for the positional lights + t = new Transform3D(); + Vector3d lPos1 = new Vector3d(0.0, 0.0, 2.0); + t.set(lPos1); + TransformGroup l1Trans = new TransformGroup(t); + l1RotTrans.addChild(l1Trans); + + t = new Transform3D(); + Vector3d lPos2 = new Vector3d(0.5, 0.8, 2.0); + t.set(lPos2); + TransformGroup l2Trans = new TransformGroup(t); + l2RotTrans.addChild(l2Trans); + + // Create Geometry for point lights + ColoringAttributes caL1 = new ColoringAttributes(); + ColoringAttributes caL2 = new ColoringAttributes(); + caL1.setColor(lColor1); + caL2.setColor(lColor2); + Appearance appL1 = new Appearance(); + Appearance appL2 = new Appearance(); + appL1.setColoringAttributes(caL1); + appL2.setColoringAttributes(caL2); + + Sphere sph2 = new Sphere(0.05f, appL1); + makeNIO(sph2); + l1Trans.addChild(sph2); + Sphere sph3 = new Sphere(0.05f, appL2); + makeNIO(sph3); + l2Trans.addChild(sph3); + + // Create lights + AmbientLight aLgt = new AmbientLight(alColor); + + Light lgt1 = null; + Light lgt2 = null; + + Point3f lPoint = new Point3f(0.0f, 0.0f, 0.0f); + Point3f atten = new Point3f(1.0f, 0.0f, 0.0f); + Vector3f lDirect1 = new Vector3f(lPos1); + Vector3f lDirect2 = new Vector3f(lPos2); + lDirect1.negate(); + lDirect2.negate(); + + switch (lightType) + { + case DIRECTIONAL_LIGHT: + lgt1 = new DirectionalLight(lColor1, lDirect1); + lgt2 = new DirectionalLight(lColor2, lDirect2); + break; + case POINT_LIGHT: + lgt1 = new PointLight(lColor1, lPoint, atten); + lgt2 = new PointLight(lColor2, lPoint, atten); + break; + case SPOT_LIGHT: + lgt1 = new SpotLight(lColor1, lPoint, atten, lDirect1, 25.0f * (float) Math.PI / 180.0f, 10.0f); + lgt2 = new SpotLight(lColor2, lPoint, atten, lDirect2, 25.0f * (float) Math.PI / 180.0f, 10.0f); + break; + } + + // Set the influencing bounds + aLgt.setInfluencingBounds(bounds); + lgt1.setInfluencingBounds(bounds); + lgt2.setInfluencingBounds(bounds); + + // Add the lights into the scene graph + objScale.addChild(aLgt); + l1Trans.addChild(lgt1); + l2Trans.addChild(lgt2); + + // Create a new Behavior object that will perform the desired + // operation on the specified transform object and add it into the + // scene graph. + Transform3D yAxis = new Transform3D(); + Alpha rotor1Alpha = new Alpha(-1, Alpha.INCREASING_ENABLE, 0, 0, 4000, 0, 0, 0, 0, 0); + RotationInterpolator rotator1 = new RotationInterpolator(rotor1Alpha, l1RotTrans, yAxis, 0.0f, (float) Math.PI * 2.0f); + rotator1.setSchedulingBounds(bounds); + l1RotTrans.addChild(rotator1); + + // Create a new Behavior object that will perform the desired + // operation on the specified transform object and add it into the + // scene graph. + Alpha rotor2Alpha = new Alpha(-1, Alpha.INCREASING_ENABLE, 0, 0, 1000, 0, 0, 0, 0, 0); + RotationInterpolator rotator2 = new RotationInterpolator(rotor2Alpha, l2RotTrans, yAxis, 0.0f, 0.0f); + bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + rotator2.setSchedulingBounds(bounds); + l2RotTrans.addChild(rotator2); + + // Create a position interpolator and attach it to the view + // platform + TransformGroup vpTrans = univ.getViewingPlatform().getViewPlatformTransform(); + Transform3D axisOfTranslation = new Transform3D(); + Alpha transAlpha = new Alpha(-1, Alpha.INCREASING_ENABLE | Alpha.DECREASING_ENABLE, 0, 0, 5000, 0, 0, 5000, 0, 0); + axisOfTranslation.rotY(-Math.PI / 2.0); + PositionInterpolator translator = new PositionInterpolator(transAlpha, vpTrans, axisOfTranslation, 2.0f, 3.5f); + translator.setSchedulingBounds(bounds); + objScale.addChild(translator); + + // Let Java 3D perform optimizations on this scene graph. + objRoot.compile(); + + return objRoot; + } + + + + private Canvas3D createUniverse() + { + // Get the preferred graphics configuration for the default screen + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + // Create a Canvas3D using the preferred configuration + Canvas3D canvas3d = new Canvas3D(config); + + // Create simple universe with view branch + univ = new SimpleUniverse(canvas3d); + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + + // Add a ShaderErrorListener + univ.addShaderErrorListener(new ShaderErrorListener() { + public void errorOccurred(ShaderError error) + { + error.printVerbose(); + JOptionPane.showMessageDialog(SphereGLSL.this, error.toString(), "ShaderError", JOptionPane.ERROR_MESSAGE); + } + }); + + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + univ.getViewingPlatform().setNominalViewingTransform(); + + // Ensure at least 5 msec per frame (i.e., < 200Hz) + univ.getViewer().getView().setMinimumFrameCycleTime(5); + + return canvas3d; + } + + /** + * Creates new form SphereGLSL + */ + public SphereGLSL() + { + + // Initialize the GUI components + initComponents(); + + // Create Canvas3D and SimpleUniverse; add canvas to drawing panel + Canvas3D c = createUniverse(); + drawingPanel.add(c, java.awt.BorderLayout.CENTER); + + // Create the content branch and add it to the universe + scene = createSceneGraph(); + univ.addBranchGraph(scene); + } + + // ---------------------------------------------------------------- + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents + private void initComponents() + { + drawingPanel = new javax.swing.JPanel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setTitle("SphereGLSL"); + drawingPanel.setLayout(new java.awt.BorderLayout()); + + drawingPanel.setPreferredSize(new java.awt.Dimension(700, 700)); + getContentPane().add(drawingPanel, java.awt.BorderLayout.CENTER); + + pack(); + }// </editor-fold>//GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(final String args[]) + { + System.setProperty("sun.awt.noerasebackground", "true"); + System.setProperty("j3d.rend", "jogl2es2"); + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() + { + SphereGLSL sphereGLSL = new SphereGLSL(); + sphereGLSL.setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel drawingPanel; + + + + // End of variables declaration//GEN-END:variables + public static void makeNIO(Sphere sph) + { + //Make it NIO + TriangleStripArray geo = (TriangleStripArray) sph.getShape().getGeometry(); + int[] stripVertexCounts = new int[geo.getNumStrips()]; + geo.getStripVertexCounts(stripVertexCounts); + TriangleStripArray newGeo = new TriangleStripArray(geo.getVertexCount(), GeometryArray.COORDINATES | GeometryArray.NORMALS + //| GeometryArray.TEXTURE_COORDINATE_2 + | GeometryArray.USE_NIO_BUFFER | GeometryArray.BY_REFERENCE, stripVertexCounts); + + float[] coords = new float[geo.getValidVertexCount() * 3]; + geo.getCoordinates(0, coords); + newGeo.setCoordRefBuffer(new J3DBuffer(makeFloatBuffer(coords))); + float[] norms = new float[geo.getValidVertexCount() * 3]; + geo.getNormals(0, norms); + newGeo.setNormalRefBuffer(new J3DBuffer(makeFloatBuffer(norms))); + sph.getShape().setGeometry(newGeo); + + } + + private static FloatBuffer makeFloatBuffer(float[] arr) + { + ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); + bb.order(ByteOrder.nativeOrder()); + FloatBuffer fb = bb.asFloatBuffer(); + fb.put(arr); + fb.position(0); + return fb; + } +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/VertexAttrTestGLSL.form b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/VertexAttrTestGLSL.form new file mode 100644 index 0000000..6e31a8f --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/VertexAttrTestGLSL.form @@ -0,0 +1,203 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.0" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> + <NonVisualComponents> + <Menu class="javax.swing.JMenuBar" name="jMenuBar1"> + <SubComponents> + <Menu class="javax.swing.JMenu" name="fileMenu"> + <Properties> + <Property name="text" type="java.lang.String" value="File"/> + </Properties> + <SubComponents> + <MenuItem class="javax.swing.JMenuItem" name="exitMenuItem"> + <Properties> + <Property name="text" type="java.lang.String" value="Exit"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="exitMenuItemActionPerformed"/> + </Events> + </MenuItem> + </SubComponents> + </Menu> + </SubComponents> + </Menu> + </NonVisualComponents> + <Properties> + <Property name="title" type="java.lang.String" value="VertexAttrTestGLSL"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="menuBar" type="java.lang.String" value="jMenuBar1"/> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + </SyntheticProperties> + <Events> + <EventHandler event="windowClosing" listener="java.awt.event.WindowListener" parameters="java.awt.event.WindowEvent" handler="exitForm"/> + </Events> + <AuxValues> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="mainPanel"> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="guiPanel"> + <Properties> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.LineBorderInfo"> + <LineBorder/> + </Border> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="North"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="vertexCheckBoxPanel"> + <Properties> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo"> + <TitledBorder title="vertexFormat"> + <Font PropertyName="font" name="Lucida Sans" size="10" style="0"/> + </TitledBorder> + </Border> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="0" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="2" insetsLeft="2" insetsBottom="2" insetsRight="2" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Container class="javax.swing.JPanel" name="jPanel1"> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="11" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Component class="javax.swing.JSeparator" name="jSeparator1"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[0, 4]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="1" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + <Component class="javax.swing.JSeparator" name="jSeparator2"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[0, 4]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="3" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + </SubComponents> + </Container> + <Container class="javax.swing.JPanel" name="jPanel2"> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="11" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Component class="javax.swing.JCheckBox" name="vertexAttrsBox"> + <Properties> + <Property name="selected" type="boolean" value="true"/> + <Property name="text" type="java.lang.String" value="VertexAttrs"/> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="4" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + </SubComponents> + </Container> + </SubComponents> + </Container> + <Container class="javax.swing.JPanel" name="geometryPanel"> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="0" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="2" insetsLeft="2" insetsBottom="2" insetsRight="2" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/> + <SubComponents> + <Component class="javax.swing.JButton" name="createButton"> + <Properties> + <Property name="text" type="java.lang.String" value="Create Geometry"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="createButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + <Component class="javax.swing.JButton" name="destroyButton"> + <Properties> + <Property name="text" type="java.lang.String" value="Destroy Geometry"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="destroyButtonActionPerformed"/> + </Events> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription"> + <GridBagConstraints gridX="0" gridY="-1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="2" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/> + </Constraint> + </Constraints> + </Component> + </SubComponents> + </Container> + </SubComponents> + </Container> + <Container class="javax.swing.JPanel" name="drawingPanel"> + <Properties> + <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[500, 500]"/> + </Property> + </Properties> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription"> + <BorderConstraints direction="Center"/> + </Constraint> + </Constraints> + + <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/> + </Container> + </SubComponents> + </Container> + </SubComponents> +</Form> diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/VertexAttrTestGLSL.java b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/VertexAttrTestGLSL.java new file mode 100644 index 0000000..96bc0c9 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/VertexAttrTestGLSL.java @@ -0,0 +1,451 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +package org.jdesktop.j3d.examples.gl2es2pipeline; + +import java.awt.GraphicsConfiguration; +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import javax.swing.JFrame; +import javax.swing.JOptionPane; + +import org.jogamp.java3d.Appearance; +import org.jogamp.java3d.Background; +import org.jogamp.java3d.BoundingSphere; +import org.jogamp.java3d.BranchGroup; +import org.jogamp.java3d.Canvas3D; +import org.jogamp.java3d.GLSLShaderProgram; +import org.jogamp.java3d.GeometryArray; +import org.jogamp.java3d.J3DBuffer; +import org.jogamp.java3d.Shader; +import org.jogamp.java3d.ShaderAppearance; +import org.jogamp.java3d.ShaderError; +import org.jogamp.java3d.ShaderErrorListener; +import org.jogamp.java3d.ShaderProgram; +import org.jogamp.java3d.Shape3D; +import org.jogamp.java3d.SourceCodeShader; +import org.jogamp.java3d.TransformGroup; +import org.jogamp.java3d.TriangleArray; +import org.jogamp.java3d.utils.shader.StringIO; +import org.jogamp.java3d.utils.universe.SimpleUniverse; +import org.jogamp.java3d.utils.universe.ViewingPlatform; +import org.jogamp.vecmath.Color3f; +import org.jogamp.vecmath.Point3d; + +public class VertexAttrTestGLSL extends javax.swing.JFrame +{ + + SimpleUniverse univ = null; + BranchGroup scene = null; + + public BranchGroup createSceneGraph(boolean hasVertexAttrs) + { + + // Bounds for BG and behavior + BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); + + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + objRoot.setCapability(BranchGroup.ALLOW_DETACH); + + // Set up the background + Color3f bgColor = new Color3f(0.1f, 0.1f, 0.1f); + Background bg = new Background(bgColor); + bg.setApplicationBounds(bounds); + objRoot.addChild(bg); + + // Create the TransformGroup node and initialize it to the + // identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at run time. Add it to + // the root of the subgraph. + TransformGroup objTrans = new TransformGroup(); + objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objRoot.addChild(objTrans); + + // Create a simple Shape3D node; add it to the scene graph. + objTrans.addChild(new MyShape(this, hasVertexAttrs)); + + return objRoot; + } + + private Canvas3D initScene() + { + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + Canvas3D c = new Canvas3D(config); + univ = new SimpleUniverse(c); + + // Add a ShaderErrorListener + univ.addShaderErrorListener(new ShaderErrorListener() { + public void errorOccurred(ShaderError error) + { + error.printVerbose(); + JOptionPane.showMessageDialog(VertexAttrTestGLSL.this, error.toString(), "ShaderError", JOptionPane.ERROR_MESSAGE); + } + }); + + ViewingPlatform viewingPlatform = univ.getViewingPlatform(); + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + viewingPlatform.setNominalViewingTransform(); + + return c; + } + + /** + * Creates new form VertexAttrTestGLSL + */ + public VertexAttrTestGLSL() + { + // Initialize the GUI components + initComponents(); + + // Create the scene and add the Canvas3D to the drawing panel + Canvas3D c = initScene(); + drawingPanel.add(c, java.awt.BorderLayout.CENTER); + } + + static class MyShape extends Shape3D + { + + // Coordinate data + private static final float[] coords = { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, }; + + private static final int[] sizes = { 1, 3 }; + private static final float[] weights = { 0.45f, 0.15f, 0.95f, }; + private static final float[] temps = { 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, }; + + private static final String[] vaNames = { "weight", "temperature" }; + + J3DBuffer createDirectFloatBuffer(float[] arr) + { + ByteOrder order = ByteOrder.nativeOrder(); + + FloatBuffer nioBuf = ByteBuffer.allocateDirect(arr.length * 4).order(order).asFloatBuffer(); + nioBuf.put(arr); + return new J3DBuffer(nioBuf); + } + + MyShape(JFrame frame, boolean hasVertexAttrs) + { + + int vertexFormat = GeometryArray.COORDINATES; + int vertexAttrCount = 0; + int[] vertexAttrSizes = null; + String[] vertexAttrNames = null; + String[] shaderAttrNames = null; + + if (hasVertexAttrs) + { + vertexFormat |= GeometryArray.VERTEX_ATTRIBUTES; + vertexAttrCount = vaNames.length; + vertexAttrSizes = sizes; + vertexAttrNames = vaNames; + } + + //GL2ES2: requires by reference + vertexFormat |= GeometryArray.BY_REFERENCE; + + TriangleArray tri = new TriangleArray(6, vertexFormat, 0, null, vertexAttrCount, vertexAttrSizes); + tri.setValidVertexCount(3); + //tri.setCoordinates(0, coords); + tri.setCoordRefFloat(coords); + + if (hasVertexAttrs) + { + //tri.setVertexAttrs(0, 0, weights); + //tri.setVertexAttrs(1, 0, temps); + + tri.setVertexAttrRefFloat(0, weights); + tri.setVertexAttrRefFloat(1, temps); + + String vertexProgram = null; + String fragmentProgram = null; + try + { + vertexProgram = StringIO.readFully(new File( + System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/vertexshader.vert")); + fragmentProgram = StringIO.readFully(new File( + System.getProperty("user.dir") + "/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/vertexshader.frag")); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + + Shader[] shaders = new Shader[2]; + shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); + shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); + + ShaderProgram shaderProgram = new GLSLShaderProgram(); + shaderProgram.setShaders(shaders); + shaderProgram.setVertexAttrNames(vertexAttrNames); + shaderProgram.setShaderAttrNames(shaderAttrNames); + + ShaderAppearance app = new ShaderAppearance(); + app.setShaderProgram(shaderProgram); + + this.setGeometry(tri); + + this.setAppearance(app); + } + else + { + this.setGeometry(tri); + this.setAppearance(new Appearance()); + } + } + } + + // ---------------------------------------------------------------- + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents + private void initComponents() + { + java.awt.GridBagConstraints gridBagConstraints; + + mainPanel = new javax.swing.JPanel(); + guiPanel = new javax.swing.JPanel(); + vertexCheckBoxPanel = new javax.swing.JPanel(); + jPanel1 = new javax.swing.JPanel(); + jSeparator1 = new javax.swing.JSeparator(); + jSeparator2 = new javax.swing.JSeparator(); + jPanel2 = new javax.swing.JPanel(); + vertexAttrsBox = new javax.swing.JCheckBox(); + geometryPanel = new javax.swing.JPanel(); + createButton = new javax.swing.JButton(); + destroyButton = new javax.swing.JButton(); + drawingPanel = new javax.swing.JPanel(); + jMenuBar1 = new javax.swing.JMenuBar(); + fileMenu = new javax.swing.JMenu(); + exitMenuItem = new javax.swing.JMenuItem(); + + setTitle("VertexAttrTestGLSL"); + addWindowListener(new java.awt.event.WindowAdapter() { + public void windowClosing(java.awt.event.WindowEvent evt) + { + exitForm(evt); + } + }); + + mainPanel.setLayout(new java.awt.BorderLayout()); + + guiPanel.setLayout(new java.awt.GridBagLayout()); + + guiPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + vertexCheckBoxPanel.setLayout(new java.awt.GridBagLayout()); + + vertexCheckBoxPanel.setBorder( + javax.swing.BorderFactory.createTitledBorder(null, "vertexFormat", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Lucida Sans", 0, 10))); + jPanel1.setLayout(new java.awt.GridBagLayout()); + + jSeparator1.setPreferredSize(new java.awt.Dimension(0, 4)); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 1; + jPanel1.add(jSeparator1, gridBagConstraints); + + jSeparator2.setPreferredSize(new java.awt.Dimension(0, 4)); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 3; + jPanel1.add(jSeparator2, gridBagConstraints); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; + vertexCheckBoxPanel.add(jPanel1, gridBagConstraints); + + jPanel2.setLayout(new java.awt.GridBagLayout()); + + vertexAttrsBox.setSelected(true); + vertexAttrsBox.setText("VertexAttrs"); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.gridy = 4; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + jPanel2.add(vertexAttrsBox, gridBagConstraints); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; + vertexCheckBoxPanel.add(jPanel2, gridBagConstraints); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridy = 0; + gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); + guiPanel.add(vertexCheckBoxPanel, gridBagConstraints); + + geometryPanel.setLayout(new java.awt.GridBagLayout()); + + createButton.setText("Create Geometry"); + createButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + createButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + geometryPanel.add(createButton, gridBagConstraints); + + destroyButton.setText("Destroy Geometry"); + destroyButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + destroyButtonActionPerformed(evt); + } + }); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridx = 0; + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; + gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); + geometryPanel.add(destroyButton, gridBagConstraints); + + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridy = 0; + gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); + guiPanel.add(geometryPanel, gridBagConstraints); + + mainPanel.add(guiPanel, java.awt.BorderLayout.NORTH); + + drawingPanel.setLayout(new java.awt.BorderLayout()); + + drawingPanel.setPreferredSize(new java.awt.Dimension(500, 500)); + mainPanel.add(drawingPanel, java.awt.BorderLayout.CENTER); + + getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER); + + fileMenu.setText("File"); + exitMenuItem.setText("Exit"); + exitMenuItem.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + exitMenuItemActionPerformed(evt); + } + }); + + fileMenu.add(exitMenuItem); + + jMenuBar1.add(fileMenu); + + setJMenuBar(jMenuBar1); + + pack(); + }// </editor-fold>//GEN-END:initComponents + + private void destroyButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_destroyButtonActionPerformed + if (scene != null) + { + univ.getLocale().removeBranchGraph(scene); + scene = null; + } + }//GEN-LAST:event_destroyButtonActionPerformed + + private void createButtonActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_createButtonActionPerformed + if (scene == null) + { + boolean hasVertexAttrs = vertexAttrsBox.isSelected(); + scene = createSceneGraph(hasVertexAttrs); + univ.addBranchGraph(scene); + } + }//GEN-LAST:event_createButtonActionPerformed + + private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) + {//GEN-FIRST:event_exitMenuItemActionPerformed + System.exit(0); + }//GEN-LAST:event_exitMenuItemActionPerformed + + /** Exit the Application */ + private void exitForm(java.awt.event.WindowEvent evt) + {//GEN-FIRST:event_exitForm + System.exit(0); + }//GEN-LAST:event_exitForm + + /** + * @param args the command line arguments + */ + public static void main(String args[]) + { + System.setProperty("sun.awt.noerasebackground", "true"); + System.setProperty("j3d.rend","jogl2es2"); + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() + { + new VertexAttrTestGLSL().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton createButton; + private javax.swing.JButton destroyButton; + private javax.swing.JPanel drawingPanel; + private javax.swing.JMenuItem exitMenuItem; + private javax.swing.JMenu fileMenu; + private javax.swing.JPanel geometryPanel; + private javax.swing.JPanel guiPanel; + private javax.swing.JMenuBar jMenuBar1; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JSeparator jSeparator1; + private javax.swing.JSeparator jSeparator2; + private javax.swing.JPanel mainPanel; + private javax.swing.JCheckBox vertexAttrsBox; + private javax.swing.JPanel vertexCheckBoxPanel; + // End of variables declaration//GEN-END:variables + +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/aabrick.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/aabrick.frag new file mode 100644 index 0000000..030b811 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/aabrick.frag @@ -0,0 +1,56 @@ +// +// Fragment shader for antialiased procedural bricks +// +// Authors: Dave Baldwin, Randi Rost +// based on a shader by Darwyn Peachey +// +// Copyright (c) 2002-2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// + +uniform vec3 BrickColor; +//uniform vec3 MortarColor; +//uniform vec2 BrickSize; +//uniform vec2 BrickPct; +//uniform vec2 MortarPct; + +//const vec3 BrickColor = vec3 (1, 0.3, 0.2); +const vec3 MortarColor = vec3 (0.85, 0.86, 0.84); +const vec2 BrickSize = vec2 (0.3, 0.15); +const vec2 BrickPct = vec2 (0.9, 0.85); +const vec2 MortarPct = vec2 (0.1, 0.15); + +varying vec2 MCposition; +varying float LightIntensity; + +#define Integral(x, p, notp) ((floor(x)*(p)) + max(fract(x)-(notp), 0.0)) + +void main(void) +{ + vec2 position, fw, useBrick; + vec3 color; + + // Determine position within the brick pattern + position = MCposition / BrickSize; + + // Adjust every other row by an offset of half a brick + if (fract(position.y * 0.5) > 0.5) + position.x += 0.5; + + // Calculate filter size + //fw = fwidth(position); //fwidth not implemented on WildcatVP + fw = (abs(dFdx(MCposition)) + abs(dFdy(MCposition))) / BrickSize; + + // Perform filtering by integrating the 2D pulse made by the + // brick pattern over the filter width and height + useBrick = (Integral(position + fw, BrickPct, MortarPct) - + Integral(position, BrickPct, MortarPct)) / fw; + + // Determine final color + color = mix(MortarColor, BrickColor, useBrick.x * useBrick.y); + color *= LightIntensity; + + // GL2ES2: gl_FragColor is unchanged + gl_FragColor = vec4 (color, 1.0); +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/aabrick.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/aabrick.vert new file mode 100644 index 0000000..9b96195 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/aabrick.vert @@ -0,0 +1,64 @@ +// +// Vertex shader for antialiased procedural bricks +// +// Authors: Dave Baldwin, Steve Koren, Randi Rost +// based on a shader by Darwyn Peachey +// +// Copyright (c) 2002-2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewMatrix; +uniform mat4 glModelViewProjectionMatrix; +uniform mat3 glNormalMatrix; + + +uniform vec3 LightPosition; +//const vec3 LightPosition = vec3 (0, 4, 4); + +const float SpecularContribution = 0.3; +const float DiffuseContribution = 1.0 - SpecularContribution; + +varying float LightIntensity; +varying vec2 MCposition; + +void main(void) +{ + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec3 ecPosition = vec3 (gl_ModelViewMatrix * gl_Vertex); + vec3 ecPosition = vec3 (glModelViewMatrix * glVertex); + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec3 tnorm = normalize(gl_NormalMatrix * glNormal); + vec3 tnorm = normalize(glNormalMatrix * glNormal); + + + vec3 lightVec = normalize(LightPosition - ecPosition); + vec3 reflectVec = reflect(-lightVec, tnorm); + vec3 viewVec = normalize(-ecPosition); + float diffuse = max(dot(lightVec, tnorm), 0.0); + float spec = 0.0; + + if (diffuse > 0.0) + { + spec = max(dot(reflectVec, viewVec), 0.0); + spec = pow(spec, 16.0); + } + + LightIntensity = DiffuseContribution * diffuse + + SpecularContribution * spec; + + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //MCposition = gl_Vertex.xy; + MCposition = glVertex.xy; + + // GL2ES2: ftransform() no longer exists, but it is simple (note use of Java3D built-in uniforms and attributes) + // GL2ES2: gl_Position is unchanged + //gl_Position = ftransform(); + gl_Position = glModelViewProjectionMatrix * glVertex; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/dimple.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/dimple.frag new file mode 100644 index 0000000..b2a2ef7 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/dimple.frag @@ -0,0 +1,68 @@ + +// +// dimple.frag: Fragment shader for bump mapping dimples (bumps) +// +// author: John Kessenich +// +// Copyright (c) 2002: 3Dlabs, Inc. +// +// + +// GL2ES2: non buit-in varyings +varying vec2 glTexCoord0; +varying vec4 C; + +varying vec3 LightDir; +varying vec3 EyeDir; +varying vec3 Normal; + +//const vec3 Color = vec3(0.7, 0.6, 0.18); + +//const float Density = 16.0; +//const float Size = 0.25; + +uniform vec3 Color; +uniform float Density; +uniform float Size; +// uniform float SpecularFactor; + +//float Density = 27.6; +//float Size = 0.13025; + + +//uniform float Scale; + +const float SpecularFactor = 0.4; + +void main (void) +{ + vec3 litColor; + + // GL2ES2: non buit-in varying + vec2 c = Density * (glTexCoord0.xy); + vec2 p = fract(c) - vec2(0.5); + float d = (p.x * p.x) + (p.y * p.y); + if (d >= Size) + p = vec2(0.0); + + vec3 normDelta = vec3(-p.x, -p.y, 1.0); + + litColor = Color * max(0.0, dot(normDelta, LightDir)); + + float t = 2.0 * dot(LightDir, normDelta); + vec3 reflectDir = t * normDelta; + reflectDir = LightDir - reflectDir; + +// vec3 reflectDir = LightDir - 2.0 * dot(LightDir, normDelta) * normDelta; + + float spec = max(dot(EyeDir, reflectDir), 0.0); + spec = spec * spec; + spec = spec * spec; + spec *= SpecularFactor; + + litColor = min(litColor + spec, vec3(1.0)); + // GL2ES2: gl_FragColor is unchanged, C is a non built-in varying + gl_FragColor = vec4(litColor, C.a); +// gl_FragColor = vec4(litColor, 1.0); +// gl_FragColor = vec4(Scale); +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/dimple.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/dimple.vert new file mode 100644 index 0000000..9b06148 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/dimple.vert @@ -0,0 +1,76 @@ +#version 120 +// +// dimple.vert: Vertex shader for bump mapping dimples (bumps) +// +// author: John Kessenich +// +// Copyright (c) 2002: 3Dlabs, Inc. +// + + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; +attribute vec4 glColor; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewMatrix; +uniform mat4 glModelViewProjectionMatrix; +uniform mat3 glNormalMatrix; + +uniform vec4 glFrontMaterialdiffuse; +uniform int ignoreVertexColors; + +// GL2ES2: new output varyings, these replace gl_TexCoord[] and gl_FrontColor (along with A and D) +varying vec2 glTexCoord0; +varying vec4 C; + +varying vec3 LightDir; +varying vec3 EyeDir; +varying vec3 Normal; + +uniform vec3 LightPosition; +// uniform float Scale; +// vec3 LightPosition = vec3(0.0, 0.0, 5.0); +float Scale = 1.0; + + + +void main(void) +{ + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + vec4 pos = glModelViewMatrix * glVertex; + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + gl_Position = glModelViewProjectionMatrix * glVertex; + vec3 eyeDir = vec3(pos); + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + // GL2ES2: swap built-in varying for declared varying + //gl_TexCoord[0] = gl_MultiTexCoord0; + glTexCoord0 = glVertex.xy; + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + // GL2ES2: swap built-in varying for declared varying + //gl_FrontColor = gl_Color; + + if( ignoreVertexColors != 0) + C = glFrontMaterialdiffuse; + else + C = glColor; + + vec3 n = normalize(glNormalMatrix * glNormal); + vec3 t = normalize(cross(vec3(1.141, 2.78, 3.14), n)); + vec3 b = cross(n, t); + + vec3 v; + v.x = dot(LightPosition, t); + v.y = dot(LightPosition, b); + v.z = dot(LightPosition, n); + LightDir = normalize(v); + + v.x = dot(eyeDir, t); + v.y = dot(eyeDir, b); + v.z = dot(eyeDir, n); + EyeDir = normalize(v); + + + +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/envmap.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/envmap.frag new file mode 100644 index 0000000..3e298f8 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/envmap.frag @@ -0,0 +1,61 @@ +// +// Fragment shader for environment mapping with an +// equirectangular 2D texture +// +// Authors: John Kessenich, Randi Rost +// +// Copyright (c) 2002-2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// + +const vec3 Xunitvec = vec3 (1.0, 0.0, 0.0); +const vec3 Yunitvec = vec3 (0.0, 1.0, 0.0); + +uniform vec3 BaseColor; +uniform float MixRatio; + +uniform sampler2D EnvMap; + +varying vec3 Normal; +varying vec3 EyeDir; +varying float LightIntensity; + +void main (void) +{ + // Compute reflection vector + vec3 reflectDir = reflect(EyeDir, Normal); + + // Compute altitude and azimuth angles + + vec2 index; + + index.y = dot(normalize(reflectDir), Yunitvec); + reflectDir.y = 0.0; + index.x = dot(normalize(reflectDir), Xunitvec) * 0.5; + + // Translate index values into proper range + + if (reflectDir.z >= 0.0) + index = (index + 1.0) * 0.5; + else + { + index.t = (index.t + 1.0) * 0.5; + index.s = (-index.s) * 0.5 + 1.0; + } + + // if reflectDir.z >= 0.0, s will go from 0.25 to 0.75 + // if reflectDir.z < 0.0, s will go from 0.75 to 1.25, and + // that's OK, because we've set the texture to wrap. + + // Do a lookup into the environment map. + + vec3 envColor = vec3 (texture2D(EnvMap, index)); + + // Add lighting to base color and mix + + vec3 base = LightIntensity * BaseColor; + envColor = mix(envColor, base, MixRatio); + + gl_FragColor = vec4 (envColor, 1.0); +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/envmap.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/envmap.vert new file mode 100644 index 0000000..2cae4ab --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/envmap.vert @@ -0,0 +1,46 @@ +// +// Vertex shader for environment mapping with an +// equirectangular 2D texture +// +// Authors: John Kessenich, Randi Rost +// +// Copyright (c) 2002-2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewMatrix; +uniform mat4 glModelViewProjectionMatrix; +uniform mat3 glNormalMatrix; + + +varying vec3 Normal; +varying vec3 EyeDir; +varying float LightIntensity; + +uniform vec3 LightPos; + +void main(void) +{ + // GL2ES2: ftransform() no longer exists, but it is simple (note use of Java3D built-in uniforms and attributes) + // GL2ES2: gl_Position is unchanged + //gl_Position = ftransform(); + gl_Position = glModelViewProjectionMatrix * glVertex; + + // compute the transformed normal + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec3 Normal = normalize(gl_NormalMatrix * gl_Normal); + vec3 Normal = normalize(glNormalMatrix * glNormal); + + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec4 pos = gl_ModelViewMatrix * gl_Vertex; + vec4 pos = glModelViewMatrix * glVertex; + + EyeDir = pos.xyz; + LightIntensity = max(dot(normalize(LightPos - EyeDir), Normal), 0.0); +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/gouraud.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/gouraud.frag new file mode 100644 index 0000000..9169661 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/gouraud.frag @@ -0,0 +1,50 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +// Simple GLSL fragment program to add the primary and secondary (specular) colors + +void main() +{ + gl_FragColor = gl_Color + gl_SecondaryColor; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/gouraud.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/gouraud.vert new file mode 100644 index 0000000..900f598 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/gouraud.vert @@ -0,0 +1,109 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +// A GLSL vertex program for handling 1 directional light with specular. +// This implements per-vertex lighting (Gouraud shading). + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewMatrix; +uniform mat4 glModelViewProjectionMatrix; +uniform mat3 glNormalMatrix; + +void directionalLight0( + in vec3 normal, + inout vec4 ambient, + inout vec4 diffuse, + inout vec4 specular) +{ + // Normalized light direction and half vector + vec3 lightDirection = normalize(vec3(gl_LightSource[0].position)); + vec3 halfVector = normalize(vec3(gl_LightSource[0].halfVector)); + + float nDotVP; // normal . light_direction + float nDotHV; // normal . light_half_vector + float pf; // power factor + + nDotVP = max(0.0, dot(normal, lightDirection)); + nDotHV = max(0.0, dot(normal, halfVector)); + + if (nDotVP == 0.0) { + pf = 0.0; + } + else { + pf = pow(nDotHV, gl_FrontMaterial.shininess); + } + + ambient += gl_LightSource[0].ambient; + diffuse += gl_LightSource[0].diffuse * nDotVP; + specular += gl_LightSource[0].specular * pf; +} + + +void main() +{ + vec3 tnorm = normalize(vec3(glNormalMatrix * glNormal)); + vec4 amb = vec4(0.0); + vec4 diff = vec4(0.0); + vec4 spec = vec4(0.0); + int i; + + // Transform the vertex + vec4 outPosition = glModelViewProjectionMatrix * glVertex; + + directionalLight0(tnorm, amb, diff, spec); + + // Apply the result of the lighting equation + vec4 outSecondaryColor = vec4(vec3(spec * gl_FrontMaterial.specular), 1.0); + vec4 outColor = vec4(vec3(gl_FrontLightModelProduct.sceneColor + + amb * gl_FrontMaterial.ambient + + diff * gl_FrontMaterial.diffuse), 1.0); + + gl_FrontColor = outColor; + gl_FrontSecondaryColor = outSecondaryColor; + gl_Position = outPosition; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/multitex.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/multitex.frag new file mode 100644 index 0000000..3606b31 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/multitex.frag @@ -0,0 +1,64 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +uniform float cloudFactor; +uniform sampler2D earthTex; +uniform sampler2D cloudTex; + +uniform sampler2D EnvMap; + +varying vec2 texCoord0; +varying vec2 texCoord1; + +void main (void) +{ + vec2 tc0 = texCoord0.xy; + vec2 tc1 = texCoord1.xy; + + vec3 color0 = vec3(texture2D(cloudTex, tc0)); + vec3 color1 = vec3(texture2D(earthTex, tc1)); + vec3 finalColor = color0*cloudFactor + color1; + + gl_FragColor = vec4(finalColor, 1.0); +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/multitex.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/multitex.vert new file mode 100644 index 0000000..4132cae --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/multitex.vert @@ -0,0 +1,69 @@ +// tex coord gen sample from http://www.ogre3d.org/forums/viewtopic.php?f=4&t=59737 + + + + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewProjectionMatrix; +uniform mat4 glModelViewMatrix; +uniform mat3 glNormalMatrix; + +// Per-pixel normal (output to fragment shader) +varying vec3 Normal; + +varying vec2 texCoord0; +varying vec2 texCoord1; + + //Example 8-4 Sphere Map Texture Coordinate Generation + // position is the normalized position coordinate in eye space + // normal is the normalized normal coordinate in eye space + // returns a vec2 texture coordinate +vec2 sphere_map(vec3 position, vec3 normal) +{ + vec3 reflection = reflect(position, normal); + float m = 2.0 * sqrt(reflection.x * reflection.x + reflection.y * reflection.y + (reflection.z + 1.0) * (reflection.z + 1.0)); + return vec2((reflection.x / m + 0.5), (reflection.y / m + 0.5)); +} + + //Example 8-5 Cube Map Texture Coordinate Generation + + // position is the normalized position coordinate in eye space + // normal is the normalized normal coordinate in eye space + // returns the reflection vector as a vec3 texture coordinate +vec3 cube_map(vec3 position, vec3 normal) +{ + return reflect(position, normal); +} + +//Object Linear Mapping +//When the texture generation mode is set to GL_OBJECT_LINEAR, texture coordinates are generated using the following function: +//coord = P1*X + P2*Y + P3*Z + P4*W +// The X, Y, Z, and W values are the vertex coordinates from the object being textured, and the P1–P4 values are the coefficients for a plane equation. + +//For this shader in my code I have: +//Vector4f plane0S = new Vector4f(3.0f, 1.5f, 0.3f, 0.0f); //to calc coord S +//Vector4f plane0T = new Vector4f(1.0f, 2.5f, 0.24f, 0.0f); //to calc coord T +//I could hand them is as uniforms, but I choose to hard code them + + +vec2 object_linear(vec4 pos, vec4 planeOS, vec4 planeOT) +{ + return vec2(pos.x*planeOS.x+pos.y*planeOS.y+pos.z*planeOS.z+ pos.w*planeOS.w,pos.x*planeOT.x+pos.y*planeOT.y+pos.z*planeOT.z+pos.w*planeOT.w); +} + + +void main() +{ + Normal = normalize(vec3(glNormalMatrix * glNormal)); + + // Transform the vertex + gl_Position = glModelViewProjectionMatrix * glVertex; + + texCoord0 = object_linear(gl_Position, vec4(3.0, 1.5, 0.3, 0.0),vec4(1.0, 2.5, 0.24, 0.0)); + texCoord1 = sphere_map(gl_Position.xyz, Normal); + +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/phong.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/phong.frag new file mode 100644 index 0000000..fdea058 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/phong.frag @@ -0,0 +1,123 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +// A GLSL fragment program for handling 1 directional light with specular. +// This implements per-pixel lighting (Phong shading) + +uniform vec4 glLightSource0position; +uniform vec4 glLightSource0diffuse; + +uniform vec4 glLightModelambient; + +uniform vec4 glFrontMaterialdiffuse; +uniform float glFrontMaterialshininess; +uniform vec3 glFrontMaterialspecular; + +varying vec3 worldPos; + +void directionalLight0(in vec3 normal, inout vec4 ambient, inout vec4 diffuse, inout vec3 specular) +{ + // Normalized light direction and half vector + vec3 lightDirection = normalize(vec3(glLightSource0position)); + + + // half vector requires a few calcs + //vec3 halfVector = normalize(vec3(gl_LightSource[0].halfVector)); + + vec3 L = normalize(glLightSource0position.xyz - worldPos); + vec3 V = vec3(0,0,1);//eye position + vec3 halfVector = (L + V); + + + float nDotVP; // normal . light_direction + float nDotHV; // normal . light_half_vector + float pf; // power factor + + nDotVP = max(0.0, dot(normal, lightDirection)); + nDotHV = max(0.0, dot(normal, halfVector)); + + if (nDotVP == 0.0) { + pf = 0.0; + } + else { + pf = pow(nDotHV, glFrontMaterialshininess); + } + + // GL2ES2: ambient is part of light model + //ambient += gl_LightSource[0].ambient; + ambient += glLightModelambient; + diffuse += glLightSource0diffuse * nDotVP; + + // GL2ES2: specular is part of material + //specular += gl_LightSource[0].specular * pf; + specular += glFrontMaterialspecular * pf; +} + + +// Per-pixel normal (input from vertex shader) +varying vec3 Normal; + +void main() +{ + vec3 unitNorm = normalize(Normal); + vec4 amb = vec4(0.0); + vec4 diff = vec4(0.0); + vec3 spec = vec3(0.0); + int i; + + + directionalLight0(unitNorm, amb, diff, spec); + + + // Apply the result of the lighting equation + vec4 secondaryColor = vec4(spec * glFrontMaterialspecular, 1.0); + // GL2ES2: need to look up the calculations on sceneColor + //vec4 color = vec4(vec3(gl_FrontLightModelProduct.sceneColor + + // amb * glFrontMaterialambient + + vec4 color = vec4(vec3(glFrontMaterialdiffuse + + amb * glLightModelambient + + diff * glFrontMaterialdiffuse), 1.0); + + gl_FragColor = color + secondaryColor; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/phong.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/phong.vert new file mode 100644 index 0000000..b436ee2 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/phong.vert @@ -0,0 +1,70 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +// A GLSL vertex program for doing Phone shading (per-fragment lighting) + + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewProjectionMatrix; +uniform mat4 glModelViewMatrix; +uniform mat3 glNormalMatrix; + +// Per-pixel normal (output to fragment shader) +varying vec3 Normal; +varying vec3 worldPos; + + +void main() +{ + Normal = normalize(vec3(glNormalMatrix * glNormal)); + + worldPos = vec3(glModelViewMatrix * glVertex); + + // Transform the vertex + gl_Position = glModelViewProjectionMatrix * glVertex; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/polkadot3d.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/polkadot3d.frag new file mode 100644 index 0000000..605cb5f --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/polkadot3d.frag @@ -0,0 +1,49 @@ +// +// Fragment shader for 3 dimensional polka dot shader. +// +// Author: Joshua Doss +// +// Copyright (C) 2002-2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// +varying float LightIntensity; +varying vec3 MCPosition; + +//Create uniform variables so dots can be spaced and scaled by user +//uniform vec3 Spacing; +//uniform float DotSize; +const vec3 Spacing = vec3 (0.314, 0.36, 0.261); +const float DotSize = 0.123; + +//Create colors as uniform variables so they can be easily changed +//uniform vec3 ModelColor, PolkaDotColor; +const vec3 ModelColor = vec3 (0.75, 0.2, 0.1); +const vec3 PolkaDotColor = vec3 (1, 1, 1); + +void main(void) +{ + float insidesphere, sphereradius, scaledpointlength; + vec3 scaledpoint, finalcolor; + + // Scale the coordinate system + // The following line of code is not yet implemented in current drivers: + // mcpos = mod(Spacing, MCposition); + // We will use a workaround found below for now + scaledpoint = MCPosition - (Spacing * floor(MCPosition/Spacing)); + + // Bring the scaledpoint vector into the center of the scaled coordinate system + scaledpoint = scaledpoint - Spacing/2.0; + + // Find the length of the scaledpoint vector and compare it to the dotsize + scaledpointlength = length(scaledpoint); + insidesphere = step(scaledpointlength,DotSize); + + // Determine final output color before lighting + finalcolor = vec3(mix(ModelColor, PolkaDotColor, insidesphere)); + + // Output final color and factor in lighting + // GL2ES2: gl_FragColor is unchanged + gl_FragColor = clamp((vec4( finalcolor, 1.0 ) * LightIntensity), vec4(0.0), vec4(1.0)); +} + diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/polkadot3d.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/polkadot3d.vert new file mode 100644 index 0000000..0422670 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/polkadot3d.vert @@ -0,0 +1,75 @@ +// This is the Vertex Shader for three dimensional polka dots. +// +// author(s): Joshua Doss +// +// Copyright (C) 2002-2004 3Dlabs Inc. Ltd. + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewMatrix; +uniform mat4 glModelViewProjectionMatrix; +uniform mat3 glNormalMatrix; + +//Create uniform variables for lighting to allow user interaction +//uniform float SpecularContribution; +//uniform vec3 LightPosition; + +const float SpecularContribution = 0.36; +const vec3 LightPosition = vec3 (0, 4, 5); + +varying vec3 MCPosition; +varying float LightIntensity; + +void main(void) +{ + float diffusecontribution = 1.0 - SpecularContribution; + + // compute the vertex position in eye coordinates + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec3 ecPosition = vec3(gl_ModelViewMatrix * gl_Vertex); + vec3 ecPosition = vec3(glModelViewMatrix * glVertex); + + // compute the transformed normal + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec3 tnorm = normalize(gl_NormalMatrix * gl_Normal); + vec3 tnorm = normalize(glNormalMatrix * glNormal); + + // compute a vector from the model to the light position + vec3 lightVec = normalize(LightPosition - ecPosition); + + // compute the reflection vector + vec3 reflectVec = reflect(-lightVec, tnorm); + + // compute a unit vector in direction of viewing position + vec3 viewVec = normalize(-ecPosition); + + // calculate amount of diffuse light based on normal and light angle + float diffuse = max(dot(lightVec, tnorm), 0.0); + float spec = 0.0; + + // if there is diffuse lighting, calculate specular + if(diffuse > 0.0) + { + spec = max(dot(reflectVec, viewVec), 0.0); + spec = pow(spec, 16.0); + } + + // add up the light sources, since this is a varying (global) it will pass to frag shader + LightIntensity = diffusecontribution * diffuse * 1.5 + + SpecularContribution * spec; + + // the varying variable MCPosition will be used by the fragment shader to determine where + // in model space the current pixel is + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //MCPosition = vec3 (gl_Vertex); + MCPosition = vec3 (glVertex); + + // send vertex information + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; + gl_Position = glModelViewProjectionMatrix * glVertex; +} + diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/simple.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/simple.frag new file mode 100644 index 0000000..96a6e64 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/simple.frag @@ -0,0 +1,68 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +// Simple GLSL fragment program to attenuate the input fragment color as a +// function of the distance of the fragment position from the center +// of the window + +//GL2ES2: varying color data needs to be defined +varying vec4 glFrontColor; +varying vec4 glFrontSecondaryColor; + +//GL2ES2: see particle system point size for mechanism +const float windowSize = 700.0; // TODO: this should be a built-in parameter! + +void main() +{ + // Compute distance from center in range [0.0, 1.0] + //GL2ES2: gl_FragCoord still exists + vec2 dist = min(abs((gl_FragCoord.xy - (windowSize)/2.0) / windowSize), 1.0); + vec2 invDist = 1.0 - dist; + + // Compute attenuation + float atten = invDist.x * invDist.y; + vec4 outcolor = (glFrontColor + glFrontSecondaryColor) * atten; + + gl_FragColor = outcolor; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/simple.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/simple.vert new file mode 100644 index 0000000..96ccf6b --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/simple.vert @@ -0,0 +1,174 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +// A simple GLSL vertex program for handling 2 directional lights with +// separate specular + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; +attribute vec4 glColor; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewMatrix; +uniform mat4 glModelViewProjectionMatrix; +uniform mat3 glNormalMatrix; + +uniform vec4 glFrontMaterialdiffuse; +uniform vec4 glFrontMaterialemission; +uniform vec3 glFrontMaterialspecular; +uniform float glFrontMaterialshininess; +uniform int ignoreVertexColors; + +uniform vec4 glLightModelambient; + +uniform vec4 glLightSource0position; +uniform vec4 glLightSource0diffuse; + +//GL2ES2: varying color data needs to be defined +varying vec4 glFrontColor; +varying vec4 glFrontSecondaryColor; + +void directionalLight( + in int i, + in vec3 normal, + inout vec4 ambient, + inout vec4 diffuse, + inout vec3 specular) +{ + // Normalized light direction and half vector + // (shouldn't they be pre-normalized?!) + + //GL2ES2 notice not using the i parameter but hard coded to 0 + vec3 lightDirection = normalize(vec3(glLightSource0position)); + + //GL2ES2: half vector must be calculated + //vec3 halfVector = normalize(vec3(gl_LightSource[0].halfVector)); + vec3 worldPos = vec3(glModelViewMatrix * glVertex); + vec3 L = normalize(glLightSource0position.xyz - worldPos); + vec3 V = vec3(0,0,1);//eye position + vec3 halfVector = (L + V); + + + + float nDotVP; // normal . light_direction + float nDotHV; // normal . light_half_vector + float pf; // power factor + + nDotVP = max(0.0, dot(normal, lightDirection)); + nDotHV = max(0.0, dot(normal, halfVector)); + + if (nDotVP == 0.0) { + pf = 0.0; + } + else { + pf = pow(nDotHV, glFrontMaterialshininess); + } + + ambient += glLightModelambient; + diffuse += glLightSource0diffuse * nDotVP; + specular += glFrontMaterialspecular * pf; +} + +//GL2ES2: only a single light for now +const int numEnabledLights = 1; // TODO: this should be a built-in parameter! + +void main() +{ + //vec4 ecPosition = gl_ModelViewMatrix * gl_Vertex; + //vec3 ecPosition3 = ecPosition.xyz / ecPosition.w; + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec3 tnorm = normalize(vec3(gl_NormalMatrix * gl_Normal)); + vec3 tnorm = normalize(vec3(glNormalMatrix * glNormal)); + vec4 amb = vec4(0.0); + vec4 diff = vec4(0.0); + vec3 spec = vec3(0.0); + int i; + + // Transform the vertex + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec4 outPosition = gl_ModelViewProjectionMatrix * gl_Vertex; + vec4 outPosition = glModelViewProjectionMatrix * glVertex; + + for (i = 0; i < numEnabledLights; i++) { + directionalLight(i, tnorm, amb, diff, spec); + } + + vec4 sceneColor; + if( ignoreVertexColors != 0) + sceneColor = glFrontMaterialdiffuse; + else + sceneColor = glColor; + + // Apply the result of the lighting equation + vec4 outSecondaryColor = vec4(vec3(spec * glFrontMaterialspecular), 1.0); + vec3 color0 = vec3(sceneColor + + amb * glLightModelambient + + diff * glFrontMaterialdiffuse); + + // Generate a pseudo-random noise pattern + vec3 xyz = clamp((outPosition.xyz + 1.0) * 0.5, 0.0, 1.0); + + xyz = fract(xyz * 262144.0); + float randSeed = fract(3.0 * xyz.x + 5.0 * xyz.y + 7.0 * xyz.z); + + vec3 altColor; + + randSeed = fract(37.0 * randSeed); + altColor.x = randSeed * 0.5 + 0.5; + randSeed = fract(37.0 * randSeed); + altColor.y = randSeed * 0.5 + 0.5; + randSeed = fract(37.0 * randSeed); + altColor.z = randSeed * 0.5 + 0.5; + randSeed = fract(37.0 * randSeed); + float altAlpha = randSeed * 0.5; + + // Apply noise and output final vertex color + vec4 outColor; + outColor = vec4(mix(color0, altColor, altAlpha), 1.0); + + glFrontColor = outColor; + glFrontSecondaryColor = outSecondaryColor; + gl_Position = outPosition; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/toon.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/toon.frag new file mode 100644 index 0000000..fa50453 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/toon.frag @@ -0,0 +1,34 @@ +// +// Fragment shader for cartoon-style shading +// +// Author: Philip Rideout +// +// Copyright (c) 2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// + +//uniform vec3 DiffuseColor; +//uniform vec3 PhongColor; +//uniform float Edge; +//uniform float Phong; + +vec3 DiffuseColor = vec3(0.5,0.5,1.0); +vec3 PhongColor = vec3(0.75,0.75,1.0); +float Edge = 0.64; +float Phong = 0.90; + +varying vec3 Normal; +varying vec3 LightDir; + +void main (void) +{ + vec3 color = DiffuseColor; + float f = max( 0.0, dot(LightDir,Normal)); + if (abs(f) < Edge) + color = DiffuseColor * 0.2; + if (f > Phong) + color = PhongColor; + + gl_FragColor = vec4(color, 1); +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/toon.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/toon.vert new file mode 100644 index 0000000..d044af7 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/toon.vert @@ -0,0 +1,19 @@ +// +// Vertex shader for cartoon-style shading +// +// Author: Philip Rideout +// +// Copyright (c) 2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// + +varying vec3 Normal; +varying vec3 LightDir; + +void main(void) +{ + Normal = normalize(gl_NormalMatrix * gl_Normal); + gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; + LightDir = vec3(normalize(gl_LightSource[0].position)); +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/vertexshader.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/vertexshader.frag new file mode 100644 index 0000000..029b044 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/vertexshader.frag @@ -0,0 +1,52 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + + +//GL2ES2: varying color data needs to be defined +varying vec4 glFrontColor; + +void main() +{ + gl_FragColor = glFrontColor; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/vertexshader.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/vertexshader.vert new file mode 100644 index 0000000..12f3662 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/vertexshader.vert @@ -0,0 +1,70 @@ +/* + * $RCSfile$ + * + * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL + * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF + * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR + * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, + * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND + * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR + * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or + * intended for use in the design, construction, operation or + * maintenance of any nuclear facility. + * + * $Revision$ + * $Date$ + * $State$ + */ + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewProjectionMatrix; + +// A simple GLSL vertex program for demo. vertex attributes + +attribute float weight; +attribute vec3 temperature; + +//GL2ES2: varying color data needs to be defined +varying vec4 glFrontColor; + +void main() +{ + // Transform the vertex + vec4 outPosition = glModelViewProjectionMatrix * glVertex; + + // Compute color from temperature + vec4 outColor; + outColor = vec4(temperature * weight, 1); + // Assign output parameters + glFrontColor = outColor; + gl_Position = outPosition; +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/wood.frag b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/wood.frag new file mode 100644 index 0000000..6686190 --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/wood.frag @@ -0,0 +1,67 @@ +// +// Simple fragment shader for wood +// +// Author: John Kessenich +// +// Copyright (c) 2002-2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// + +//uniform float GrainSizeRecip; +//uniform vec3 DarkColor; +//uniform vec3 spread; +const float GrainSizeRecip = 1.0; +const vec3 DarkColor = vec3 (0.6, 0.3, 0.1); +const vec3 spread = vec3 (0.15, 0.075, 0.0); + +varying float lightIntensity; +varying vec3 Position; + +void main (void) +{ + // + // cheap noise + // + vec3 location = Position; + vec3 floorvec = vec3(floor(10.0 * Position.x), 0.0, floor(10.0 * Position.z)); + vec3 noise = Position * 10.0 - floorvec - 0.5; + noise *= noise; + location += noise * 0.12; + + // + // distance from axis + // + float dist = location.x * location.x + location.z * location.z; + float grain = dist * GrainSizeRecip; + + // + // grain effects as function of distance + // + float brightness = fract(grain); + if (brightness > 0.5) + brightness = (1.0 - brightness); + vec3 color = DarkColor + brightness * spread; + + brightness = fract(grain * 7.0); + if (brightness > 0.5) + brightness = 1.0 - brightness; + color -= brightness * spread; + + // + // also as a function of lines parallel to the axis + // + brightness = fract(grain * 47.0) * 0.60; + float line = fract(Position.z + Position.x); + float snap = floor(line * 20.0) * (1.0/20.0); + if (line < snap + 0.006) + color -= brightness * spread; + + // + // apply lighting effects from vertex processor + // + color = clamp(color * lightIntensity, 0.0, 1.0); + + // GL2ES2: gl_FragColor is unchanged + gl_FragColor = vec4(color, 1.0); +} diff --git a/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/wood.vert b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/wood.vert new file mode 100644 index 0000000..e04ba6d --- /dev/null +++ b/src/classes/org/jdesktop/j3d/examples/gl2es2pipeline/wood.vert @@ -0,0 +1,43 @@ +// +// Simple vertex shader for wood +// +// Author: John Kessenich +// +// Copyright (c) 2002-2004 3Dlabs Inc. Ltd. +// +// See 3Dlabs-License.txt for license information +// + +// GL2ES2: Java3D built-in attributes, these are calculated and passsed in if declared here +attribute vec4 glVertex; +attribute vec3 glNormal; + +// GL2ES2: Java3D built-in uniforms, these are calculated and passsed in if declared here +uniform mat4 glModelViewMatrix; +uniform mat4 glModelViewProjectionMatrix; +uniform mat3 glNormalMatrix; + +varying float lightIntensity; +varying vec3 Position; +//uniform vec3 LightPosition; +//uniform float Scale; +const vec3 LightPosition = vec3 (0.0,0.0,0.4); +const float Scale = 1.0; + +void main(void) +{ + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec4 pos = glModelViewMatrix * glVertex; + vec4 pos = glModelViewMatrix * glVertex; + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //Position = vec3(glVertex) * Scale; + Position = vec3(glVertex) * Scale; + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //vec3 tnorm = normalize(gl_NormalMatrix * gl_Normal); + vec3 tnorm = normalize(glNormalMatrix * glNormal); + lightIntensity = max(dot(normalize(LightPosition - vec3(pos)), tnorm), 0.0) * 1.5; + + // GL2ES2: swap built-in variable for Java3d built-in uniforms and attributes gl_* = gl* + declaration (at top) + //gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; + gl_Position = glModelViewProjectionMatrix * glVertex; +} |