LWJGL Forum

Please login or register.

Login with username, password and session length
Pages: 1 [2] 3 4 ... 10
 11 
 on: June 22, 2017, 09:29:43 
Started by RDM - Last post by RDM
mapped buffers and glsl

I'm sorry, could you elaborate a little bit? I'd like to understand what I was doing wrong but I'm afraid this is a tad too little to go on ^^

 12 
 on: June 22, 2017, 09:22:45 
Started by RDM - Last post by Evan407
mapped buffers and glsl

 13 
 on: June 22, 2017, 09:13:40 
Started by RDM - Last post by RDM
Hi all,

I've recently started dabbling in OpenGL and was following one of the tutorials on the wiki. The following happened to me using the OpenGL context 4.0 core profile on a macOS Sierra 10.12.5 MBP with an integrated graphics card capable of running up to OpenGL 4.1, with JDK 1.8.0_121 and LWJGL 3.1.2.

The triangle tutorial is very simple and basically does the following:
- use glfw to create a window
- create a vertex shader and fragment shader
- create a VBO describing the triangle's position and color
- draw the triangle

The tutorial code ran without issues (though it took me a while to figure out I had to move GL.createCapabilities() from the render loop to my init method, before trying to create the shaders etc!) but the screen remained black. After hours I found that the reason for this was related to the
Code: [Select]
GL15.glBufferData method. I was using the overloaded version which takes a FloatBuffer as second parameter. Replacing this FloatBuffer by the backing float[] solved my issue and suddenly my triangle was visible on screen.

I tried creating the FloatBuffer in numerous ways:
- via MemoryStack.stackPush().mallocFloat(...).put(..).put(..)....flip()
- via FloatBuffer.allocate(..).put(..).put(..)....flip()
- via FloatBuffer.wrap(new float[]{...})
but in none of these cases did the triangle appear on screen. However, when using the overloaded version of GL15.glBufferData which directly takes the float[] as second parameter, the triangle is shown.

Below you can find a minimal verifiable code example (2 java files and 2 shader files) to reproduce this issue. I say issue but I'm not sure if it even is an issue, I might just be doing something wrong with the buffer, but I don't see what.

Code: [Select]
import org.lwjgl.Version;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.MemoryStack;

import java.nio.IntBuffer;

import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.system.MemoryStack.stackPush;
import static org.lwjgl.system.MemoryUtil.NULL;

/**
 * Created by RDM on 21/06/2017.
 */
public class Test3 {
    // The window handle
    private long window;
    // the vertex array
    private int vao;
    // a vertex buffer object
    private int vbo;
    // a vertex shader
    private int vertexShader;
    // a fragment shader
    private int fragmentShader;
    // a shader program
    private int shaderProgram;

    public static void main(String[] args) {
        new Test3().run();
    }

    public void run() {
        System.out.println("Hello LWJGL " + Version.getVersion() + "!");

        init();
        loop();

        System.out.println("Starting clean up routine!");
        destroyShaders();
        destroyVBO();

        // Free the window callbacks and destroy the window
        glfwFreeCallbacks(window);
        glfwDestroyWindow(window);

        // Terminate GLFW and free the error callback
        glfwTerminate();
        glfwSetErrorCallback(null).free();
    }

