Skip to content

Nifty 1.4 LWJGL example (without Maven)

void256 edited this page Sep 5, 2014 · 1 revision

Nifty 1.4 LWJGL example (without Maven)

I'm using Eclipse. I've downloaded the nifty-1.4.0-complete.zip from sf.net. Starting from 06.08.2014 this zip will contain a dependencies folder with three additional external libs that Nifty will need:

  • eventbus-1.4.jar
  • jglfont-core-1.4.jar
  • xpp3-1.1.4c.jar

Since this example uses LWJGL you'll need to download LWJGL 2.9.1 from http://lwjgl.org/download.php

So, that's all we need!

I've put the libs into a lib folder inside of my Java project in Eclipse. For me it looks like that:

Dependencies

I've added these libs to my build classpath which looks like that:

Build Path

For good measure here is my .classpath file:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
	<classpathentry kind="src" path="src"/>
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.launching.macosx.MacOSXType/jdk1.7.0_45"/>
	<classpathentry kind="lib" path="libs/lwjgl/jar/jinput.jar"/>
	<classpathentry kind="lib" path="libs/lwjgl/jar/lwjgl.jar"/>
	<classpathentry kind="lib" path="libs/nifty/nifty-1.4.0.jar"/>
	<classpathentry kind="lib" path="libs/nifty/nifty-default-controls-1.4.0.jar"/>
	<classpathentry kind="lib" path="libs/nifty/nifty-lwjgl-renderer-1.4.0.jar"/>
	<classpathentry kind="lib" path="libs/nifty/nifty-style-black-1.4.0.jar"/>
	<classpathentry kind="lib" path="libs/lwjgl/jar/lwjgl_util.jar"/>
	<classpathentry kind="lib" path="libs/nifty/dependencies/eventbus-1.4.jar"/>
	<classpathentry kind="lib" path="libs/nifty/dependencies/jglfont-core-1.4.jar"/>
	<classpathentry kind="lib" path="libs/nifty/dependencies/xpp3-1.1.4c.jar"/>
	<classpathentry kind="output" path="bin"/>
</classpath>

And finally here is a somewhat minimal all in one demo class that will setup LWJGL, the inputsystem and init Nifty for core profile batched renderer and shows a simple screen and then quits when a button is pressed. The result will look like that:

Hello 1.4 LWJGL core profile

And finally the Java code:

import static org.lwjgl.opengl.GL11.glBlendFunc;
import static org.lwjgl.opengl.GL11.glClear;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL11.glViewport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import org.lwjgl.opengl.ContextAttribs;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.PixelFormat;
import org.lwjgl.util.glu.GLU;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.builder.EffectBuilder;
import de.lessvoid.nifty.builder.LayerBuilder;
import de.lessvoid.nifty.builder.PanelBuilder;
import de.lessvoid.nifty.builder.ScreenBuilder;
import de.lessvoid.nifty.builder.TextBuilder;
import de.lessvoid.nifty.controls.ButtonClickedEvent;
import de.lessvoid.nifty.controls.button.builder.ButtonBuilder;
import de.lessvoid.nifty.nulldevice.NullSoundDevice;
import de.lessvoid.nifty.render.batch.BatchRenderDevice;
import de.lessvoid.nifty.renderer.lwjgl.input.LwjglInputSystem;
import de.lessvoid.nifty.renderer.lwjgl.render.LwjglBatchRenderBackendCoreProfileFactory;
import de.lessvoid.nifty.screen.DefaultScreenController;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import de.lessvoid.nifty.spi.time.impl.AccurateTimeProvider;
import de.lessvoid.nifty.tools.Color;
import de.lessvoid.nifty.tools.SizeValue;


public class LwjglCoreProfileMain {
  private static final int WIDTH = 1024;
  private static final int HEIGHT = 768;

  public static void main(final String[] args) throws Exception {
    initLWJGL();
    initGL();
    LwjglInputSystem inputSystem = initInput();
    Nifty nifty = initNifty(inputSystem);
    nifty.loadStyleFile("nifty-default-styles.xml");
    nifty.loadControlFile("nifty-default-controls.xml");
    createIntroScreen(nifty, new MyScreenController());
    nifty.gotoScreen("start");
    renderLoop(nifty);
    shutDown(inputSystem);
  }

  private static LwjglInputSystem initInput() throws Exception {
    LwjglInputSystem inputSystem = new LwjglInputSystem();
    inputSystem.startup();
    return inputSystem;
  }

  private static void initLWJGL() throws Exception {
    DisplayMode currentMode = Display.getDisplayMode();
    DisplayMode[] modes = Display.getAvailableDisplayModes();
    List<DisplayMode> matching = new ArrayList<DisplayMode>();
    for (int i=0; i<modes.length; i++) {
      DisplayMode mode = modes[i];
      if (mode.getWidth() == WIDTH &&
          mode.getHeight() == HEIGHT &&
          mode.getBitsPerPixel() == 32 ) {
        matching.add(mode);
      }
    }

    DisplayMode[] matchingModes = matching.toArray(new DisplayMode[0]);
    boolean found = false;
    for (int i=0; i<matchingModes.length; i++) {
      if (matchingModes[i].getFrequency() == currentMode.getFrequency()) {
        Display.setDisplayMode(matchingModes[i]);
        found = true;
        break;
      }
    }

    if (!found) {
      Arrays.sort(matchingModes, new Comparator < DisplayMode >() {
        public int compare(final DisplayMode o1, final DisplayMode o2) {
          if (o1.getFrequency() > o2.getFrequency()) {
            return 1;
          } else if (o1.getFrequency() < o2.getFrequency()) {
            return -1;
          } else {
            return 0;
          }
        }
      });

      for (int i=0; i<matchingModes.length; i++) {
        Display.setDisplayMode(matchingModes[i]);
        break;
      }
    }

    int x = (currentMode.getWidth() - Display.getDisplayMode().getWidth()) / 2;
    int y = (currentMode.getHeight() - Display.getDisplayMode().getHeight()) / 2;
    Display.setLocation(x, y);
    Display.setFullscreen(false);
    Display.create(new PixelFormat(), new ContextAttribs(3, 2).withProfileCore(true));
    Display.setVSyncEnabled(false);
    Display.setTitle("Hello Nifty");
  }

  private static void initGL() {
    glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL11.GL_COLOR_BUFFER_BIT);
    glEnable(GL11.GL_BLEND);
    glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
  }

  private static Nifty initNifty(final LwjglInputSystem inputSystem) throws Exception {
    return new Nifty(
        new BatchRenderDevice(LwjglBatchRenderBackendCoreProfileFactory.create()),
        new NullSoundDevice(),
        inputSystem,
        new AccurateTimeProvider());
  }

  private static Screen createIntroScreen(final Nifty nifty, final ScreenController controller) {
    return new ScreenBuilder("start") {{
      controller(controller);
      layer(new LayerBuilder("layer") {{
        childLayoutCenter();
        onStartScreenEffect(new EffectBuilder("fade") {{
          length(500);
          effectParameter("start", "#0");
          effectParameter("end", "#f");
        }});
        onEndScreenEffect(new EffectBuilder("fade") {{
          length(500);
          effectParameter("start", "#f");
          effectParameter("end", "#0");
        }});
        onActiveEffect(new EffectBuilder("gradient") {{
          effectValue("offset", "0%", "color", "#333f");
          effectValue("offset", "100%", "color", "#ffff");
        }});
        panel(new PanelBuilder() {{
          childLayoutVertical();
          text(new TextBuilder() {{
            text("Nifty 1.4 Core Hello World");
            style("base-font");
            color(Color.BLACK);
            alignCenter();
            valignCenter();
          }});
          panel(new PanelBuilder(){{
            height(SizeValue.px(10));
          }});
          control(new ButtonBuilder("exit", "Pretty Cool!") {{
            alignCenter();
            valignCenter();
          }});
        }});
      }});
    }}.build(nifty);
  }

  private static void renderLoop(final Nifty nifty) {
    boolean done = false;
    while (!Display.isCloseRequested() && !done) {
      Display.update();
      if (nifty.update()) {
        done = true;
      }
      nifty.render(true);
      int error = GL11.glGetError();
      if (error != GL11.GL_NO_ERROR) {
        String glerrmsg = GLU.gluErrorString(error);
        System.err.println(glerrmsg);
      }
    }
  }

  private static void shutDown(final LwjglInputSystem inputSystem) {
    inputSystem.shutdown();
    Display.destroy();
    System.exit(0);
  }

  public static class MyScreenController extends DefaultScreenController {
    @NiftyEventSubscriber(id="exit")
    public void exit(final String id, final ButtonClickedEvent event) {
      nifty.exit();
    }
  }
}

Clone this wiki locally