Package view

Source Code of view.Shaders

package view;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.ARBShaderObjects.*;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBFragmentShader;
import org.lwjgl.opengl.ARBVertexShader;
import org.lwjgl.opengl.GL11;


public class Shaders {

 
  public static int buildProgram(int[] shaders) {
      int program = glCreateProgram();
      for (int shader : shaders) {
        glAttachShader(program, shader);
      }
      glLinkProgram(program);
     
      if (glGetProgram(program, GL_LINK_STATUS) == 0) {
          System.err.println("Failed to link shader program:");
          System.err.println(glGetInfoLogARB(program, 200));
          glDeleteProgram(program);
          return 0;
      }
      return program;
  }
 
  public static int buildVertexShader(String filename) {
    return buildShader(filename, ARBVertexShader.GL_VERTEX_SHADER_ARB);
  }
 
  public static int buildFragmentShader(String filename) {
    return buildShader(filename, ARBFragmentShader.GL_FRAGMENT_SHADER_ARB);
  }
 
  private static int buildShader(String filename, int type) {
    int shader = glCreateShaderObjectARB(type);
    if (shader == 0) {
      return 0;
    }
    String code = "";
    String line;
    try {
      BufferedReader reader = new BufferedReader(new FileReader(filename));
      while ((line = reader.readLine()) != null) {
        code += line + "\n";
      }
    } catch (Exception e) {
      System.out.println("Failed reading shader code of " + filename);
      return 0;
    }
    glShaderSourceARB(shader, code);
    glCompileShaderARB(shader);
    if (glGetObjectParameteriARB(shader, GL_OBJECT_COMPILE_STATUS_ARB) == GL11.GL_FALSE) {
      printLogInfo(shader);
      shader = 0;
    }
    return shader;
  }

  private static boolean printLogInfo(int obj) {
    IntBuffer iVal = BufferUtils.createIntBuffer(1);
    glGetObjectParameterARB(obj, GL_OBJECT_INFO_LOG_LENGTH_ARB, iVal);

    int length = iVal.get();
    if (length > 1) {
      ByteBuffer infoLog = BufferUtils.createByteBuffer(length);
      iVal.flip();
      glGetInfoLogARB(obj, iVal, infoLog);
      byte[] infoBytes = new byte[length];
      infoLog.get(infoBytes);
      String out = new String(infoBytes);
      System.out.println("Info log:\n" + out);
    } else
      return true;
    return false;
  }

}
TOP

Related Classes of view.Shaders

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.