    private void init() {
        // Setup an error callback. The default implementation
        // will print the error message in System.err.
        GLFWErrorCallback.createPrint(System.err).set();

        // Initialize GLFW. Most GLFW functions will not work before doing this.
        if (!glfwInit())
            throw new IllegalStateException("Unable to initialize GLFW");

        // Configure GLFW
        glfwDefaultWindowHints(); // optional, the current window hints are already the default
        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
//        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
//        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

        // Create the window
        window = glfwCreateWindow(300, 300, "Hello World!", NULL, NULL);
        if (window == NULL)
            throw new RuntimeException("Failed to create the GLFW window");

        // Setup a key callback. It will be called every time a key is pressed, repeated or released.
        glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
                glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop
        });

        // Get the thread stack and push a new frame
        try (MemoryStack stack = stackPush()) {
            IntBuffer pWidth = stack.mallocInt(1); // int*
            IntBuffer pHeight = stack.mallocInt(1); // int*

            // Get the window size passed to glfwCreateWindow
            glfwGetWindowSize(window, pWidth, pHeight);

            // Get the resolution of the primary monitor
            GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

            // Center the window
            glfwSetWindowPos(
                    window,
                    (vidmode.width() - pWidth.get(0)) / 2,
                    (vidmode.height() - pHeight.get(0)) / 2
            );
        } // the stack frame is popped automatically

        // Make the OpenGL context current
        glfwMakeContextCurrent(window);
        // Enable v-sync
        glfwSwapInterval(1);

        // This line is critical for LWJGL's interoperation with GLFW's
        // OpenGL context, or any context that is managed externally.
        // LWJGL detects the context that is current in the current thread,
        // creates the GLCapabilities instance and makes the OpenGL
        // bindings available for use.
        GL.createCapabilities();

        vao = glGenVertexArrays();
        glBindVertexArray(vao);

        glViewport(0, 0, 300, 300);

        createShaders();
        createVBO();

        // Make the window visible
        glfwShowWindow(window);
    }

    private void loop() {
        // Set the clear color
        glClearColor(0.6f, 0.6f, 0.6f, 0.0f);

        // Run the rendering loop until the user has attempted to close
        // the window or has pressed the ESCAPE key.
        while (!glfwWindowShouldClose(window)) {
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

//            System.out.println("drawing VAO");
            glDrawArrays(GL_TRIANGLES, 0, 3);

            glfwSwapBuffers(window); // swap the color buffers

            // Poll for window events. The key callback above will only be
            // invoked during this call.
//            glfwPollEvents();
            // "If instead you only need to update your rendering once you have received new input, glfwWaitEvents is a better choice. It waits until at least one event has been received, putting the thread to sleep in the meantime, and then processes all received events. This saves a great deal of CPU cycles and is useful for, for example, many kinds of editing tools."
            glfwWaitEvents();
        }
    }

    private void createVBO() {

        try (MemoryStack stack = MemoryStack.stackPush()) {
            float[] vertexData = {-.8f, -.8f, 0, 1, 1, 0, 0, 1,
                    0, .8f, 0, 1, 0, 1, 0, 1,
                    .8f, -.8f, 0, 1, 0, 0, 1, 1};
            vbo = glGenBuffers();
            glBindBuffer(GL_ARRAY_BUFFER, vbo);
//            glBufferData(GL_ARRAY_BUFFER, FloatBuffer.wrap(vertexData), GL_STATIC_DRAW);
            glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW);
            int positionLocation = glGetAttribLocation(shaderProgram, "position");
            int colorLocation = glGetAttribLocation(shaderProgram, "color");
            int floatSize = 4;
            glVertexAttribPointer(positionLocation, 4, GL_FLOAT, false, 8 * floatSize, 0);
            glVertexAttribPointer(colorLocation, 4, GL_FLOAT, false, 8 * floatSize, 4 * floatSize);
            glEnableVertexAttribArray(positionLocation);
            glEnableVertexAttribArray(colorLocation);

            int e = glGetError();
            if (e != GL_NO_ERROR) {
                throw new RuntimeException("Error creating VBO");
            }

            System.out.println("Initialized VBO (pos=" + positionLocation + ", col=" + colorLocation + ")");
        }
    }

    private void createShaders() {
        Shader vertexShader = Shader.loadShader(GL_VERTEX_SHADER, "triangle.vs");
        this.vertexShader = vertexShader.getID();
        System.out.println("Created vertex shader");
        Shader fragmentShader = Shader.loadShader(GL_FRAGMENT_SHADER, "triangle.fs");
        this.fragmentShader = fragmentShader.getID();
        System.out.println("Created fragment shader");

        shaderProgram = glCreateProgram();
        System.out.println("Created shader program");
        glAttachShader(shaderProgram, this.vertexShader);
        glAttachShader(shaderProgram, this.fragmentShader);
        glLinkProgram(shaderProgram);
        System.out.println("Linked shader program");
        if (glGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) {
            throw new RuntimeException(glGetProgramInfoLog(shaderProgram));
        }
        glUseProgram(shaderProgram);
        System.out.println("Using shader program");
    }

    private void destroyShaders() {
        glUseProgram(0);
        glDetachShader(shaderProgram, vertexShader);
        glDetachShader(shaderProgram, fragmentShader);
        glDeleteShader(vertexShader);
        glDeleteProgram(shaderProgram);
    }

    private void destroyVBO() {
        // position
        glDisableVertexAttribArray(0);
        // color
        glDisableVertexAttribArray(1);

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glDeleteBuffers(vbo);

        glBindVertexArray(0);
        glDeleteVertexArrays(vao);
    }
}

