Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.nio.ByteBuffer;
- import java.nio.FloatBuffer;
- import java.nio.IntBuffer;
- import org.lwjgl.BufferUtils;
- import org.lwjgl.Sys;
- import org.lwjgl.input.Keyboard;
- import org.lwjgl.input.Mouse;
- import org.lwjgl.opengl.ContextAttribs;
- import org.lwjgl.opengl.Display;
- import org.lwjgl.opengl.DisplayMode;
- import org.lwjgl.opengl.PixelFormat;
- import org.lwjgl.util.vector.Vector3f;
- import org.newdawn.slick.Color;
- import org.newdawn.slick.TrueTypeFont;
- import static org.lwjgl.opengl.GL11.*;
- import static org.lwjgl.opengl.GL12.*;
- import static org.lwjgl.opengl.GL13.*;
- import static org.lwjgl.opengl.GL15.*;
- import static org.lwjgl.opengl.GL20.*;
- import static org.lwjgl.util.glu.GLU.*;
- import de.matthiasmann.twl.utils.PNGDecoder;
- public class MainScreen {
- private static boolean isFullScreen=false;//Check full screen settings
- private static boolean isGameRunning=true;//End of game settings
- private static boolean initialCameraPositionHasBeenSet = false;//origin location for the camera for setUpUtil making sure it has a starting pos
- private static boolean hasBeenSetUp=false;//For setting up utils so that i can create it once and never worry again,
- private boolean wireFrameMode=true;
- private static float lastTime=0.0f;//Used mainly for handling time offsets for mouse control
- private static float time,dt;/////// Could be used for other time issues but will need another variable because they are both used
- private static float mouseSensitivity = 1.0f;//Mouse sensitivity settings
- private static float movementSpeed = 1.0f; //General ms (Movement Speed) settings
- private static final float CUBE_LENGTH=1.0f;//Base final cube size, Note: this cannot change as everything graphically is based off it
- private static int blockX,blockY,blockZ;//For all of the x,y,z locations of the blocks in the game, VBO positions of the quads are based off this.
- private static float screenResolutionWidth=800,screenResolutionHeight=600;//screen resolution x, y
- static int VBOVertexHandle;//GL location vertex
- static int VBONormalHandle;///GL color vertex
- static int VBOTextureHandle;//GL Texture vertex
- static int dirtTexture;
- static int defaultTexture;
- static int fps;
- int shaderProgram;
- int vertexShader;
- int fragmentShader;
- StringBuilder vertexShaderSource = new StringBuilder();;
- StringBuilder fragmentShaderSource = new StringBuilder();
- TrueTypeFont font;
- static Block blocks[][][]= new Block[Chunk.CHUNK_SIZE][Chunk.CHUNK_SIZE][Chunk.CHUNK_SIZE];//Created blocks, to be held in multiple chunks
- static Chunk chunks;//Rendered chunks in 16 * 16 *16 lots
- Camera c =new Camera();// Main camera mode, created from user defined Camera class
- DisplayMode displayMode;//GL display mode settings for the main window
- /**
- * Main game loop method, all is controlled here
- *
- */
- public void runGame(){
- while(isGameRunning){
- try {
- createWindow();
- setUpUtil();
- running();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- /**Main method in this class that runs all of the methods used for openGl and creating the images
- * in the 3D space
- *
- */
- private void running() {
- InitGL();
- chunks=new Chunk(0,0,0,blocks);
- while (!Display.isCloseRequested()) {
- try{
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- glLoadIdentity();// Can be replaces by push matrix pop matrix around open gl code before update
- c.processMouse(mouseSensitivity);
- c.processKeyboard(getTimeChange(), movementSpeed);
- c.applyTranslations();
- startTime();
- if(c.yaw() %60==0){
- RebuildMesh(0,0,0);
- }
- render();
- Display.update();
- Display.sync(60);
- }catch(Exception e){
- }
- }
- destroy();
- isGameRunning=false;
- }
- /**
- * Destroys everything that has been created
- */
- private void destroy() {
- //need to destroy open GL bindings in here also
- glDisableClientState(GL_VERTEX_ARRAY);
- glDisableClientState(GL_TEXTURE_COORD_ARRAY);
- glDisableClientState(GL_SHADE_MODEL);
- glDeleteBuffers(VBOVertexHandle);
- glDeleteBuffers(VBOTextureHandle);
- glDeleteBuffers(VBONormalHandle);
- glDeleteShader(vertexShader);
- glDeleteShader(fragmentShader);
- Display.destroy();
- Keyboard.destroy();
- Mouse.destroy();
- }
- /**
- * Initiates the inital values of the camera, x,y,zand all of the initial mouse positions.
- */
- void setUpUtil()
- {
- if(!hasBeenSetUp){
- loadTextures();
- font=FontCreator.loadFont("simplifica");
- if(!initialCameraPositionHasBeenSet)
- {
- c.setPosition(0,0,9.0f);
- initialCameraPositionHasBeenSet=true;
- }
- hasBeenSetUp=true;
- }
- c.applyOptimalStates();
- c.processMouse(mouseSensitivity);
- c.processKeyboard(getTimeChange(),movementSpeed);
- }
- /**
- * Texture to be loaded
- */
- private void loadTextures() {
- dirtTexture = setupTextures("dirt_32");
- defaultTexture = setupTextures("default_32");
- }
- /**
- * Creates the basic main window to view the game is.
- * Fullscreen is set here upon first start up of the game.
- * @throws Exception
- */
- void createWindow() throws Exception
- {
- if(!Display.isCreated())
- {
- Display.setFullscreen(isFullScreen);
- DisplayMode d[] = Display.getAvailableDisplayModes();
- for (int i = 0; i < d.length; i++)
- {
- if (d[i].getWidth() == screenResolutionWidth && d[i].getHeight() == screenResolutionHeight && d[i].getBitsPerPixel() == 32) {
- displayMode = d[i];
- break;
- }
- }
- Display.setDisplayMode(displayMode);
- Display.setTitle("Bending");
- Display.create();
- }
- }
- /**
- *
- * @param key used as a base pathfile name /resources/texures will already by created just need the png file name, without the extention
- */
- private int setupTextures(String key) {
- IntBuffer tmp = BufferUtils.createIntBuffer(1);
- glGenTextures(tmp);
- tmp.rewind();
- try {
- InputStream in = new FileInputStream("res/Textures/"+key+".png");
- PNGDecoder decoder = new PNGDecoder(in);
- System.out.println("width=" + decoder.getWidth());
- System.out.println("height=" + decoder.getHeight());
- ByteBuffer buf = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight());
- decoder.decode(buf, decoder.getWidth() * 4, PNGDecoder.Format.RGBA);
- buf.flip();
- glBindTexture(GL_TEXTURE_2D, tmp.get(0));
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
- glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buf);
- int unsigned = (buf.get(0) & 0xff);
- System.out.println(unsigned);
- System.out.println(buf.get(1));
- System.out.println(buf.get(2));
- System.out.println(buf.get(3));
- } catch (FileNotFoundException ex) {
- System.out.println("Error " + "/res/Textures/" + key + ".png" + " not found");
- } catch (IOException e) {
- System.out.println("Error decoding " + "/res/Textures/" + key + ".png");
- }
- tmp.rewind();
- return tmp.get(0);
- }
- /**
- * Basic render of the game, handles all of the visible chunks and blocks within view
- * @param wireFrameMode
- *
- */
- public void render()
- {
- calculateFps();
- glPushMatrix();
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, defaultTexture);
- glBindBuffer(GL_ARRAY_BUFFER, VBOVertexHandle);
- glVertexPointer(3, GL_FLOAT, 0, 0L);
- glBindBuffer(GL_ARRAY_BUFFER, VBONormalHandle);
- glNormalPointer(GL_FLOAT, 0, 0L);
- glBindBuffer(GL_ARRAY_BUFFER, VBOTextureHandle);
- glTexCoordPointer(2, GL_FLOAT, 0, 0L);
- if(wireFrameMode){
- glDrawArrays(GL_LINE_LOOP,0,Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * 4 * 6);
- }else{
- glDrawArrays(GL_QUADS, 0, Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * 4 * 6);//24 points on a cube to draw. 4 points per face 6 faces
- }
- font.drawString(50, 50, "FPS: " + fps, Color.green);
- glPopMatrix();
- glFlush();
- }
- private static int getTexture(Block block)
- {
- switch (block.GetID()) {
- case 1:
- case 2:
- return dirtTexture;
- case 3:
- }
- return defaultTexture;//failed to load texture
- }
- /**
- * Creates the Chunk for rendering
- *
- */
- public static void createChunk(float x, float y, float z){
- chunks.setStartX((int) x);
- chunks.setStartY((int) y);
- chunks.setStartZ((int) z);
- return;
- }
- /**
- * Creates a basic cube for the engine, fundimental method
- * @param x position in the world
- * @param y also position in the world
- * @param z also position in the world
- * @return returns a float array for use in openGL
- */
- public static float[] createBlock(float x, float y, float z)
- {
- int offset = (int) (CUBE_LENGTH / 2);
- return new float[] {
- x + offset, y + offset,z,
- x - offset, y + offset,z,
- x - offset, y + offset,z - CUBE_LENGTH,
- x + offset, y + offset,z - CUBE_LENGTH,
- x + offset, y - offset, z - CUBE_LENGTH,
- x - offset, y - offset,z - CUBE_LENGTH,
- x - offset, y - offset,z,
- x + offset, y - offset,z,
- x + offset, y + offset, z - CUBE_LENGTH,
- x - offset, y + offset, z - CUBE_LENGTH,
- x - offset, y - offset,z - CUBE_LENGTH,
- x + offset, y - offset,z - CUBE_LENGTH,
- x + offset, y - offset, z,
- x - offset, y - offset, z,
- x - offset, y + offset, z,
- x + offset, y + offset, z,
- x - offset, y + offset, z - CUBE_LENGTH,
- x - offset, y + offset, z,
- x - offset, y - offset, z,
- x - offset, y - offset,z - CUBE_LENGTH,
- x + offset, y + offset, z,
- x + offset, y + offset,z - CUBE_LENGTH,
- x + offset, y - offset, z - CUBE_LENGTH,
- x + offset, y - offset, z
- };
- }
- /**
- * Write fps and info to top left off screen for dev mode
- * turns on free flight and a range of other dev options
- */
- private void setDevMode(){
- }
- /**
- * Starts up base settings of open GL
- * This is where the Depth and base background and 2d textures on all of the polygons is set
- *
- */
- private void InitGL()
- {
- glEnable(GL_TEXTURE_2D);
- glShadeModel(GL_SMOOTH);glClearColor(0.4f, 0.6f, 0.9f, 0f);
- glClearDepth(1.0f);
- glEnable(GL_DEPTH_TEST);
- glDepthFunc(GL_LEQUAL);
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glEnableClientState(GL_VERTEX_ARRAY);
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- gluPerspective( 45.0f, (float)displayMode.getWidth() / (float)displayMode.getHeight(), 0.1f, 100.0f);
- glMatrixMode(GL_MODELVIEW);
- glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
- }
- public static void RebuildMesh(float startX, float startY, float startZ) {
- VBOTextureHandle = glGenBuffers();
- VBOVertexHandle = glGenBuffers();
- VBONormalHandle = glGenBuffers();
- FloatBuffer VertexTextureData = BufferUtils.createFloatBuffer((Chunk.CHUNK_SIZE* Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE)*6 * 8);
- FloatBuffer VertexPositionData = BufferUtils.createFloatBuffer((Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE) * 6 * 3 * 4);//6 faces, (3*4) 12 is made up of 4 points to a quad and 3 values xyz
- FloatBuffer VertexNormalData = BufferUtils.createFloatBuffer((Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE) * 6 * 3 * 4);
- for (float x = 0; x < Chunk.CHUNK_SIZE; x += 1) {
- for (float y = 0; y < Chunk.CHUNK_SIZE; y += 1) {
- for (float z = 0; z < Chunk.CHUNK_SIZE; z += 1) {
- VertexPositionData.put(createBlock((float) startX + x * CUBE_LENGTH, (float) startY + y * CUBE_LENGTH, (float) startZ + z * CUBE_LENGTH));
- VertexNormalData.put(createBlock((float) startX + x * CUBE_LENGTH, (float) startY + y * CUBE_LENGTH, (float) startZ + z * CUBE_LENGTH));
- VertexTextureData.put(getTexPosData());
- }
- }
- }
- VertexTextureData.flip();
- VertexPositionData.flip();
- VertexNormalData.flip();
- glBindBuffer(GL_ARRAY_BUFFER, VBOVertexHandle);
- glBufferData(GL_ARRAY_BUFFER, VertexPositionData, GL_STATIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- glBindBuffer(GL_ARRAY_BUFFER, VBONormalHandle);
- glBufferData(GL_ARRAY_BUFFER, VertexNormalData, GL_STATIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- glBindBuffer(GL_ARRAY_BUFFER, VBOTextureHandle);
- glBufferData(GL_ARRAY_BUFFER, VertexTextureData, GL_STATIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- }
- private static float[] getTexPosData() {
- return new float[]{
- 0,0, 0,1, 1,1, 1,0,// once for each face 6 faces
- 0,0, 0,1, 1,1, 1,0,
- 0,0, 0,1, 1,1, 1,0,
- 0,0, 0,1, 1,1, 1,0,
- 0,0, 0,1, 1,1, 1,0,
- 0,0, 0,1, 1,1, 1,0
- };
- }
- private float getTimeChange()
- {
- time=Sys.getTime() * 1000 / Sys.getTimerResolution();
- dt = (time - lastTime);
- lastTime = time;
- return dt;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement