Java-Gaming.org    
Featured games (78)
games approved by the League of Dukes
Games in Showcase (426)
Games in Android Showcase (89)
games submitted by our members
Games in WIP (466)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
  JavaGaming.org - Pastebin



Author: ziddia (posted 2014-01-20 19:29:28, viewed 57 times)

1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99   100   101   102   103   104   105   106   107   108   109   110   111   112   113   114   115   116   117   118   119   120   121   122   123   124   125   126   127   128   129   130   131   132   133   134   135   136   137   138   139   140   141   142   143   144   145   146   147   148   149   150   151   152   153   154   155   156   157   158   159   160   161   162   163   164   165   166   167   168   169   170   171   172   173   174   175   176   177   178   179   180   181   182   183   184   185   186   187   188   189   190   191   192   193   194   195   196   197   198   199   200   201   202   203   204   205   206   207   208   209   210   211   212   213   214   215   216   217   218   219   220   221   222   223   224   225   226   227   228   229   230   231   232   233   234   235   236   237   238   239   240   241   242   243   244   245   246   247   248   249   250   251   252   253   254   255   256   257   258   259   260   261   262   263   264   265   266   267   268   269   270   271   272   273   274   275   276   277   278   279   280   281   282   283   284   285   286   287   288   289   290   291   292   293   294   295   296   297   298   299   300   301   302   303   304   305   306   307   308   309   310   311   312   313   314   315   316   317   318   319   320   321   322   323   324   325   326   327   328   329   330   331   332   333   334   335   336   337   338   339   340   341   342   343   344   345   346   347   348   349   350   351   352  
package com.ziddia.game;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.ContextAttribs;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.PixelFormat;

import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;

/**
 * Represents a basic Game. Extend this to use its functionality.
 * @author Josh
 *
 */
public abstract class Game
{
   
   static int width = 800;
   static int height = 600;
   
   static String windowTitle = "A Game";
   
   /** Static hook to the game. */
   private static Game instance;
   
   /** The camera for the game. */
   public static Camera camera = new Camera();
   
    /**
     * Initialize the game
     */
    public abstract void init();

    /**
     * Update the game
     */
    public abstract void update(long elapsedTime);

    /**
     * Render the game
     */
    public abstract void render();

    /**
     * Handle Display resizing
     */
    public void resized()
    {
       GL11.glViewport (0, 0, width, height);
    }

    /**
     * Dispose the game
     */
    public abstract void dispose();

    /**
     * Create a new Game
     */
    public Game()
    {
        try
        {
            // Set the static reference
            instance = this;
            
            // data for specific ogl version
            PixelFormat pixelFormat = new PixelFormat();
            ContextAttribs contextAttributes = new ContextAttribs(3, 2).withForwardCompatible(true).withProfileCore(true);
            
            Display.create(/*pixelFormat, contextAttributes*/);
            setDisplayMode(width, height, false);
            Display.setResizable(true);

            // Start the game
            gameLoop();
        }
        catch (LWJGLException e)
        {
            e.printStackTrace();
            System.exit(-1); // There is no point in running without hardware acceleration right?
        }
        
        // update viewport
        GL11.glViewport(0, 0, width, height);
    }
    
    /**
     * The actual loop. Handles rendering, updating, and initialization.
     */
    private void gameLoop()
    {
        long lastFrame = getCurrentTime();
        long thisFrame = getCurrentTime();
        
        init();

        while (!Display.isCloseRequested())
        {
            thisFrame = getCurrentTime();
            update(thisFrame - lastFrame);
            render();

            lastFrame = thisFrame;
            Display.update();

            // Check the resize property
            if (Display.wasResized())
                resized();

            Display.sync(60);  // You can write this value to a variable to change it.
        }

        end();
    }
    
    /**
     * End the game, and dispose of any resources.
     */
    public static void end()
    {
        instance.dispose();
        Display.destroy();
        System.exit(0);
    }
    
    /**
     * Utility method to retrieve the current system time.
     * @return
     */
    public static long getCurrentTime()
    {
        return Sys.getTime() * 1000 / Sys.getTimerResolution();
    }
    
    /**
     * Sets a DisplayMode after selecting for a better one.
     * 
     * Utility method taken from the LWJGL wiki.
     * 
     * @param width The width of the display.
     * @param height The height of the display.
     * @param fullscreen The fullscreen mode.
     *
     * @return True if switching is successful. Else false.
     */
    public static boolean setDisplayMode(int width, int height, boolean fullscreen)
    {
        // return if requested DisplayMode is already set
        if ((Display.getDisplayMode().getWidth() == width) &&
            (Display.getDisplayMode().getHeight() == height) &&
            (Display.isFullscreen() == fullscreen))
            return true;

        try
        {
            // The target DisplayMode
            DisplayMode targetDisplayMode = null;

            if (fullscreen)
            {
                // Gather all the DisplayModes available at fullscreen
                DisplayMode[] modes = Display.getAvailableDisplayModes();
                int freq = 0;

                // Iterate through all of them
                for (DisplayMode current: modes)
                {
                    // Make sure that the width and height matches
                    if ((current.getWidth() == width) && (current.getHeight() == height))
                    {
                        // Select the one with greater frequency
                        if ((targetDisplayMode == null) || (current.getFrequency() >= freq))
                        {
                            // Select the one with greater bits per pixel
                            if ((targetDisplayMode == null) || (current.getBitsPerPixel() > targetDisplayMode.getBitsPerPixel()))
                            {
                                targetDisplayMode = current;
                                freq = targetDisplayMode.getFrequency();
                            }
                        }

                        // if we've found a match for bpp and frequency against the 
                        // original display mode then it's probably best to go for this one
                        // since it's most likely compatible with the monitor
                        if ((current.getBitsPerPixel() == Display.getDesktopDisplayMode().getBitsPerPixel()) &&
                            (current.getFrequency() == Display.getDesktopDisplayMode().getFrequency()))
                        {
                            targetDisplayMode = current;
                            break;
                        }
                    }
                }
            }
            else
            {
                // No need to query for windowed mode
                targetDisplayMode = new DisplayMode(width, height);
            }

            if (targetDisplayMode == null)
            {
                System.out.println("Failed to find value mode: " + width + "x" + height + " fs=" + fullscreen);
                return false;
            }

            // Set the DisplayMode we've found
            Display.setDisplayMode(targetDisplayMode);
            Display.setFullscreen(fullscreen);

            System.out.println("Selected DisplayMode: " + targetDisplayMode.toString());

            // Generate a resized event
            instance.resized();

            return true;
        }
        catch (LWJGLException e)
        {
            System.out.println("Unable to setup mode " + width + "x" + height + " fullscreen=" + fullscreen + e);
        }

        return false;
    }
    
    /**
     * Loads and compiles a shader from the parameters given.
     * @param filename
     * @param type
     * @return the new shader ID
     */
    public static int loadShader(String filename, int type) {
       StringBuilder shaderSource = new StringBuilder();
       int shaderID = 0;
       
       try {
          BufferedReader reader = new BufferedReader(new FileReader(filename));
          String line;
          while ((line = reader.readLine()) != null) {
             shaderSource.append(line).append("\n");
          }
          reader.close();
       } catch (IOException e) {
          System.err.println("Could not read file.");
          e.printStackTrace();
          System.exit(-1);
       }
       
       shaderID = GL20.glCreateShader(type);
       GL20.glShaderSource(shaderID, shaderSource);
       GL20.glCompileShader(shaderID);
       
       return shaderID;
    }
    
    /**
     * Loads a texture and returns a texture ID.
     * @param filename
     * @param textureUnit
     * @return
     */
    public static int loadPNGTexture(String filename, int textureUnit) {
      ByteBuffer buf = null;
      int tWidth = 0;
      int tHeight = 0;
      
      try {
         // Open the PNG file as an InputStream
         InputStream in = new FileInputStream(filename);
         // Link the PNG decoder to this stream
         PNGDecoder decoder = new PNGDecoder(in);
         
         // Get the width and height of the texture
         tWidth = decoder.getWidth();
         tHeight = decoder.getHeight();
         
         
         // Decode the PNG file in a ByteBuffer
         buf = ByteBuffer.allocateDirect(
               4 * decoder.getWidth() * decoder.getHeight());
         decoder.decode(buf, decoder.getWidth() * 4, Format.RGBA);
         buf.flip();
         
         in.close();
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
      
      // Create a new texture object in memory and bind it
      int texId = GL11.glGenTextures();
      GL13.glActiveTexture(textureUnit);
      GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId);
      
      // All RGB bytes are aligned to each other and each component is 1 byte
      GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
      
      // Upload the texture data and generate mip maps (for scaling)
      GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, tWidth, tHeight, 0, 
            GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);
      GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
      
      // Setup the ST coordinate system
      GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
      GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
      
      // Setup what to do when the texture has to be scaled
      GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, 
            GL11.GL_NEAREST);
      GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, 
            GL11.GL_LINEAR_MIPMAP_LINEAR);
      
      return texId;
   }
    
    /**
     * Cotangent function.
     * @param angle
     * @return
     */
    public static float coTangent(float angle) 
    {
      return (float)(1f / Math.tan(angle));
   }
   
    /**
     * Degrees to radians utility function.
     * Rads = degrees * (pi/180)
     * 
     * @param degrees
     * @return
     */
   public static float degreesToRadians(float degrees) 
   {
      return degrees * (float)(Math.PI / 180d);
   }
    
}





Dump your java code here :



Special syntax:
  • To highlight a line (yellow background), prefix it with '@@'
  • To indicate that a line should be removed (red background), prefix it with '-'
  • To indicate that a line should be added (green background), prefix it with '+'
  • To post multiple snippets, seperate them by '~~~~'
  EOF
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (73 views)
2014-04-15 18:08:23

BurntPizza (68 views)
2014-04-15 03:46:01

UprightPath (79 views)
2014-04-14 17:39:50

UprightPath (65 views)
2014-04-14 17:35:47

Porlus (80 views)
2014-04-14 15:48:38

tom_mai78101 (104 views)
2014-04-10 04:04:31

BurntPizza (164 views)
2014-04-08 23:06:04

tom_mai78101 (260 views)
2014-04-05 13:34:39

trollwarrior1 (210 views)
2014-04-04 12:06:45

CJLetsGame (220 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!