I use a the Shader utility class (copied directly from the SilverTiger tutorial to lwjgl3 from the wiki) to load 2 shaders:

triangle.vs:

Code: [Select]
#version 400 core

in vec4 position;
in vec4 color;

out vec4 vertexColor;

void main() {
    vertexColor = color;
    gl_Position = position;
}

triangle.fs:

Code: [Select]
#version 400

in vec4 vertexColor;

out vec4 fragColor;

void main() {
    fragColor = vertexColor;
}

The Shader utility class file containing Shader.loadShader:

Code: [Select]
import java.io.*;

import static org.lwjgl.opengl.GL11.GL_TRUE;
import static org.lwjgl.opengl.GL20.*;

/**
 * This class represents a shader.
 *
 * @author Heiko Brumme
 */
public class Shader {

    /**
     * Stores the handle of the shader.
     */
    private final int id;

    /**
     * Creates a shader with specified type. The type in the tutorial should be
     * either <code>GL_VERTEX_SHADER</code> or <code>GL_FRAGMENT_SHADER</code>.
     *
     * @param type Type of the shader
     */
    public Shader(int type) {
        id = glCreateShader(type);
    }

    /**
     * Creates a shader with specified type and source and compiles it. The type
     * in the tutorial should be either <code>GL_VERTEX_SHADER</code> or
     * <code>GL_FRAGMENT_SHADER</code>.
     *
     * @param type   Type of the shader
     * @param source Source of the shader
     * @return Compiled Shader from the specified source
     */
    public static Shader createShader(int type, CharSequence source) {
        Shader shader = new Shader(type);
        shader.source(source);
        shader.compile();

        return shader;
    }

    /**
     * Loads a shader from a file.
     *
     * @param type Type of the shader
     * @param path File path of the shader
     * @return Compiled Shader from specified file
     */
    public static Shader loadShader(int type, String path) {
        StringBuilder builder = new StringBuilder();

        File file = new File(path);
        try (InputStream in = new FileInputStream(file);
//        try (InputStream in = Shader.class.getResourceAsStream(path);
             BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line).append("\n");
            }
        } catch (IOException ex) {
            throw new RuntimeException("Failed to load a shader file: <" + file.getAbsolutePath() + ">"
                                               + System.lineSeparator() + ex.getMessage());
        }
        CharSequence source = builder.toString();

        return createShader(type, source);
    }

    /**
     * Sets the source code of this shader.
     *
     * @param source GLSL Source Code for the shader
     */
    public void source(CharSequence source) {
        glShaderSource(id, source);
    }

    /**
     * Compiles the shader and checks it's status afertwards.
     */
    public void compile() {
        glCompileShader(id);

        checkStatus();
    }

    /**
     * Checks if the shader was compiled successfully.
     */
    private void checkStatus() {
        int status = glGetShaderi(id, GL_COMPILE_STATUS);
        if (status != GL_TRUE) {
            throw new RuntimeException(glGetShaderInfoLog(id));
        }
    }

    /**
     * Deletes the shader.
     */
    public void delete() {
        glDeleteShader(id);
    }

    /**
     * Getter for the shader ID.
     *
     * @return Handle of this shader
     */
    public int getID() {
        return id;
    }

}

 14 
 on: June 22, 2017, 09:08:00 
Started by bluevideogame - Last post by spasi
This is a macOS limitation and it is per process. If you need multiple event loops for some reason, then you'd have to launch your application multiple times and use an IPC mechanism to talk to each other.

 15 
 on: June 22, 2017, 08:57:14 
Started by bluevideogame - Last post by yoojeen
some error.

Exception in thread "Thread-0" java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalStateException: GLFW windows may only be created on the main thread.
   at org.lwjgl.glfw.EventLoop$OffScreen.<clinit>(EventLoop.java:37)
   ... 4 more

okay, it's works in main thread.

but what we do if client-server application engineering, and server part use main thread, and GUI needed in second thread for local run of app, or just use in main for app with implements Runnable (runnable make another thread) ????

is this a hard/soft restriction or bug? with what is connected? can i work around it?

 16 
 on: June 22, 2017, 04:48:24 
Started by Lightbuffer - Last post by Evan407
Hello there! :)

I'm starting working on a low-poly 3D game, but before I can actually start working on the games, I need some basic game engine. I'm working with LWJGL3.1.1 and OpenGL3.3. My requirements for skeletal animation doesn't really require dynamic per vertex animation, rather something like Minecraft-ish animations where each box rotates all its vertexes around its given origin (anchor), but also preferably with relationship of one parent box -> one or more children boxes.

Should I go with "traditional" (as far as I understand it's the traditional method) method like described here or here? Or is there a simpler way to implement such animation?

Thanks for attention!
I implemented bones and animations with my own code. Then interpolation between the tweens or moments or whatever they are called. Time length of each moment.
The bones also have a child parent structure. One bone's transformation matrix is passed onto its children and the children bone is rotated about its parent bone. It is complicated but I found it easier to make my own formats.

 17 
 on: June 22, 2017, 04:45:46 
Started by Evan407 - Last post by Evan407
You're using the wrong overload. Try:

Code: [Select]
clCompileProgram(
    program,
    platforms[0]._devices,
    "",//options
    (PointerBuffer)null,//input header
    null,//header include name
    pfn_notify,
    MemoryUtil.NULL
);

I may end up removing the other overloads, they're indeed confusing.
Thanks that got it working  8)

 18 
 on: June 21, 2017, 13:04:39 
Started by Lightbuffer - Last post by josephdoss
I ended up having to use quaternions to calculate my joints, and then to calculate the skin vertices from it. It's a real headache to figure out, but I think it's how the pros do it and it really is worth learning. Your second link discusses it a little. If you're talented with geometry shaders, you can calculate all the skin in the GPU.

 19 
 on: June 21, 2017, 12:45:55 
Started by josephdoss - Last post by josephdoss
Hey,
I could use some help with texturing. I'm drawing a square for each of my character's eyes and I want to draw a little eye picture on it. I seem to be loading the image correctly and even binding it to the texture, but when I try to draw the texture, I get nothing... Except for that one time I got two white squares. I think my problem is either in my shader or where I set my glVertexAttribPointer. If anyone out there can see where I'm messing up, please let me know. Attached is the entire class file. Below are the parts I think are most relevant for this.

Before you tell me to go look at the demos and simply google it, I have... every day... for the last three months. Whatever I'm missing I haven't been able to work out from the examples and documentation out there.

From outside this class, there are only three ways it's used.
When it's constructed, when the 4 vertices are updated, and when draw() is called.
So, to follow the opengl logic you can start with glConstruct() and draw().

Right now my character's eyes look like this, so you understand why I'm wanting textures.




Here is most of the relevant code. If you want to see it all, see the attached file.


public class human2_eye_textured
{
   int[] skinEyeIndicesDraw = {   
         0, 2,1               
         , 0, 3,2//
   };

   float[] skinEyeVerticesDraw = {
         // vertices            //textures
         0f, 0f, 0f,             0f,0f,  // 0 Bottom Right   , outward bottom left
         0f, 0f, 0f,             0f,1f,  // 1 top right      , outward top left
         10f, 10f, 0f,           1f,1f,  // 2  top left      , outward top right
         -10f, -30f, 0f          ,1f,0f  // 3 bottom left     , outward bottom right
    };
   
   int skinEyeVAOID = -1;
   int skinEyeVBOID = -1;
   int skinEyeVBOIID = -1;
   int textureID = -1;

   public int skinEyeGLMVPUniformLocation;
   public int skinEyeGLRGBAUniformLocation;

   public FloatBuffer skinEyeFB = BufferUtils.createFloatBuffer(20);//(16);

   public int skinEyeProgramId;
   public int skinEyeVertexShaderId;
   public int skinEyeFragmentShaderId;
   public int skinEyeGLTextureCoordLocation;
   public int skinEyeGLTextureImageUniform;

   boolean isSkinEyeIndexBound = false;

   public Matrix4f MVP;

   FloatBuffer verticesBufferSkinEye;

   float distTR, distTL, distBR, distBL;

   float eyeColorRed = 0.545f;
   float eyeColorGreen = 0.271f;
   float eyeColorBlue = 0.075f;

   Vector3f topLeftVertex;
   Vector3f topRightVertex;
   Vector3f botLeftVertex;
   Vector3f botRightVertex;

   Vector3f topLeftRotate;
   Vector3f topRightRotate;
   Vector3f botLeftRotate;
   Vector3f botRightRotate;

   IntBuffer textureWidth = BufferUtils.createIntBuffer(1);
   IntBuffer textureHeight = BufferUtils.createIntBuffer(1);
   IntBuffer textureComponents = BufferUtils.createIntBuffer(1);
   ByteBuffer textureData;

   String textureSourceLeft = "resources" + File.separatorChar + "states" + File.separatorChar + "human2" + File.separatorChar + "eyes" + File.separatorChar + "tester.png";// "eye-default-left.png";
   String textureSourceRight = "resources" + File.separatorChar + "states" + File.separatorChar + "human2" + File.separatorChar + "eyes" + File.separatorChar +"tester.jpg";// "eye-default-Right.jpg";

   public human2_eye_textured(String lr) {
      System.out.println("human2_eye_textured just entered constructor with arg:" + lr);
      String textureSource;
      if (lr == "left") {
         textureSource = textureSourceLeft;
      } else {
         textureSource = textureSourceRight;
      }
      
      System.out.println("human2_eye_textured using this value for textureSource:"+textureSource);
      
      try {
         textureData = stbi_load_from_memory(ioResourceToByteBuffer(textureSource, 20*1024), textureWidth, textureHeight, textureComponents, 4);
      } catch (Exception e) {
         System.out.println("human2_eye_textured constructor : error thrown making the texture message:" + e.getMessage() + " stacktrace:" + e.getStackTrace());
      }
      
      try{
      glConstruct();
      }catch(Exception e)
      {System.out.println("error caught in human2_eye_textured constructor around glConstruct() message:"+e.getMessage()+" stacktrace:"+e.getStackTrace());}
   }

   
   public float[] actionJoints() {

      float[] vertices = skinEyeVerticesDraw;
      int index = 0;

      vertices[index++] = botRightVertex.x;
      vertices[index++] = botRightVertex.y;
      vertices[index++] = botRightVertex.z;
      vertices[index++]=0f;
      vertices[index++]=0f;

      vertices[index++] = topRightVertex.x;
      vertices[index++] = topRightVertex.y;
      vertices[index++] = topRightVertex.z;
      vertices[index++]=0f;
      vertices[index++]=1f;

      vertices[index++] = topLeftVertex.x;
      vertices[index++] = topLeftVertex.y;
      vertices[index++] = topLeftVertex.z;
      vertices[index++]=1f;
      vertices[index++]=1f;

      vertices[index++] = botLeftVertex.x;
      vertices[index++] = botLeftVertex.y;
      vertices[index++] = botLeftVertex.z;
      vertices[index++]=1f;
      vertices[index++]=0f;

      return vertices;
   }

   public void bindSkinEyeVertexData() {
      // if (isDrawChange)
      {

         if (true) {
            if (verticesBufferSkinEye == null) {
               verticesBufferSkinEye = BufferUtils.createFloatBuffer(skinEyeVerticesDraw.length);
            }
            verticesBufferSkinEye.put(skinEyeVerticesDraw).flip();

            if (textureID == -1) {
               textureID = glGenTextures();
               
               glBindTexture(GL_TEXTURE_2D,textureID);
               //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
               //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
               
               System.out.println("about to do glTexImage2D");
               glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,textureWidth.get(),textureHeight.get(),0,GL_RGBA,GL_UNSIGNED_BYTE,textureData);
               stbi_image_free(textureData);
               System.out.println("done with glTexImage2D");

               
               
               glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
               glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);         
               
               glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
               glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);               
   
               //System.out.println("texture width and height : "+textureWidth.get() + " " +textureHeight.get());
               if(textureData==null)
               {System.out.println("about to make texture with null textureData");}
            
            }
            //glBindTexture(GL_TEXTURE_2D, textureID);

            if (skinEyeVAOID == -1) {
               skinEyeVAOID = glGenVertexArrays();
            }
            glBindVertexArray(skinEyeVAOID);

            if (skinEyeVBOID == -1) {
               skinEyeVBOID = glGenBuffers();
            }
            glBindBuffer(GL_ARRAY_BUFFER, skinEyeVBOID);
            glBufferData(GL_ARRAY_BUFFER, verticesBufferSkinEye, GL_DYNAMIC_DRAW);
            //works without texture vals in vertices[]
            //glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); // the one that works without texture
            glVertexAttribPointer(0, 3, GL_FLOAT, false, 20, 0);
            glVertexAttribPointer(0, 2, GL_FLOAT, false, 20, 12);
            //glVertexAttribPointer(2, 2, GL_FLOAT, false, 8*4, 0);
            glBindBuffer(GL_ARRAY_BUFFER, 0);
            // glBindVertexArray(0);
            //glEnableVertexAttribArray(2);
            
            
   
            
            
         

            

            if (!isSkinEyeIndexBound) {
               skinEyeIndicesCount = skinEyeIndicesDraw.length;
               IntBuffer indicesBuffer = BufferUtils.createIntBuffer(skinEyeIndicesCount);
               indicesBuffer.put(skinEyeIndicesDraw);
               indicesBuffer.flip();

               skinEyeVBOIID = glGenBuffers();
               glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skinEyeVBOIID);
               glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_DYNAMIC_DRAW);
               glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

               isSkinEyeIndexBound = true;
            }
         }

         // isDrawChange = false;
      }
   }

   public void calculateJointsVertices() {
      // System.out.println("human1.move(); called");

      double radian = Math.toRadians(degreeRotateZ);
      float cosRadian = (float) Math.cos(radian);
      float sinRadian = (float) Math.sin(radian);

      float fX, fY, fZ;

      int indexCount = 0;
      float[] vertices = {};// .clone();// act.getVertices();

      // jointsVerticesDraw =
      actionJoints();
      vertices = skinEyeVerticesDraw;

      for (int i = vertices.length; indexCount < i; indexCount += 5) {

         fX = vertices[indexCount];
         fY = vertices[indexCount + 1];
         fZ = vertices[indexCount + 2];
         setVertices(indexCount, cosRadian, sinRadian, fX, fY, fZ, vertices);
      }

       //for(int i = 0; i < vertices.length; i++)
       //{ System.out.println("skinEye draw vertex : i:"+i+" val:"+vertices);}

   }

   public void draw() {
      calculateJointsVertices();
      drawSkinEye();
   }

   public void drawSkinEye() {// System.out.println("human.drawJoints");
      glEnable(GL_DEPTH_TEST);
      glEnable(GL_CULL_FACE);
      glCullFace(GL_FRONT);
      glEnable(GL_TEXTURE_2D);
      //glEnable(GL_BLEND);
      //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
      glUseProgram(skinEyeProgramId);
      bindSkinEyeVertexData();
      

      
      
      
      

      glUniformMatrix4fv(skinEyeGLMVPUniformLocation, false, MVP.get(skinEyeFB));
      // glUniform4f(skinEyeGLRGBAUniformLocation, skinRed, skinGreen,
      // skinBlue, 1.0f);
      //glUniform

      glBindVertexArray(skinEyeVAOID);
      glEnableVertexAttribArray(0);
      //glEnableVertexAttribArray(1);

      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skinEyeVBOIID);
      glBindTexture(GL_TEXTURE_2D,textureID);
      glDrawElements(GL_TRIANGLES, skinEyeIndicesCount, GL_UNSIGNED_INT, 0);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
      // System.out.println("human.drawJoints
      // jointsIndicesCount:"+jointsIndicesLinesCount);
      glDisableVertexAttribArray(0);
       //glDisableVertexAttribArray(1);
      glBindVertexArray(0);
      
      //glBindTexture(GL_TEXTURE_2D,textureID);

      glUseProgram(0);

      // System.out.println("just drew eye");
      glDisable(GL_BLEND);
      //glDisable(GL_TEXTURE_2D);
   }

   public void glConstruct() {

      glConstructSkinEye();

   }

   public void glConstructSkinEye() {
      try {
         try {
            skinEyeProgramId = glCreateProgram();

            glCreateVertexShaderSkinEye("#version 130         \n"//
                  + "uniform mat4 MVP;                       \n"//
                  + "in vec3 position;                       \n"//
                  + "in vec2 texcoord;                       \n"//
                  // +"in vec4 in_color; \n"//
                  // +"out vec4 pass_color; \n"//
                  + "out vec2 textureCoord;              \n"//
                  + "void main() {                           \n"//
                  + "     gl_Position =MVP* vec4(position, 1.0); \n"//
                  // +" pass_color=in_color; \n"//
                  // +" pass_color=vec4(1.0,1.0,1.0,1.0); \n"//
                  + "       textureCoord = texcoord;           \n"//
                  + "}");

            glCreateFragmentShaderSkinEye("#version 130       \n"//
                  // +"in vec4 pass_color; \n"//
                  + "in vec2 textureCoord;              \n"//
                  + "uniform sampler2D texImage;             \n"//
                  + "out vec4 out_color;                     \n"//
                  + "void main() {                           \n"//
                  // +" vec4 textureColor =
                  // texture(texImage,textureCoord);\n"//
                  // +" out_color=pass_color*textureColor; \n"//
                  // +" out_color=vec4(1f,1f,1f,1f); \n"//
                  //+ "   out_color= vec4(1.0,1.0,1.0,1.0);\n"//texture(texImage,textureCoord);\n"//
                  + "   out_color= texture(texImage,textureCoord)*vec4(1.0f,1.0f,1.0f,1.0f);\n"//
                  + "}   ");

            glLink(skinEyeProgramId);

            glUseProgram(skinEyeProgramId);
            skinEyeGLMVPUniformLocation = glGetUniformLocation(skinEyeProgramId, "MVP");
            // skinEyeGLRGBAUniformLocation =
            // glGetUniformLocation(skinEyeProgramId, "RGBA");
            skinEyeGLTextureCoordLocation = glGetAttribLocation(skinEyeProgramId, "texcoord");
            skinEyeGLTextureImageUniform = glGetUniformLocation(skinEyeProgramId, "texImage");

            glUseProgram(0);

            // glEnable(GL_PROGRAM_POINT_SIZE);

         } catch (Exception e) {
            System.out.println("exception caught:" + e.getMessage() + " " + e.getStackTrace());
         }

         if (skinEyeProgramId == 0) {
            throw new Exception("Could not create Shader");
         }

      } catch (Exception e) {
         System.out.println("exception caught in init " + e.getMessage() + " " + e.getStackTrace());
      }
      // move();
   }

   public void glCreateFragmentShaderSkinEye(String shaderCode) throws Exception {
      skinEyeFragmentShaderId = glCreateThisShader(shaderCode, GL_FRAGMENT_SHADER, skinEyeProgramId);
   }

   protected int glCreateThisShader(String shaderCode, int shaderType, int programID) throws Exception {
      int shaderId = glCreateShader(shaderType);
      if (shaderId == 0) {
         throw new Exception("Error creating shader. Code: " + shaderId);
      }
      glShaderSource(shaderId, shaderCode);
      glCompileShader(shaderId);
      if (glGetShaderi(shaderId, GL_COMPILE_STATUS) == 0) {
         throw new Exception("Error compiling Shader code: " + glGetShaderInfoLog(shaderId, 1024));
      }
      glAttachShader(programID, shaderId);
      return shaderId;
   }

   public void glCreateVertexShaderSkinEye(String shaderCode) throws Exception {
      skinEyeVertexShaderId = glCreateThisShader(shaderCode, GL_VERTEX_SHADER, skinEyeProgramId);
   }

   public void glLink(int programId) throws Exception {
      glLinkProgram(programId);
      if (glGetProgrami(programId, GL_LINK_STATUS) == 0) {
         throw new Exception("Error linking Shader code: " + glGetProgramInfoLog(programId, 1024));
      }
      glValidateProgram(programId);
      if (glGetProgrami(programId, GL_VALIDATE_STATUS) == 0) {
         System.err.println("Warning validating Shader code: " + glGetProgramInfoLog(programId, 1024));
      }
   }

   public ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
      //System.out.println("ioResourceToByteBuffer entered");
      ByteBuffer buffer;  //    System.out.println("ioResourceToByteBuffer buffer made");
      //URL url = Thread.currentThread().getContextClassLoader().getResource(resource);   System.out.println("ioResourceToByteBuffer attempting to get resource");
      //URL url = Thread.currentThread().getContextClassLoader().getResource(resource);   System.out.println("ioResourceToByteBuffer attempting to get resource");
      //URL url = new URL("file",resource);
      //ClassLoader cl = getClass().getClassLoader();
      //URL url = cl.getResource(resource);
      File file = new File(resource);// new File(url.getFile());   System.out.println("ioResourceToByteBuffer file created");
      URL url = file.toURI().toURL();
      
      
      if(url==null)
      {System.out.println("ioResourceToByteBuffer url is null");}
      
      
      
      //System.out.println("ioResourceToByteBuffer url:"+url.toString());
      
      if (file.isFile()) {    //    System.out.println("ioResourcetoByteBuffer file is a file");
         FileInputStream fis = new FileInputStream(file);
         FileChannel fc = fis.getChannel();
         buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); //System.out.println("figured out buffer size itself : "+fc.size());
         fc.close();
         fis.close();
      } else { //System.out.println("ioResourcetoByteBuffer file is not a file");
         buffer = BufferUtils.createByteBuffer(bufferSize);
         InputStream source =  url.openStream();
         if (source == null)
            throw new FileNotFoundException(resource);
         try {
            ReadableByteChannel rbc = Channels.newChannel(source);
            try {
               while (true) {
                  int bytes = rbc.read(buffer);
                  if (bytes == -1)
                     break;
                  if (buffer.remaining() == 0)
                     buffer = resizeBuffer(buffer, buffer.capacity() * 2);
               }
               buffer.flip();          //System.out.println("didn't figure out buffersize myself ");
            } finally {
               rbc.close();
            }
         } finally {
            source.close();
         }
      }
      return buffer;
   }

   private ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
      ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
      buffer.flip();
      newBuffer.put(buffer);
      return newBuffer;
   }


   public void setKeyVertices(Vector3f topLeftVertex, Vector3f topRightVertex, Vector3f botLeftVertex, Vector3f botRightVertex) {
      this.topLeftVertex = topLeftVertex;
      this.topRightVertex = topRightVertex;
      this.botLeftVertex = botLeftVertex;
      this.botRightVertex = botRightVertex;
   }

   public void setMVP(Matrix4f mvp) {
      MVP = mvp;
   }

}

 20 
 on: June 21, 2017, 09:21:07 
Started by Evan407 - Last post by spasi
You're using the wrong overload. Try:

Code: [Select]
clCompileProgram(
    program,
    platforms[0]._devices,
    "",//options
    (PointerBuffer)null,//input header
    null,//header include name
    pfn_notify,
    MemoryUtil.NULL
);

I may end up removing the other overloads, they're indeed confusing.

Pages: 1 [2] 3 4 ... 10