diff --git a/src/com/bwyap/engine/Engine.java b/src/com/bwyap/engine/Engine.java index e93f35f..0c05080 100644 --- a/src/com/bwyap/engine/Engine.java +++ b/src/com/bwyap/engine/Engine.java @@ -2,35 +2,29 @@ import com.bwyap.engine.window.WindowInterface; -/** - * An abstract Engine that holds a {@code WindowInterface}. +/** An abstract Engine that holds a {@code WindowInterface}. * This class should be extended to implement the main engine - * loop which calls the {@code update} and {@code render} + * loop which calls the {@code update} and {@code render} * methods. - * @author bwyap - * - */ -public abstract class Engine implements EngineInterface { - + * + * @author bwyap */ +public abstract class Engine implements EngineInterface +{ protected final WindowInterface window; - protected int targetFPS; protected float fps; - - - public Engine(WindowInterface window, int targetFPS) throws Exception { + + public Engine(WindowInterface window, int targetFPS) throws Exception + { this.window = window; this.targetFPS = targetFPS; } - + @Override - public float getFPS() { - return fps; - } - + public float getFPS() + { return fps; } + @Override - public int getTargetFPS() { - return targetFPS; - } - + public int getTargetFPS() + { return targetFPS; } } diff --git a/src/com/bwyap/engine/EngineInterface.java b/src/com/bwyap/engine/EngineInterface.java index 7575426..63adfee 100644 --- a/src/com/bwyap/engine/EngineInterface.java +++ b/src/com/bwyap/engine/EngineInterface.java @@ -1,55 +1,41 @@ package com.bwyap.engine; -/** - * Specifies the methods that an engine requires. - * @author bwyap - * - */ -public interface EngineInterface { - - /** - * Run the game engine loop. - */ +/** Specifies the methods that an engine requires. + * + * @author bwyap */ +public interface EngineInterface +{ + /** Run the game engine loop. */ public void run(); - - /** - * Initialise the engine and prepare resources for rendering - */ + + /** Initialise the engine and prepare resources for rendering */ public void init(); - - /** - * Get the current system time - * @return - */ + + /** Get the current system time + * + * @return */ public float getCurrentTime(); - - /** - * Update the application - * @param timestep - */ + + /** Update the application + * + * @param timestep */ public void update(float timestep); - - /** - * Render the graphics of the application - * @param timestep - */ + + /** Render the graphics of the application + * + * @param timestep */ public void render(float timestep); - - /** - * Frees resources that are no longer needed. - */ + + /** Frees resources that are no longer needed. */ public void cleanup(); - - /** - * Get the last measured FPS of the engine. - * @return - */ + + /** Get the last measured FPS of the engine. + * + * @return */ public float getFPS(); - - /** - * Gets the target FPS of the game. - * @return - */ + + /** Gets the target FPS of the game. + * + * @return */ public int getTargetFPS(); - } diff --git a/src/com/bwyap/engine/FixedTimestepEngine.java b/src/com/bwyap/engine/FixedTimestepEngine.java index 7dc5b77..9bd36e5 100644 --- a/src/com/bwyap/engine/FixedTimestepEngine.java +++ b/src/com/bwyap/engine/FixedTimestepEngine.java @@ -2,64 +2,51 @@ import com.bwyap.engine.window.WindowInterface; -/** - * An Engine implementation which uses a fixed time loop. - * This class should be extended to provide implementations +/** An Engine implementation which uses a fixed time loop. + * This class should be extended to provide implementations * for the {@code update} and {@code render} methods. - * @author bwyap - * - */ -public abstract class FixedTimestepEngine extends Engine { - + * + * @author bwyap */ +public abstract class FixedTimestepEngine extends Engine +{ + public FixedTimestepEngine(WindowInterface window, int targetFPS) throws Exception + { super(window, targetFPS); } - public FixedTimestepEngine(WindowInterface window, int targetFPS) throws Exception { - super(window, targetFPS); - } - - - /** - * Run the engine loop using a fixed timestep. - * This method should not be altered. - */ + /** Run the engine loop using a fixed timestep. + * This method should not be altered. */ @Override - public final void run() { + public final void run() + { float now, delta; - float last = 0f, fpsTimer = 0f, secsPerUpdate = 1f/targetFPS; + float last = 0f, fpsTimer = 0f, secsPerUpdate = 1f / targetFPS; int fps = 0; - init(); - - while (!window.shouldClose()) { + while (!window.shouldClose()) + { now = this.getCurrentTime(); delta = now - last; last = now; - window.processEvents(); update(delta); render(delta); window.swapDisplayBuffers(); - fps++; fpsTimer += delta; - - window.setFpsDisplay(fps/fpsTimer); - - if (fpsTimer >= 1.0f) { + window.setFpsDisplay(fps / fpsTimer); + if (fpsTimer >= 1.0f) + { this.fps = fps; fpsTimer -= 1.0f; fps = 0; } - - while ((float) this.getCurrentTime() < now + secsPerUpdate) { + while ((float) this.getCurrentTime() < now + secsPerUpdate) + { // wait } } - cleanup(); } } - - // Old method /* public final void run() { diff --git a/src/com/bwyap/engine/gui/GUI.java b/src/com/bwyap/engine/gui/GUI.java index e44c4e9..f0a80d1 100644 --- a/src/com/bwyap/engine/gui/GUI.java +++ b/src/com/bwyap/engine/gui/GUI.java @@ -3,25 +3,22 @@ import com.bwyap.engine.gui.element.RectangularPanel; import com.bwyap.engine.input.InputHandler; -/** - * A GUI Panel which is intended to span the whole screen. +/** A GUI Panel which is intended to span the whole screen. * Its origin is always at (0,0). - * @author bwyap - * - */ -public abstract class GUI extends RectangularPanel implements GUIInterface { - - public GUI(float width, float height) { + * + * @author bwyap */ +public abstract class GUI extends RectangularPanel implements GUIInterface +{ + public GUI(float width, float height) + { super(0, 0, width, height); setRenderShape(false); } - - + @Override - public final void handleInput(InputHandler input) { + public final void handleInput(InputHandler input) + { // Handle input with this panel as the bounds super.handleInput(input, this); } - - } diff --git a/src/com/bwyap/engine/gui/GUIController.java b/src/com/bwyap/engine/gui/GUIController.java index 9cb9011..bfe9863 100644 --- a/src/com/bwyap/engine/gui/GUIController.java +++ b/src/com/bwyap/engine/gui/GUIController.java @@ -3,52 +3,36 @@ import com.bwyap.engine.input.InputHandler; import com.bwyap.engine.window.WindowInterface; - -/** - * A controller class that can render a GUI. +/** A controller class that can render a GUI. * It uses a {@code GUIRenderer} to render * the current GUI which must be set. If the * currentGUI is {@code null}, nothing will * be rendered by the renderer. - * @author bwyap - * - */ -public abstract class GUIController implements GUIControllerInterface { - - + * + * @author bwyap */ +public abstract class GUIController implements GUIControllerInterface +{ protected GUI currentGUI; protected final GUIRenderer renderer; - - - public GUIController(GUIRenderer renderer) { - this.renderer = renderer; - } - - - /** - * Set the GUI to update and render - * @param gui - */ - public void setGUI(GUI gui) { - this.currentGUI = gui; - } - - + + public GUIController(GUIRenderer renderer) + { this.renderer = renderer; } + + /** Set the GUI to update and render + * + * @param gui */ + public void setGUI(GUI gui) + { this.currentGUI = gui; } + @Override - public final void handleInput(InputHandler input) { - if (currentGUI != null) currentGUI.handleInput(input); - } + public final void handleInput(InputHandler input) + { if (currentGUI != null) currentGUI.handleInput(input); } - @Override - public final void update(float timestep) { - if (currentGUI != null) currentGUI.update(timestep); - } - + public final void update(float timestep) + { if (currentGUI != null) currentGUI.update(timestep); } @Override - public final void render(WindowInterface window) { - if (currentGUI != null) renderer.render(currentGUI, window); - } - + public final void render(WindowInterface window) + { if (currentGUI != null) renderer.render(currentGUI, window); } } diff --git a/src/com/bwyap/engine/gui/GUIControllerInterface.java b/src/com/bwyap/engine/gui/GUIControllerInterface.java index 8d4ce85..e00552d 100644 --- a/src/com/bwyap/engine/gui/GUIControllerInterface.java +++ b/src/com/bwyap/engine/gui/GUIControllerInterface.java @@ -3,31 +3,23 @@ import com.bwyap.engine.input.InputHandler; import com.bwyap.engine.window.WindowInterface; -/** - * Provides methods that a GUI controller should implement. - * @author bwyap - * - */ -public interface GUIControllerInterface { - - /** - * Polls input for the current GUI - * @param input - */ +/** Provides methods that a GUI controller should implement. + * + * @author bwyap */ +public interface GUIControllerInterface +{ + /** Polls input for the current GUI + * + * @param input */ public void handleInput(InputHandler input); - - - /** - * Updates the current GUI - * @param timestep - */ + + /** Updates the current GUI + * + * @param timestep */ public void update(float timestep); - - - /** - * Renders the current GUI - * @param window - */ + + /** Renders the current GUI + * + * @param window */ public void render(WindowInterface window); - } diff --git a/src/com/bwyap/engine/gui/GUIInterface.java b/src/com/bwyap/engine/gui/GUIInterface.java index 5cf7643..a2a9eb6 100644 --- a/src/com/bwyap/engine/gui/GUIInterface.java +++ b/src/com/bwyap/engine/gui/GUIInterface.java @@ -3,43 +3,32 @@ import com.bwyap.engine.gui.interfaces.GUIElementInterface; import com.bwyap.engine.input.InputHandler; -/** - * An interface for a GUI that can hold GUI elements. - * @author bwyap - * - */ -public interface GUIInterface { - - - /** - * Update elements in the GUI - * @param timestep - */ +/** An interface for a GUI that can hold GUI elements. + * + * @author bwyap */ +public interface GUIInterface +{ + /** Update elements in the GUI + * + * @param timestep */ public void update(float timestep); - - - /** - * Poll input for the elements in the GUI + + /** Poll input for the elements in the GUI + * * @param input - * @param timetep - */ + * @param timetep */ public void handleInput(InputHandler input); - - - /** - * Add a new element to the GUI - * @param element - */ + + /** Add a new element to the GUI + * + * @param element */ public void addElement(GUIElementInterface e, float x, float y); - - - /** - * Remove an element from the GUI. - * Returns true if the element was + + /** Remove an element from the GUI. + * Returns true if the element was * found and was successfully removed. - * @param element - * @return - */ + * + * @param element + * @return */ public boolean removeElement(GUIElementInterface e); - } diff --git a/src/com/bwyap/engine/gui/GUIRenderer.java b/src/com/bwyap/engine/gui/GUIRenderer.java index a2fd39e..94be53e 100644 --- a/src/com/bwyap/engine/gui/GUIRenderer.java +++ b/src/com/bwyap/engine/gui/GUIRenderer.java @@ -9,8 +9,7 @@ import com.bwyap.engine.gui.interfaces.IColouredVectorShape; import com.bwyap.engine.window.WindowInterface; -/** - *

+/**

* A renderer that can render GUI elements to the screen. * The concrete implementation of how the elements should be * rendered is library specific and must be provided in a @@ -19,113 +18,87 @@ *

* Supported GUI elements: *

- * * TODO: * *

* - * @author bwyap - * - * - */ -public abstract class GUIRenderer implements GUIRendererInterface { - - + * @author bwyap */ +public abstract class GUIRenderer implements GUIRendererInterface +{ @Override - public final void render(GUI gui, WindowInterface window) { + public final void render(GUI gui, WindowInterface window) + { beginRenderGUI(window); renderGUI(gui, window); endRenderGUI(); } - - - /** - * Set up the resources to render the GUI - * @param window - */ + + /** Set up the resources to render the GUI + * + * @param window */ protected abstract void beginRenderGUI(WindowInterface window); - - - /** - *

Render the GUI elements.

+ + /**

Render the GUI elements.

*

* Calls to draw all GUI elements should be made in this method. * This method is called automatically. *

+ * * @param gui - * @param window - */ + * @param window */ protected abstract void renderGUI(Panel panel, WindowInterface window); - - - /** - * CLean up the resources after rendering the GUI - */ + + /** CLean up the resources after rendering the GUI */ protected abstract void endRenderGUI(); - - /* =================== * AUXILIARY METHODS * =================== */ - - - /** - * Render text onto the screen. If the given font has not yet been loaded, it will be loaded + /** Render text onto the screen. If the given font has not yet been loaded, it will be loaded * via the {@code NVGFont.acquireFont} method. This method should handle cases where the text * is null appropriately. - * @param text the text component - * @param element the bounds the text component is attached to - */ + * + * @param text the text component + * @param element the bounds the text component is attached to */ public abstract void renderText(TextComponent text, GUIBoundsInterface element); - - - /** - * Render a vector drawn button - * @param button - */ + + /** Render a vector drawn button + * + * @param button */ protected abstract void renderVectorButton(VectorButton button); - - - /** - * Render a textured button - * @param button - */ + + /** Render a textured button + * + * @param button */ protected abstract void renderTexturedButton(TexturedButton button); - - - /** - * Render a vector drawn radio button - * @param radio - */ + + /** Render a vector drawn radio button + * + * @param radio */ protected abstract void renderVectorRadioButton(VectorRadioButton radio); - - - /** - * Render a coloured vector shape to the screen + + /** Render a coloured vector shape to the screen + * * @param shape - * @param e - */ + * @param e */ protected abstract void renderColouredVectorShape(IColouredVectorShape shape, GUIBoundsInterface e, float offsetX, float offsetY); - - } diff --git a/src/com/bwyap/engine/gui/GUIRendererInterface.java b/src/com/bwyap/engine/gui/GUIRendererInterface.java index 1dbb656..1af15c0 100644 --- a/src/com/bwyap/engine/gui/GUIRendererInterface.java +++ b/src/com/bwyap/engine/gui/GUIRendererInterface.java @@ -14,24 +14,18 @@ import com.bwyap.engine.gui.element.vector.VectorTextField; import com.bwyap.engine.window.WindowInterface; - -/** - * An interface for methods that a GUI renderer should provide. - * @author bwyap - * - */ -public interface GUIRendererInterface { - - - /** - * Renders the GUI on the window. +/** An interface for methods that a GUI renderer should provide. + * + * @author bwyap */ +public interface GUIRendererInterface +{ + /** Renders the GUI on the window. * This step should be done after other elements are rendered. * All preparation for GUI rendering should be handled by the GUI system. - * @param window - */ + * + * @param window */ public void render(GUI gui, WindowInterface window); - /* * ================= * RENDERING METHODS @@ -39,78 +33,57 @@ public interface GUIRendererInterface { * The following methods must be implemented to be able * to render the provided GUI elements in this library. */ - - - /** - * Render a panel and the elements contained within it - * @param panel the panel to render + /** Render a panel and the elements contained within it + * + * @param panel the panel to render * @param window the bounding window - * @param parent the parent of the panel - */ + * @param parent the parent of the panel */ public void renderPanel(Panel panel, WindowInterface window, Vector2f parent); - - - /** - * Render a scroll area and the elements contained within it + + /** Render a scroll area and the elements contained within it + * * @param scrollArea - * @param window - */ + * @param window */ public void renderVectorScrollArea(VectorScrollArea scrollArea, WindowInterface window); - - - /** - * Render a label - * @param label - */ + + /** Render a label + * + * @param label */ public void renderLabel(Label label); - - - /** - * Render a text field - * @param textfield - */ + + /** Render a text field + * + * @param textfield */ public void renderVectorTextField(VectorTextField textfield); - - /** - * Render a text box - * @param textBox - */ + /** Render a text box + * + * @param textBox */ public void renderVectorTextBox(VectorTextBox textBox); - - - /** - * Render a button - * @param button - */ + + /** Render a button + * + * @param button */ public void renderButton(Button button); - - - /** - * Render a check box - * @param checkbox - */ + + /** Render a check box + * + * @param checkbox */ public void renderVectorCheckBox(VectorCheckBox checkbox); - - - /** - * Render a radio button group + + /** Render a radio button group + * * @param group - * @param parentPanel - */ + * @param parentPanel */ public void renderRadioButtonGroup(RadioButtonGroup group, Panel parentPanel); - - - /** - * Render a progress bar - * @param progressBar - */ + + /** Render a progress bar + * + * @param progressBar */ public void renderVectorProgressBar(VectorProgressBar progressBar); - - - /** - * Render an image - * @param holder - */ + + /** Render an image + * + * @param holder */ public void renderImage(ImageHolder holder); } diff --git a/src/com/bwyap/engine/gui/element/CircularRadioButton.java b/src/com/bwyap/engine/gui/element/CircularRadioButton.java index 04494ea..5cb361b 100644 --- a/src/com/bwyap/engine/gui/element/CircularRadioButton.java +++ b/src/com/bwyap/engine/gui/element/CircularRadioButton.java @@ -4,84 +4,64 @@ import com.bwyap.engine.gui.element.vector.VectorRadioButton; import com.bwyap.engine.gui.interfaces.IVectorEllipse; - -/** - * A circular radio button. +/** A circular radio button. * See {@link RadioButton}. - * @author bwyap - * - */ -public class CircularRadioButton extends VectorRadioButton implements IVectorEllipse{ + * + * @author bwyap */ +public class CircularRadioButton extends VectorRadioButton implements IVectorEllipse +{ + public CircularRadioButton(String name, float x, float y, float radius) + { super(name, x, y, radius, radius); } - - public CircularRadioButton(String name, float x, float y, float radius) { - super(name, x, y, radius, radius); - } - - - public CircularRadioButton(float x, float y, float radius) { - super(x, y, radius, radius); - } - - - /** - * Set the radius and positional offset of the elliptical bounds. - * @param x offset - * @param y offset + public CircularRadioButton(float x, float y, float radius) + { super(x, y, radius, radius); } + + /** Set the radius and positional offset of the elliptical bounds. + * + * @param x offset + * @param y offset * @param rx semi-major radius - * @param ry semi-major radius - */ + * @param ry semi-major radius */ @Override - public void setBounds(float xOffset, float yOffset, float rx, float ry) { - super.setBounds(xOffset, yOffset, rx, ry); - } - - - /** - * Set the radius of the elliptical bounds. + public void setBounds(float xOffset, float yOffset, float rx, float ry) + { super.setBounds(xOffset, yOffset, rx, ry); } + + /** Set the radius of the elliptical bounds. * The offset of the bounding ellipse is set * to (0, 0). + * * @param rx semi-major radius - * @param ry semi-major radius - */ + * @param ry semi-major radius */ @Override - public void setBounds(float rx, float ry) { - super.setBounds(rx, ry); - } - + public void setBounds(float rx, float ry) + { super.setBounds(rx, ry); } - /** - * Set the radius of the circular bounds. + /** Set the radius of the circular bounds. * The offset of the bounding circle is set * to (0, 0). - * @param r radius for semi-major and semi-minor axes - */ - public void setBoundsRadius(float r) { - setBounds(0, 0, r, r); - } - - + * + * @param r radius for semi-major and semi-minor axes */ + public void setBoundsRadius(float r) + { setBounds(0, 0, r, r); } + @Override - public boolean withinBounds(float x, float y) { + public boolean withinBounds(float x, float y) + { /* * Formula: * (x-h)^2/(rx)^2 + (y-k)^2/(ry)^2 <= 1 */ - float xtop = (float)Math.pow(x - (position.x + bounds.x + boundsOffset.x), 2); - float xbot = (float)Math.pow(bounds.x, 2); - float ytop = (float)Math.pow(y - (position.y + bounds.y + boundsOffset.y), 2); - float ybot = (float)Math.pow(bounds.y, 2); - - return (xtop/xbot) + (ytop/ybot) <= 1.0f; + float xtop = (float) Math.pow(x - (position.x + bounds.x + boundsOffset.x), 2); + float xbot = (float) Math.pow(bounds.x, 2); + float ytop = (float) Math.pow(y - (position.y + bounds.y + boundsOffset.y), 2); + float ybot = (float) Math.pow(bounds.y, 2); + return (xtop / xbot) + (ytop / ybot) <= 1.0f; } - - - /** - * {@inheritDoc} + + /** {@inheritDoc} *

* Override this method to implement custom functionality. - *

- */ - public void update(float timestep) { } - + *

*/ + public void update(float timestep) + {} } diff --git a/src/com/bwyap/engine/gui/element/EllipticalButton.java b/src/com/bwyap/engine/gui/element/EllipticalButton.java index b70cfaf..4d4707c 100644 --- a/src/com/bwyap/engine/gui/element/EllipticalButton.java +++ b/src/com/bwyap/engine/gui/element/EllipticalButton.java @@ -3,76 +3,60 @@ import com.bwyap.engine.gui.element.vector.VectorButton; import com.bwyap.engine.gui.interfaces.IVectorEllipse; -/** - * An elliptical button that is drawn by the graphics rendering system. +/** An elliptical button that is drawn by the graphics rendering system. * See {@link Button}. - * @author bwyap - * - */ -public abstract class EllipticalButton extends VectorButton implements IVectorEllipse { - - - public EllipticalButton(float x, float y, float xr, float yr) { - super(x, y, xr, yr); - - } - + * + * @author bwyap */ +public abstract class EllipticalButton extends VectorButton implements IVectorEllipse +{ + public EllipticalButton(float x, float y, float xr, float yr) + { super(x, y, xr, yr); } - /** - * Set the radius and positional offset of the elliptical bounds. - * @param x offset - * @param y offset + /** Set the radius and positional offset of the elliptical bounds. + * + * @param x offset + * @param y offset * @param rx semi-major radius - * @param ry semi-major radius - */ + * @param ry semi-major radius */ @Override - public void setBounds(float xOffset, float yOffset, float rx, float ry) { - super.setBounds(xOffset, yOffset, rx, ry); - } - - - /** - * Set the radius of the elliptical bounds. + public void setBounds(float xOffset, float yOffset, float rx, float ry) + { super.setBounds(xOffset, yOffset, rx, ry); } + + /** Set the radius of the elliptical bounds. * The offset of the bounding ellipse is set * to (0, 0). + * * @param rx semi-major radius - * @param ry semi-major radius - */ + * @param ry semi-major radius */ @Override - public void setBounds(float rx, float ry) { - super.setBounds(0, 0, rx, ry); - } - + public void setBounds(float rx, float ry) + { super.setBounds(0, 0, rx, ry); } - /** - * Set the radius of the circular bounds. + /** Set the radius of the circular bounds. * The offset of the bounding circle is set * to (0, 0). - * @param r radius for semi-major and semi-minor axes - */ - public void setBoundsRadius(float r) { - super.setBounds(0, 0, r, r); - } - - + * + * @param r radius for semi-major and semi-minor axes */ + public void setBoundsRadius(float r) + { super.setBounds(0, 0, r, r); } + @Override - public boolean withinBounds(float x, float y) { + public boolean withinBounds(float x, float y) + { /* * Formula: * (x-h)^2/(rx)^2 + (y-k)^2/(ry)^2 <= 1 */ - float xtop = (float)Math.pow(x - (position.x + bounds.x + boundsOffset.x), 2); - float xbot = (float)Math.pow(bounds.x, 2); - float ytop = (float)Math.pow(y - (position.y + bounds.y + boundsOffset.y), 2); - float ybot = (float)Math.pow(bounds.y, 2); - + float xtop = (float) Math.pow(x - (position.x + bounds.x + boundsOffset.x), 2); + float xbot = (float) Math.pow(bounds.x, 2); + float ytop = (float) Math.pow(y - (position.y + bounds.y + boundsOffset.y), 2); + float ybot = (float) Math.pow(bounds.y, 2); /* // circular bounds float xcenter = position.x + circularBoundsRadius; float ycenter = position.y + circularBoundsRadius; return Math.pow(x - xcenter, 2) + Math.pow(y - ycenter, 2) <= Math.pow(circularBoundsRadius, 2); */ - return (xtop/xbot) + (ytop/ybot) <= 1.0f; + return (xtop / xbot) + (ytop / ybot) <= 1.0f; } - } diff --git a/src/com/bwyap/engine/gui/element/Label.java b/src/com/bwyap/engine/gui/element/Label.java index 83aa23c..4203e80 100644 --- a/src/com/bwyap/engine/gui/element/Label.java +++ b/src/com/bwyap/engine/gui/element/Label.java @@ -9,21 +9,17 @@ import com.bwyap.engine.input.InputHandler; import com.bwyap.lwjgl.engine.resource.LWJGLResourceManager; - -/** - * An GUI element that displays text. NOTE: The bounds for this element +/** An GUI element that displays text. NOTE: The bounds for this element * are not used to describe the bounds of the text. If you need to detect * mouse interaction with the element, use a button instead. - * @author bwyap - * - */ -public class Label extends GUIElement implements GUIElementInterface, ITextDisplay { - - + * + * @author bwyap */ +public class Label extends GUIElement implements GUIElementInterface, ITextDisplay +{ private TextComponent text; - - - public Label(String string, float x, float y) { + + public Label(String string, float x, float y) + { super(x, y, 1, 1); text = new TextComponent(string); text.setClipText(false); @@ -32,19 +28,16 @@ public Label(String string, float x, float y) { // Set the font of the label text text.setFontName(LWJGLResourceManager.instance().lib.getFont("default")); } - - - @Override - public TextComponent getTextComponent() { - return text; - } - @Override - public void update(float timestep) { } - + public TextComponent getTextComponent() + { return text; } @Override - public void handleInput(InputHandler input, GUIBoundsInterface bounds) { } + public void update(float timestep) + {} + @Override + public void handleInput(InputHandler input, GUIBoundsInterface bounds) + {} } diff --git a/src/com/bwyap/engine/gui/element/RectangularButton.java b/src/com/bwyap/engine/gui/element/RectangularButton.java index 492dfc1..85a57a8 100644 --- a/src/com/bwyap/engine/gui/element/RectangularButton.java +++ b/src/com/bwyap/engine/gui/element/RectangularButton.java @@ -4,17 +4,12 @@ import com.bwyap.engine.gui.element.vector.VectorButton; import com.bwyap.engine.gui.interfaces.IVectorRect; -/** - * A rectangular button that is drawn by the graphics rendering system. +/** A rectangular button that is drawn by the graphics rendering system. * See {@link Button}. - * @author bwyap - * - */ -public abstract class RectangularButton extends VectorButton implements IVectorRect { - - - public RectangularButton(int x, int y, float width, float height) { - super(x, y, width, height); - } - + * + * @author bwyap */ +public abstract class RectangularButton extends VectorButton implements IVectorRect +{ + public RectangularButton(int x, int y, float width, float height) + { super(x, y, width, height); } } diff --git a/src/com/bwyap/engine/gui/element/RectangularCheckBox.java b/src/com/bwyap/engine/gui/element/RectangularCheckBox.java index 0a7d9e8..60308f3 100644 --- a/src/com/bwyap/engine/gui/element/RectangularCheckBox.java +++ b/src/com/bwyap/engine/gui/element/RectangularCheckBox.java @@ -4,30 +4,22 @@ import com.bwyap.engine.gui.element.vector.VectorCheckBox; import com.bwyap.engine.gui.interfaces.IVectorRect; -/** - * A rectangular check box. +/** A rectangular check box. * See {@link CheckBox}. - * @author bwyap - * - */ -public class RectangularCheckBox extends VectorCheckBox implements IVectorRect { + * + * @author bwyap */ +public class RectangularCheckBox extends VectorCheckBox implements IVectorRect +{ + public RectangularCheckBox(float x, float y, float width, CheckBoxCheckStyle style) + { super(x, y, width, width, style); } - public RectangularCheckBox(float x, float y, float width, CheckBoxCheckStyle style) { - super(x, y, width, width, style); - } - - - public RectangularCheckBox(float x, float y, float width) { - super(x, y, width, width); - } + public RectangularCheckBox(float x, float y, float width) + { super(x, y, width, width); } - - /** - * {@inheritDoc} + /** {@inheritDoc} *

* Override this method to implement custom functionality. - *

- */ - public void update(float timestep) { } - + *

*/ + public void update(float timestep) + {} } diff --git a/src/com/bwyap/engine/gui/element/RectangularPanel.java b/src/com/bwyap/engine/gui/element/RectangularPanel.java index 343f5a7..1d344a6 100644 --- a/src/com/bwyap/engine/gui/element/RectangularPanel.java +++ b/src/com/bwyap/engine/gui/element/RectangularPanel.java @@ -3,30 +3,20 @@ import com.bwyap.engine.gui.element.base.Panel; import com.bwyap.engine.gui.interfaces.IVectorRect; - -/** - * A rectangular panel. +/** A rectangular panel. * See {@link Panel}. - * @author bwyap - * - */ -public class RectangularPanel extends Panel implements IVectorRect { - + * + * @author bwyap */ +public class RectangularPanel extends Panel implements IVectorRect +{ + public RectangularPanel(float x, float y, float width, float height) + { super(x, y, width, height); } - public RectangularPanel(float x, float y, float width, float height) { - super(x, y, width, height); - } - - @Override - public float getWidth() { - return bounds.x; - } - - + public float getWidth() + { return bounds.x; } + @Override - public float getHeight() { - return bounds.y; - } - + public float getHeight() + { return bounds.y; } } diff --git a/src/com/bwyap/engine/gui/element/RectangularPanelWindow.java b/src/com/bwyap/engine/gui/element/RectangularPanelWindow.java index d8c91d8..4e3c5b8 100644 --- a/src/com/bwyap/engine/gui/element/RectangularPanelWindow.java +++ b/src/com/bwyap/engine/gui/element/RectangularPanelWindow.java @@ -3,16 +3,12 @@ import com.bwyap.engine.gui.element.base.PanelWindow; import com.bwyap.engine.gui.interfaces.IVectorRect; -/** - * A rectangular panel window. +/** A rectangular panel window. * See {@link PanelWindow}. - * @author bwyap - * - */ -public abstract class RectangularPanelWindow extends PanelWindow implements IVectorRect { - - public RectangularPanelWindow(String title, float x, float y, float width, float height) { - super(title, x, y, width, height); - } - + * + * @author bwyap */ +public abstract class RectangularPanelWindow extends PanelWindow implements IVectorRect +{ + public RectangularPanelWindow(String title, float x, float y, float width, float height) + { super(title, x, y, width, height); } } diff --git a/src/com/bwyap/engine/gui/element/RectangularScrollArea.java b/src/com/bwyap/engine/gui/element/RectangularScrollArea.java index 6ea9f7f..5246780 100644 --- a/src/com/bwyap/engine/gui/element/RectangularScrollArea.java +++ b/src/com/bwyap/engine/gui/element/RectangularScrollArea.java @@ -4,17 +4,12 @@ import com.bwyap.engine.gui.element.vector.VectorScrollArea; import com.bwyap.engine.gui.interfaces.IVectorRect; - -/** - * A rectangular scroll area. +/** A rectangular scroll area. * See {@link ScrollArea}. - * @author bwyap - * - */ -public class RectangularScrollArea extends VectorScrollArea implements IVectorRect { - - public RectangularScrollArea(float x, float y, float width, float height, float scrollLength, ScrollDirection scrollDirection) { - super(x, y, width, height, scrollLength, scrollDirection); - } - + * + * @author bwyap */ +public class RectangularScrollArea extends VectorScrollArea implements IVectorRect +{ + public RectangularScrollArea(float x, float y, float width, float height, float scrollLength, ScrollDirection scrollDirection) + { super(x, y, width, height, scrollLength, scrollDirection); } } diff --git a/src/com/bwyap/engine/gui/element/RectangularSolidProgressBar.java b/src/com/bwyap/engine/gui/element/RectangularSolidProgressBar.java index 3919e2d..e51ec4e 100644 --- a/src/com/bwyap/engine/gui/element/RectangularSolidProgressBar.java +++ b/src/com/bwyap/engine/gui/element/RectangularSolidProgressBar.java @@ -6,31 +6,24 @@ import com.bwyap.engine.gui.interfaces.IVectorRect; import com.bwyap.engine.input.InputHandler; +/** A rectangular progress bar filled with a solid colour. + * See {@link ProgressBar}. + * + * @author bwyap */ +public class RectangularSolidProgressBar extends SolidVectorProgressBar implements IVectorRect +{ + public RectangularSolidProgressBar(float x, float y, float width, float height) + { super(x, y, width, height); } -/** - * A rectangular progress bar filled with a solid colour. - * See {@link ProgressBar}. - * @author bwyap - * - */ -public class RectangularSolidProgressBar extends SolidVectorProgressBar implements IVectorRect { - - public RectangularSolidProgressBar(float x, float y, float width, float height) { - super(x, y, width, height); - } - - - /** - * {@inheritDoc} + /** {@inheritDoc} *

* Override this method to implement custom functionality. - *

- */ + *

*/ @Override - public void update(float timestep) { } + public void update(float timestep) + {} - @Override - public void handleInput(InputHandler input, GUIBoundsInterface bounds) { } - + public void handleInput(InputHandler input, GUIBoundsInterface bounds) + {} } diff --git a/src/com/bwyap/engine/gui/element/RectangularTextBox.java b/src/com/bwyap/engine/gui/element/RectangularTextBox.java index 301ed67..596fe33 100644 --- a/src/com/bwyap/engine/gui/element/RectangularTextBox.java +++ b/src/com/bwyap/engine/gui/element/RectangularTextBox.java @@ -4,17 +4,12 @@ import com.bwyap.engine.gui.element.vector.VectorTextBox; import com.bwyap.engine.gui.interfaces.IVectorRect; - -/** - * A rectangular text box. +/** A rectangular text box. * See {@link TextBox}. - * @author bwyap - * - */ -public abstract class RectangularTextBox extends VectorTextBox implements IVectorRect { - - public RectangularTextBox(float x, float y, float width, float height, float padding) { - super(x, y, width, height, padding); - } - + * + * @author bwyap */ +public abstract class RectangularTextBox extends VectorTextBox implements IVectorRect +{ + public RectangularTextBox(float x, float y, float width, float height, float padding) + { super(x, y, width, height, padding); } } diff --git a/src/com/bwyap/engine/gui/element/RectangularTextfield.java b/src/com/bwyap/engine/gui/element/RectangularTextfield.java index c0b3fad..979f99f 100644 --- a/src/com/bwyap/engine/gui/element/RectangularTextfield.java +++ b/src/com/bwyap/engine/gui/element/RectangularTextfield.java @@ -4,17 +4,12 @@ import com.bwyap.engine.gui.element.vector.VectorTextField; import com.bwyap.engine.gui.interfaces.IVectorRect; -/** - * A vector drawn rectangular text field. +/** A vector drawn rectangular text field. * See {@link TextField}. - * @author bwyap - * - */ -public abstract class RectangularTextfield extends VectorTextField implements IVectorRect { - - public RectangularTextfield(int x, int y, float width, float height) { - super(x, y, width, height); - - } - + * + * @author bwyap */ +public abstract class RectangularTextfield extends VectorTextField implements IVectorRect +{ + public RectangularTextfield(int x, int y, float width, float height) + { super(x, y, width, height); } } diff --git a/src/com/bwyap/engine/gui/element/RoundedRectangularButton.java b/src/com/bwyap/engine/gui/element/RoundedRectangularButton.java index bdd3e13..95b31a4 100644 --- a/src/com/bwyap/engine/gui/element/RoundedRectangularButton.java +++ b/src/com/bwyap/engine/gui/element/RoundedRectangularButton.java @@ -4,32 +4,27 @@ import com.bwyap.engine.gui.element.vector.VectorButton; import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; -/** - * A rounded rectangular button that is drawn by the graphics rendering system. +/** A rounded rectangular button that is drawn by the graphics rendering system. * See {@link Button}. - * @author bwyap - * - */ -public abstract class RoundedRectangularButton extends VectorButton implements IVectorRoundedRect { - + * + * @author bwyap */ +public abstract class RoundedRectangularButton extends VectorButton implements IVectorRoundedRect +{ protected float radius; - - public RoundedRectangularButton(int x, int y, float width, float height, float radius) { + + public RoundedRectangularButton(int x, int y, float width, float height, float radius) + { super(x, y, width, height); this.radius = radius; } - + @Override - public float getRadius() { - return radius; - } - - /** - * Set the radius of the corners - * @param radius - */ - public void setRadius(float radius) { - this.radius = radius; - } - + public float getRadius() + { return radius; } + + /** Set the radius of the corners + * + * @param radius */ + public void setRadius(float radius) + { this.radius = radius; } } diff --git a/src/com/bwyap/engine/gui/element/RoundedRectangularCheckBox.java b/src/com/bwyap/engine/gui/element/RoundedRectangularCheckBox.java index 4469aea..9f43f5e 100644 --- a/src/com/bwyap/engine/gui/element/RoundedRectangularCheckBox.java +++ b/src/com/bwyap/engine/gui/element/RoundedRectangularCheckBox.java @@ -4,39 +4,34 @@ import com.bwyap.engine.gui.element.vector.VectorCheckBox; import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; -/** - * A rounded rectangular check box. +/** A rounded rectangular check box. * See {@link CheckBox}. - * @author bwyap - * - */ -public class RoundedRectangularCheckBox extends VectorCheckBox implements IVectorRoundedRect { - + * + * @author bwyap */ +public class RoundedRectangularCheckBox extends VectorCheckBox implements IVectorRoundedRect +{ private float radius; - - public RoundedRectangularCheckBox(float x, float y, float width, float radius, CheckBoxCheckStyle style) { + + public RoundedRectangularCheckBox(float x, float y, float width, float radius, CheckBoxCheckStyle style) + { super(x, y, width, width, style); this.radius = radius; } - - - public RoundedRectangularCheckBox(float x, float y, float width, float radius) { + + public RoundedRectangularCheckBox(float x, float y, float width, float radius) + { super(x, y, width, width); this.radius = radius; } - - + @Override - public float getRadius() { - return radius; - } - - - /** - * {@inheritDoc} + public float getRadius() + { return radius; } + + /** {@inheritDoc} *

* Override this method to implement custom functionality. - *

- */ - public void update(float timestep) { } + *

*/ + public void update(float timestep) + {} } diff --git a/src/com/bwyap/engine/gui/element/RoundedRectangularPanel.java b/src/com/bwyap/engine/gui/element/RoundedRectangularPanel.java index 837cdbc..d83b492 100644 --- a/src/com/bwyap/engine/gui/element/RoundedRectangularPanel.java +++ b/src/com/bwyap/engine/gui/element/RoundedRectangularPanel.java @@ -3,25 +3,21 @@ import com.bwyap.engine.gui.element.base.Panel; import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; -/** - * A rounded rectangular panel. +/** A rounded rectangular panel. * See {@link Panel}. - * @author bwyap - * - */ -public class RoundedRectangularPanel extends Panel implements IVectorRoundedRect { - + * + * @author bwyap */ +public class RoundedRectangularPanel extends Panel implements IVectorRoundedRect +{ private float radius; - public RoundedRectangularPanel(float x, float y, float width, float height, float radius) { + public RoundedRectangularPanel(float x, float y, float width, float height, float radius) + { super(x, y, width, height); this.radius = radius; } - - - @Override - public float getRadius() { - return radius; - } + @Override + public float getRadius() + { return radius; } } diff --git a/src/com/bwyap/engine/gui/element/RoundedRectangularPanelWindow.java b/src/com/bwyap/engine/gui/element/RoundedRectangularPanelWindow.java index 99df778..9083f04 100644 --- a/src/com/bwyap/engine/gui/element/RoundedRectangularPanelWindow.java +++ b/src/com/bwyap/engine/gui/element/RoundedRectangularPanelWindow.java @@ -3,25 +3,21 @@ import com.bwyap.engine.gui.element.base.PanelWindow; import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; -/** - * A rounded rectangular panel window. +/** A rounded rectangular panel window. * See {@link PanelWindow}. - * @author bwyap - * - */ -public abstract class RoundedRectangularPanelWindow extends PanelWindow implements IVectorRoundedRect { - + * + * @author bwyap */ +public abstract class RoundedRectangularPanelWindow extends PanelWindow implements IVectorRoundedRect +{ private float radius; - public RoundedRectangularPanelWindow(String title, float x, float y, float width, float height, float radius) { + public RoundedRectangularPanelWindow(String title, float x, float y, float width, float height, float radius) + { super(title, x, y, width, height); this.radius = radius; } - @Override - public float getRadius() { - return radius; - } - + public float getRadius() + { return radius; } } diff --git a/src/com/bwyap/engine/gui/element/RoundedRectangularScrollArea.java b/src/com/bwyap/engine/gui/element/RoundedRectangularScrollArea.java index 83f3071..db4cd93 100644 --- a/src/com/bwyap/engine/gui/element/RoundedRectangularScrollArea.java +++ b/src/com/bwyap/engine/gui/element/RoundedRectangularScrollArea.java @@ -4,35 +4,27 @@ import com.bwyap.engine.gui.element.vector.VectorScrollArea; import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; - -/** - * A rounded rectangular scroll area. +/** A rounded rectangular scroll area. * See {@link ScrollArea}. - * @author bwyap - * - */ -public class RoundedRectangularScrollArea extends VectorScrollArea implements IVectorRoundedRect { - + * + * @author bwyap */ +public class RoundedRectangularScrollArea extends VectorScrollArea implements IVectorRoundedRect +{ private float radius; - - public RoundedRectangularScrollArea(float x, float y, float width, float height, float scrollLength, ScrollDirection scrollDirection, float radius) { + + public RoundedRectangularScrollArea(float x, float y, float width, float height, float scrollLength, ScrollDirection scrollDirection, float radius) + { super(x, y, width, height, scrollLength, scrollDirection); this.radius = radius; } - - - /** - * Set the radius of the corners - * @param radius - */ - public void setRadius(float radius) { - this.radius = radius; - } - - - @Override - public float getRadius() { - return radius; - } + /** Set the radius of the corners + * + * @param radius */ + public void setRadius(float radius) + { this.radius = radius; } + + @Override + public float getRadius() + { return radius; } } diff --git a/src/com/bwyap/engine/gui/element/RoundedRectangularSolidProgressBar.java b/src/com/bwyap/engine/gui/element/RoundedRectangularSolidProgressBar.java index 936b378..ca4e3bf 100644 --- a/src/com/bwyap/engine/gui/element/RoundedRectangularSolidProgressBar.java +++ b/src/com/bwyap/engine/gui/element/RoundedRectangularSolidProgressBar.java @@ -6,42 +6,33 @@ import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; import com.bwyap.engine.input.InputHandler; - -/** - * A rounded rectangular progress bar filled with a solid colour. +/** A rounded rectangular progress bar filled with a solid colour. * See {@link ProgressBar}. - * @author bwyap - * - */ -public class RoundedRectangularSolidProgressBar extends SolidVectorProgressBar implements IVectorRoundedRect { - + * + * @author bwyap */ +public class RoundedRectangularSolidProgressBar extends SolidVectorProgressBar implements IVectorRoundedRect +{ private float radius; - - - public RoundedRectangularSolidProgressBar(float x, float y, float width, float height, float radius) { + + public RoundedRectangularSolidProgressBar(float x, float y, float width, float height, float radius) + { super(x, y, width, height); this.radius = radius; } - - + @Override - public float getRadius() { - return radius; - } - - - /** - * {@inheritDoc} + public float getRadius() + { return radius; } + + /** {@inheritDoc} *

* Override this method to implement custom functionality. - *

- */ + *

*/ @Override - public void update(float timestep) { } + public void update(float timestep) + {} - @Override - public void handleInput(InputHandler input, GUIBoundsInterface bounds) { } - - + public void handleInput(InputHandler input, GUIBoundsInterface bounds) + {} } diff --git a/src/com/bwyap/engine/gui/element/RoundedRectangularTextBox.java b/src/com/bwyap/engine/gui/element/RoundedRectangularTextBox.java index 7777c60..3c401d2 100644 --- a/src/com/bwyap/engine/gui/element/RoundedRectangularTextBox.java +++ b/src/com/bwyap/engine/gui/element/RoundedRectangularTextBox.java @@ -4,34 +4,27 @@ import com.bwyap.engine.gui.element.vector.VectorTextBox; import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; - -/** - * A rounded rectangular text box. +/** A rounded rectangular text box. * See {@link TextBox}. - * @author bwyap - * - */ -public abstract class RoundedRectangularTextBox extends VectorTextBox implements IVectorRoundedRect{ - + * + * @author bwyap */ +public abstract class RoundedRectangularTextBox extends VectorTextBox implements IVectorRoundedRect +{ private float radius; - - public RoundedRectangularTextBox(float x, float y, float width, float height, float radius, float padding) { + + public RoundedRectangularTextBox(float x, float y, float width, float height, float radius, float padding) + { super(x, y, width, height, padding); this.radius = radius; } - - - /** - * Set the radius of the rounded rectangle - * @param radius - */ - public void setRadius(float radius) { - this.radius = radius; - } - - + + /** Set the radius of the rounded rectangle + * + * @param radius */ + public void setRadius(float radius) + { this.radius = radius; } + @Override - public float getRadius() { - return radius; - } + public float getRadius() + { return radius; } } diff --git a/src/com/bwyap/engine/gui/element/RoundedRectangularTextfield.java b/src/com/bwyap/engine/gui/element/RoundedRectangularTextfield.java index c22e40d..e8af550 100644 --- a/src/com/bwyap/engine/gui/element/RoundedRectangularTextfield.java +++ b/src/com/bwyap/engine/gui/element/RoundedRectangularTextfield.java @@ -4,34 +4,27 @@ import com.bwyap.engine.gui.element.vector.VectorTextField; import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; - -/** - * A vector drawn rounded rectangular text field. +/** A vector drawn rounded rectangular text field. * See {@link TextField}. - * @author bwyap - * - */ -public abstract class RoundedRectangularTextfield extends VectorTextField implements IVectorRoundedRect { - + * + * @author bwyap */ +public abstract class RoundedRectangularTextfield extends VectorTextField implements IVectorRoundedRect +{ protected float radius; - public RoundedRectangularTextfield(int x, int y, float width, float height, float radius) { + public RoundedRectangularTextfield(int x, int y, float width, float height, float radius) + { super(x, y, width, height); this.radius = radius; } - @Override - public float getRadius() { - return radius; - } - - /** - * Set the radius of the corners - * @param radius - */ - public void setRadius(float radius) { - this.radius = radius; - } - + public float getRadius() + { return radius; } + + /** Set the radius of the corners + * + * @param radius */ + public void setRadius(float radius) + { this.radius = radius; } } diff --git a/src/com/bwyap/engine/gui/element/TexturedButton.java b/src/com/bwyap/engine/gui/element/TexturedButton.java index fd7ebb9..938ce59 100644 --- a/src/com/bwyap/engine/gui/element/TexturedButton.java +++ b/src/com/bwyap/engine/gui/element/TexturedButton.java @@ -2,86 +2,69 @@ import com.bwyap.engine.gui.element.base.Button; -/** - * A button that is rendered with a texture. +/** A button that is rendered with a texture. * See {@link Button}. - * @author bwyap - * - */ -public abstract class TexturedButton extends Button { - + * + * @author bwyap */ +public abstract class TexturedButton extends Button +{ protected String texture, mouseoverTexture, pressedTexture; - - - public TexturedButton(int x, int y, int width, int height) { - super(x, y, width, height); - } - - /** - * Set the normal texture and mouseover texture to use by its name - * @param texture - */ - public void setTextures(String texture, String mouseoverTexture) { + + public TexturedButton(int x, int y, int width, int height) + { super(x, y, width, height); } + + /** Set the normal texture and mouseover texture to use by its name + * + * @param texture */ + public void setTextures(String texture, String mouseoverTexture) + { this.texture = texture; this.mouseoverTexture = mouseoverTexture; } - - /** - * Set the normal texture, mouseover and pressed texture to use by its name - * @param texture - */ - public void setTextures(String texture, String mouseoverTexture, String pressedTexture) { + + /** Set the normal texture, mouseover and pressed texture to use by its name + * + * @param texture */ + public void setTextures(String texture, String mouseoverTexture, String pressedTexture) + { this.texture = texture; this.mouseoverTexture = mouseoverTexture; this.pressedTexture = pressedTexture; } - - /** - * Set the button texture to use by its name - * @param texture - */ - public void setTexture(String texture) { - this.texture = texture; - } - - /** - * Get the name of the button texture - * @return - */ - public String getTexture() { - return texture; - } - - /** - * Set the mouseover texture to use by its name - * @param texture - */ - public void setMouseoverTexture(String texture) { - this.mouseoverTexture = texture; - } - - /** - * Get the name of the mouseover texture - * @return - */ - public String getMouseoverTexture() { - return mouseoverTexture; - } - - /** - * Set the button pressed texture to use by its name - * @param texture - */ - public void setPressedTexture(String pressedTexture) { - this.pressedTexture = pressedTexture; - } - - /** - * Get the name of the button pressed texture - * @return - */ - public String getPressedTexture() { - return pressedTexture; - } - + + /** Set the button texture to use by its name + * + * @param texture */ + public void setTexture(String texture) + { this.texture = texture; } + + /** Get the name of the button texture + * + * @return */ + public String getTexture() + { return texture; } + + /** Set the mouseover texture to use by its name + * + * @param texture */ + public void setMouseoverTexture(String texture) + { this.mouseoverTexture = texture; } + + /** Get the name of the mouseover texture + * + * @return */ + public String getMouseoverTexture() + { return mouseoverTexture; } + + /** Set the button pressed texture to use by its name + * + * @param texture */ + public void setPressedTexture(String pressedTexture) + { this.pressedTexture = pressedTexture; } + + /** Get the name of the button pressed texture + * + * @return */ + public String getPressedTexture() + { return pressedTexture; } } diff --git a/src/com/bwyap/engine/gui/element/base/AbstractGUIElement.java b/src/com/bwyap/engine/gui/element/base/AbstractGUIElement.java index 1b29436..5eea0dc 100644 --- a/src/com/bwyap/engine/gui/element/base/AbstractGUIElement.java +++ b/src/com/bwyap/engine/gui/element/base/AbstractGUIElement.java @@ -5,178 +5,145 @@ import com.bwyap.engine.gui.interfaces.GUIElementInterface; import com.bwyap.engine.window.BoundsInterface; - -/** - * A dummy class that can be extended by GUI elements +/** A dummy class that can be extended by GUI elements * that should not be rendered themselves, but need to * be to be processed by the renderer. - * @author bwyap - * - */ -public abstract class AbstractGUIElement implements GUIElementInterface { - + * + * @author bwyap */ +public abstract class AbstractGUIElement implements GUIElementInterface +{ protected boolean enabled; - - + @Override - public final void setEnabled(boolean enabled) { - this.enabled = enabled; - } + public final void setEnabled(boolean enabled) + { this.enabled = enabled; } - @Override - public final boolean isEnabled() { - return enabled; - } - - + public final boolean isEnabled() + { return enabled; } + /* * ============== * UNUSED METHODS * ============== */ - - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public float getWidth() {return 0;} - - /** - * Unused method in this class. - */ + public float getWidth() + { return 0; } + + /** Unused method in this class. */ @Override - public float getHeight() {return 0;} + public float getHeight() + { return 0; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public float getPaddingTop() {return 0;} + public float getPaddingTop() + { return 0; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public float getPaddingBottom() {return 0;} + public float getPaddingBottom() + { return 0; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public float getPaddingLeft() {return 0;} + public float getPaddingLeft() + { return 0; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public float getPaddingRight() {return 0;} + public float getPaddingRight() + { return 0; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public Vector2f getPosition() {return null;} + public Vector2f getPosition() + { return null; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public Vector2f getAbsolutePosition() {return null;} + public Vector2f getAbsolutePosition() + { return null; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public float getPositionX() {return 0;} + public float getPositionX() + { return 0; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public float getPositionY() {return 0;} + public float getPositionY() + { return 0; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public Vector2f getBounds() {return null;} + public Vector2f getBounds() + { return null; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public Vector2f getAbsoluteBounds() {return null;} + public Vector2f getAbsoluteBounds() + { return null; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public Vector2f getOriginalBounds() {return null;} + public Vector2f getOriginalBounds() + { return null; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public void updateBounds(BoundsInterface window, Vector2f parent) {} + public void updateBounds(BoundsInterface window, Vector2f parent) + {} - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public void setPosition(float x, float y) {} + public void setPosition(float x, float y) + {} - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public void setPosition(Vector2f position) {} + public void setPosition(Vector2f position) + {} - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public void setPadding(float top, float bottom, float left, float right) {} + public void setPadding(float top, float bottom, float left, float right) + {} - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public void setBounds(float x, float y, float width, float height) {} + public void setBounds(float x, float y, float width, float height) + {} - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public void setBounds(float width, float height) {} + public void setBounds(float width, float height) + {} - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public boolean withinBounds(float x, float y) {return false;} + public boolean withinBounds(float x, float y) + { return false; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public void setPositionAbsolute(boolean absolute) {} + public void setPositionAbsolute(boolean absolute) + {} - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public boolean isPositionAbsolute() {return false;} + public boolean isPositionAbsolute() + { return false; } - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public void setScaleAbsolute(boolean absolute) {} + public void setScaleAbsolute(boolean absolute) + {} - /** - * Unused method in this class. - */ + /** Unused method in this class. */ @Override - public boolean isScaleAbsolute() {return false;} + public boolean isScaleAbsolute() + { return false; } } diff --git a/src/com/bwyap/engine/gui/element/base/Button.java b/src/com/bwyap/engine/gui/element/base/Button.java index 2b84ca6..c868bdb 100644 --- a/src/com/bwyap/engine/gui/element/base/Button.java +++ b/src/com/bwyap/engine/gui/element/base/Button.java @@ -5,48 +5,38 @@ import com.bwyap.engine.gui.interfaces.ITextDisplay; import com.bwyap.engine.input.InputHandler; -/** - * An abstract model of a button that supports a text component. - * @author bwyap - * - */ -public abstract class Button extends ClickableElement implements ITextDisplay{ - +/** An abstract model of a button that supports a text component. + * + * @author bwyap */ +public abstract class Button extends ClickableElement implements ITextDisplay +{ protected final TextComponent text; - - public Button(float x, float y, float width, float height) { + + public Button(float x, float y, float width, float height) + { super(x, y, width, height); text = new TextComponent(1.0f, 1.0f, 1.0f, 1.0f); } - - + @Override - public TextComponent getTextComponent() { - return text; - } - - - /** - * {@inheritDoc} - *

Override this method for custom update functionality.

- */ + public TextComponent getTextComponent() + { return text; } + + /** {@inheritDoc} + *

Override this method for custom update functionality.

*/ @Override - public void onMouseOver(float x, float y) { } - - - /** - * {@inheritDoc} - *

Override this method for custom update functionality.

- */ + public void onMouseOver(float x, float y) + {} + + /** {@inheritDoc} + *

Override this method for custom update functionality.

*/ @Override - public void update(float timestep) { } + public void update(float timestep) + {} - - /** - * {@inheritDoc} - *

Override this method for custom input handling functionality.

- */ + /** {@inheritDoc} + *

Override this method for custom input handling functionality.

*/ @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { } - + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + {} } diff --git a/src/com/bwyap/engine/gui/element/base/CheckBox.java b/src/com/bwyap/engine/gui/element/base/CheckBox.java index 340746a..6b72749 100644 --- a/src/com/bwyap/engine/gui/element/base/CheckBox.java +++ b/src/com/bwyap/engine/gui/element/base/CheckBox.java @@ -3,64 +3,59 @@ import com.bwyap.engine.gui.interfaces.GUIBoundsInterface; import com.bwyap.engine.input.InputHandler; - -/** - * A check box which can be selected. It holds its selected state until - * it is clicked again. Its state can be checked using the {@code isSelected} +/** A check box which can be selected. It holds its selected state until + * it is clicked again. Its state can be checked using the {@code isSelected} * method. The methods {@code onSelect} and {@code onDeselect} can be overridden * to implement custom functionality. - * @author bwyap - * - */ -public abstract class CheckBox extends SelectableElement { + * + * @author bwyap */ +public abstract class CheckBox extends SelectableElement +{ + public CheckBox(float x, float y, float width, float height) + { super(x, y, width, height); } - - public CheckBox(float x, float y, float width, float height) { - super(x, y, width, height); - } - - @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + { // Override SelectableElement functionality } - - + @Override - public void onMouseClicked(float x, float y, int mouseButton) { - if (isSelectable()) { - for (int button : acceptedButtons) { - if (button == mouseButton) { - if (!isSelected()) { + public void onMouseClicked(float x, float y, int mouseButton) + { + if (isSelectable()) + { + for (int button : acceptedButtons) + { + if (button == mouseButton) + { + if (!isSelected()) + { setSelected(true); - onSelect(); + onSelect(); } - else { + else + { setSelected(false); onDeselect(); } - break; + break; } } } } - - /** - * {@inheritDoc} + /** {@inheritDoc} *

* Override this method to implement custom functionality. - *

- */ - public void onSelect() { } + *

*/ + public void onSelect() + {} - - /** - * {@inheritDoc} + /** {@inheritDoc} *

* Override this method to implement custom functionality. - *

- */ - public void onDeselect() { } - + *

*/ + public void onDeselect() + {} } diff --git a/src/com/bwyap/engine/gui/element/base/ClickableElement.java b/src/com/bwyap/engine/gui/element/base/ClickableElement.java index 9a920c4..ce4a0ba 100644 --- a/src/com/bwyap/engine/gui/element/base/ClickableElement.java +++ b/src/com/bwyap/engine/gui/element/base/ClickableElement.java @@ -8,122 +8,101 @@ import com.bwyap.engine.input.InputHandler; import com.bwyap.lwjgl.engine.resource.LWJGLResourceManager; -/** - * A GUI element that can be clicked by specified mouse buttons. +/** A GUI element that can be clicked by specified mouse buttons. * Valid mouse buttons are in the list {@code acceptedButtons}. * - * @author bwyap - * - */ -public abstract class ClickableElement extends GUIElement implements MouseDownInterface { - + * @author bwyap */ +public abstract class ClickableElement extends GUIElement implements MouseDownInterface +{ protected List acceptedButtons; - protected boolean mouseOverReact; protected boolean mouseOver; protected int currentClick; - - public ClickableElement(float x, float y, float width, float height) { + public ClickableElement(float x, float y, float width, float height) + { super(x, y, width, height); this.currentClick = -1; this.acceptedButtons = new ArrayList(); mouseOverReact = true; - // Default accepted button is left click acceptedButtons.add(LWJGLResourceManager.instance().inputMapping().getBinding("mouse_left")); } - - + @Override - public final void handleInput(InputHandler input, GUIBoundsInterface bounds) { - if (enabled) { + public final void handleInput(InputHandler input, GUIBoundsInterface bounds) + { + if (enabled) + { // Check if the mouse is over the button's bounds - if (bounds.withinBounds((float)input.getMouseX(), (float)input.getMouseY()) && - withinBounds((int)input.getMouseX(), (int)input.getMouseY())) { + if (bounds.withinBounds((float) input.getMouseX(), (float) input.getMouseY()) && + withinBounds((int) input.getMouseX(), (int) input.getMouseY())) + { mouseOver = true; - if (mouseOverReact) onMouseOver((int)input.getMouseX(), (int)input.getMouseY()); + if (mouseOverReact) onMouseOver((int) input.getMouseX(), (int) input.getMouseY()); } else mouseOver = false; - // Check if the button has been clicked - if (mouseOver && currentClick == -1) { - for (int mouseButton : acceptedButtons) { - if (input.isMouseDown(mouseButton)) { + if (mouseOver && currentClick == -1) + { + for (int mouseButton : acceptedButtons) + { + if (input.isMouseDown(mouseButton)) + { currentClick = mouseButton; - onMouseDown((int)input.getMouseX(), (int)input.getMouseY(), mouseButton); + onMouseDown((int) input.getMouseX(), (int) input.getMouseY(), mouseButton); } } } - // Reset the click if the click has been released - if (currentClick >= 0) { - if (!input.isMouseDown(currentClick)) { - if (bounds.withinBounds((float)input.getMouseX(), (float)input.getMouseY()) && - withinBounds((int)input.getMouseX(), (int)input.getMouseY())) { - onMouseClicked((int)input.getMouseX(), (int)input.getMouseY(), currentClick); - } + if (currentClick >= 0) + { + if (!input.isMouseDown(currentClick)) + { + if (bounds.withinBounds((float) input.getMouseX(), (float) input.getMouseY()) && + withinBounds((int) input.getMouseX(), (int) input.getMouseY())) + { onMouseClicked((int) input.getMouseX(), (int) input.getMouseY(), currentClick); } currentClick = -1; } } - onHandleInput(input, bounds); } } - - - - /** - * {@inheritDoc} + + /** {@inheritDoc} *
- * Override this function for custom functionality - */ + * Override this function for custom functionality */ @Override - public void onMouseDown(float x, float y, int mouseButton) { - - } - - - /** - * Handle how the GUI element should respond to input. + public void onMouseDown(float x, float y, int mouseButton) + {} + + /** Handle how the GUI element should respond to input. * This method is called by the parent's {@code handleInput} method. + * * @param input - * @param bounds - */ + * @param bounds */ public abstract void onHandleInput(InputHandler input, GUIBoundsInterface bounds); - - + @Override - public boolean mouseOverReact() { - return mouseOverReact; - } - - - /** - * Set whether the element should react when the mouse is over the element. + public boolean mouseOverReact() + { return mouseOverReact; } + + /** Set whether the element should react when the mouse is over the element. * The {@code onMouseClicked} method should still work when {@code mouseOverReact} is {@code false}. - * @param mouseOverReact - */ - public void setReactToMouseOver(boolean mouseOverReact) { - this.mouseOverReact = mouseOverReact; - } - - + * + * @param mouseOverReact */ + public void setReactToMouseOver(boolean mouseOverReact) + { this.mouseOverReact = mouseOverReact; } + @Override - public boolean isMouseOver() { - return mouseOver; - } - - + public boolean isMouseOver() + { return mouseOver; } + @Override - public boolean isMouseDown() { - return currentClick >= 0; - } - - + public boolean isMouseDown() + { return currentClick >= 0; } + @Override - public boolean isMouseDown(int mouseButton) { - return currentClick == mouseButton; - } - + public boolean isMouseDown(int mouseButton) + { return currentClick == mouseButton; } } diff --git a/src/com/bwyap/engine/gui/element/base/ETextAlignment.java b/src/com/bwyap/engine/gui/element/base/ETextAlignment.java index 50947b7..eaccbfe 100644 --- a/src/com/bwyap/engine/gui/element/base/ETextAlignment.java +++ b/src/com/bwyap/engine/gui/element/base/ETextAlignment.java @@ -1,50 +1,23 @@ package com.bwyap.engine.gui.element.base; -public enum ETextAlignment { - - /** - * Aligned to the middle left. - */ - LEFT, - - /** - * Aligned to the middle center. - */ - CENTER, - - /** - * Aligned to the middle right. - */ +public enum ETextAlignment +{ + /** Aligned to the middle left. */ + LEFT, + /** Aligned to the middle center. */ + CENTER, + /** Aligned to the middle right. */ RIGHT, - - /** - * Aligned to the top left. - */ - TOP_LEFT, - - /** - * Aligned to the top center. - */ - TOP_CENTER, - - /** - * Aligned to the top right. - */ + /** Aligned to the top left. */ + TOP_LEFT, + /** Aligned to the top center. */ + TOP_CENTER, + /** Aligned to the top right. */ TOP_RIGHT, - - /** - * Aligned to the bottom left. - */ + /** Aligned to the bottom left. */ BOTTOM_LEFT, - - /** - * Aligned to the bottom center. - */ + /** Aligned to the bottom center. */ BOTTOM_CENTER, - - /** - * Aligned to the bottom right. - */ + /** Aligned to the bottom right. */ BOTTOM_RIGHT; - } diff --git a/src/com/bwyap/engine/gui/element/base/GUIElement.java b/src/com/bwyap/engine/gui/element/base/GUIElement.java index cec044d..478cf64 100644 --- a/src/com/bwyap/engine/gui/element/base/GUIElement.java +++ b/src/com/bwyap/engine/gui/element/base/GUIElement.java @@ -5,56 +5,47 @@ import com.bwyap.engine.gui.interfaces.GUIElementInterface; import com.bwyap.engine.window.BoundsInterface; - -/** - *

+/**

* A template that provides core methods for an arbitrary GUI element * that can be selected, enabled, scaled, and has a position. *

*

* Uses the {@code JOML} library for Vector operations. *

- * @author bwyap - * - */ -public abstract class GUIElement extends AbstractGUIElement implements GUIElementInterface { - + * + * @author bwyap */ +public abstract class GUIElement extends AbstractGUIElement implements GUIElementInterface +{ protected final Vector2f absolutePosition, position; protected boolean positionAbsolute; protected boolean scaleAbsolute; - protected float scaleX; protected float scaleY; - private float paddingTop = 2.0f; private float paddingBottom = 2.0f; private float paddingLeft = 2.0f; private float paddingRight = 2.0f; - protected final Vector2f boundsOffset, absoluteBoundsOffset; protected final Vector2f bounds, absoluteBounds, originalBounds; - - - /** - * Create a new GUIElement at the specified co-ordinates + + /** Create a new GUIElement at the specified co-ordinates * with bounds given by the width and height. + * * @param x * @param y * @param width - * @param height - */ - public GUIElement(float x, float y, float width, float height) { + * @param height */ + public GUIElement(float x, float y, float width, float height) + { this.absolutePosition = new Vector2f(x, y); this.position = new Vector2f(x, y); this.enabled = true; this.originalBounds = new Vector2f(width, height); this.absoluteBounds = new Vector2f(width, height); this.bounds = new Vector2f(width, height); - // default bounds have an offset of 0 - this.boundsOffset = new Vector2f(0, 0); - this.absoluteBoundsOffset = new Vector2f(0, 0); - + this.boundsOffset = new Vector2f(0, 0); + this.absoluteBoundsOffset = new Vector2f(0, 0); // by default GUI elements are not absolutely positioned // that is, they should be scaled according to the screen AR this.positionAbsolute = false; @@ -63,186 +54,145 @@ public GUIElement(float x, float y, float width, float height) { this.scaleY = 1.0f; } - - /** - * Create a new GUIElement at the specified co-ordinates. + /** Create a new GUIElement at the specified co-ordinates. * Bounds initially set to 0. + * * @param x - * @param y - */ - public GUIElement(float x, float y) { - this(x, y, 0, 0); - } - + * @param y */ + public GUIElement(float x, float y) + { this(x, y, 0, 0); } @Override - public void updateBounds(BoundsInterface window, Vector2f parent) { - if (!scaleAbsolute) { - scaleX = (float)window.getBounds().x/window.getOriginalBounds().x; - scaleY = (float)window.getBounds().y/window.getOriginalBounds().y; + public void updateBounds(BoundsInterface window, Vector2f parent) + { + if (!scaleAbsolute) + { + scaleX = (float) window.getBounds().x / window.getOriginalBounds().x; + scaleY = (float) window.getBounds().y / window.getOriginalBounds().y; boundsOffset.x = absoluteBoundsOffset.x * scaleX; boundsOffset.y = absoluteBoundsOffset.y * scaleY; bounds.x = absoluteBounds.x * scaleX; bounds.y = absoluteBounds.y * scaleY; } - - if (!positionAbsolute) { - position.x = (absolutePosition.x * (float)window.getBounds().x/window.getOriginalBounds().x) + parent.x; - position.y = (absolutePosition.y * (float)window.getBounds().y/window.getOriginalBounds().y) + parent.y; + if (!positionAbsolute) + { + position.x = (absolutePosition.x * (float) window.getBounds().x / window.getOriginalBounds().x) + parent.x; + position.y = (absolutePosition.y * (float) window.getBounds().y / window.getOriginalBounds().y) + parent.y; } - else { + else + { position.x = (absolutePosition.x) + parent.x; position.y = (absolutePosition.y) + parent.y; } } - @Override - public final void setPosition(float x, float y) { + public final void setPosition(float x, float y) + { absolutePosition.x = x; absolutePosition.y = y; } - - - @Override - public final void setPosition(Vector2f position) { - setPosition(position.x, position.y); - } - @Override - public final Vector2f getPosition() { - return position; - } - + public final void setPosition(Vector2f position) + { setPosition(position.x, position.y); } @Override - public final Vector2f getAbsolutePosition() { - return absolutePosition; - } - + public final Vector2f getPosition() + { return position; } @Override - public final float getPositionX() { - return position.x; - } + public final Vector2f getAbsolutePosition() + { return absolutePosition; } + @Override + public final float getPositionX() + { return position.x; } @Override - public final float getPositionY() { - return position.y; - } - - + public final float getPositionY() + { return position.y; } + @Override - public void setBounds(float xOffset, float yOffset, float width, float height) { + public void setBounds(float xOffset, float yOffset, float width, float height) + { absoluteBoundsOffset.x = xOffset; absoluteBoundsOffset.y = yOffset; absoluteBounds.x = width; absoluteBounds.y = height; } - - + @Override - public void setBounds(float width, float height) { - setBounds(0, 0, width, height); - } - - + public void setBounds(float width, float height) + { setBounds(0, 0, width, height); } + @Override - public Vector2f getBounds() { - return bounds; - } - - + public Vector2f getBounds() + { return bounds; } + @Override - public float getWidth() { - return bounds.x; - } - - + public float getWidth() + { return bounds.x; } + @Override - public float getHeight() { - return bounds.y; - } - - + public float getHeight() + { return bounds.y; } + @Override - public Vector2f getAbsoluteBounds() { - return absoluteBounds; - } - - + public Vector2f getAbsoluteBounds() + { return absoluteBounds; } + @Override - public Vector2f getOriginalBounds() { - return originalBounds; - } - + public Vector2f getOriginalBounds() + { return originalBounds; } @Override - public void setPadding(float top, float bottom, float left, float right) { + public void setPadding(float top, float bottom, float left, float right) + { paddingTop = top; paddingBottom = bottom; paddingLeft = left; paddingRight = right; } - - + @Override - public float getPaddingTop() { - return paddingTop; - } - - + public float getPaddingTop() + { return paddingTop; } + @Override - public float getPaddingBottom() { - return paddingBottom; - } - - + public float getPaddingBottom() + { return paddingBottom; } + @Override - public float getPaddingLeft() { - return paddingLeft; - } - - + public float getPaddingLeft() + { return paddingLeft; } + @Override - public float getPaddingRight() { - return paddingRight; - } - - + public float getPaddingRight() + { return paddingRight; } + @Override - public boolean withinBounds(float x, float y) { - if((x >= (position.x + boundsOffset.x) && x < (position.x + boundsOffset.x + bounds.x)) && - (y >= (position.y + boundsOffset.y) && y < (position.y + boundsOffset.y + bounds.y))) { - return true; - } + public boolean withinBounds(float x, float y) + { + if ((x >= (position.x + boundsOffset.x) && x < (position.x + boundsOffset.x + bounds.x)) && + (y >= (position.y + boundsOffset.y) && y < (position.y + boundsOffset.y + bounds.y))) + { return true; } return false; } - - + @Override - public void setPositionAbsolute(boolean absolute) { - this.positionAbsolute = absolute; - } - - + public void setPositionAbsolute(boolean absolute) + { this.positionAbsolute = absolute; } + @Override - public boolean isPositionAbsolute() { - return positionAbsolute; - } - - + public boolean isPositionAbsolute() + { return positionAbsolute; } + @Override - public void setScaleAbsolute(boolean absolute) { - this.scaleAbsolute = absolute; - } - - + public void setScaleAbsolute(boolean absolute) + { this.scaleAbsolute = absolute; } + @Override - public boolean isScaleAbsolute() { - return scaleAbsolute; - } - + public boolean isScaleAbsolute() + { return scaleAbsolute; } } diff --git a/src/com/bwyap/engine/gui/element/base/ImageHolder.java b/src/com/bwyap/engine/gui/element/base/ImageHolder.java index bbe52be..03bf500 100644 --- a/src/com/bwyap/engine/gui/element/base/ImageHolder.java +++ b/src/com/bwyap/engine/gui/element/base/ImageHolder.java @@ -6,26 +6,20 @@ import com.bwyap.engine.input.InputHandler; import com.bwyap.engine.window.BoundsInterface; - -/** - * An image holder represents a set of bounds in which to render an image. +/** An image holder represents a set of bounds in which to render an image. * The image to render is specified by name and its ID retrieved from the * {@code NVGTexture} class' static map when rendering. - * @author bwyap - * - */ -public class ImageHolder extends GUIElement { - - + * + * @author bwyap */ +public class ImageHolder extends GUIElement +{ private String textureName; - private float imageX, imageY, absoluteImageX, absoluteImageY; private float imageWidth, imageHeight, absoluteImageWidth, absoluteImageHeight; - - /** - * Create an image holder with the specified image, with custom + /** Create an image holder with the specified image, with custom * parameters for the image's position and dimensions. + * * @param textureName * @param x * @param y @@ -34,136 +28,105 @@ public class ImageHolder extends GUIElement { * @param width * @param height * @param imageWidth - * @param imageHeight - */ - public ImageHolder(String textureName, float x, float y, float imageX, float imageY, float width, float height, float imageWidth, float imageHeight) { + * @param imageHeight */ + public ImageHolder(String textureName, float x, float y, float imageX, float imageY, float width, float height, float imageWidth, float imageHeight) + { super(x, y, width, height); this.imageX = this.absoluteImageX = imageX; this.imageY = this.absoluteImageY = imageY; this.imageWidth = this.absoluteImageWidth = imageWidth; - this.imageHeight = this.absoluteImageHeight = imageHeight; + this.imageHeight = this.absoluteImageHeight = imageHeight; this.textureName = textureName; } - - - /** - * Create an image holder with the specified image, with + + /** Create an image holder with the specified image, with * its position and dimensions the same as the image holder. + * * @param textureName * @param x * @param y * @param width - * @param height - */ - public ImageHolder(String textureName, float x, float y, float width, float height) { - this(textureName, x, y, x, y, width, height, width, height); - } - - - /** - * Set the absolute x-position of the image. + * @param height */ + public ImageHolder(String textureName, float x, float y, float width, float height) + { this(textureName, x, y, x, y, width, height, width, height); } + + /** Set the absolute x-position of the image. * The image is clipped by the bounds of the image holder. - * @param imageX - */ - public void setImageX(float imageX) { - this.absoluteImageX = imageX; - } - - - /** - * Get the x-position of the image. + * + * @param imageX */ + public void setImageX(float imageX) + { this.absoluteImageX = imageX; } + + /** Get the x-position of the image. * The image is clipped by the bounds of the image holder. - * @return - */ - public float getImageX() { - return imageX; - } - - - /** - * Set the absolute y-position of the image. + * + * @return */ + public float getImageX() + { return imageX; } + + /** Set the absolute y-position of the image. * The image is clipped by the bounds of the image holder. - * @param imageY - */ - public void setImageY(float imageY) { - this.absoluteImageY = imageY; - } - - - /** - * Get the y-position of the image. + * + * @param imageY */ + public void setImageY(float imageY) + { this.absoluteImageY = imageY; } + + /** Get the y-position of the image. * The image is clipped by the bounds of the image holder. - * @return - */ - public float getImageY() { - return imageY; - } - - - /** - * Set the absolute width of the image. + * + * @return */ + public float getImageY() + { return imageY; } + + /** Set the absolute width of the image. * The image is clipped by the bounds of the image holder. - * @param imageWidth - */ - public void setImageWidth(float imageWidth) { - this.absoluteImageWidth = imageWidth; - } - - /** - * Get the width of the image. + * + * @param imageWidth */ + public void setImageWidth(float imageWidth) + { this.absoluteImageWidth = imageWidth; } + + /** Get the width of the image. * The image is clipped by the bounds of the image holder. - * @return - */ - public float getImageWidth() { - return imageWidth; - } - - - /** - * Set the absolute height of the image. + * + * @return */ + public float getImageWidth() + { return imageWidth; } + + /** Set the absolute height of the image. * The image is clipped by the bounds of the image holder. - * @param imageHeight - */ - public void setImageHeight(float imageHeight) { - this.absoluteImageHeight = imageHeight; - } - - - /** - * Get the height of the image. + * + * @param imageHeight */ + public void setImageHeight(float imageHeight) + { this.absoluteImageHeight = imageHeight; } + + /** Get the height of the image. * The image is clipped by the bounds of the image holder. - * @return - */ - public float getImageHeight() { - return imageHeight; - } - - - /** - * Get the name of the texture - * @return - */ - public String getTextureName() { - return textureName; - } - - + * + * @return */ + public float getImageHeight() + { return imageHeight; } + + /** Get the name of the texture + * + * @return */ + public String getTextureName() + { return textureName; } + @Override - public void updateBounds(BoundsInterface window, Vector2f parent) { + public void updateBounds(BoundsInterface window, Vector2f parent) + { super.updateBounds(window, parent); - imageX = scaleX * absoluteImageX; imageY = scaleY * absoluteImageY; imageWidth = scaleX * absoluteImageWidth; imageHeight = scaleY * absoluteImageHeight; } - - + @Override - public void update(float timestep) {} + public void update(float timestep) + {} - @Override - public void handleInput(InputHandler input, GUIBoundsInterface bounds) { } - + public void handleInput(InputHandler input, GUIBoundsInterface bounds) + {} } diff --git a/src/com/bwyap/engine/gui/element/base/Panel.java b/src/com/bwyap/engine/gui/element/base/Panel.java index 3254a71..330ca4a 100644 --- a/src/com/bwyap/engine/gui/element/base/Panel.java +++ b/src/com/bwyap/engine/gui/element/base/Panel.java @@ -13,231 +13,189 @@ import com.bwyap.engine.gui.interfaces.IColouredVectorShape; import com.bwyap.engine.input.InputHandler; - -/** - * A panel is a renderable GUI element which can +/** A panel is a renderable GUI element which can * contain other GUI elements. The updating and rendering * of the GUIPanel should also take care of updating * and rendering all child elements. - * @author bwyap - * - */ -public abstract class Panel extends SelectableElement implements IColouredVectorShape, Iterable, Iterator { - + * + * @author bwyap */ +public abstract class Panel extends SelectableElement implements IColouredVectorShape, Iterable, Iterator +{ protected static final int DEFAULT_PRIORITY = 100; - protected final VectorShapeColourProperties colours; - private boolean renderShape; private boolean clip; - // Use a hash map to keep track of GUI elements with given priorities private final Map> elements; - // Auxiliary variables for keeping track of GUI elements with given priorities private int elementCount = 0; private int iteratorNext = 0; private boolean elementsModified = false; private List sortedElements; - - - public Panel(float x, float y, float width, float height) { + + public Panel(float x, float y, float width, float height) + { super(x, y, width, height); colours = new VectorShapeColourProperties(); renderShape = true; clip = true; - elements = new HashMap>(); sortedElements = new ArrayList(); } - - + @Override - public VectorShapeColourProperties colourProperties() { - return colours; - } - - - /** - * Add an element to the panel at the given co-ordinates + public VectorShapeColourProperties colourProperties() + { return colours; } + + /** Add an element to the panel at the given co-ordinates * with the default priority. Co-ordinates are relative to the panel. - * @param e - */ - public void addElement(GUIElementInterface e, float x, float y) { + * + * @param e */ + public void addElement(GUIElementInterface e, float x, float y) + { e.setPosition(x, y); addElement(DEFAULT_PRIORITY, e); } - - /** - * Add an element to the panel at the given co-ordinates + + /** Add an element to the panel at the given co-ordinates * with the specified priority. Co-ordinates are relative to the panel. - * @param e - */ - public void addElement(int priority, GUIElementInterface e, float x, float y) { + * + * @param e */ + public void addElement(int priority, GUIElementInterface e, float x, float y) + { e.setPosition(x, y); addElement(priority, e); } - - - /** - * Add an element to the panel with the default priority (100). - * @param e - */ - public void addElement(GUIElementInterface e) { - addElement(DEFAULT_PRIORITY, e); - } - - - /** - * Add an element to the panel with the specified priority. + + /** Add an element to the panel with the default priority (100). + * + * @param e */ + public void addElement(GUIElementInterface e) + { addElement(DEFAULT_PRIORITY, e); } + + /** Add an element to the panel with the specified priority. + * * @param priority - * @param e - */ - public void addElement(int priority, GUIElementInterface e) { + * @param e */ + public void addElement(int priority, GUIElementInterface e) + { elementsModified = true; elementCount++; - if (elements.containsKey(priority)) { + if (elements.containsKey(priority)) + { elements.get(priority).add(e); } - else { + else + { List list = new ArrayList(); list.add(e); elements.put(priority, list); } } - - - - /** - * Removes an element from the panel. - * @param e - * @return - */ - public boolean removeElement(GUIElementInterface e) { + + /** Removes an element from the panel. + * + * @param e + * @return */ + public boolean removeElement(GUIElementInterface e) + { elementsModified = true; elementCount--; - // Find the element and remove it - for (int k : elements.keySet()) { - if (elements.get(k).contains(e)) { - return elements.get(k).remove(e); - } + for (int k : elements.keySet()) + { + if (elements.get(k).contains(e)) + { return elements.get(k).remove(e); } } return false; } - - - /** - * Set whether the panel should clip all GUI + + /** Set whether the panel should clip all GUI * elements rendered outside its bounds - * @param clip - */ - public void setClip(boolean clip) { - this.clip = clip; - } - - - /** - * Check if the panel clips all GUI + * + * @param clip */ + public void setClip(boolean clip) + { this.clip = clip; } + + /** Check if the panel clips all GUI * elements rendered outside its bounds - * @return - */ - public boolean isClip() { - return clip; - } - - - /** - * Set whether the panel should render the vector + * + * @return */ + public boolean isClip() + { return clip; } + + /** Set whether the panel should render the vector * shape that represents the panel - * @param renderColour - */ - public void setRenderShape(boolean renderShape) { - this.renderShape = renderShape; - } - - + * + * @param renderColour */ + public void setRenderShape(boolean renderShape) + { this.renderShape = renderShape; } + @Override - public boolean renderShape() { - return renderShape; - } - - + public boolean renderShape() + { return renderShape; } + @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { - if (!mouseOver && input.isMouseDown()) { - setSelected(false); - } - + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + { + if (!mouseOver && input.isMouseDown()) + { setSelected(false); } Iterator it = iterator(); - while (it.hasNext()) { - it.next().handleInput(input, this); - } + while (it.hasNext()) + { it.next().handleInput(input, this); } } - - + @Override - public final void update(float timestep) { + public final void update(float timestep) + { Iterator it = iterator(); - while(it.hasNext()) { - it.next().update(timestep); - } + while (it.hasNext()) + { it.next().update(timestep); } onUpdate(timestep); } - - + @Override - public Iterator iterator() { + public Iterator iterator() + { iteratorNext = 0; - // Sort element order if new element has been added - if (elementsModified) { + if (elementsModified) + { elementsModified = false; List keys = new ArrayList(elements.keySet()); - Collections.sort(keys, Collections.reverseOrder()); - sortedElements.clear(); - for (int k : keys) { - sortedElements.addAll(elements.get(k)); - } + for (int k : keys) + { sortedElements.addAll(elements.get(k)); } } return this; } - - + @Override - public boolean hasNext() { - return iteratorNext < elementCount; - } - - + public boolean hasNext() + { return iteratorNext < elementCount; } + @Override - public GUIElementInterface next() { - return sortedElements.get(iteratorNext++); - } - - - /** - * Override this method for custom update functionality - * @param timestep - */ - public void onUpdate(float timestep) { } - - - /** - * Override this method for custom onSelect functionality - * @param timestep - */ + public GUIElementInterface next() + { return sortedElements.get(iteratorNext++); } + + /** Override this method for custom update functionality + * + * @param timestep */ + public void onUpdate(float timestep) + {} + + /** Override this method for custom onSelect functionality + * + * @param timestep */ @Override - public void onSelect() { } + public void onSelect() + {} - - /** - * Override this method for custom onDeselect functionality - * @param timestep - */ + /** Override this method for custom onDeselect functionality + * + * @param timestep */ @Override - public void onDeselect() { } - + public void onDeselect() + {} } diff --git a/src/com/bwyap/engine/gui/element/base/PanelWindow.java b/src/com/bwyap/engine/gui/element/base/PanelWindow.java index c82d0bf..64f6aa9 100644 --- a/src/com/bwyap/engine/gui/element/base/PanelWindow.java +++ b/src/com/bwyap/engine/gui/element/base/PanelWindow.java @@ -11,69 +11,58 @@ import com.bwyap.engine.input.InputHandler; import com.bwyap.lwjgl.engine.resource.LWJGLResourceManager; - -/** - * A extension of the panel class that can be used +/** A extension of the panel class that can be used * as an in-screen window, which can be moved, resized - * and closed. - * @author bwyap - * - */ -public abstract class PanelWindow extends Panel implements IFade, ITextDisplay { - + * and closed. + * + * @author bwyap */ +public abstract class PanelWindow extends Panel implements IFade, ITextDisplay +{ private float MIN_WIDTH = 25; private float MIN_HEIGHT = 25; private float MAX_WIDTH; private float MAX_HEIGHT; private float RESIZE_AREA = 6; - // Window properties private boolean resizable; private boolean movable; - private boolean canMove; // disabled when the mouse button is pressed + private boolean canMove; // disabled when the mouse button is pressed private boolean visible; private boolean keepWithinParent; - - private boolean fadeOnClose; + private boolean fadeOnClose; private final Fade fade; - private EllipticalButton closeButton; private float closeButtonRadius = 6, closeButtonPadding = 6; - private boolean moving = false; private boolean resizing = false; - private final TextComponent title; - - - /** - * Create a panel window with the specified dimensions. + + /** Create a panel window with the specified dimensions. * The panel is not resizable but is movable by default. * The maxWidth and maxHeight are set to its width and height. + * * @param x * @param y * @param width - * @param height - */ - public PanelWindow(String title, float x, float y, float width, float height) { + * @param height */ + public PanelWindow(String title, float x, float y, float width, float height) + { this(title, x, y, width, height, 100000, 100000); setResizable(false); } - - - /** - * Create a panel window with the specified dimensions and specified maxWidth and maxHeight. + + /** Create a panel window with the specified dimensions and specified maxWidth and maxHeight. * This panel is resizable and movable by default. + * * @param x * @param y * @param width * @param height * @param maxWidth - * @param maxHeight - */ - public PanelWindow(String name, float x, float y, float width, float height, float maxWidth, float maxHeight) { + * @param maxHeight */ + public PanelWindow(String name, float x, float y, float width, float height, float maxWidth, float maxHeight) + { super(x, y, width, height); - fade = new Fade(); fadeOnClose = true; keepWithinParent = true; @@ -84,39 +73,39 @@ public PanelWindow(String name, float x, float y, float width, float height, flo title.setAlignment(ETextAlignment.TOP_CENTER); title.setOffset(0, 3); title.setTextSize(15.0f); - MAX_WIDTH = maxWidth; MAX_HEIGHT = maxHeight; - initButtons(); initElements(); } - - - /** - * Initialise the close button - */ - private void initButtons() { - closeButton = new EllipticalButton(closeButtonPadding, closeButtonPadding, closeButtonRadius, closeButtonRadius) { + + /** Initialise the close button */ + private void initButtons() + { + closeButton = new EllipticalButton(closeButtonPadding, closeButtonPadding, closeButtonRadius, closeButtonRadius) + { @Override - public void onMouseClicked(float x, float y, int mouseButton) { - if (!resizing) { - if (fadeOnClose) { + public void onMouseClicked(float x, float y, int mouseButton) + { + if (!resizing) + { + if (fadeOnClose) + { fade.setFading(true); fade.setFade(1.0f); } else close(); } } - + @Override - public void onMouseDown(float x, float y, int mouseButton) { + public void onMouseDown(float x, float y, int mouseButton) + { // Disable moving the window when the mouse button is down over the close button // re-enabled when the mouse is released (see onHandleInput method) canMove = moving || false; } }; - closeButton.setScaleAbsolute(true); closeButton.setPositionAbsolute(true); closeButton.colourProperties().setColour(1.0f, 0.0f, 0.0f, 1.0f); @@ -124,246 +113,206 @@ public void onMouseDown(float x, float y, int mouseButton) { closeButton.colourProperties().setMouseDownColour(1.0f, 0.2f, 0.2f, 1.0f); addElement(closeButton); } - - + @Override - public TextComponent getTextComponent() { - return title; - } - - + public TextComponent getTextComponent() + { return title; } + @Override - public Fade getFade() { - return fade; - } - - - /** - * Initialise any GUI components that should be displayed in the window - */ + public Fade getFade() + { return fade; } + + /** Initialise any GUI components that should be displayed in the window */ protected abstract void initElements(); - - + @Override - public void onUpdate(float timestep) { - if (fade.isFading()) { + public void onUpdate(float timestep) + { + if (fade.isFading()) + { fade.decreaseFade(timestep * 5.0f); - if (fade.getFade() == 0) { + if (fade.getFade() == 0) + { fade.setFading(false); close(); } } } - - + @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + { super.onHandleInput(input, bounds); - // Resize window if (resizable) resizeWindow(input, bounds); - // Move window if (movable && canMove && !resizing) moveWindow(input, bounds); - if (!input.isMouseDown()) canMove = true; } - private Vector2f mouseDisplacement; private Vector2f original; - - /** - * Resize the window according to the mouse movement + + /** Resize the window according to the mouse movement + * * @param input - * @param bounds - */ - private void resizeWindow(InputHandler input, GUIBoundsInterface bounds) { + * @param bounds */ + private void resizeWindow(InputHandler input, GUIBoundsInterface bounds) + { // Check if the mouse is within the resize area if ((input.getMouseX() > getPositionX() + (getWidth() - RESIZE_AREA) && - input.getMouseX() < getPositionX() + getWidth() && - input.getMouseY() > getPositionY() + (getHeight() - RESIZE_AREA) && - input.getMouseY() < getPositionY() + getHeight()) - || resizing) { + input.getMouseX() < getPositionX() + getWidth() && + input.getMouseY() > getPositionY() + (getHeight() - RESIZE_AREA) && + input.getMouseY() < getPositionY() + getHeight()) + || resizing) + { // Check if the mouse is down - if (input.isMouseDown(LWJGLResourceManager.instance().inputMapping().getBinding("mouse_left"))) { + if (input.isMouseDown(LWJGLResourceManager.instance().inputMapping().getBinding("mouse_left"))) + { mouseOver = true; - if (!resizing) { + if (!resizing) + { // Set resize origin resizing = true; - mouseDisplacement = new Vector2f((float)input.getMouseX(), (float)input.getMouseY()); + mouseDisplacement = new Vector2f((float) input.getMouseX(), (float) input.getMouseY()); original = new Vector2f(getWidth(), getHeight()); } - // Calculate displacement - float newWidth = ((float)input.getMouseX() - mouseDisplacement.x + original.x)/scaleX; - float newHeight = ((float)input.getMouseY() - mouseDisplacement.y + original.y)/scaleY; - + float newWidth = ((float) input.getMouseX() - mouseDisplacement.x + original.x) / scaleX; + float newHeight = ((float) input.getMouseY() - mouseDisplacement.y + original.y) / scaleY; // Cut resizing if the panel must stay within its parent - if (keepWithinParent) { - if (newWidth + getAbsolutePosition().x > bounds.getBounds().x/scaleX) newWidth = bounds.getBounds().x/scaleX - getAbsolutePosition().x; - if (newHeight + getAbsolutePosition().y > bounds.getBounds().y/scaleY) newHeight = bounds.getBounds().y/scaleY - getAbsolutePosition().y; + if (keepWithinParent) + { + if (newWidth + getAbsolutePosition().x > bounds.getBounds().x / scaleX) newWidth = bounds.getBounds().x / scaleX - getAbsolutePosition().x; + if (newHeight + getAbsolutePosition().y > bounds.getBounds().y / scaleY) newHeight = bounds.getBounds().y / scaleY - getAbsolutePosition().y; } - // Resize within minimum and maximum size - setBounds(newWidth < MIN_WIDTH ? MIN_WIDTH : (newWidth > MAX_WIDTH ? MAX_WIDTH : newWidth), - newHeight < MIN_HEIGHT ? MIN_HEIGHT : (newHeight > MAX_HEIGHT ? MAX_HEIGHT : newHeight)); + setBounds(newWidth < MIN_WIDTH ? MIN_WIDTH : (newWidth > MAX_WIDTH ? MAX_WIDTH : newWidth), + newHeight < MIN_HEIGHT ? MIN_HEIGHT : (newHeight > MAX_HEIGHT ? MAX_HEIGHT : newHeight)); } else resizing = false; } } - - - /** - * Move the window according to the input handler + + /** Move the window according to the input handler + * * @param input - * @param bounds - */ - protected void moveWindow(InputHandler input, GUIBoundsInterface bounds) { + * @param bounds */ + protected void moveWindow(InputHandler input, GUIBoundsInterface bounds) + { // Check if the window should be moved - if (withinBounds((float)input.getMouseX(), (float)input.getMouseY()) || moving) { + if (withinBounds((float) input.getMouseX(), (float) input.getMouseY()) || moving) + { // Check if the mouse is down - if (input.isMouseDown(LWJGLResourceManager.instance().inputMapping().getBinding("mouse_left"))) { + if (input.isMouseDown(LWJGLResourceManager.instance().inputMapping().getBinding("mouse_left"))) + { mouseOver = true; - if (!moving) { + if (!moving) + { // Set movement origin moving = true; - mouseDisplacement = new Vector2f((float)input.getMouseX(), (float)input.getMouseY()).sub(new Vector2f(getPosition())); + mouseDisplacement = new Vector2f((float) input.getMouseX(), (float) input.getMouseY()).sub(new Vector2f(getPosition())); } - // Calculate displacement - float xOffset = ((float)input.getMouseX() - mouseDisplacement.x - bounds.getPositionX())/scaleX; - float yOffset = ((float)input.getMouseY() - mouseDisplacement.y - bounds.getPositionY())/scaleY; - + float xOffset = ((float) input.getMouseX() - mouseDisplacement.x - bounds.getPositionX()) / scaleX; + float yOffset = ((float) input.getMouseY() - mouseDisplacement.y - bounds.getPositionY()) / scaleY; // Cut movement if the panel must stay within its parent - if (keepWithinParent) { - if (getWidth()/scaleX + xOffset > bounds.getBounds().x/scaleX) xOffset = (bounds.getBounds().x - getWidth())/scaleX; + if (keepWithinParent) + { + if (getWidth() / scaleX + xOffset > bounds.getBounds().x / scaleX) + xOffset = (bounds.getBounds().x - getWidth()) / scaleX; else if (xOffset < 0) xOffset = 0; - if (getHeight()/scaleY + yOffset > bounds.getBounds().y/scaleY) yOffset = (bounds.getBounds().y - getHeight())/scaleY; + if (getHeight() / scaleY + yOffset > bounds.getBounds().y / scaleY) + yOffset = (bounds.getBounds().y - getHeight()) / scaleY; else if (yOffset < 0) yOffset = 0; } - // Set the position setPosition(xOffset, yOffset); } else moving = false; } } - - /** - * Close the window. - * Override this method to implement custom functionality - * (ensure you call {@code super.close()}). - */ - public void close() { - setVisible(false); - } - - - /** - * Set whether the window should fade out on close - * @param fadeOnClose - */ - public void setFadeOnClose(boolean fadeOnClose) { - this.fadeOnClose = fadeOnClose; - } + /** Close the window. + * Override this method to implement custom functionality + * (ensure you call {@code super.close()}). */ + public void close() + { setVisible(false); } - - /** - * Checks if the window will fade out on close - * @return - */ - public boolean fadeOnClose() { - return fadeOnClose; - } - - - /** - * Check if the panel window is visible - * @return - */ - public boolean isVisible() { - return visible; - } - - - /** - * Set whether the panel window is visible - * @param visible - */ - public void setVisible(boolean visible) { - this.visible = visible; - } - - - /** - * Check if the panel window is movable - * @return - */ - public boolean isMovable() { - return movable; - } - - - /** - * Set whether the panel window is movable - * @param movable - */ - public void setMovable(boolean movable) { - this.movable = movable; - } - + /** Set whether the window should fade out on close + * + * @param fadeOnClose */ + public void setFadeOnClose(boolean fadeOnClose) + { this.fadeOnClose = fadeOnClose; } - /** - * Check if the panel window is resizable - * @return - */ - public boolean isResizable() { - return resizable; - } - - - /** - * Set whether the panel window is resizable - * @param resizable - */ - public void setResizable(boolean resizable) { - this.resizable = resizable; - } - - - /** - * Set the maximum dimensions for this panel window. + /** Checks if the window will fade out on close + * + * @return */ + public boolean fadeOnClose() + { return fadeOnClose; } + + /** Check if the panel window is visible + * + * @return */ + public boolean isVisible() + { return visible; } + + /** Set whether the panel window is visible + * + * @param visible */ + public void setVisible(boolean visible) + { this.visible = visible; } + + /** Check if the panel window is movable + * + * @return */ + public boolean isMovable() + { return movable; } + + /** Set whether the panel window is movable + * + * @param movable */ + public void setMovable(boolean movable) + { this.movable = movable; } + + /** Check if the panel window is resizable + * + * @return */ + public boolean isResizable() + { return resizable; } + + /** Set whether the panel window is resizable + * + * @param resizable */ + public void setResizable(boolean resizable) + { this.resizable = resizable; } + + /** Set the maximum dimensions for this panel window. * These should be greater than the minimum dimensions. + * * @param maxWidth - * @param maxHeight - */ - public void setMaxDimensions(float maxWidth, float maxHeight) { + * @param maxHeight */ + public void setMaxDimensions(float maxWidth, float maxHeight) + { this.MAX_WIDTH = maxWidth; this.MAX_HEIGHT = maxHeight; } - - - /** - * Set the minimum dimensions for this panel window. + + /** Set the minimum dimensions for this panel window. * These should be less than the maximum dimensions. + * * @param minWidth - * @param minHeight - */ - public void setMinDimensions(float minWidth, float minHeight) { + * @param minHeight */ + public void setMinDimensions(float minWidth, float minHeight) + { this.MIN_WIDTH = minWidth; this.MIN_HEIGHT = minHeight; } - - - /** - * Set whether this panel window must + + /** Set whether this panel window must * be kept within its parent when moved. - * @param keepWithinParent - */ - public void setKeepWithinParent(boolean keepWithinParent) { - this.keepWithinParent = keepWithinParent; - } - + * + * @param keepWithinParent */ + public void setKeepWithinParent(boolean keepWithinParent) + { this.keepWithinParent = keepWithinParent; } } diff --git a/src/com/bwyap/engine/gui/element/base/ProgressBar.java b/src/com/bwyap/engine/gui/element/base/ProgressBar.java index fab18a6..013a7c4 100644 --- a/src/com/bwyap/engine/gui/element/base/ProgressBar.java +++ b/src/com/bwyap/engine/gui/element/base/ProgressBar.java @@ -1,81 +1,63 @@ package com.bwyap.engine.gui.element.base; - -/** - * A progress bar that can be used to show the progress of a process. - * @author bwyap - * - */ -public abstract class ProgressBar extends GUIElement { - - /** - * Fill style (direction) of a progress bar. - * @author bwyap - * - */ - public enum ProgressFillStyle { +/** A progress bar that can be used to show the progress of a process. + * + * @author bwyap */ +public abstract class ProgressBar extends GUIElement +{ + /** Fill style (direction) of a progress bar. + * + * @author bwyap */ + public enum ProgressFillStyle + { UP, DOWN, LEFT, RIGHT; } - - + private float progress; private ProgressFillStyle fillStyle; - - - public ProgressBar(float x, float y, float width, float height) { + + public ProgressBar(float x, float y, float width, float height) + { super(x, y, width, height); this.progress = 0.0f; this.fillStyle = ProgressFillStyle.RIGHT; } - - - /** - * Get the fill style (direction) of the progress bar - * @return - */ - public ProgressFillStyle getFillStyle() { - return fillStyle; - } - - - /** - * Get the fill style (direction of the progress bar) - * @param fillStyle - */ - public void setFillStyle(ProgressFillStyle fillStyle) { - this.fillStyle = fillStyle; - } - - - /** - * Set the progress value of the bar. + + /** Get the fill style (direction) of the progress bar + * + * @return */ + public ProgressFillStyle getFillStyle() + { return fillStyle; } + + /** Get the fill style (direction of the progress bar) + * + * @param fillStyle */ + public void setFillStyle(ProgressFillStyle fillStyle) + { this.fillStyle = fillStyle; } + + /** Set the progress value of the bar. * Values range between {@code 0.0f} to {@code 1.0f}. - * @param progress - */ - public void setProgress(float progress) { - this.progress = progress > 1.0f ? 1.0f : progress < 0.0f ? 0.0f : progress; - } - - - /** - * Add to the progress value of the bar. + * + * @param progress */ + public void setProgress(float progress) + { this.progress = progress > 1.0f ? 1.0f : progress < 0.0f ? 0.0f : progress; } + + /** Add to the progress value of the bar. * Values range between {@code 0.0f} to {@code 1.0f}. - * @param progress - */ - public void addProgress(float progress) { + * + * @param progress */ + public void addProgress(float progress) + { this.progress += progress; - if (progress > 1.0f) progress = 1.0f; + if (progress > 1.0f) + progress = 1.0f; else if (progress < 0.0f) progress = 0.0f; } - - - /** - * Get the progress value of the bar. + + /** Get the progress value of the bar. * Values range between {@code 0.0f} to {@code 1.0f}. - * @param progress - */ - public float getProgress() { - return progress; - } - + * + * @param progress */ + public float getProgress() + { return progress; } } diff --git a/src/com/bwyap/engine/gui/element/base/RadioButton.java b/src/com/bwyap/engine/gui/element/base/RadioButton.java index 39d5a57..95ae94e 100644 --- a/src/com/bwyap/engine/gui/element/base/RadioButton.java +++ b/src/com/bwyap/engine/gui/element/base/RadioButton.java @@ -3,101 +3,78 @@ import com.bwyap.engine.gui.interfaces.GUIBoundsInterface; import com.bwyap.engine.input.InputHandler; -/** - * A radio button which can be selected. It holds its selected state until - * it is reset or another radio button within its button group is selected. - * Its state can be checked using the {@code isSelected} method. The methods - * {@code onSelect} and {@code onDeselect} can be overridden to implement +/** A radio button which can be selected. It holds its selected state until + * it is reset or another radio button within its button group is selected. + * Its state can be checked using the {@code isSelected} method. The methods + * {@code onSelect} and {@code onDeselect} can be overridden to implement * custom functionality. - * @author bwyap - * - */ - -public abstract class RadioButton extends SelectableElement { - + * + * @author bwyap */ +public abstract class RadioButton extends SelectableElement +{ private String name; private RadioButtonGroup buttonGroup; - - - /** - * Create a radio button with the specified name. + + /** Create a radio button with the specified name. + * * @param name * @param x * @param y * @param width - * @param height - */ - public RadioButton(String name, float x, float y, float width, float height) { + * @param height */ + public RadioButton(String name, float x, float y, float width, float height) + { super(x, y, width, height); - this.name = name; + this.name = name; } - - - /** - * Create a radio button with a default name of "unamed". + + /** Create a radio button with a default name of "unamed". + * * @param x * @param y * @param width - * @param height - */ - public RadioButton(float x, float y, float width, float height) { - this("unamed", x, y, width, height); - } - - - /** - * Set the button group this radio button is attached to. - * @param buttonGroup - */ - protected void setButtonGroup(RadioButtonGroup buttonGroup) { - this.buttonGroup = buttonGroup; - } - - - /** - * Set the name of the radio button. + * @param height */ + public RadioButton(float x, float y, float width, float height) + { this("unamed", x, y, width, height); } + + /** Set the button group this radio button is attached to. + * + * @param buttonGroup */ + protected void setButtonGroup(RadioButtonGroup buttonGroup) + { this.buttonGroup = buttonGroup; } + + /** Set the name of the radio button. * The name is used purely for identification purposes within a button group. - * @param name - */ - public void setName(String name) { - this.name = name; - } - - - /** - * Get the name of the radio button. + * + * @param name */ + public void setName(String name) + { this.name = name; } + + /** Get the name of the radio button. * The name is used purely for identification purposes within a button group. - * @return - */ - public String getName() { - return name; - } - - + * + * @return */ + public String getName() + { return name; } + @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + { // Override SelectableElement functionality } - - /** - * {@inheritDoc} + /** {@inheritDoc} *

* Override this method to implement custom functionality. * Ensure you also call {@code super.onSelected()} if overriding. - *

- */ - public void onSelect() { - if (buttonGroup != null) buttonGroup.selectNew(this.getName()); - } + *

*/ + public void onSelect() + { if (buttonGroup != null) buttonGroup.selectNew(this.getName()); } - - /** - * {@inheritDoc} + /** {@inheritDoc} *

* Override this method to implement custom functionality. - *

- */ - public void onDeselect() { } - + *

*/ + public void onDeselect() + {} } diff --git a/src/com/bwyap/engine/gui/element/base/RadioButtonGroup.java b/src/com/bwyap/engine/gui/element/base/RadioButtonGroup.java index 7e283a2..ca3b075 100644 --- a/src/com/bwyap/engine/gui/element/base/RadioButtonGroup.java +++ b/src/com/bwyap/engine/gui/element/base/RadioButtonGroup.java @@ -6,104 +6,89 @@ import com.bwyap.engine.gui.interfaces.GUIBoundsInterface; import com.bwyap.engine.input.InputHandler; - -/** - * A RadioButtonGroup stores a collection of radio buttons which are - * dependent on each other. When a radio button is selected, the - * previously selected radio button is deselected automatically. Only +/** A RadioButtonGroup stores a collection of radio buttons which are + * dependent on each other. When a radio button is selected, the + * previously selected radio button is deselected automatically. Only * one radio button can be selected at a time in a radio button group. - * @author bwyap - * - */ -public class RadioButtonGroup extends AbstractGUIElement { - + * + * @author bwyap */ +public class RadioButtonGroup extends AbstractGUIElement +{ private final Map buttons; - private String selectedButton; - - - /** - * Create a new radio button group with no button selected by default. - */ - public RadioButtonGroup() { + + /** Create a new radio button group with no button selected by default. */ + public RadioButtonGroup() + { buttons = new HashMap(); selectedButton = null; } - - - /** - * Create a new radio button group with the specified radio + + /** Create a new radio button group with the specified radio * button (if it exists) as the selected option by default. - * @param defaultSelected - */ - public RadioButtonGroup(String defaultSelected) { + * + * @param defaultSelected */ + public RadioButtonGroup(String defaultSelected) + { buttons = new HashMap(); selectedButton = defaultSelected; } - - - /** - * Get the mapping of the buttons in the button group - * @return - */ - public Map getButtonMap() { - return buttons; - } - - - /** - * Add a radio button to the group. - */ - public void add(RadioButton button) { + + /** Get the mapping of the buttons in the button group + * + * @return */ + public Map getButtonMap() + { return buttons; } + + /** Add a radio button to the group. */ + public void add(RadioButton button) + { button.setButtonGroup(this); buttons.put(button.getName(), button); } - - - /** - * Get a radio button with the specified name. + + /** Get a radio button with the specified name. * If it does not exist, {@code null} will be returned. - * @param name - * @return - */ - public RadioButton get(String name) { - return buttons.get(name); - } - - - /** - * Remove the radio button with the specified name from the button group. + * + * @param name + * @return */ + public RadioButton get(String name) + { return buttons.get(name); } + + /** Remove the radio button with the specified name from the button group. * Returns the removed radio button if it exists. - * @param name - * @return - */ - public RadioButton remove(String name) { + * + * @param name + * @return */ + public RadioButton remove(String name) + { RadioButton button = buttons.remove(name); if (button != null) button.setButtonGroup(null); return button; } - - - /** - * Get the currently selected radio button. + + /** Get the currently selected radio button. * If no button is selected, {@code null} will be returned. - * @return - */ - public RadioButton getSelected() { - if (selectedButton != null) return buttons.get(selectedButton); + * + * @return */ + public RadioButton getSelected() + { + if (selectedButton != null) + return buttons.get(selectedButton); else return null; } - - - /** - * Signal the button group that a new radioButton with the given name is being selected. + + /** Signal the button group that a new radioButton with the given name is being selected. * This will deselect the previously selected button, ONLY IF the newly selected button * and the previously selected button actually exists. - * @param name - */ - public void selectNew(String name) { - if (buttons.containsKey(name)) { - if (buttons.containsKey(selectedButton)) { + * + * @param name */ + public void selectNew(String name) + { + if (buttons.containsKey(name)) + { + if (buttons.containsKey(selectedButton)) + { RadioButton old = buttons.get(selectedButton); old.onDeselect(); old.setSelected(false); @@ -112,15 +97,14 @@ public void selectNew(String name) { } } - @Override - public void update(float timestep) { } - + public void update(float timestep) + {} @Override - public void handleInput(InputHandler input, GUIBoundsInterface bounds) { - for (String name : buttons.keySet()) { - buttons.get(name).handleInput(input, bounds); - } + public void handleInput(InputHandler input, GUIBoundsInterface bounds) + { + for (String name : buttons.keySet()) + { buttons.get(name).handleInput(input, bounds); } } } diff --git a/src/com/bwyap/engine/gui/element/base/ScrollArea.java b/src/com/bwyap/engine/gui/element/base/ScrollArea.java index f159a09..d912491 100644 --- a/src/com/bwyap/engine/gui/element/base/ScrollArea.java +++ b/src/com/bwyap/engine/gui/element/base/ScrollArea.java @@ -9,52 +9,45 @@ import com.bwyap.engine.input.InputHandler; import com.bwyap.engine.window.BoundsInterface; - -/** - * A scroll area provides a panel which has the ability to scroll +/** A scroll area provides a panel which has the ability to scroll * to access GUI elements outside the panel bounds. - * @author bwyap - * - */ -public abstract class ScrollArea extends Panel { - - /** - * A enumeration of the directions the scroll area can scroll. - * @author bwyap - */ - public enum ScrollDirection { + * + * @author bwyap */ +public abstract class ScrollArea extends Panel +{ + /** A enumeration of the directions the scroll area can scroll. + * + * @author bwyap */ + public enum ScrollDirection + { HORIZONTAL, VERTICAL; } - - + static final float TOP_LIMIT = 0; static final float PADDING = 2; static final float SCROLL_SPEED = 5; static final float SCROLL_BAR_RADIUS = 2; - private boolean renderScrollBar; private float scrollLength; private float scrollPosition; private float scrollDelta; private float scrollBarLength; private float scrollBarPosition; - private final ScrollBar scrollBar; private final ScrollDirection scrollDirection; - - - /** - * Create a scroll area with the specified scroll length. - * The scroll length is the length in pixels which the - * panel can be scrolled past its starting position. + + /** Create a scroll area with the specified scroll length. + * The scroll length is the length in pixels which the + * panel can be scrolled past its starting position. + * * @param x * @param y * @param width * @param height * @param scrollLength - * @param scrollDirection - */ - public ScrollArea(float x, float y, float width, float height, float scrollLength, ScrollDirection scrollDirection) { + * @param scrollDirection */ + public ScrollArea(float x, float y, float width, float height, float scrollLength, ScrollDirection scrollDirection) + { super(x, y, width, height); this.scrollPosition = 0; this.scrollDirection = scrollDirection; @@ -62,160 +55,132 @@ public ScrollArea(float x, float y, float width, float height, float scrollLengt setScrollLength(scrollLength); setSelectable(false); setReactToMouseOver(false); - - if (scrollDirection == ScrollDirection.VERTICAL) + if (scrollDirection == ScrollDirection.VERTICAL) this.scrollBar = new ScrollBar(width - 6, PADDING, 4, getScrollBarLength(), SCROLL_BAR_RADIUS); - else - this.scrollBar = new ScrollBar(PADDING, height - 6, getScrollBarLength(), 4, SCROLL_BAR_RADIUS); - } - - - /** - * Check whether the scroll bar should be rendered at the moment - * @return - */ - public boolean renderScrollBar() { - return renderScrollBar; + else + this.scrollBar = new ScrollBar(PADDING, height - 6, getScrollBarLength(), 4, SCROLL_BAR_RADIUS); } - - - /** - * Get the scroll bar for this scroll area - * @return - */ - public ScrollBar getScrollBar() { - return scrollBar; - } - - - /** - * Set the scroll length of the scroll area. + + /** Check whether the scroll bar should be rendered at the moment + * + * @return */ + public boolean renderScrollBar() + { return renderScrollBar; } + + /** Get the scroll bar for this scroll area + * + * @return */ + public ScrollBar getScrollBar() + { return scrollBar; } + + /** Set the scroll length of the scroll area. * This value should be larger than the height * of the GUI element. - * @param scrollLength - */ - public void setScrollLength(float scrollLength) { + * + * @param scrollLength */ + public void setScrollLength(float scrollLength) + { this.scrollLength = scrollLength; - if (scrollDirection == ScrollDirection.VERTICAL) { - scrollBarLength = (getHeight()/(getHeight() + scrollLength + 2 * PADDING)) * getHeight(); + if (scrollDirection == ScrollDirection.VERTICAL) + { + scrollBarLength = (getHeight() / (getHeight() + scrollLength + 2 * PADDING)) * getHeight(); } - else if (scrollDirection == ScrollDirection.HORIZONTAL) { - scrollBarLength = (getWidth()/(getWidth() + scrollLength + 2 * PADDING)) * getWidth(); - } - } - - - /** - * Get the scroll length of the scroll area - * @return - */ - public float getScrollLength() { - return scrollLength; - } - - - /** - * Get the length of the scrollbar for the scroll area - * @return - */ - public float getScrollBarLength() { - return scrollBarLength; - } - - - /** - * Get the scroll direction of the scroll area. - * @return - */ - public ScrollDirection getScrollDirection() { - return scrollDirection; - } - - - /** - * Get the position of the scroll bar - * @return - */ - public float getScrollBarPosition() { - return scrollBarPosition; + else if (scrollDirection == ScrollDirection.HORIZONTAL) + { scrollBarLength = (getWidth() / (getWidth() + scrollLength + 2 * PADDING)) * getWidth(); } } - - - /** - * Set the scroll position of the scroll area - * @param position - */ - public void setScrollPosition(float newScrollPosition) { - setScrollDelta(newScrollPosition - scrollPosition); - } - - - /** - * Move the scroll position by the specified amount - * @param scrollDelta - */ - public void setScrollDelta(float scrollDelta) { + + /** Get the scroll length of the scroll area + * + * @return */ + public float getScrollLength() + { return scrollLength; } + + /** Get the length of the scrollbar for the scroll area + * + * @return */ + public float getScrollBarLength() + { return scrollBarLength; } + + /** Get the scroll direction of the scroll area. + * + * @return */ + public ScrollDirection getScrollDirection() + { return scrollDirection; } + + /** Get the position of the scroll bar + * + * @return */ + public float getScrollBarPosition() + { return scrollBarPosition; } + + /** Set the scroll position of the scroll area + * + * @param position */ + public void setScrollPosition(float newScrollPosition) + { setScrollDelta(newScrollPosition - scrollPosition); } + + /** Move the scroll position by the specified amount + * + * @param scrollDelta */ + public void setScrollDelta(float scrollDelta) + { float position = scrollPosition + scrollDelta; - if (position < -scrollLength) { - this.scrollDelta = - scrollPosition - scrollLength; + if (position < -scrollLength) + { + this.scrollDelta = -scrollPosition - scrollLength; } - else if (position > TOP_LIMIT) { - this.scrollDelta = - scrollPosition; + else if (position > TOP_LIMIT) + { + this.scrollDelta = -scrollPosition; } - else { + else + { this.scrollDelta = scrollDelta; } - - scrollPosition += this.scrollDelta; - scrollBarPosition = PADDING + (scrollPosition/(scrollLength + 2*PADDING)) * (getScrollBarLength() - (scrollDirection == ScrollDirection.VERTICAL ? getHeight() : getWidth())); - } - - - /** - * Get the current scroll position of the scroll area - */ - public float getScrollPosition() { - return scrollPosition; + scrollPosition += this.scrollDelta; + scrollBarPosition = PADDING + (scrollPosition / (scrollLength + 2 * PADDING)) * (getScrollBarLength() - (scrollDirection == ScrollDirection.VERTICAL ? getHeight() : getWidth())); } - - + + /** Get the current scroll position of the scroll area */ + public float getScrollPosition() + { return scrollPosition; } + @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + { super.onHandleInput(input, bounds); - // Handle input for the scroll bar and the elements within the scroll area - if (withinBounds((float)input.getMouseX(), (float)input.getMouseY())) { + if (withinBounds((float) input.getMouseX(), (float) input.getMouseY())) + { renderScrollBar = true; scrollBar.handleInput(input, bounds); - // Position the scroll bar - if (scrollDirection == ScrollDirection.VERTICAL) setScrollDelta((float)input.consumeMouseScrollY()); + if (scrollDirection == ScrollDirection.VERTICAL) + setScrollDelta((float) input.consumeMouseScrollY()); else if (scrollDirection == ScrollDirection.HORIZONTAL) setScrollDelta((float) input.consumeMouseScrollX()); } else renderScrollBar = false; } - - + @Override - public void updateBounds(BoundsInterface window, Vector2f parent) { + public void updateBounds(BoundsInterface window, Vector2f parent) + { super.updateBounds(window, parent); scrollBar.updateBounds(this, parent); - // Set position of GUI elements Iterator it = iterator(); - while (it.hasNext()) { + while (it.hasNext()) + { GUIElementInterface e = it.next(); - if (scrollDirection == ScrollDirection.VERTICAL) + if (scrollDirection == ScrollDirection.VERTICAL) e.setPosition(e.getAbsolutePosition().x, e.getAbsolutePosition().y + scrollDelta * SCROLL_SPEED); - else if (scrollDirection == ScrollDirection.HORIZONTAL) + else if (scrollDirection == ScrollDirection.HORIZONTAL) e.setPosition(e.getAbsolutePosition().x + scrollDelta * SCROLL_SPEED, e.getAbsolutePosition().y); } - // Set position of scroll bar - if (scrollDirection == ScrollDirection.VERTICAL) + if (scrollDirection == ScrollDirection.VERTICAL) scrollBar.setPosition(scrollBar.getAbsolutePosition().x, getScrollBarPosition()); - else if (scrollDirection == ScrollDirection.HORIZONTAL) - scrollBar.setPosition(getScrollBarPosition(), scrollBar.getAbsolutePosition().y); + else if (scrollDirection == ScrollDirection.HORIZONTAL) + scrollBar.setPosition(getScrollBarPosition(), scrollBar.getAbsolutePosition().y); } - } diff --git a/src/com/bwyap/engine/gui/element/base/ScrollBar.java b/src/com/bwyap/engine/gui/element/base/ScrollBar.java index d95d04a..5c32fdb 100644 --- a/src/com/bwyap/engine/gui/element/base/ScrollBar.java +++ b/src/com/bwyap/engine/gui/element/base/ScrollBar.java @@ -6,59 +6,43 @@ import com.bwyap.engine.gui.interfaces.IVectorRoundedRect; import com.bwyap.engine.input.InputHandler; - -/** - * Used in the scroll area to indicate what position the scroll area is in. - * @author bwyap - * - */ -class ScrollBar extends ClickableElement implements IColouredVectorShape, IVectorRoundedRect { - +/** Used in the scroll area to indicate what position the scroll area is in. + * + * @author bwyap */ +class ScrollBar extends ClickableElement implements IColouredVectorShape, IVectorRoundedRect +{ private float radius; private final VectorShapeColourProperties colour; - - public ScrollBar(float x, float y, float width, float height, float radius) { + public ScrollBar(float x, float y, float width, float height, float radius) + { super(x, y, width, height); this.radius = radius; colour = new VectorShapeColourProperties(); colour.setColour(0.1f, 0.1f, 0.1f, 0.5f); } - - - @Override - public float getRadius() { - return radius; - } - - - @Override - public VectorShapeColourProperties colourProperties() { - return colour; - } - @Override - public void onMouseClicked(float x, float y, int mouseButton) { - - } - - + public float getRadius() + { return radius; } + @Override - public void onMouseOver(float x, float y) { - - } + public VectorShapeColourProperties colourProperties() + { return colour; } + @Override + public void onMouseClicked(float x, float y, int mouseButton) + {} @Override - public void update(float timestep) { - - } + public void onMouseOver(float x, float y) + {} + @Override + public void update(float timestep) + {} @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { - - } - + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + {} } diff --git a/src/com/bwyap/engine/gui/element/base/SelectableElement.java b/src/com/bwyap/engine/gui/element/base/SelectableElement.java index 91345e4..7754ec0 100644 --- a/src/com/bwyap/engine/gui/element/base/SelectableElement.java +++ b/src/com/bwyap/engine/gui/element/base/SelectableElement.java @@ -4,95 +4,79 @@ import com.bwyap.engine.gui.interfaces.ISelectable; import com.bwyap.engine.input.InputHandler; - -/** - * A clickable GUI element which can be selected. +/** A clickable GUI element which can be selected. * Accepted select buttons are inherited from the ClickableElement class. - * @author bwyap - * - */ -public abstract class SelectableElement extends ClickableElement implements ISelectable { - - private boolean selected; + * + * @author bwyap */ +public abstract class SelectableElement extends ClickableElement implements ISelectable +{ + private boolean selected; private boolean selectable; - - public SelectableElement(float x, float y, float width, float height) { + + public SelectableElement(float x, float y, float width, float height) + { super(x, y, width, height); selected = false; selectable = true; } - - - @Override - public boolean isSelectable() { - return selectable; - } - - + @Override - public void setSelectable(boolean selectable) { - this.selectable = selectable; - } - + public boolean isSelectable() + { return selectable; } - /** - * Set whether the GUI element has been selected or not. - * @param selected - * @return - */ - public void setSelected(boolean selected) { - this.selected = selected; - } - - @Override - public final boolean isSelected() { - return selected; - } + public void setSelectable(boolean selectable) + { this.selectable = selectable; } + /** Set whether the GUI element has been selected or not. + * + * @param selected + * @return */ + public void setSelected(boolean selected) + { this.selected = selected; } + + @Override + public final boolean isSelected() + { return selected; } @Override - public void onMouseClicked(float x, float y, int mouseButton) { - if (selectable) { - for (int button : acceptedButtons) { - if (button == mouseButton && !isSelected()) { + public void onMouseClicked(float x, float y, int mouseButton) + { + if (selectable) + { + for (int button : acceptedButtons) + { + if (button == mouseButton && !isSelected()) + { setSelected(true); onSelect(); - break; + break; } } } } - @Override - public void onMouseOver(float x, float y) {} - + public void onMouseOver(float x, float y) + {} - /** - * {@inheritDoc} + /** {@inheritDoc} * Handles the deselection of the element when the mouse is clicked * outside the bounds of the element. - *

Override this method for custom input handling functionality.

- */ + *

Override this method for custom input handling functionality.

*/ @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { - if (!mouseOver && input.isMouseDown() && isSelected()) { + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + { + if (!mouseOver && input.isMouseDown() && isSelected()) + { setSelected(false); onDeselect(); } } - - - /** - * Action to perform when the element is selected - */ + + /** Action to perform when the element is selected */ public abstract void onSelect(); - - - /** - * Action to perform when the element is deselected - */ - public abstract void onDeselect(); + /** Action to perform when the element is deselected */ + public abstract void onDeselect(); } diff --git a/src/com/bwyap/engine/gui/element/base/TextBox.java b/src/com/bwyap/engine/gui/element/base/TextBox.java index 8a922c2..172e134 100644 --- a/src/com/bwyap/engine/gui/element/base/TextBox.java +++ b/src/com/bwyap/engine/gui/element/base/TextBox.java @@ -5,69 +5,60 @@ import com.bwyap.engine.gui.interfaces.IColouredVectorShape; import com.bwyap.engine.window.BoundsInterface; - -/** - * A text box which wraps text at the specified width. - * @author bwyap - * - */ -public abstract class TextBox extends TextField implements IColouredVectorShape { - - +/** A text box which wraps text at the specified width. + * + * @author bwyap */ +public abstract class TextBox extends TextField implements IColouredVectorShape +{ private float absoluteTextBoxWidth; private float absolutePadding; private boolean submittable; - - - public TextBox(float x, float y, float width, float height, float padding) { + + public TextBox(float x, float y, float width, float height, float padding) + { super(x, y, width, height); this.absolutePadding = padding; this.absoluteTextBoxWidth = width; this.submittable = false; - text.setTextBox(true); text.setAlignment(ETextAlignment.TOP_LEFT); text.setPadding(absolutePadding, absolutePadding, absolutePadding, absolutePadding); text.setTextBoxWidth(absoluteTextBoxWidth - 2 * absolutePadding); } - - - /** - * Check whether the contents of the text box are sent to the {@code onSubmit} method - * @return - */ - public boolean isSubmittable() { - return submittable; - } - - - /** - * Set whether the contents of the text box are sent to the {@code onSubmit} method - * @param submittable - */ - public void setSubmittable(boolean submittable) { - this.submittable = submittable; - } - - + + /** Check whether the contents of the text box are sent to the {@code onSubmit} method + * + * @return */ + public boolean isSubmittable() + { return submittable; } + + /** Set whether the contents of the text box are sent to the {@code onSubmit} method + * + * @param submittable */ + public void setSubmittable(boolean submittable) + { this.submittable = submittable; } + @Override - public void updateBounds(BoundsInterface window, Vector2f parent) { + public void updateBounds(BoundsInterface window, Vector2f parent) + { super.updateBounds(window, parent); - if (!scaleAbsolute) { + if (!scaleAbsolute) + { text.setTextBoxWidth(absoluteTextBoxWidth * scaleX - 2 * absolutePadding * scaleX); text.setPadding(absolutePadding * scaleY, absolutePadding * scaleY, absolutePadding * scaleX, absolutePadding * scaleX); } } - - + @Override - public void enterPressed() { - if (isSubmittable()) { + public void enterPressed() + { + if (isSubmittable()) + { super.enterPressed(); } - else { + else + { putChar('\n'); } } - } diff --git a/src/com/bwyap/engine/gui/element/base/TextField.java b/src/com/bwyap/engine/gui/element/base/TextField.java index 7158fee..86eda64 100644 --- a/src/com/bwyap/engine/gui/element/base/TextField.java +++ b/src/com/bwyap/engine/gui/element/base/TextField.java @@ -5,26 +5,22 @@ import com.bwyap.engine.gui.interfaces.ITextDisplay; import com.bwyap.engine.input.InputHandler; - -/** - * A text field that allows text to be entered within it +/** A text field that allows text to be entered within it * when it is selected. It contains a {@code TextComponent} * to hold text for rendering. - * @author bwyap - * - */ -public abstract class TextField extends SelectableElement implements ITextDisplay { - + * + * @author bwyap */ +public abstract class TextField extends SelectableElement implements ITextDisplay +{ protected final TextComponent text; - private boolean editable; private boolean showCaret; private boolean displayingCaret; private float caretBlinkTime = 0; private float BLINK_TIME = 0.5f; - - - public TextField(float x, float y, float width, float height) { + + public TextField(float x, float y, float width, float height) + { super(x, y, width, height); text = new TextComponent(); text.setText(""); @@ -32,107 +28,83 @@ public TextField(float x, float y, float width, float height) { showCaret = true; editable = true; } - - - /** - * Check if the text field is showing the blinking caret. - */ - public boolean showCaret() { - return showCaret; - } - - - /** - * Set whether the text field should show the caret when it is selected. - * @param showCaret - */ - public void setShowCaret(boolean showCaret) { - this.showCaret = showCaret; - } - - - /** - * Set the blink time of the caret. + + /** Check if the text field is showing the blinking caret. */ + public boolean showCaret() + { return showCaret; } + + /** Set whether the text field should show the caret when it is selected. + * + * @param showCaret */ + public void setShowCaret(boolean showCaret) + { this.showCaret = showCaret; } + + /** Set the blink time of the caret. * Default is 0.5f. - * @param blinkTime - */ - public void setBlinkTime(float blinkTime) { - this.BLINK_TIME = blinkTime; - } - - - /** - * Get the blink time of the caret. - * @return - */ - public float getBlinkTime() { - return BLINK_TIME; - } + * + * @param blinkTime */ + public void setBlinkTime(float blinkTime) + { this.BLINK_TIME = blinkTime; } + /** Get the blink time of the caret. + * + * @return */ + public float getBlinkTime() + { return BLINK_TIME; } - /** - * Check whether the contents of this text field are editable - * @return - */ - public boolean isEditable() { - return editable; - } - - - /** - * Set whether the contents of this text field are editable - * @param editable - */ - public void setEditable(boolean editable) { - this.editable = editable; - } - - - /** - * Action to perform when the text field data is to be submitted - * @param text - */ + /** Check whether the contents of this text field are editable + * + * @return */ + public boolean isEditable() + { return editable; } + + /** Set whether the contents of this text field are editable + * + * @param editable */ + public void setEditable(boolean editable) + { this.editable = editable; } + + /** Action to perform when the text field data is to be submitted + * + * @param text */ public abstract void onSubmit(String text); - - + @Override - public void onSelect() { - if (editable) beginEnterText(); - } - - + public void onSelect() + { if (editable) beginEnterText(); } + @Override - public void onDeselect() { - if (editable) stopEnterText(); - } - - + public void onDeselect() + { if (editable) stopEnterText(); } + @Override - public void onMouseOver(float x, float y) {} + public void onMouseOver(float x, float y) + {} - @Override - public TextComponent getTextComponent() { - return text; - } - - - /** - * {@inheritDoc} - *

Override this method for custom update functionality.

- */ + public TextComponent getTextComponent() + { return text; } + + /** {@inheritDoc} + *

Override this method for custom update functionality.

*/ @Override - public void update(float timestep) { - if (showCaret) { - if (isSelected() && editable) { + public void update(float timestep) + { + if (showCaret) + { + if (isSelected() && editable) + { caretBlinkTime += timestep; - if (caretBlinkTime >= BLINK_TIME) { + if (caretBlinkTime >= BLINK_TIME) + { caretBlinkTime = 0; - if (displayingCaret) { + if (displayingCaret) + { text.setText(text.getText().substring(0, text.getText().length() - 1) + " "); displayingCaret = false; } - else { + else + { text.setText(text.getText().substring(0, text.getText().length() - 1) + "|"); displayingCaret = true; } @@ -141,94 +113,86 @@ public void update(float timestep) { } } - - /** - * {@inheritDoc} - *

Override this method for custom input handling functionality.

- */ + /** {@inheritDoc} + *

Override this method for custom input handling functionality.

*/ @Override - public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) { + public void onHandleInput(InputHandler input, GUIBoundsInterface bounds) + { super.onHandleInput(input, bounds); - if (isSelected() && editable) enterText(input); } - - + private boolean clearCharBuffer; - - /** - * Set up the text component to begin editing the text - */ - protected void beginEnterText() { + + /** Set up the text component to begin editing the text */ + protected void beginEnterText() + { displayingCaret = true; text.appendText("|"); caretBlinkTime = 0; clearCharBuffer = true; } - - - /** - * Clean up after text in the text component has been edited - */ - protected void stopEnterText() { - if (text.getText().length() > 0) text.setText(text.getText().substring(0, text.getText().length() - 1)); - } - - - /** - * Poll the input handler to edit the text in the text component - */ - protected void enterText(InputHandler input) { - if (clearCharBuffer) { + + /** Clean up after text in the text component has been edited */ + protected void stopEnterText() + { if (text.getText().length() > 0) text.setText(text.getText().substring(0, text.getText().length() - 1)); } + + /** Poll the input handler to edit the text in the text component */ + protected void enterText(InputHandler input) + { + if (clearCharBuffer) + { input.consumeLastTypedChar(); clearCharBuffer = false; } char c = input.consumeLastTypedChar(); - if (c == '\b') { + if (c == '\b') + { // Remove a character if the key was backspace - removeChar(); + removeChar(); } - else if (c == '\n') { + else if (c == '\n') + { // Call the enter method if the enter key was pressed enterPressed(); } - else if (c != 0) { + else if (c != 0) + { // Add a character to the text field putChar(c); } } - - - /** - * Add a character to the text field - * @param c - */ - protected final void putChar(char c) { - if (showCaret) { - if (displayingCaret) text.setText(text.getText().substring(0, text.getText().length() - 1) + c + "|"); + + /** Add a character to the text field + * + * @param c */ + protected final void putChar(char c) + { + if (showCaret) + { + if (displayingCaret) + text.setText(text.getText().substring(0, text.getText().length() - 1) + c + "|"); else text.setText(text.getText().substring(0, text.getText().length() - 1) + c + " "); } else text.setText(text.getText() + c); } - - - /** - * Remove a character from the text field - */ - protected final void removeChar() { - if (showCaret && displayingCaret) { + + /** Remove a character from the text field */ + protected final void removeChar() + { + if (showCaret && displayingCaret) + { if (text.getText().length() > 1) text.setText(text.getText().substring(0, text.getText().length() - 2) + "|"); } else if (text.getText().length() > 1) text.setText(text.getText().substring(0, text.getText().length() - 2) + " "); } - - - /** - * Action to perform when the enter key is pressed - */ - protected void enterPressed() { + + /** Action to perform when the enter key is pressed */ + protected void enterPressed() + { // Call the enter method if the enter key was pressed - if (showCaret) onSubmit(text.getText().substring(0, text.getText().length() - 1)); + if (showCaret) + onSubmit(text.getText().substring(0, text.getText().length() - 1)); else onSubmit(text.getText()); } } diff --git a/src/com/bwyap/engine/gui/element/properties/Fade.java b/src/com/bwyap/engine/gui/element/properties/Fade.java index 67c1f95..5d5712a 100644 --- a/src/com/bwyap/engine/gui/element/properties/Fade.java +++ b/src/com/bwyap/engine/gui/element/properties/Fade.java @@ -1,73 +1,58 @@ package com.bwyap.engine.gui.element.properties; -/** - * A class to hold the fade amount of a rendered element. - * @author bwyap - * - */ -public class Fade implements GUIProperty { - +/** A class to hold the fade amount of a rendered element. + * + * @author bwyap */ +public class Fade implements GUIProperty +{ private float alpha; private boolean fading; - - /** - * Set whether the vector shape is fading - * @return - */ - public boolean isFading() { - return fading; - } - - - /** - * Set whether the vector shape is fading - * @param fading - */ - public void setFading(boolean fading) { - this.fading = fading; - } - - - /** - * Get the fade value - * @return - */ - public float getFade() { - return alpha; - } - - - /** - * Set the fade value. + /** Set whether the vector shape is fading + * + * @return */ + public boolean isFading() + { return fading; } + + /** Set whether the vector shape is fading + * + * @param fading */ + public void setFading(boolean fading) + { this.fading = fading; } + + /** Get the fade value + * + * @return */ + public float getFade() + { return alpha; } + + /** Set the fade value. * Clamped between 0 and 1. - * @param fade - */ - public void setFade(float fade) { + * + * @param fade */ + public void setFade(float fade) + { this.alpha = fade; // Clamp between 0 and 1 decreaseFade(0); increaseFade(0); } - - - /** - * Decrease the fade by the specified amount - * @param amount - */ - public void decreaseFade(float amount) { + + /** Decrease the fade by the specified amount + * + * @param amount */ + public void decreaseFade(float amount) + { alpha -= amount; if (alpha < 0) alpha = 0; } - - - /** - * Increase the fade by the specified amount - * @param amount - */ - public void increaseFade(float amount) { + + /** Increase the fade by the specified amount + * + * @param amount */ + public void increaseFade(float amount) + { alpha += amount; if (alpha > 1) alpha = 1; } - } diff --git a/src/com/bwyap/engine/gui/element/properties/GUIProperty.java b/src/com/bwyap/engine/gui/element/properties/GUIProperty.java index 9c9e0cd..51b2087 100644 --- a/src/com/bwyap/engine/gui/element/properties/GUIProperty.java +++ b/src/com/bwyap/engine/gui/element/properties/GUIProperty.java @@ -1,10 +1,8 @@ package com.bwyap.engine.gui.element.properties; -/** - * Indicates that the class is a property of a GUI element - * @author bwyap - * - */ -public interface GUIProperty { - +/** Indicates that the class is a property of a GUI element + * + * @author bwyap */ +public interface GUIProperty +{ } diff --git a/src/com/bwyap/engine/gui/element/properties/TextComponent.java b/src/com/bwyap/engine/gui/element/properties/TextComponent.java index 7bb06eb..fad98df 100644 --- a/src/com/bwyap/engine/gui/element/properties/TextComponent.java +++ b/src/com/bwyap/engine/gui/element/properties/TextComponent.java @@ -5,14 +5,12 @@ import com.bwyap.engine.gui.element.base.ETextAlignment; -/** - * A class to hold information for a text component +/** A class to hold information for a text component * to be rendered using the graphics rendering system. - * @author bwyap - * - */ -public class TextComponent implements GUIProperty { - + * + * @author bwyap */ +public class TextComponent implements GUIProperty +{ private String text = ""; private float absoluteTextSize, textSize; private final Vector2f positionOffset; @@ -23,52 +21,42 @@ public class TextComponent implements GUIProperty { private boolean scale; private boolean textBox; private float textBoxWidth; - private float paddingTop, paddingBottom, paddingLeft, paddingRight; - - - /** - * Create a text component with an empty string - * and default settings (Font size 20, white colour). - */ - public TextComponent() { - this(1.0f, 1.0f, 1.0f, 1.0f); - } - - - /** - * Create a text component with the given string + + /** Create a text component with an empty string + * and default settings (Font size 20, white colour). */ + public TextComponent() + { this(1.0f, 1.0f, 1.0f, 1.0f); } + + /** Create a text component with the given string * and default settings (Font size 20, white colour). - * @param text - */ - public TextComponent(String text) { + * + * @param text */ + public TextComponent(String text) + { this(); setText(text); } - - /** - * Create a text component with an empty + /** Create a text component with an empty * string and assign it the given colour. + * * @param r * @param g * @param b - * @param a - */ - public TextComponent(float r, float g, float b, float a) { - this("", r, g, b, a); - } + * @param a */ + public TextComponent(float r, float g, float b, float a) + { this("", r, g, b, a); } - - /** - * Create a text component with the given + /** Create a text component with the given * string and assign it the given colour. + * * @param r * @param g * @param b - * @param a - */ - public TextComponent(String text, float r, float g, float b, float a) { + * @param a */ + public TextComponent(String text, float r, float g, float b, float a) + { positionOffset = new Vector2f(); textColour = new Vector4f(r, b, g, a); textSize = absoluteTextSize = 20.0f; @@ -76,218 +64,176 @@ public TextComponent(String text, float r, float g, float b, float a) { scale = true; alignment = ETextAlignment.CENTER; } - - - /** - * Set the text component's width for rendering as a text box. + + /** Set the text component's width for rendering as a text box. * Use the {@code setTextBox} to enable rendering as a text box. - * @param textBoxWidth - */ - public void setTextBoxWidth(float textBoxWidth) { - this.textBoxWidth = textBoxWidth; - } - - - /** - * Set whether this text component should be rendered as a text box - * @param textBox - */ - public void setTextBox(boolean textBox) { - this.textBox = textBox; - } - - - /** - * Check if this text component should be rendered as a text box - * @return - */ - public boolean isTextBox() { - return textBox; - } - - - /** - * Get the width of the textbox in which the text should be rendered - * @return - */ - public float getTextBoxWidth() { - return textBoxWidth; - } - - - /** - * Get the position offset of the text component. + * + * @param textBoxWidth */ + public void setTextBoxWidth(float textBoxWidth) + { this.textBoxWidth = textBoxWidth; } + + /** Set whether this text component should be rendered as a text box + * + * @param textBox */ + public void setTextBox(boolean textBox) + { this.textBox = textBox; } + + /** Check if this text component should be rendered as a text box + * + * @return */ + public boolean isTextBox() + { return textBox; } + + /** Get the width of the textbox in which the text should be rendered + * + * @return */ + public float getTextBoxWidth() + { return textBoxWidth; } + + /** Get the position offset of the text component. * This is relative to its alignment position. - * @return - */ - public Vector2f getOffset() { - return positionOffset; - } - - - /** - * Set the position offset of the text component. + * + * @return */ + public Vector2f getOffset() + { return positionOffset; } + + /** Set the position offset of the text component. * This is relative to its alignment position. + * * @param x - * @param y - */ - public void setOffset(float x, float y) { + * @param y */ + public void setOffset(float x, float y) + { positionOffset.x = x; positionOffset.y = y; } - - /** - * Set the padding for the text component + /** Set the padding for the text component + * * @param top * @param bottom * @param left - * @param right - */ - public void setPadding(float top, float bottom, float left, float right) { + * @param right */ + public void setPadding(float top, float bottom, float left, float right) + { paddingTop = top; paddingBottom = bottom; paddingLeft = left; paddingRight = right; } - - - public float getPaddingTop() { return paddingTop; } - public float getPaddingBottom() { return paddingBottom; } - public float getPaddingLeft() { return paddingLeft; } - public float getPaddingRight() { return paddingRight; } - - - /** - * Check if the text will be clipped to the bounds of the component. + + public float getPaddingTop() + { return paddingTop; } + + public float getPaddingBottom() + { return paddingBottom; } + + public float getPaddingLeft() + { return paddingLeft; } + + public float getPaddingRight() + { return paddingRight; } + + /** Check if the text will be clipped to the bounds of the component. * By default this is set to true. - * @return - */ - public boolean isClipText() { - return clipText; - } - - - /** - * Set whether the text will be clipped to the bounds of the component. - * @param clipText - */ - public void setClipText(boolean clipText) { - this.clipText = clipText; - } - - - /** - * Set the alignment of the text to render. - * The alignment tag can be used by the + * + * @return */ + public boolean isClipText() + { return clipText; } + + /** Set whether the text will be clipped to the bounds of the component. + * + * @param clipText */ + public void setClipText(boolean clipText) + { this.clipText = clipText; } + + /** Set the alignment of the text to render. + * The alignment tag can be used by the * renderer to specify the text alignment, * but it can be ignored. - * @param alignment - */ - public void setAlignment(ETextAlignment alignment) { - this.alignment = alignment; - } - - /** - * Get the alignment of the text. - * @return - */ - public ETextAlignment getAlignment() { - return alignment; - } - - /** - * Get the button text - * @return - */ - public String getText() { - return text; - } - - /** - * Set the button text - * @param text - */ - public void setText(String text) { - this.text = text; - } - - /** - * Append some text to the current text - * @param text - */ - public void appendText(String text) { - this.text += text; - } - - /** - * Get the name of the font used to render the text - * @return - */ - public String getFontName() { - return fontName; - } - - /** - * Set the name of the font used to render the text - * @param font - */ - public void setFontName(String font) { - this.fontName = font; - } - - /** - * Get the colour of the text - * @return - */ - public Vector4f getTextColour() { - return textColour; - } - - /** - * Set the colour of the text + * + * @param alignment */ + public void setAlignment(ETextAlignment alignment) + { this.alignment = alignment; } + + /** Get the alignment of the text. + * + * @return */ + public ETextAlignment getAlignment() + { return alignment; } + + /** Get the button text + * + * @return */ + public String getText() + { return text; } + + /** Set the button text + * + * @param text */ + public void setText(String text) + { this.text = text; } + + /** Append some text to the current text + * + * @param text */ + public void appendText(String text) + { this.text += text; } + + /** Get the name of the font used to render the text + * + * @return */ + public String getFontName() + { return fontName; } + + /** Set the name of the font used to render the text + * + * @param font */ + public void setFontName(String font) + { this.fontName = font; } + + /** Get the colour of the text + * + * @return */ + public Vector4f getTextColour() + { return textColour; } + + /** Set the colour of the text + * * @param r * @param g * @param b - * @param a - */ - public void setTextColour(float r, float g, float b, float a) { + * @param a */ + public void setTextColour(float r, float g, float b, float a) + { this.textColour.x = r; this.textColour.y = g; this.textColour.z = b; this.textColour.w = a; } - - /** - * Get the text size - * @return - */ - public float getTextSize() { - return textSize; - } - - /** - * Get the absolute text size (unmodified by screen scaling) - * @return - */ - public float getAbsoluteTextSize() { - return absoluteTextSize; - } - - /** - * Set the absolute text size - * @param size - */ - public void setTextSize(float size) { - this.absoluteTextSize = size; - } - - /** - * Check if the text component should be scaled according to its parent. + + /** Get the text size + * + * @return */ + public float getTextSize() + { return textSize; } + + /** Get the absolute text size (unmodified by screen scaling) + * + * @return */ + public float getAbsoluteTextSize() + { return absoluteTextSize; } + + /** Set the absolute text size + * + * @param size */ + public void setTextSize(float size) + { this.absoluteTextSize = size; } + + /** Check if the text component should be scaled according to its parent. * Default is true. - * @return - */ - public boolean scale() { - return scale; - } + * + * @return */ + public boolean scale() + { return scale; } } diff --git a/src/com/bwyap/engine/gui/element/properties/VectorShapeColourProperties.java b/src/com/bwyap/engine/gui/element/properties/VectorShapeColourProperties.java index 7d4ffae..b9e061b 100644 --- a/src/com/bwyap/engine/gui/element/properties/VectorShapeColourProperties.java +++ b/src/com/bwyap/engine/gui/element/properties/VectorShapeColourProperties.java @@ -2,22 +2,19 @@ import org.joml.Vector4f; - -/** - * A class that holds the colours that - * should be used to render a GUI element. - * @author bwyap - * - */ -public class VectorShapeColourProperties implements GUIProperty { - +/** A class that holds the colours that + * should be used to render a GUI element. + * + * @author bwyap */ +public class VectorShapeColourProperties implements GUIProperty +{ public final Vector4f colour, mouseoverColour, mouseDownColour, selectedColour; public final Vector4f borderColour, borderMouseoverColour; public boolean hasBorder; public float borderWidth; - - public VectorShapeColourProperties() { + public VectorShapeColourProperties() + { colour = new Vector4f(0.4f, 0.4f, 0.4f, 1.0f); mouseoverColour = new Vector4f(0.5f, 0.5f, 0.5f, 1.0f); mouseDownColour = new Vector4f(0.6f, 0.6f, 0.6f, 0.95f); @@ -26,218 +23,184 @@ public VectorShapeColourProperties() { borderMouseoverColour = new Vector4f(0.9f, 0.9f, 0.9f, 1.0f); borderWidth = 3.0f; } - - - /** - * Set the colour of the shape + + /** Set the colour of the shape + * * @param r * @param g * @param b - * @param a - */ - public void setColour(float r, float g, float b, float a) { + * @param a */ + public void setColour(float r, float g, float b, float a) + { this.colour.x = r; this.colour.y = g; this.colour.z = b; this.colour.w = a; } - - /** - * Set the colour of the shape - * @param colour - */ - public void setColour(Vector4f colour) { - setColour(colour.x, colour.y, colour.z, colour.w); - } - - /** - * Get the colour of the shape - * @return - */ - public Vector4f getColour() { - return colour; - } - - /** - * Set the colour of the shape when it is selected + + /** Set the colour of the shape + * + * @param colour */ + public void setColour(Vector4f colour) + { setColour(colour.x, colour.y, colour.z, colour.w); } + + /** Get the colour of the shape + * + * @return */ + public Vector4f getColour() + { return colour; } + + /** Set the colour of the shape when it is selected + * * @param r * @param g * @param b - * @param a - */ - public void setSelectedColour(float r, float g, float b, float a) { + * @param a */ + public void setSelectedColour(float r, float g, float b, float a) + { this.selectedColour.x = r; this.selectedColour.y = g; this.selectedColour.z = b; this.selectedColour.w = a; } - - /** - * Set the colour of the shape when it is selected - * @param colour - */ - public void setSelectedColour(Vector4f colour) { - setSelectedColour(colour.x, colour.y, colour.z, colour.w); - } - - /** - * Get the colour of the shape - * @return - */ - public Vector4f getSelectedColour() { - return selectedColour; - } - - /** - * Set the colour of the shape when the mouse is over it + + /** Set the colour of the shape when it is selected + * + * @param colour */ + public void setSelectedColour(Vector4f colour) + { setSelectedColour(colour.x, colour.y, colour.z, colour.w); } + + /** Get the colour of the shape + * + * @return */ + public Vector4f getSelectedColour() + { return selectedColour; } + + /** Set the colour of the shape when the mouse is over it + * * @param r * @param g * @param b - * @param a - */ - public void setMouseoverColour(float r, float g, float b, float a) { + * @param a */ + public void setMouseoverColour(float r, float g, float b, float a) + { this.mouseoverColour.x = r; this.mouseoverColour.y = g; this.mouseoverColour.z = b; this.mouseoverColour.w = a; - } - - /** - * Set the colour of the shape when the mouse is over it - * @param colour - */ - public void setMouseoverColour(Vector4f colour) { - setMouseoverColour(colour.x, colour.y, colour.z, colour.w); - } - - /** - * Get the colour of the shape when the mouse is over it - * @return - */ - public Vector4f getMouseoverColour() { - return mouseoverColour; } - - /** - * Set the colour of the shape when the mouse is pressing it + + /** Set the colour of the shape when the mouse is over it + * + * @param colour */ + public void setMouseoverColour(Vector4f colour) + { setMouseoverColour(colour.x, colour.y, colour.z, colour.w); } + + /** Get the colour of the shape when the mouse is over it + * + * @return */ + public Vector4f getMouseoverColour() + { return mouseoverColour; } + + /** Set the colour of the shape when the mouse is pressing it + * * @param r * @param g * @param b - * @param a - */ - public void setMouseDownColour(float r, float g, float b, float a) { + * @param a */ + public void setMouseDownColour(float r, float g, float b, float a) + { this.mouseDownColour.x = r; this.mouseDownColour.y = g; this.mouseDownColour.z = b; this.mouseDownColour.w = a; } - - /** - * Set the colour of the shape when the mouse is pressing it - * @param colour - */ - public void setMouseDownColour(Vector4f colour) { - setMouseDownColour(colour.x, colour.y, colour.z, colour.w); - } - - /** - * Get the colour of the shape when the mouse is pressing it - * @return - */ - public Vector4f getMouseDownColour() { - return mouseDownColour; - } - - /** - * Set the colour of the border + + /** Set the colour of the shape when the mouse is pressing it + * + * @param colour */ + public void setMouseDownColour(Vector4f colour) + { setMouseDownColour(colour.x, colour.y, colour.z, colour.w); } + + /** Get the colour of the shape when the mouse is pressing it + * + * @return */ + public Vector4f getMouseDownColour() + { return mouseDownColour; } + + /** Set the colour of the border + * * @param r * @param g * @param b - * @param a - */ - public void setBorderColour(float r, float g, float b, float a) { + * @param a */ + public void setBorderColour(float r, float g, float b, float a) + { this.borderColour.x = r; this.borderColour.y = g; this.borderColour.z = b; this.borderColour.w = a; } - - /** - * Set the colour of the border - * @param colour - */ - public void setBorderColour(Vector4f colour) { - setBorderColour(colour.x, colour.y, colour.z, colour.w); - } - - /** - * Get the colour of the border - * @return - */ - public Vector4f getBorderColour() { - return borderColour; - } - - /** - * Set the colour of the border when the mouse is over the shape + + /** Set the colour of the border + * + * @param colour */ + public void setBorderColour(Vector4f colour) + { setBorderColour(colour.x, colour.y, colour.z, colour.w); } + + /** Get the colour of the border + * + * @return */ + public Vector4f getBorderColour() + { return borderColour; } + + /** Set the colour of the border when the mouse is over the shape + * * @param r * @param g * @param b - * @param a - */ - public void setBorderMouseoverColour(float r, float g, float b, float a) { + * @param a */ + public void setBorderMouseoverColour(float r, float g, float b, float a) + { this.borderMouseoverColour.x = r; this.borderMouseoverColour.y = g; this.borderMouseoverColour.z = b; this.borderMouseoverColour.w = a; } - - /** - * Set the colour of the border when the mouse is over the shape - * @param colour - */ - public void setBorderMouseoverColour(Vector4f colour) { - setBorderMouseoverColour(colour.x, colour.y, colour.z, colour.w); - } - - /** - * Get the colour of the border when the mouse is over the shape - * @return - */ - public Vector4f getBorderMouseoverColour() { - return borderMouseoverColour; - } - - /** - * Set whether the shape should be rendered with a border - * @param hasBorder - */ - public void setHasBorder(boolean hasBorder) { - this.hasBorder = hasBorder; - } - - /** - * Check if the shape should be rendered with a border - * @return - */ - public boolean hasBorder() { - return hasBorder; - } - - /** - * Set the width of the border - * @param width - */ - public void setBorderWidth(float width) { - this.borderWidth = width; - } - - /** - * Get the width of the border - * @return - */ - public float getBorderWidth() { - return borderWidth; - } - + + /** Set the colour of the border when the mouse is over the shape + * + * @param colour */ + public void setBorderMouseoverColour(Vector4f colour) + { setBorderMouseoverColour(colour.x, colour.y, colour.z, colour.w); } + + /** Get the colour of the border when the mouse is over the shape + * + * @return */ + public Vector4f getBorderMouseoverColour() + { return borderMouseoverColour; } + + /** Set whether the shape should be rendered with a border + * + * @param hasBorder */ + public void setHasBorder(boolean hasBorder) + { this.hasBorder = hasBorder; } + + /** Check if the shape should be rendered with a border + * + * @return */ + public boolean hasBorder() + { return hasBorder; } + + /** Set the width of the border + * + * @param width */ + public void setBorderWidth(float width) + { this.borderWidth = width; } + + /** Get the width of the border + * + * @return */ + public float getBorderWidth() + { return borderWidth; } } diff --git a/src/com/bwyap/engine/gui/element/vector/EVectorShape.java b/src/com/bwyap/engine/gui/element/vector/EVectorShape.java index f772366..c21eaf9 100644 --- a/src/com/bwyap/engine/gui/element/vector/EVectorShape.java +++ b/src/com/bwyap/engine/gui/element/vector/EVectorShape.java @@ -1,10 +1,9 @@ package com.bwyap.engine.gui.element.vector; -/** - * A vector shape which can be drawn by the graphics rendering system. - * @author bwyap - * - */ -public enum EVectorShape { +/** A vector shape which can be drawn by the graphics rendering system. + * + * @author bwyap */ +public enum EVectorShape +{ RECTANGLE, ROUNDED_RECT, ELLIPSE; } diff --git a/src/com/bwyap/engine/gui/element/vector/SolidVectorProgressBar.java b/src/com/bwyap/engine/gui/element/vector/SolidVectorProgressBar.java index 3277ba8..f4410e5 100644 --- a/src/com/bwyap/engine/gui/element/vector/SolidVectorProgressBar.java +++ b/src/com/bwyap/engine/gui/element/vector/SolidVectorProgressBar.java @@ -4,41 +4,34 @@ import com.bwyap.engine.gui.element.base.ProgressBar; - -/** - * A vector drawn progress bar that is filled with a solid colour. +/** A vector drawn progress bar that is filled with a solid colour. * See {@link ProgressBar}. - * @author bwyap - * - */ -public abstract class SolidVectorProgressBar extends VectorProgressBar { - + * + * @author bwyap */ +public abstract class SolidVectorProgressBar extends VectorProgressBar +{ private final Vector4f fillColour; - - public SolidVectorProgressBar(float x, float y, float width, float height) { + public SolidVectorProgressBar(float x, float y, float width, float height) + { super(x, y, width, height); fillColour = new Vector4f(0.0f, 0.8f, 0.1f, 1.0f); } - - - /** - * Set the fill colour of the progress bar - * @param fillColour - */ - public void setFillColour(Vector4f fillColour) { - this.fillColour.x = fillColour.x; - this.fillColour.y = fillColour.y; - this.fillColour.z = fillColour.z; - this.fillColour.w = fillColour.w; - } - - - /** - * Get the fill colour of the progress bar - * @return - */ - public Vector4f getFillColour() { - return fillColour; + + /** Set the fill colour of the progress bar + * + * @param fillColour */ + public void setFillColour(Vector4f fillColour) + { + this.fillColour.x = fillColour.x; + this.fillColour.y = fillColour.y; + this.fillColour.z = fillColour.z; + this.fillColour.w = fillColour.w; } + + /** Get the fill colour of the progress bar + * + * @return */ + public Vector4f getFillColour() + { return fillColour; } } diff --git a/src/com/bwyap/engine/gui/element/vector/VectorButton.java b/src/com/bwyap/engine/gui/element/vector/VectorButton.java index 0e02812..9d8895d 100644 --- a/src/com/bwyap/engine/gui/element/vector/VectorButton.java +++ b/src/com/bwyap/engine/gui/element/vector/VectorButton.java @@ -4,35 +4,30 @@ import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; import com.bwyap.engine.gui.interfaces.IColouredVectorShape; -/** - * A button that is rendered using the graphics rendering system. +/** A button that is rendered using the graphics rendering system. * It can be one of the shapes as enumerated by {@code ButtonShape}. * See {@link Button}. - * @author bwyap - * - */ -public abstract class VectorButton extends Button implements IColouredVectorShape { - - protected final VectorShapeColourProperties colours; - - /** - * A button is given default mouseOver, mouseDown, border and borderMouseover colours. + * + * @author bwyap */ +public abstract class VectorButton extends Button implements IColouredVectorShape +{ + protected final VectorShapeColourProperties colours; + + /** A button is given default mouseOver, mouseDown, border and borderMouseover colours. * Initially the value of {@code hasBorder} is false. + * * @param x * @param y * @param width * @param height - * @param shape - */ - public VectorButton(float x, float y, float width, float height) { + * @param shape */ + public VectorButton(float x, float y, float width, float height) + { super(x, y, width, height); this.colours = new VectorShapeColourProperties(); } - - + @Override - public VectorShapeColourProperties colourProperties() { - return colours; - } - + public VectorShapeColourProperties colourProperties() + { return colours; } } diff --git a/src/com/bwyap/engine/gui/element/vector/VectorCheckBox.java b/src/com/bwyap/engine/gui/element/vector/VectorCheckBox.java index 5bb3f91..9a6622c 100644 --- a/src/com/bwyap/engine/gui/element/vector/VectorCheckBox.java +++ b/src/com/bwyap/engine/gui/element/vector/VectorCheckBox.java @@ -6,32 +6,28 @@ import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; import com.bwyap.engine.gui.interfaces.IColouredVectorShape; - -/** - * A vector drawn check box. +/** A vector drawn check box. * See {@link CheckBox}. - * @author bwyap - * - */ -public abstract class VectorCheckBox extends CheckBox implements IColouredVectorShape { - - /** - * Style to use to indicate a checked check box. - * @author bwyap - */ - public enum CheckBoxCheckStyle { + * + * @author bwyap */ +public abstract class VectorCheckBox extends CheckBox implements IColouredVectorShape +{ + /** Style to use to indicate a checked check box. + * + * @author bwyap */ + public enum CheckBoxCheckStyle + { TICK, CROSS, DOT, NONE; } - + protected final VectorShapeColourProperties colours; - private CheckBoxCheckStyle checkStyle; private float checkStrokeWidth; private float checkPadding; private final Vector4f checkColour; - - - public VectorCheckBox(float x, float y, float width, float height, CheckBoxCheckStyle style) { + + public VectorCheckBox(float x, float y, float width, float height, CheckBoxCheckStyle style) + { super(x, y, width, height); this.colours = new VectorShapeColourProperties(); this.checkColour = new Vector4f(1.0f, 1.0f, 1.0f, 1.0f); @@ -39,106 +35,76 @@ public VectorCheckBox(float x, float y, float width, float height, CheckBoxCheck this.checkStrokeWidth = 2f; this.checkPadding = 3f; } - - - public VectorCheckBox(float x, float y, float width, float height) { - this(x, y, width, height, CheckBoxCheckStyle.TICK); - } - - - /** - * Get the check style of the check box - * @return - */ - public CheckBoxCheckStyle getCheckStyle() { - return checkStyle; - } - - - /** - * Set the check style of the check box - * @return - */ - public void setCheckStyle(CheckBoxCheckStyle style) { - this.checkStyle = style; - } - - - /** - * Get the stroke width of the check mark - * @return - */ - public float getCheckStrokeWidth() { - return checkStrokeWidth; - } - - - /** - * Set the stroke width of the check mark - * @param checkStrokeWidth - */ - public void setCheckStrokeWidth(float checkStrokeWidth) { - this.checkStrokeWidth = checkStrokeWidth; - } - - - /** - * Get the amount of padding the check mark has from the edge of the check box - * @return - */ - public float getCheckPadding() { - return checkPadding; - } - - - /** - * Set the amount of padding the check mark has from the edge of the check box - * @param style - */ - public void setCheckPadding(float checkPadding) { - this.checkPadding = checkPadding; - } - - - /** - * Get the colour of the check mark - * @return - */ - public Vector4f getCheckColour() { - return checkColour; - } - - - /** - * Set the colour of the check mark + + public VectorCheckBox(float x, float y, float width, float height) + { this(x, y, width, height, CheckBoxCheckStyle.TICK); } + + /** Get the check style of the check box + * + * @return */ + public CheckBoxCheckStyle getCheckStyle() + { return checkStyle; } + + /** Set the check style of the check box + * + * @return */ + public void setCheckStyle(CheckBoxCheckStyle style) + { this.checkStyle = style; } + + /** Get the stroke width of the check mark + * + * @return */ + public float getCheckStrokeWidth() + { return checkStrokeWidth; } + + /** Set the stroke width of the check mark + * + * @param checkStrokeWidth */ + public void setCheckStrokeWidth(float checkStrokeWidth) + { this.checkStrokeWidth = checkStrokeWidth; } + + /** Get the amount of padding the check mark has from the edge of the check box + * + * @return */ + public float getCheckPadding() + { return checkPadding; } + + /** Set the amount of padding the check mark has from the edge of the check box + * + * @param style */ + public void setCheckPadding(float checkPadding) + { this.checkPadding = checkPadding; } + + /** Get the colour of the check mark + * + * @return */ + public Vector4f getCheckColour() + { return checkColour; } + + /** Set the colour of the check mark + * * @param r * @param g * @param b - * @param a - */ - public void setCheckColour(float r, float g, float b, float a) { + * @param a */ + public void setCheckColour(float r, float g, float b, float a) + { checkColour.x = r; checkColour.y = g; checkColour.z = b; checkColour.w = a; } - - - /** - * Set the colour of the check mark + + /** Set the colour of the check mark + * * @param r * @param g * @param b - * @param a - */ - public void setCheckColour(Vector4f colour) { - setCheckColour(colour.x, colour.y, colour.z, colour.w); - } - - - @Override - public VectorShapeColourProperties colourProperties() { - return colours; - } + * @param a */ + public void setCheckColour(Vector4f colour) + { setCheckColour(colour.x, colour.y, colour.z, colour.w); } + @Override + public VectorShapeColourProperties colourProperties() + { return colours; } } diff --git a/src/com/bwyap/engine/gui/element/vector/VectorProgressBar.java b/src/com/bwyap/engine/gui/element/vector/VectorProgressBar.java index 421eb8a..0a2f752 100644 --- a/src/com/bwyap/engine/gui/element/vector/VectorProgressBar.java +++ b/src/com/bwyap/engine/gui/element/vector/VectorProgressBar.java @@ -6,28 +6,22 @@ import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; import com.bwyap.engine.gui.interfaces.IColouredVectorShape; - -/** - * A Vector drawn progress bar. +/** A Vector drawn progress bar. * See {@link ProgressBar}. - * @author bwyap - * - */ -public abstract class VectorProgressBar extends ProgressBar implements IColouredVectorShape { - + * + * @author bwyap */ +public abstract class VectorProgressBar extends ProgressBar implements IColouredVectorShape +{ private final VectorShapeColourProperties colours; - - - public VectorProgressBar(float x, float y, float width, float height) { + + public VectorProgressBar(float x, float y, float width, float height) + { super(x, y, width, height); colours = new VectorShapeColourProperties(); colours.setColour(new Vector4f(0.0f, 0.0f, 0.0f, 1.0f)); } - - + @Override - public VectorShapeColourProperties colourProperties() { - return colours; - } - + public VectorShapeColourProperties colourProperties() + { return colours; } } diff --git a/src/com/bwyap/engine/gui/element/vector/VectorRadioButton.java b/src/com/bwyap/engine/gui/element/vector/VectorRadioButton.java index eba2df5..03c2719 100644 --- a/src/com/bwyap/engine/gui/element/vector/VectorRadioButton.java +++ b/src/com/bwyap/engine/gui/element/vector/VectorRadioButton.java @@ -6,93 +6,74 @@ import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; import com.bwyap.engine.gui.interfaces.IColouredVectorShape; - -/** - * A vector drawn radio button. +/** A vector drawn radio button. * See {@link RadioButton}. - * @author bwyap - * - */ -public abstract class VectorRadioButton extends RadioButton implements IColouredVectorShape { - + * + * @author bwyap */ +public abstract class VectorRadioButton extends RadioButton implements IColouredVectorShape +{ protected final VectorShapeColourProperties colours; - private final Vector4f checkColour; private float checkPadding; - public VectorRadioButton(String name, float x, float y, float width, float height) { + public VectorRadioButton(String name, float x, float y, float width, float height) + { super(name, x, y, width, height); this.colours = new VectorShapeColourProperties(); this.checkColour = new Vector4f(1.0f, 1.0f, 1.0f, 1.0f); this.checkPadding = 4f; } - - - public VectorRadioButton(float x, float y, float width, float height) { + + public VectorRadioButton(float x, float y, float width, float height) + { super(x, y, width, height); this.colours = new VectorShapeColourProperties(); this.checkColour = new Vector4f(1.0f, 1.0f, 1.0f, 1.0f); this.checkPadding = 4f; } - - /** - * Get the amount of padding between the check mark and the edge of the button - * @return - */ - public float getCheckPadding() { - return checkPadding; - } - - - /** - * Set the amount of padding between the check mark and the edge of the button - * @return - */ - public void setCheckPadding(float checkPadding) { - this.checkPadding = checkPadding; - } - - - /** - * Get the colour of the check mark - * @return - */ - public Vector4f getCheckColour() { - return checkColour; - } - - - /** - * Set the colour of the check mark + /** Get the amount of padding between the check mark and the edge of the button + * + * @return */ + public float getCheckPadding() + { return checkPadding; } + + /** Set the amount of padding between the check mark and the edge of the button + * + * @return */ + public void setCheckPadding(float checkPadding) + { this.checkPadding = checkPadding; } + + /** Get the colour of the check mark + * + * @return */ + public Vector4f getCheckColour() + { return checkColour; } + + /** Set the colour of the check mark + * * @param r * @param g * @param b - * @param a - */ - public void setCheckColour(float r, float g, float b, float a) { + * @param a */ + public void setCheckColour(float r, float g, float b, float a) + { checkColour.x = r; checkColour.y = g; checkColour.z = b; checkColour.w = a; } - - - /** - * Set the colour of the check mark + + /** Set the colour of the check mark + * * @param r * @param g * @param b - * @param a - */ - public void setCheckColour(Vector4f colour) { - setCheckColour(colour.x, colour.y, colour.z, colour.w); - } - - + * @param a */ + public void setCheckColour(Vector4f colour) + { setCheckColour(colour.x, colour.y, colour.z, colour.w); } + @Override - public VectorShapeColourProperties colourProperties() { - return colours; - } - + public VectorShapeColourProperties colourProperties() + { return colours; } } diff --git a/src/com/bwyap/engine/gui/element/vector/VectorScrollArea.java b/src/com/bwyap/engine/gui/element/vector/VectorScrollArea.java index 1a56d98..cf7a45f 100644 --- a/src/com/bwyap/engine/gui/element/vector/VectorScrollArea.java +++ b/src/com/bwyap/engine/gui/element/vector/VectorScrollArea.java @@ -4,26 +4,21 @@ import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; import com.bwyap.engine.gui.interfaces.IColouredVectorShape; -/** - * A scroll area with a vector drawn background. +/** A scroll area with a vector drawn background. * See {@link ScrollArea}. - * @author bwyap - * - */ -public abstract class VectorScrollArea extends ScrollArea implements IColouredVectorShape { - - protected final VectorShapeColourProperties colours; - - - public VectorScrollArea(float x, float y, float width, float height, float scrollLength, ScrollDirection scrollDirection) { + * + * @author bwyap */ +public abstract class VectorScrollArea extends ScrollArea implements IColouredVectorShape +{ + protected final VectorShapeColourProperties colours; + + public VectorScrollArea(float x, float y, float width, float height, float scrollLength, ScrollDirection scrollDirection) + { super(x, y, width, height, scrollLength, scrollDirection); this.colours = new VectorShapeColourProperties(); } - - - @Override - public VectorShapeColourProperties colourProperties() { - return colours; - } + @Override + public VectorShapeColourProperties colourProperties() + { return colours; } } diff --git a/src/com/bwyap/engine/gui/element/vector/VectorTextBox.java b/src/com/bwyap/engine/gui/element/vector/VectorTextBox.java index 5b06b20..85d3e5e 100644 --- a/src/com/bwyap/engine/gui/element/vector/VectorTextBox.java +++ b/src/com/bwyap/engine/gui/element/vector/VectorTextBox.java @@ -4,26 +4,21 @@ import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; import com.bwyap.engine.gui.interfaces.IColouredVectorShape; - -/** - * A text box with a vector drawn background. +/** A text box with a vector drawn background. * See {@link TextBox}. - * @author bwyap - * - */ -public abstract class VectorTextBox extends TextBox implements IColouredVectorShape { - + * + * @author bwyap */ +public abstract class VectorTextBox extends TextBox implements IColouredVectorShape +{ protected final VectorShapeColourProperties colours; - - public VectorTextBox(float x, float y, float width, float height, float padding) { + + public VectorTextBox(float x, float y, float width, float height, float padding) + { super(x, y, width, height, padding); this.colours = new VectorShapeColourProperties(); } - @Override - public VectorShapeColourProperties colourProperties() { - return colours; - } - + public VectorShapeColourProperties colourProperties() + { return colours; } } diff --git a/src/com/bwyap/engine/gui/element/vector/VectorTextField.java b/src/com/bwyap/engine/gui/element/vector/VectorTextField.java index 05debe5..775e8bb 100644 --- a/src/com/bwyap/engine/gui/element/vector/VectorTextField.java +++ b/src/com/bwyap/engine/gui/element/vector/VectorTextField.java @@ -4,25 +4,21 @@ import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; import com.bwyap.engine.gui.interfaces.IColouredVectorShape; -/** - * A text field with a vector drawn background. +/** A text field with a vector drawn background. * See {@link TextField}. - * @author bwyap - * - */ -public abstract class VectorTextField extends TextField implements IColouredVectorShape { + * + * @author bwyap */ +public abstract class VectorTextField extends TextField implements IColouredVectorShape +{ + protected final VectorShapeColourProperties colours; - protected final VectorShapeColourProperties colours; - - public VectorTextField(int x, int y, float width, float height) { + public VectorTextField(int x, int y, float width, float height) + { super(x, y, width, height); this.colours = new VectorShapeColourProperties(); } - - + @Override - public VectorShapeColourProperties colourProperties() { - return colours; - } - + public VectorShapeColourProperties colourProperties() + { return colours; } } diff --git a/src/com/bwyap/engine/gui/interfaces/GUIBoundsInterface.java b/src/com/bwyap/engine/gui/interfaces/GUIBoundsInterface.java index 81c430f..5b49608 100644 --- a/src/com/bwyap/engine/gui/interfaces/GUIBoundsInterface.java +++ b/src/com/bwyap/engine/gui/interfaces/GUIBoundsInterface.java @@ -2,63 +2,45 @@ import com.bwyap.engine.window.BoundsInterface; -/** - * Provides methods that a GUI element with bounds should implement. - * @author bwyap - * - */ -public interface GUIBoundsInterface extends BoundsInterface { - - - /** - * Check if a specified co-ordinate is within the bounds of this element - * @param x - * @param y - * @return - */ +/** Provides methods that a GUI element with bounds should implement. + * + * @author bwyap */ +public interface GUIBoundsInterface extends BoundsInterface +{ + /** Check if a specified co-ordinate is within the bounds of this element + * + * @param x + * @param y + * @return */ public boolean withinBounds(float x, float y); - - - /** - * Get the width of the element - * @return - */ + + /** Get the width of the element + * + * @return */ public float getWidth(); - - - /** - * Get the height of this element - * @return - */ + + /** Get the height of this element + * + * @return */ public float getHeight(); - - /** - * Get the padding amount for the top of the element - * @return - */ + /** Get the padding amount for the top of the element + * + * @return */ public float getPaddingTop(); - - - /** - * Get the padding amount for the bottom of the element - * @return - */ + + /** Get the padding amount for the bottom of the element + * + * @return */ public float getPaddingBottom(); - - - /** - * Get the padding amount for the left of the element - * @return - */ + + /** Get the padding amount for the left of the element + * + * @return */ public float getPaddingLeft(); - - - /** - * Get the padding amount for the right of the element - * @return - */ + + /** Get the padding amount for the right of the element + * + * @return */ public float getPaddingRight(); - - } diff --git a/src/com/bwyap/engine/gui/interfaces/GUIElementInterface.java b/src/com/bwyap/engine/gui/interfaces/GUIElementInterface.java index 5c14b43..893365d 100644 --- a/src/com/bwyap/engine/gui/interfaces/GUIElementInterface.java +++ b/src/com/bwyap/engine/gui/interfaces/GUIElementInterface.java @@ -5,149 +5,114 @@ import com.bwyap.engine.input.InputHandler; import com.bwyap.engine.window.BoundsInterface; - -/** - *

+/**

* Methods that all GUI elements should implement. *

*

* Uses the {@code JOML} library for Vector operations. *

- * @author bwyap - * - */ -public interface GUIElementInterface extends GUIBoundsInterface { - - - /** - * Update the GUI element - * @param timestep - */ + * + * @author bwyap */ +public interface GUIElementInterface extends GUIBoundsInterface +{ + /** Update the GUI element + * + * @param timestep */ public void update(float timestep); - - - /** - * Handle how the GUI element should respond to input. - * @param window - */ + + /** Handle how the GUI element should respond to input. + * + * @param window */ public void handleInput(InputHandler input, GUIBoundsInterface bounds); - - - /** - * Update the GUI element's position and bounds according to the bounding window. - * This method should be called before the element is rendered. - */ + + /** Update the GUI element's position and bounds according to the bounding window. + * This method should be called before the element is rendered. */ public void updateBounds(BoundsInterface window, Vector2f parent); - - - /** - * Set the absolute position of the GUI element. + + /** Set the absolute position of the GUI element. * Co-ordinates are in screen co-ordinates. + * * @param x - * @param y - */ + * @param y */ public void setPosition(float x, float y); - - - /** - * Set the absolute position of the GUI element. + + /** Set the absolute position of the GUI element. * Co-ordinates are in screen co-ordinates. + * * @param x - * @param y - */ + * @param y */ public void setPosition(Vector2f position); - - /** - * Set the padding for the panel + /** Set the padding for the panel + * * @param top * @param bottom * @param left - * @param right - */ + * @param right */ public void setPadding(float top, float bottom, float left, float right); - - - /** - * Set the bounds of this GUI element using a rectangle. + + /** Set the bounds of this GUI element using a rectangle. * By default a GUI element will use rectangular bounds * unless otherwise specified with the {@code useCircularBounds} * method. - * @param x offset from the element's x position - * @param y offset from the element's y position - * @param width width of the bounds - * @param height height of the bounds - */ + * + * @param x offset from the element's x position + * @param y offset from the element's y position + * @param width width of the bounds + * @param height height of the bounds */ public void setBounds(float x, float y, float width, float height); - - - /** - * Set the bounds of this GUI element using a rectangle. + + /** Set the bounds of this GUI element using a rectangle. * The offset of the bounds is set to (0, 0). - * @param width width of the bounds - * @param height height of the bounds - */ + * + * @param width width of the bounds + * @param height height of the bounds */ public void setBounds(float width, float height); - - - /** - * Checks if the given screen co-ordinates are within + + /** Checks if the given screen co-ordinates are within * the set bounds of this GUI element. The element could * be using rectangular bounds or circular bounds - which - * can be set using the {@code setRectangularBounds} or + * can be set using the {@code setRectangularBounds} or * {@code setCircularBounds} method. - * @param x - * @param y - * @return true if the given co-ordinates are within bounds of the GUI element - */ + * + * @param x + * @param y + * @return true if the given co-ordinates are within bounds of the GUI element */ public boolean withinBounds(float x, float y); - - - /** - * Set the GUI element to be enabled or disabled. - * @param enabled - */ + + /** Set the GUI element to be enabled or disabled. + * + * @param enabled */ public void setEnabled(boolean enabled); - - - /** - *

Check if the GUI element is currently enabled.

+ + /**

Check if the GUI element is currently enabled.

*

* A disabled GUI element cannot be activated * (It should have a different texture to indicate its state to the user). *

- * @return - */ + * + * @return */ public boolean isEnabled(); - - - /** - * Set whether the GUI element's position should be absolute. - * @param absolute - */ + + /** Set whether the GUI element's position should be absolute. + * + * @param absolute */ public void setPositionAbsolute(boolean absolute); - - - /** - * Check if the GUI element's position is absolute. + + /** Check if the GUI element's position is absolute. * Default is false. - * @return - */ + * + * @return */ public boolean isPositionAbsolute(); - - - /** - * Set whether the GUI element's scale should be absolute. - * @param absolute - */ + + /** Set whether the GUI element's scale should be absolute. + * + * @param absolute */ public void setScaleAbsolute(boolean absolute); - - - /** - * Check if the GUI element's scale is absolute. + + /** Check if the GUI element's scale is absolute. * Default is false. - * @return - */ + * + * @return */ public boolean isScaleAbsolute(); - } diff --git a/src/com/bwyap/engine/gui/interfaces/IColouredVectorShape.java b/src/com/bwyap/engine/gui/interfaces/IColouredVectorShape.java index 21def0b..998e0b3 100644 --- a/src/com/bwyap/engine/gui/interfaces/IColouredVectorShape.java +++ b/src/com/bwyap/engine/gui/interfaces/IColouredVectorShape.java @@ -2,12 +2,10 @@ import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; -public interface IColouredVectorShape extends IVectorShape { - - /** - * Gets the VectorShapeColour object for this GUI element - * @return - */ +public interface IColouredVectorShape extends IVectorShape +{ + /** Gets the VectorShapeColour object for this GUI element + * + * @return */ public VectorShapeColourProperties colourProperties(); - } diff --git a/src/com/bwyap/engine/gui/interfaces/IFade.java b/src/com/bwyap/engine/gui/interfaces/IFade.java index 7cc8f0f..33ad5e7 100644 --- a/src/com/bwyap/engine/gui/interfaces/IFade.java +++ b/src/com/bwyap/engine/gui/interfaces/IFade.java @@ -2,13 +2,10 @@ import com.bwyap.engine.gui.element.properties.Fade; -public interface IFade { - - - /** - * Get the fade property of the GUI element - * @return - */ +public interface IFade +{ + /** Get the fade property of the GUI element + * + * @return */ public Fade getFade(); - } diff --git a/src/com/bwyap/engine/gui/interfaces/ISelectable.java b/src/com/bwyap/engine/gui/interfaces/ISelectable.java index 6e418ad..09b5871 100644 --- a/src/com/bwyap/engine/gui/interfaces/ISelectable.java +++ b/src/com/bwyap/engine/gui/interfaces/ISelectable.java @@ -1,24 +1,19 @@ package com.bwyap.engine.gui.interfaces; -public interface ISelectable { - - /** - * Check whether the GUI element has been selected - * @return - */ +public interface ISelectable +{ + /** Check whether the GUI element has been selected + * + * @return */ public boolean isSelected(); - - - /** - * Set whether the GUI element is currently selectable - * @param selectable - */ + + /** Set whether the GUI element is currently selectable + * + * @param selectable */ public void setSelectable(boolean selectable); - - - /** - * Check whether he GUI element is currently selectable - * @return - */ + + /** Check whether he GUI element is currently selectable + * + * @return */ public boolean isSelectable(); } diff --git a/src/com/bwyap/engine/gui/interfaces/ITextDisplay.java b/src/com/bwyap/engine/gui/interfaces/ITextDisplay.java index 5e98f4d..946cf68 100644 --- a/src/com/bwyap/engine/gui/interfaces/ITextDisplay.java +++ b/src/com/bwyap/engine/gui/interfaces/ITextDisplay.java @@ -2,17 +2,13 @@ import com.bwyap.engine.gui.element.properties.TextComponent; -/** - * Indicates that a GUI element has text which can be displayed - * @author bwyap - * - */ -public interface ITextDisplay { - - /** - * Get the text component - * @return - */ +/** Indicates that a GUI element has text which can be displayed + * + * @author bwyap */ +public interface ITextDisplay +{ + /** Get the text component + * + * @return */ public TextComponent getTextComponent(); - } diff --git a/src/com/bwyap/engine/gui/interfaces/IVectorEllipse.java b/src/com/bwyap/engine/gui/interfaces/IVectorEllipse.java index 5ed0203..59ad91f 100644 --- a/src/com/bwyap/engine/gui/interfaces/IVectorEllipse.java +++ b/src/com/bwyap/engine/gui/interfaces/IVectorEllipse.java @@ -2,10 +2,9 @@ import com.bwyap.engine.gui.element.vector.EVectorShape; -public interface IVectorEllipse extends IVectorShape { - +public interface IVectorEllipse extends IVectorShape +{ @Override - default public EVectorShape getShape() { - return EVectorShape.ELLIPSE; - } + default public EVectorShape getShape() + { return EVectorShape.ELLIPSE; } } diff --git a/src/com/bwyap/engine/gui/interfaces/IVectorRect.java b/src/com/bwyap/engine/gui/interfaces/IVectorRect.java index fc6cb4a..88ea2b5 100644 --- a/src/com/bwyap/engine/gui/interfaces/IVectorRect.java +++ b/src/com/bwyap/engine/gui/interfaces/IVectorRect.java @@ -2,10 +2,9 @@ import com.bwyap.engine.gui.element.vector.EVectorShape; -public interface IVectorRect extends IVectorShape { - +public interface IVectorRect extends IVectorShape +{ @Override - default public EVectorShape getShape() { - return EVectorShape.RECTANGLE; - } + default public EVectorShape getShape() + { return EVectorShape.RECTANGLE; } } diff --git a/src/com/bwyap/engine/gui/interfaces/IVectorRoundedRect.java b/src/com/bwyap/engine/gui/interfaces/IVectorRoundedRect.java index 10b4707..c628ee3 100644 --- a/src/com/bwyap/engine/gui/interfaces/IVectorRoundedRect.java +++ b/src/com/bwyap/engine/gui/interfaces/IVectorRoundedRect.java @@ -2,18 +2,14 @@ import com.bwyap.engine.gui.element.vector.EVectorShape; -public interface IVectorRoundedRect extends IVectorRect { - - /** - * Get the radius of the rounded corners - * @return - */ +public interface IVectorRoundedRect extends IVectorRect +{ + /** Get the radius of the rounded corners + * + * @return */ public float getRadius(); - @Override - default public EVectorShape getShape() { - return EVectorShape.ROUNDED_RECT; - } - + default public EVectorShape getShape() + { return EVectorShape.ROUNDED_RECT; } } diff --git a/src/com/bwyap/engine/gui/interfaces/IVectorShape.java b/src/com/bwyap/engine/gui/interfaces/IVectorShape.java index 80c8c68..fcc0f81 100644 --- a/src/com/bwyap/engine/gui/interfaces/IVectorShape.java +++ b/src/com/bwyap/engine/gui/interfaces/IVectorShape.java @@ -2,19 +2,14 @@ import com.bwyap.engine.gui.element.vector.EVectorShape; -public interface IVectorShape { - - /** - * Get the shape of this Vector shaped GUI element - */ +public interface IVectorShape +{ + /** Get the shape of this Vector shaped GUI element */ public EVectorShape getShape(); - - - /** - * Check if the shape should be rendered - * @return - */ - default public boolean renderShape() { - return true; - } + + /** Check if the shape should be rendered + * + * @return */ + default public boolean renderShape() + { return true; } } diff --git a/src/com/bwyap/engine/gui/interfaces/MouseDownInterface.java b/src/com/bwyap/engine/gui/interfaces/MouseDownInterface.java index c2455da..fc81a33 100644 --- a/src/com/bwyap/engine/gui/interfaces/MouseDownInterface.java +++ b/src/com/bwyap/engine/gui/interfaces/MouseDownInterface.java @@ -1,36 +1,27 @@ package com.bwyap.engine.gui.interfaces; -public interface MouseDownInterface extends MouseOverInterface { - - - /** - * An action to perform when a specific mouse button is down over the GUI element +public interface MouseDownInterface extends MouseOverInterface +{ + /** An action to perform when a specific mouse button is down over the GUI element + * * @param x * @param y - * @param mouseButton - */ + * @param mouseButton */ public void onMouseDown(float x, float y, int mouseButton); - - - /** - * An action to perform when the GUI element is clicked by a specific mouse button + + /** An action to perform when the GUI element is clicked by a specific mouse button * (mouse down then released) + * * @param x * @param y - * @param mouseButton - */ + * @param mouseButton */ public void onMouseClicked(float x, float y, int mouseButton); - - - /** - * Checks if ANY accepted mouse button is down on the GUI element - */ + + /** Checks if ANY accepted mouse button is down on the GUI element */ public boolean isMouseDown(); - - - /** - * Checks if a specified mouse button is down on the GUI element - * @param mouseButton - */ + + /** Checks if a specified mouse button is down on the GUI element + * + * @param mouseButton */ public boolean isMouseDown(int mouseButton); } diff --git a/src/com/bwyap/engine/gui/interfaces/MouseOverInterface.java b/src/com/bwyap/engine/gui/interfaces/MouseOverInterface.java index 6f72d19..1da0e47 100644 --- a/src/com/bwyap/engine/gui/interfaces/MouseOverInterface.java +++ b/src/com/bwyap/engine/gui/interfaces/MouseOverInterface.java @@ -1,28 +1,21 @@ package com.bwyap.engine.gui.interfaces; -public interface MouseOverInterface { - - - /** - * An action to perform when the mouse is over the GUI element +public interface MouseOverInterface +{ + /** An action to perform when the mouse is over the GUI element + * * @param x - * @param y - */ + * @param y */ public void onMouseOver(float x, float y); - - - /** - * Checks if the mouse is over the GUI element - * @return - */ + + /** Checks if the mouse is over the GUI element + * + * @return */ public boolean isMouseOver(); - - - /** - * Check whether this element reacts to having the mouse over the element. + + /** Check whether this element reacts to having the mouse over the element. * The {@code onMouseClicked} method should still work when {@code mouseOverReact} is {@code false}. - * @return - */ + * + * @return */ public boolean mouseOverReact(); - } diff --git a/src/com/bwyap/engine/input/InputHandler.java b/src/com/bwyap/engine/input/InputHandler.java index cc7d598..e6c3b5f 100644 --- a/src/com/bwyap/engine/input/InputHandler.java +++ b/src/com/bwyap/engine/input/InputHandler.java @@ -1,92 +1,75 @@ package com.bwyap.engine.input; -/** - * Provides methods to poll for input through the +/** Provides methods to poll for input through the * keyboard and mouse. The actual keyboard and mouse * handlers must be updated manually and it is not * a responsibility of this class. - * @author bwyap - * - */ -public class InputHandler implements KeyboardHandlerInterface, MouseHandlerInterface{ - + * + * @author bwyap */ +public class InputHandler implements KeyboardHandlerInterface, MouseHandlerInterface +{ private KeyboardHandlerInterface keyboardHandler; private MouseHandlerInterface mouseHandler; - - - public InputHandler(KeyboardHandlerInterface keyboardHandler, MouseHandlerInterface mouseHandler) { + + public InputHandler(KeyboardHandlerInterface keyboardHandler, MouseHandlerInterface mouseHandler) + { this.keyboardHandler = keyboardHandler; this.mouseHandler = mouseHandler; } - - @Override - public boolean isKeyDown(int keycode) { - return keyboardHandler.isKeyDown(keycode); - } - + @Override - public char consumeLastTypedChar() { - return keyboardHandler.consumeLastTypedChar(); - } - + public boolean isKeyDown(int keycode) + { return keyboardHandler.isKeyDown(keycode); } + @Override - public boolean isMouseDown(int mouseButton) { - return mouseHandler.isMouseDown(mouseButton); - } + public char consumeLastTypedChar() + { return keyboardHandler.consumeLastTypedChar(); } @Override - public boolean isMouseDown() { - return mouseHandler.isMouseDown(); - } + public boolean isMouseDown(int mouseButton) + { return mouseHandler.isMouseDown(mouseButton); } @Override - public double getMouseX() { - return mouseHandler.getMouseX(); - } + public boolean isMouseDown() + { return mouseHandler.isMouseDown(); } @Override - public double getMouseY() { - return mouseHandler.getMouseY(); - } + public double getMouseX() + { return mouseHandler.getMouseX(); } @Override - public boolean isMouseEntered() { - return mouseHandler.isMouseEntered(); - } + public double getMouseY() + { return mouseHandler.getMouseY(); } @Override - public double getMouseScrollX() { - return mouseHandler.getMouseScrollX(); - } + public boolean isMouseEntered() + { return mouseHandler.isMouseEntered(); } @Override - public double consumeMouseScrollX() { - return mouseHandler.consumeMouseScrollX(); - } - + public double getMouseScrollX() + { return mouseHandler.getMouseScrollX(); } + @Override - public double getMouseScrollY() { - return mouseHandler.getMouseScrollY(); - } + public double consumeMouseScrollX() + { return mouseHandler.consumeMouseScrollX(); } @Override - public double consumeMouseScrollY() { - return mouseHandler.consumeMouseScrollY(); - } + public double getMouseScrollY() + { return mouseHandler.getMouseScrollY(); } @Override - public double getLastMouseScrollTime() { - return mouseHandler.getLastMouseScrollTime(); - } + public double consumeMouseScrollY() + { return mouseHandler.consumeMouseScrollY(); } @Override - public int getKeyMods() { - return keyboardHandler.getKeyMods(); - } + public double getLastMouseScrollTime() + { return mouseHandler.getLastMouseScrollTime(); } @Override - public int getKeysDown() { - return keyboardHandler.getKeysDown(); - } + public int getKeyMods() + { return keyboardHandler.getKeyMods(); } + @Override + public int getKeysDown() + { return keyboardHandler.getKeysDown(); } } diff --git a/src/com/bwyap/engine/input/InputMapping.java b/src/com/bwyap/engine/input/InputMapping.java index 9472f06..3691827 100644 --- a/src/com/bwyap/engine/input/InputMapping.java +++ b/src/com/bwyap/engine/input/InputMapping.java @@ -7,75 +7,62 @@ import com.bwyap.utility.resource.JSONWrapper; - -/** - * Provides a configurable mapping of user inputs loaded from an external JSON file - * @author bwyap - * - */ -public final class InputMapping extends JSONWrapper{ - - +/** Provides a configurable mapping of user inputs loaded from an external JSON file + * + * @author bwyap */ +public final class InputMapping extends JSONWrapper +{ private final Map inputMapping; - - - public InputMapping(JSONObject object) { + + public InputMapping(JSONObject object) + { super(object); inputMapping = new HashMap(); - - if (isValid()) { + if (isValid()) + { JSONObject mouseBindings = ((JSONObject) object.get("mouse")); - - for (Object key : mouseBindings.keySet()) { - setBinding(key.toString(), Integer.parseInt(String.valueOf(mouseBindings.get(key.toString())))); - } + for (Object key : mouseBindings.keySet()) + { setBinding(key.toString(), Integer.parseInt(String.valueOf(mouseBindings.get(key.toString())))); } } } - - - /** - * Get the map of input bindings - * @return - */ + + /** Get the map of input bindings + * + * @return */ @SuppressWarnings("unchecked") - public Map getBindings() { - return (Map) object; - } - - - /** - * Get the value of the specified binding. - * @param name - * @return - */ - public int getBinding(String name) { + public Map getBindings() + { return (Map) object; } + + /** Get the value of the specified binding. + * + * @param name + * @return */ + public int getBinding(String name) + { if (inputMapping.get(name) == null) return 0; return inputMapping.get(name); } - - - /** - * Set the value of the specified binding + + /** Set the value of the specified binding + * * @param bindingName - * @param value - */ - public void setBinding(String bindingName, int value) { - inputMapping.put(bindingName, value); - } - - + * @param value */ + public void setBinding(String bindingName, int value) + { inputMapping.put(bindingName, value); } + @Override - public boolean isValid() { - try { - if (Integer.parseInt(((JSONObject)object.get("mouse")).get("mouse_left").toString()) < 0) throw new Exception("Invalid mouse_left value"); - if (Integer.parseInt(((JSONObject)object.get("mouse")).get("mouse_right").toString()) < 0) throw new Exception("Invalid mouse_right value"); + public boolean isValid() + { + try + { + if (Integer.parseInt(((JSONObject) object.get("mouse")).get("mouse_left").toString()) < 0) throw new Exception("Invalid mouse_left value"); + if (Integer.parseInt(((JSONObject) object.get("mouse")).get("mouse_right").toString()) < 0) throw new Exception("Invalid mouse_right value"); } - catch (Exception e) { + catch (Exception e) + { e.printStackTrace(System.out); return false; } return true; } - - } diff --git a/src/com/bwyap/engine/input/KeyboardHandlerInterface.java b/src/com/bwyap/engine/input/KeyboardHandlerInterface.java index 71cda6c..b277fe4 100644 --- a/src/com/bwyap/engine/input/KeyboardHandlerInterface.java +++ b/src/com/bwyap/engine/input/KeyboardHandlerInterface.java @@ -1,38 +1,28 @@ package com.bwyap.engine.input; -/** - * Methods for polling a KeyboardHandler. - * @author bwyap - * - */ -public interface KeyboardHandlerInterface { - - /** - * Check if a key is down - * @param keycode - * @return - */ +/** Methods for polling a KeyboardHandler. + * + * @author bwyap */ +public interface KeyboardHandlerInterface +{ + /** Check if a key is down + * + * @param keycode + * @return */ public boolean isKeyDown(int keycode); - - - /** - * Get the integer representing which mod keys are active. - * @return - */ + + /** Get the integer representing which mod keys are active. + * + * @return */ public int getKeyMods(); - - /** - * Gets the number of keys that are down (pressed) at the moment. - * @return - */ + /** Gets the number of keys that are down (pressed) at the moment. + * + * @return */ public int getKeysDown(); - - - /** - * Gets the last typed character from the keyboard - * @return - */ + + /** Gets the last typed character from the keyboard + * + * @return */ public char consumeLastTypedChar(); - } diff --git a/src/com/bwyap/engine/input/MouseHandlerInterface.java b/src/com/bwyap/engine/input/MouseHandlerInterface.java index cd52075..ba831e0 100644 --- a/src/com/bwyap/engine/input/MouseHandlerInterface.java +++ b/src/com/bwyap/engine/input/MouseHandlerInterface.java @@ -1,74 +1,61 @@ package com.bwyap.engine.input; -/** - * Methods for polling a MouseHandler. - * @author bwyap - * - */ -public interface MouseHandlerInterface { - - /** - * Checks if the specified mouse button is pressed. - * @param mouseButton - * @return - */ +/** Methods for polling a MouseHandler. + * + * @author bwyap */ +public interface MouseHandlerInterface +{ + /** Checks if the specified mouse button is pressed. + * + * @param mouseButton + * @return */ public boolean isMouseDown(int mouseButton); - - /** - * Checks if any mouse button is pressed. - * @param mouseButton - * @return - */ + + /** Checks if any mouse button is pressed. + * + * @param mouseButton + * @return */ public boolean isMouseDown(); - - /** - * Gets the x position of the mouse - * @return - */ + + /** Gets the x position of the mouse + * + * @return */ public double getMouseX(); - - /** - * Gets the y position of the mouse - * @return - */ + + /** Gets the y position of the mouse + * + * @return */ public double getMouseY(); - - /** - * Checks if the cursor's position is within the window - * @return - */ + + /** Checks if the cursor's position is within the window + * + * @return */ public boolean isMouseEntered(); - - /** - * Gets the mouse scroll x value - * @return - */ + + /** Gets the mouse scroll x value + * + * @return */ public double getMouseScrollX(); - /** - * Gets the mouse scroll x value + /** Gets the mouse scroll x value * and resets it to 0 - * @return - */ + * + * @return */ public double consumeMouseScrollX(); - - /** - * Gets the mouse scroll y value - * @return - */ + + /** Gets the mouse scroll y value + * + * @return */ public double getMouseScrollY(); - - /** - * Gets the mouse scroll y value + + /** Gets the mouse scroll y value * and resets it to 0 - * @return - */ + * + * @return */ public double consumeMouseScrollY(); - - /** - * Get the last time a mouse scroll was invoked - * @return - */ + + /** Get the last time a mouse scroll was invoked + * + * @return */ public double getLastMouseScrollTime(); - } diff --git a/src/com/bwyap/engine/particle/Particle.java b/src/com/bwyap/engine/particle/Particle.java index 11ab7c4..6eb59e7 100644 --- a/src/com/bwyap/engine/particle/Particle.java +++ b/src/com/bwyap/engine/particle/Particle.java @@ -4,28 +4,26 @@ import com.bwyap.engine.render3d.entity.Entity; -/** - * Holds information about the state of a single particle. - * @author bwyap - * - */ -public abstract class Particle extends Entity { - +/** Holds information about the state of a single particle. + * + * @author bwyap */ +public abstract class Particle extends Entity +{ protected boolean alive; protected Vector3f colour; protected float radius; protected float timeCreated; protected float lifetime; - - - protected Particle(float timeCreated, float lifetime) { + + protected Particle(float timeCreated, float lifetime) + { this.timeCreated = timeCreated; this.lifetime = lifetime; this.alive = true; } - - - public Particle(Particle particle) { + + public Particle(Particle particle) + { this(particle.timeCreated, particle.lifetime); setPosition(particle.getPosition()); setVelocity(particle.getVelocity()); @@ -33,94 +31,76 @@ public Particle(Particle particle) { this.radius = particle.radius; this.alive = true; } - - /** - * Kill the particle - */ - public void kill() { - alive = false; - } - - /** - * Check if the particle is alive - * @return - */ - public boolean isAlive() { - return alive; - } - - /** - * Update the state of the particle. + + /** Kill the particle */ + public void kill() + { alive = false; } + + /** Check if the particle is alive + * + * @return */ + public boolean isAlive() + { return alive; } + + /** Update the state of the particle. * Any physics that should be applied to the particle should be implemented here. - * @param timestep - */ + * + * @param timestep */ public abstract void update(float timestep); - - /** - * Get the texture position of the particle, which should always be 0. - * @return - */ + + /** Get the texture position of the particle, which should always be 0. + * + * @return */ @Deprecated - public int getTexturePosition() { - return 0; - } - - /** - * Set the colour of the particle - * @param colour - */ - public void setColour(Vector3f colour) { - this.colour = colour; - } - - /** - * Get the colour of the particle - * @return - */ - public Vector3f getColour() { - return colour; - } - - /** - * Set the radius of the particle - * @param radius - */ - public void setRadius(float radius) { + public int getTexturePosition() + { return 0; } + + /** Set the colour of the particle + * + * @param colour */ + public void setColour(Vector3f colour) + { this.colour = colour; } + + /** Get the colour of the particle + * + * @return */ + public Vector3f getColour() + { return colour; } + + /** Set the radius of the particle + * + * @param radius */ + public void setRadius(float radius) + { this.radius = radius; this.setScale(radius); } - - /** - * Get the radius of the particle - * @return - */ - public float getRadius() { - return radius; - } - - /** - * Get the time at which the particle was created - * @return - */ - public float getTimeCreated() { - return timeCreated; - } - - /** - * Get the lifetime of the particle - * @return - */ - public float getLifetime() { - return lifetime; - } - - /** - * Reset the particle to be reused. + + /** Get the radius of the particle + * + * @return */ + public float getRadius() + { return radius; } + + /** Get the time at which the particle was created + * + * @return */ + public float getTimeCreated() + { return timeCreated; } + + /** Get the lifetime of the particle + * + * @return */ + public float getLifetime() + { return lifetime; } + + /** Reset the particle to be reused. * Assigns a new time of creation and lifetime to the particle. + * * @param timeCreated - * @param lifetime - */ - public void reset(float timeCreated, float lifetime, Vector3f position, float radius, Vector3f colour) { + * @param lifetime */ + public void reset(float timeCreated, float lifetime, Vector3f position, float radius, Vector3f colour) + { this.timeCreated = timeCreated; this.lifetime = lifetime; this.alive = true; diff --git a/src/com/bwyap/engine/particle/ParticleSystemLogic.java b/src/com/bwyap/engine/particle/ParticleSystemLogic.java index 2fec5fe..ba974f5 100644 --- a/src/com/bwyap/engine/particle/ParticleSystemLogic.java +++ b/src/com/bwyap/engine/particle/ParticleSystemLogic.java @@ -8,158 +8,142 @@ import org.joml.Quaternionf; import org.joml.Vector3f; - -/** - * An abstract class that contains the logic behind +/** An abstract class that contains the logic behind * a particle system. This needs to be extended to - * implement how the particles in this system should + * implement how the particles in this system should * be rendered. - * @author bwyap - * - * @param the particle type - */ -public abstract class ParticleSystemLogic { - + * + * @author bwyap + * @param the particle type */ +public abstract class ParticleSystemLogic +{ protected static final Random rand = new Random(); - protected boolean active; protected List activeParticles; protected List freeParticles; protected List colours; - protected int maxParticles; protected int numberToRelease; protected float releaseInterval; protected float particleLifetimeMin, particleLifetimeMax; protected float particleRadiusMin, particleRadiusMax; protected float lastUpdate, currentTime; - protected float emitRadius; protected Vector3f emitBoxBounds; - protected Vector3f position; protected Vector3f baseVelocity; protected float velocityDirectionVariance; protected float speedVariance; - - - public ParticleSystemLogic(int maxParticles, int numberToRelease, float releaseInterval) throws Exception { + + public ParticleSystemLogic(int maxParticles, int numberToRelease, float releaseInterval) throws Exception + { this.position = new Vector3f(0, 0, 0); this.maxParticles = maxParticles; this.numberToRelease = numberToRelease; this.releaseInterval = releaseInterval; this.baseVelocity = new Vector3f(0, 0, 0); - colours = new ArrayList(); activeParticles = new LinkedList(); freeParticles = new LinkedList(); } - - /** - * Update the particles in this particle system. - * @param timestep - */ - public final void update(float timestep) { + /** Update the particles in this particle system. + * + * @param timestep */ + public final void update(float timestep) + { currentTime += timestep; - // Update existing particles - for (int i = 0; i < activeParticles.size(); i++) { + for (int i = 0; i < activeParticles.size(); i++) + { updateParticle(activeParticles.get(i), currentTime, timestep); - // Remove any dead particles - if (!activeParticles.get(i).isAlive()) { - freeParticles.add(activeParticles.remove(i)); - } + if (!activeParticles.get(i).isAlive()) + { freeParticles.add(activeParticles.remove(i)); } } - // Check if it is time to release new particles - if (active && currentTime - lastUpdate >= releaseInterval) { + if (active && currentTime - lastUpdate >= releaseInterval) + { lastUpdate = currentTime; - - for(int i = 0; i < numberToRelease; i++) { + for (int i = 0; i < numberToRelease; i++) + { // Found a free particle to recycle - if (freeParticles.size() > 0) { + if (freeParticles.size() > 0) + { T p = freeParticles.remove(0); - p.reset(currentTime, - (rand.nextFloat() * (particleLifetimeMax - particleLifetimeMin)) + particleLifetimeMin, - generateStartPosition(), - generateRadius(), - generateColour()); + p.reset(currentTime, + (rand.nextFloat() * (particleLifetimeMax - particleLifetimeMin)) + particleLifetimeMin, + generateStartPosition(), + generateRadius(), + generateColour()); activeParticles.add(p); } // No free particles - create a new one if maxParticles hasn't been reached - else if (activeParticles.size() < maxParticles) { + else if (activeParticles.size() < maxParticles) + { T p = generateNewParticle(currentTime); activeParticles.add(p); } } - } + } } - - /** - * Update the state of a particle and removes any particles that have died. + /** Update the state of a particle and removes any particles that have died. + * * @param particle - * @param timestep - */ - protected void updateParticle(T particle, float currentTime, float timestep) { + * @param timestep */ + protected void updateParticle(T particle, float currentTime, float timestep) + { particle.update(timestep); - - if (particle.getLifetime() <= currentTime - particle.getTimeCreated()) { + if (particle.getLifetime() <= currentTime - particle.getTimeCreated()) + { // Particle needs to be killed particle.kill(); } } - - /** - * Generate a new particle for the system. + /** Generate a new particle for the system. * The particle will be assigned with the properties as prescribed by this system. - * @return - */ + * + * @return */ protected abstract T generateNewParticle(float now); - - /** - * Gets a position for a new particle to spawn. + /** Gets a position for a new particle to spawn. * If emit box bounds are set, a random position within the bounding box will be generated. - * Otherwise, if an emit radius has been set (a value > 0.0f) a random position within + * Otherwise, if an emit radius has been set (a value > 0.0f) a random position within * a bounding sphere with that radius will be generated. * Otherwise, the position of the system will be returned. - * @return - */ - protected Vector3f generateStartPosition() { - if (emitBoxBounds != null) { + * + * @return */ + protected Vector3f generateStartPosition() + { + if (emitBoxBounds != null) + { //Get a position within the emit box bounds //TODO } - else if (emitRadius > 0.0f) { + else if (emitRadius > 0.0f) + { float xAngle, yAngle, zAngle; - xAngle = (rand.nextFloat() * 2 * (float)Math.PI); - yAngle = (rand.nextFloat() * 2 * (float)Math.PI); - zAngle = (rand.nextFloat() * 2 * (float)Math.PI); - + xAngle = (rand.nextFloat() * 2 * (float) Math.PI); + yAngle = (rand.nextFloat() * 2 * (float) Math.PI); + zAngle = (rand.nextFloat() * 2 * (float) Math.PI); Vector3f pos = new Vector3f(rand.nextFloat() * (rand.nextInt(3) - 1), rand.nextFloat() * (rand.nextInt(3) - 1), rand.nextFloat() * (rand.nextInt(3) - 1)); Quaternionf rotation = new Quaternionf(); rotation.rotateXYZ(xAngle, yAngle, zAngle); pos.rotate(rotation); pos.normalize().mul(rand.nextFloat() * emitRadius); - return pos.add(position); } - // No emit bounds set return position; } - - - /** - * Generate a velocity for a new particle to have. + + /** Generate a velocity for a new particle to have. *

- * If a velocity variance has been set (a value > 0.0f) a + * If a velocity variance has been set (a value > 0.0f) a * slightly varied baseVelocity vector will be returned. - * The direction of the returned vector will depend on + * The direction of the returned vector will depend on * the magnitude of the velocityDirectionVariance. *

*

@@ -167,193 +151,165 @@ else if (emitRadius > 0.0f) { * {@code speedVariance}. The value by default is 0 which * will result in no speed variation. A value less than 1.0f * will generate a speed slower than the base velocity, - * while values higher than 1.0f will generate a speed + * while values higher than 1.0f will generate a speed * that is between {@code speedVariance/2} to {@code speedVariance} * times faster than the base velocity speed. - *

- * @return - */ - protected Vector3f generateStartVelocity() { - if (velocityDirectionVariance > 0.0f && baseVelocity.length() > 0) { + *

+ * + * @return */ + protected Vector3f generateStartVelocity() + { + if (velocityDirectionVariance > 0.0f && baseVelocity.length() > 0) + { float xAngle, yAngle, zAngle; - xAngle = (rand.nextFloat() * velocityDirectionVariance) - (velocityDirectionVariance/2); - yAngle = (rand.nextFloat() * velocityDirectionVariance) - (velocityDirectionVariance/2); - zAngle = (rand.nextFloat() * velocityDirectionVariance) - (velocityDirectionVariance/2); - + xAngle = (rand.nextFloat() * velocityDirectionVariance) - (velocityDirectionVariance / 2); + yAngle = (rand.nextFloat() * velocityDirectionVariance) - (velocityDirectionVariance / 2); + zAngle = (rand.nextFloat() * velocityDirectionVariance) - (velocityDirectionVariance / 2); Vector3f velocity = new Vector3f(baseVelocity); Quaternionf rotation = new Quaternionf(); rotation.rotateXYZ(xAngle, yAngle, zAngle); velocity.rotate(rotation); - float speed = baseVelocity.length() * (speedVariance > 0 ? ((speedVariance/2) * rand.nextFloat()) + (speedVariance/2) : 1) ; + float speed = baseVelocity.length() * (speedVariance > 0 ? ((speedVariance / 2) * rand.nextFloat()) + (speedVariance / 2) : 1); return velocity.normalize().mul(speed); } else return baseVelocity; } - - - /** - * Generate a colour for a new particle. + + /** Generate a colour for a new particle. * If no colours have been added, a default colour will be returned. - * @return - */ - protected Vector3f generateColour() { - if (colours.size() == 0) + * + * @return */ + protected Vector3f generateColour() + { + if (colours.size() == 0) return new Vector3f(0.8f, 0.8f, 0.8f); - else + else return colours.get(rand.nextInt(colours.size())); } - - - /** - * Generates a radius for a new particle. - * @return - */ - protected float generateRadius() { - return (rand.nextFloat() * (particleRadiusMax - particleRadiusMin)) + particleRadiusMin; - } - - - /** - * Specify a bounding box within which to emit new particles. + + /** Generates a radius for a new particle. + * + * @return */ + protected float generateRadius() + { return (rand.nextFloat() * (particleRadiusMax - particleRadiusMin)) + particleRadiusMin; } + + /** Specify a bounding box within which to emit new particles. * Centered at the particle system's position. * (EmitBoxBounds take precedence) - * @param boxBounds - */ - public void setEmitBoxBounds(float width, float height) { + * + * @param boxBounds */ + public void setEmitBoxBounds(float width, float height) + { //TODO // } - - - /** - * Set the radius of the sphere within which to emit new particles. + + /** Set the radius of the sphere within which to emit new particles. * Centered at the particle system's position. * (EmitBoxBounds take precedence) - * @param radius - */ - public void setEmitRadius(float radius) { - this.emitRadius = radius; - } - - /** - * Check if the particle system is active and releasing particles - * @return - */ - public boolean isActive() { - return active; - } - - /** - * Set whether the particle system is active - * @param active - */ - public void setActive(boolean active) { + * + * @param radius */ + public void setEmitRadius(float radius) + { this.emitRadius = radius; } + + /** Check if the particle system is active and releasing particles + * + * @return */ + public boolean isActive() + { return active; } + + /** Set whether the particle system is active + * + * @param active */ + public void setActive(boolean active) + { this.active = active; if (!active) currentTime = 0; } - - /** - * Set the position of the particle system - * @param position - */ - public void setPosition(Vector3f position) { - this.position = position; - } - - /** - * Move the position of the particle system + + /** Set the position of the particle system + * + * @param position */ + public void setPosition(Vector3f position) + { this.position = position; } + + /** Move the position of the particle system + * * @param xOffset * @param yOffset - * @param zOffset - */ - public void movePosition(float xOffset, float yOffset, float zOffset) { + * @param zOffset */ + public void movePosition(float xOffset, float yOffset, float zOffset) + { this.position.x += xOffset; this.position.y += yOffset; this.position.z += zOffset; } - - /** - * Get the position of the particle system - * @return - */ - public Vector3f getPosition() { - return position; - } - - /** - * Set the base velocity of particles emitted from this system. - * @param velocity - */ - public void setBaseVelocity(Vector3f velocity) { - this.baseVelocity = velocity; - } - - /** - * Set the particle radius bounds. + + /** Get the position of the particle system + * + * @return */ + public Vector3f getPosition() + { return position; } + + /** Set the base velocity of particles emitted from this system. + * + * @param velocity */ + public void setBaseVelocity(Vector3f velocity) + { this.baseVelocity = velocity; } + + /** Set the particle radius bounds. + * * @param radius - * @param variance - */ - public void setParticleRadius(float radius, float variance) { - particleRadiusMin = radius - variance/2; - particleRadiusMax = radius + variance/2; - } - - /** - * Set the minimum particle radius. - * @param min - */ - public void setParticleRadiusMin(float min) { - particleRadiusMin = min; + * @param variance */ + public void setParticleRadius(float radius, float variance) + { + particleRadiusMin = radius - variance / 2; + particleRadiusMax = radius + variance / 2; } - - /** - * Set the maximum particle radius. - * @param max - */ - public void setParticleRadiusMax(float max) { - particleRadiusMax = max; - } - - /** - * Set the particle lifetime bounds. + + /** Set the minimum particle radius. + * + * @param min */ + public void setParticleRadiusMin(float min) + { particleRadiusMin = min; } + + /** Set the maximum particle radius. + * + * @param max */ + public void setParticleRadiusMax(float max) + { particleRadiusMax = max; } + + /** Set the particle lifetime bounds. + * * @param lifetime - * @param variance - */ - public void setParticleLifetime(float lifetime, float variance) { - particleLifetimeMin = lifetime - variance/2; - particleLifetimeMax = lifetime + variance/2; - } - - /** - * Set the minimum particle lifetime. - * @param min - */ - public void setParticleLifetimeMin(float min) { - particleLifetimeMin = min; - } - - /** - * Set the maximum particle lifetime. - * @param max - */ - public void setParticleLifetimeMax(float max) { - particleLifetimeMax = max; - } - - /** - * Set the velocity direction variance when generating a new particle. - * @param variance - */ - public void setVelocityDirectionVariance(float variance) { - this.velocityDirectionVariance = variance; - } - - /** - * Set the speed variance when generating a new particle. - * @param speed - */ - public void setSpeedVariance(float speed) { - this.speedVariance = speed; + * @param variance */ + public void setParticleLifetime(float lifetime, float variance) + { + particleLifetimeMin = lifetime - variance / 2; + particleLifetimeMax = lifetime + variance / 2; } + /** Set the minimum particle lifetime. + * + * @param min */ + public void setParticleLifetimeMin(float min) + { particleLifetimeMin = min; } + + /** Set the maximum particle lifetime. + * + * @param max */ + public void setParticleLifetimeMax(float max) + { particleLifetimeMax = max; } + + /** Set the velocity direction variance when generating a new particle. + * + * @param variance */ + public void setVelocityDirectionVariance(float variance) + { this.velocityDirectionVariance = variance; } + + /** Set the speed variance when generating a new particle. + * + * @param speed */ + public void setSpeedVariance(float speed) + { this.speedVariance = speed; } } diff --git a/src/com/bwyap/engine/render/Texture.java b/src/com/bwyap/engine/render/Texture.java index e5ca9d0..2bae277 100644 --- a/src/com/bwyap/engine/render/Texture.java +++ b/src/com/bwyap/engine/render/Texture.java @@ -1,62 +1,48 @@ package com.bwyap.engine.render; -/** - *

- * An abstract Texture object that holds the ID a loaded texture. - * A texture can also be used as a texture atlas if its rows and - * columns are set in the constructor (by default it has a row - * and col count of 1, which means the texture is not animated). +/**

+ * An abstract Texture object that holds the ID a loaded texture. + * A texture can also be used as a texture atlas if its rows and + * columns are set in the constructor (by default it has a row + * and col count of 1, which means the texture is not animated). *

- * @author bwyap - * - */ -public abstract class Texture { - + * + * @author bwyap */ +public abstract class Texture +{ protected final int textureID; - - protected int rows; protected int cols; - - public Texture(int textureID) { + public Texture(int textureID) + { this.textureID = textureID; this.rows = 1; this.cols = 1; } - - - public Texture(int textureID, int rows, int cols) { + + public Texture(int textureID, int rows, int cols) + { this.textureID = textureID; this.rows = rows; this.cols = cols; } - - - /** - * Get the ID of the texture - * @return - */ - public int getID() { - return textureID; - } - - - /** - * Get the number of rows this texture has if it is a texture atlas. - * @return - */ - public int getRows() { - return rows; - } - - - /** - * Get the number of columns this texture has if it is a texture atlas. - * @return - */ - public int getCols() { - return cols; - } - + + /** Get the ID of the texture + * + * @return */ + public int getID() + { return textureID; } + + /** Get the number of rows this texture has if it is a texture atlas. + * + * @return */ + public int getRows() + { return rows; } + + /** Get the number of columns this texture has if it is a texture atlas. + * + * @return */ + public int getCols() + { return cols; } } diff --git a/src/com/bwyap/engine/render3d/Camera.java b/src/com/bwyap/engine/render3d/Camera.java index e57584c..fe2ad85 100644 --- a/src/com/bwyap/engine/render3d/Camera.java +++ b/src/com/bwyap/engine/render3d/Camera.java @@ -2,9 +2,7 @@ import org.joml.Vector3f; - -/** - *

+/**

* The camera is responsible for holding information which determines the point of view * from which the user will see the world and the objects within it. *

@@ -13,24 +11,20 @@ * which will be used to create the appropriate matrices to transform the objects * in the world. *

- * @author bwyap - * - */ -public class Camera { - + * + * @author bwyap */ +public class Camera +{ public static final float DEFAULT_FOV = (float) Math.toRadians(60.0f); public static final float DEFAULT_Z_NEAR = 0.01f; public static final float DEFAULT_Z_FAR = 1000.f; - - private boolean dirty; - private final Vector3f position; private final Vector3f rotation; private float zNear, zFar, FOV, aspectRatio; - - - public Camera(float zNear, float zFar, float FOV, float aspectRatio) { + + public Camera(float zNear, float zFar, float FOV, float aspectRatio) + { position = new Vector3f(0, 0, 0); rotation = new Vector3f(0, 0, 0); this.zNear = zNear; @@ -39,9 +33,9 @@ public Camera(float zNear, float zFar, float FOV, float aspectRatio) { this.aspectRatio = aspectRatio; this.dirty = true; } - - - public Camera(Vector3f position, Vector3f rotation, float zNear, float zFar, float FOV, float aspectRatio) { + + public Camera(Vector3f position, Vector3f rotation, float zNear, float zFar, float FOV, float aspectRatio) + { this.position = position; this.rotation = rotation; this.zNear = zNear; @@ -50,128 +44,103 @@ public Camera(Vector3f position, Vector3f rotation, float zNear, float zFar, flo this.aspectRatio = aspectRatio; this.dirty = true; } - - - public void update(float timestep) { - - } - - - /** - * Check if the camera's view has changed since its last update. - * @return - */ - public boolean isDirty() { - return dirty; - } - - - /** - * Set the camera's dirty setting. This should be set to true if the camera's view has changed. - * @param dirty - */ - public void setDirty(boolean dirty) { - this.dirty = dirty; - } - - - /** - * Get the position of the camera - * @return - */ - public Vector3f getPosition() { - return position; - } - - - /** - * Set the camera's position + + public void update(float timestep) + {} + + /** Check if the camera's view has changed since its last update. + * + * @return */ + public boolean isDirty() + { return dirty; } + + /** Set the camera's dirty setting. This should be set to true if the camera's view has changed. + * + * @param dirty */ + public void setDirty(boolean dirty) + { this.dirty = dirty; } + + /** Get the position of the camera + * + * @return */ + public Vector3f getPosition() + { return position; } + + /** Set the camera's position + * * @param x * @param y - * @param z - */ - public void setPosition(float x, float y, float z) { + * @param z */ + public void setPosition(float x, float y, float z) + { position.x = x; position.y = y; position.z = z; dirty = true; } - - - /** - * Move the camera's position in the direction it is pointed + + /** Move the camera's position in the direction it is pointed + * * @param xOffset * @param yOffset - * @param zOffset - */ - public void movePosition(float xOffset, float yOffset, float zOffset) { - if (zOffset != 0) { + * @param zOffset */ + public void movePosition(float xOffset, float yOffset, float zOffset) + { + if (zOffset != 0) + { position.x += (float) Math.sin(Math.toRadians(rotation.y)) * -1.0f * zOffset; position.z += (float) Math.cos(Math.toRadians(rotation.y)) * zOffset; } - - if (xOffset != 0) { + if (xOffset != 0) + { position.x += (float) Math.sin(Math.toRadians(rotation.y - 90)) * -1.0f * xOffset; position.z += (float) Math.cos(Math.toRadians(rotation.y - 90)) * xOffset; } - position.y += yOffset; - dirty = true; } - - - /** - * Get the rotation of the camera - * @return - */ - public Vector3f getRotation() { - return rotation; - } - - - /** - * Set the rotation of the camera + + /** Get the rotation of the camera + * + * @return */ + public Vector3f getRotation() + { return rotation; } + + /** Set the rotation of the camera + * * @param x * @param y - * @param z - */ - public void setRotation(float x, float y, float z) { + * @param z */ + public void setRotation(float x, float y, float z) + { rotation.x = x; rotation.y = y; rotation.z = z; dirty = true; } - - - /** - * Move the rotation of the camera + + /** Move the rotation of the camera + * * @param xOffset * @param yOffset - * @param zOffset - */ - public void moveRotation(float xOffset, float yOffset, float zOffset) { + * @param zOffset */ + public void moveRotation(float xOffset, float yOffset, float zOffset) + { rotation.x += xOffset; rotation.y += yOffset; rotation.z += zOffset; dirty = true; } - - - public float getFOV() { - return FOV; - } - - public float getZNear() { - return zNear; - } - - public float getZFar() { - return zFar; - } - - public float getAspectRatio() { - return aspectRatio; - } - + + public float getFOV() + { return FOV; } + + public float getZNear() + { return zNear; } + + public float getZFar() + { return zFar; } + + public float getAspectRatio() + { return aspectRatio; } } diff --git a/src/com/bwyap/engine/render3d/Renderer3D.java b/src/com/bwyap/engine/render3d/Renderer3D.java index f4e3768..381ba7d 100644 --- a/src/com/bwyap/engine/render3d/Renderer3D.java +++ b/src/com/bwyap/engine/render3d/Renderer3D.java @@ -2,81 +2,59 @@ import com.bwyap.engine.window.WindowInterface; - -/** - * An abstract 3D renderer class which sets up the view and projection - * matrices for rendering a 3D scene. The actual methods required to +/** An abstract 3D renderer class which sets up the view and projection + * matrices for rendering a 3D scene. The actual methods required to * render the scene using a rendering library must be implemented by * extending this class. - * @author bwyap - * - */ -public abstract class Renderer3D { - + * + * @author bwyap */ +public abstract class Renderer3D +{ public final Transformation transform; - - - public Renderer3D() { - this.transform = new Transformation(); - } - - - /** - * Set up the view and projection matrices required to render a scene + + public Renderer3D() + { this.transform = new Transformation(); } + + /** Set up the view and projection matrices required to render a scene + * * @param window - * @param camera - */ - public void startRender3D(WindowInterface window, Camera camera) { - if (window.isResized()) { + * @param camera */ + public void startRender3D(WindowInterface window, Camera camera) + { + if (window.isResized()) + { window.setResized(false); camera.setDirty(true); } - // Camera's view has changed. Update the view and projection matrices - if (camera.isDirty()) { + if (camera.isDirty()) + { camera.setDirty(false); - // Update the projection matrix transform.updateProjectionMatrix(camera.getFOV(), window.getWidth(), window.getHeight(), camera.getZNear(), camera.getZFar()); - // Update view Matrix transform.updateViewMatrix(camera); } - startRender3D(); } - - - /** - * Prepare implementation specific resources to render a 3D scene. - * The view and projection matrices are automatically updated. - */ + + /** Prepare implementation specific resources to render a 3D scene. + * The view and projection matrices are automatically updated. */ public abstract void startRender3D(); - - - /** - * Render a scene to the screen. - * @param scene - */ - public final void renderScene(Scene scene) { - scene.renderLayers(this, transform.getProjectionMatrix(), transform.getViewMatrix()); - } - - - /** - * Set the rendering system to 2D ortho projection to render a GUI. - */ + + /** Render a scene to the screen. + * + * @param scene */ + public final void renderScene(Scene scene) + { scene.renderLayers(this, transform.getProjectionMatrix(), transform.getViewMatrix()); } + + /** Set the rendering system to 2D ortho projection to render a GUI. */ public abstract void startRenderGUI(); - - /** - * Clean up resources after rendering to the screen. - */ + + /** Clean up resources after rendering to the screen. */ public abstract void stopRender(); - - - /** - * Clean up resources used by the renderer. - * Override this method to - */ + + /** Clean up resources used by the renderer. + * Override this method to */ public abstract void cleanup(); } diff --git a/src/com/bwyap/engine/render3d/Scene.java b/src/com/bwyap/engine/render3d/Scene.java index 76f4e96..07f72b1 100644 --- a/src/com/bwyap/engine/render3d/Scene.java +++ b/src/com/bwyap/engine/render3d/Scene.java @@ -7,96 +7,77 @@ import com.bwyap.engine.input.InputHandler; - -/** - *

+/**

* A scene holds scene layers which can be rendered. - * Each layer has its own shader which is used to - * shade the objects in that layer. + * Each layer has its own shader which is used to + * shade the objects in that layer. * A scene also has a camera which is used to view the layer. *

*

- * Each layer and the camera are automatically updated in the - * scene's {@code update} method. Use the {@code handleInput} + * Each layer and the camera are automatically updated in the + * scene's {@code update} method. Use the {@code handleInput} * and {@code renderLayers} methods to poll input and render * the layers respectively. *

- * @author bwyap * - */ -public abstract class Scene { - + * @author bwyap */ +public abstract class Scene +{ private List> layers; - protected Camera camera; - - - public Scene(int width, int height) { - camera = new Camera(Camera.DEFAULT_Z_NEAR, Camera.DEFAULT_Z_FAR, Camera.DEFAULT_FOV, (float) width/(float) height); + protected Camera camera; + + public Scene(int width, int height) + { + camera = new Camera(Camera.DEFAULT_Z_NEAR, Camera.DEFAULT_Z_FAR, Camera.DEFAULT_FOV, (float) width / (float) height); layers = new ArrayList>(); } - - - /** - * Get the camera looking at the scene - * @return - */ - public Camera getCamera() { - return camera; - } - - - /** - * Add a layer to the scene - * @param element - */ - public void addLayer(SceneLayer element) { - layers.add(element); - } - - - /** - * Remove a layer from the scene - * @param element - * @return - */ - public boolean removeLayer(SceneLayer element) { - return layers.remove(element); - } - - - /** - * Update each layer in the scene - * @param timestep - */ - public void update(float timestep) { - for (SceneLayer layer : layers) { - layer.update(timestep); - } + + /** Get the camera looking at the scene + * + * @return */ + public Camera getCamera() + { return camera; } + + /** Add a layer to the scene + * + * @param element */ + public void addLayer(SceneLayer element) + { layers.add(element); } + + /** Remove a layer from the scene + * + * @param element + * @return */ + public boolean removeLayer(SceneLayer element) + { return layers.remove(element); } + + /** Update each layer in the scene + * + * @param timestep */ + public void update(float timestep) + { + for (SceneLayer layer : layers) + { layer.update(timestep); } camera.update(timestep); } - - - /** - * Handle the input for each element in the scene + + /** Handle the input for each element in the scene + * * @param input - * @param timestep - */ - public void handleInput(InputHandler input, float timestep) { - for (SceneLayer layer : layers) { - layer.handleInput(input, timestep); - } + * @param timestep */ + public void handleInput(InputHandler input, float timestep) + { + for (SceneLayer layer : layers) + { layer.handleInput(input, timestep); } } - - - /** - * Render each layer in the scene + + /** Render each layer in the scene + * * @param projectionMatrix - * @param viewMatrix - */ - public void renderLayers(Renderer3D renderer, Matrix4f projectionMatrix, Matrix4f viewMatrix) { - for (SceneLayer layer : layers) { - layer.render(renderer, projectionMatrix, viewMatrix); - } + * @param viewMatrix */ + public void renderLayers(Renderer3D renderer, Matrix4f projectionMatrix, Matrix4f viewMatrix) + { + for (SceneLayer layer : layers) + { layer.render(renderer, projectionMatrix, viewMatrix); } } - } diff --git a/src/com/bwyap/engine/render3d/SceneLayer.java b/src/com/bwyap/engine/render3d/SceneLayer.java index e9e57b9..4715daf 100644 --- a/src/com/bwyap/engine/render3d/SceneLayer.java +++ b/src/com/bwyap/engine/render3d/SceneLayer.java @@ -4,60 +4,46 @@ import com.bwyap.engine.input.InputHandler; - -/** - *

+/**

* A layer within the scene containing renderable entities. * Entities within this scene layer should use the same shader. *

*

- * The type of entities to be contained in this layer should + * The type of entities to be contained in this layer should * be specified in the type parameter. *

- * @author bwyap - * - */ -public interface SceneLayer { - - - /** - * Add an entity to the scene. - * @param e - * @return - */ + * + * @author bwyap */ +public interface SceneLayer +{ + /** Add an entity to the scene. + * + * @param e + * @return */ public boolean addEntity(E e); - - - /** - * Remove an entity from the scene. + + /** Remove an entity from the scene. * Returns true if the entity was removed. - * @param e - * @return - */ + * + * @param e + * @return */ public boolean removeEntity(E e); - - - /** - * Update the entities contained in the scene layer. - * @param timestep - */ + + /** Update the entities contained in the scene layer. + * + * @param timestep */ public void update(float timestep); - - /** - * Handle the input for the entities contained in the scene layer. + /** Handle the input for the entities contained in the scene layer. + * * @param input - * @param timestep - */ + * @param timestep */ public void handleInput(InputHandler input, float timestep); - - - /** - * Render the entities in the scene layer. + + /** Render the entities in the scene layer. + * * @param renderer * @param projectionMatrix - * @param viewMatrix - */ + * @param viewMatrix */ public void render(Renderer3D renderer, Matrix4f projectionMatrix, Matrix4f viewMatrix); - } diff --git a/src/com/bwyap/engine/render3d/Transformation.java b/src/com/bwyap/engine/render3d/Transformation.java index fde099c..60da164 100644 --- a/src/com/bwyap/engine/render3d/Transformation.java +++ b/src/com/bwyap/engine/render3d/Transformation.java @@ -7,14 +7,11 @@ import com.bwyap.engine.render3d.entity.Entity; import com.bwyap.engine.render3d.entity.RotatableEntity; - -/** - * Handles the transformation matrices used to render entities in a 3D scene. - * @author bwyap - * - */ -public class Transformation { - +/** Handles the transformation matrices used to render entities in a 3D scene. + * + * @author bwyap */ +public class Transformation +{ private final Matrix4f projectionMatrix; private final Matrix4f modelMatrix; private final Matrix4f modelViewMatrix; @@ -25,7 +22,8 @@ public class Transformation { //private final Matrix4f ortho2DMatrix; //private final Matrix4f orthoModelMatrix; - public Transformation() { + public Transformation() + { projectionMatrix = new Matrix4f(); modelMatrix = new Matrix4f(); modelViewMatrix = new Matrix4f(); @@ -36,59 +34,52 @@ public Transformation() { //orthoModelMatrix = new Matrix4f(); //lightViewMatrix = new Matrix4f(); } - - /** - * Get the projection matrix. + + /** Get the projection matrix. * Update the projection matrix when the projection has changed * using the {@code updateProjectionMatrix} method. - * @return - */ - public Matrix4f getProjectionMatrix() { - return projectionMatrix; - } - - /** - * Update the projection matrix - * @param fov - * @param width - * @param height - * @param zNear - * @param zFar - * @return - */ - public Matrix4f updateProjectionMatrix(float fov, float width, float height, float zNear, float zFar) { - float aspectRatio = width / height; + * + * @return */ + public Matrix4f getProjectionMatrix() + { return projectionMatrix; } + + /** Update the projection matrix + * + * @param fov + * @param width + * @param height + * @param zNear + * @param zFar + * @return */ + public Matrix4f updateProjectionMatrix(float fov, float width, float height, float zNear, float zFar) + { + float aspectRatio = width / height; return projectionMatrix.setPerspective(fov, aspectRatio, zNear, zFar); } - + /* public final Matrix4f getOrthoProjectionMatrix() { return orthoProjMatrix; } - + public Matrix4f updateOrthoProjectionMatrix(float left, float right, float bottom, float top, float zNear, float zFar) { return orthoProjMatrix.setOrtho(left, right, bottom, top, zNear, zFar); } */ - - /** - * Get the view matrix. + /** Get the view matrix. * Update the view matrix when the camera view has changed * using the {@code updateViewMatrix} method. - * @return - */ - public Matrix4f getViewMatrix() { - return viewMatrix; - } - - /** - * Update the view matrix - * @param camera - * @return - */ - public Matrix4f updateViewMatrix(Camera camera) { - return updateGenericViewMatrix(camera.getPosition(), camera.getRotation(), viewMatrix); - } + * + * @return */ + public Matrix4f getViewMatrix() + { return viewMatrix; } + + /** Update the view matrix + * + * @param camera + * @return */ + public Matrix4f updateViewMatrix(Camera camera) + { return updateGenericViewMatrix(camera.getPosition(), camera.getRotation(), viewMatrix); } /* public Matrix4f getLightViewMatrix() { @@ -103,93 +94,85 @@ public Matrix4f updateLightViewMatrix(Vector3f position, Vector3f rotation) { return updateGenericViewMatrix(position, rotation, lightViewMatrix); } */ - - public static Matrix4f updateGenericViewMatrix(Vector3f position, Vector3f rotation, Matrix4f matrix) { + public static Matrix4f updateGenericViewMatrix(Vector3f position, Vector3f rotation, Matrix4f matrix) + { // First do the rotation so camera rotates over its position - return matrix.rotationX((float)Math.toRadians(rotation.x)) - .rotateY((float)Math.toRadians(rotation.y)) - .rotateZ((float)Math.toRadians(rotation.z)) - .translate(-position.x, -position.y, -position.z); + return matrix.rotationX((float) Math.toRadians(rotation.x)) + .rotateY((float) Math.toRadians(rotation.y)) + .rotateZ((float) Math.toRadians(rotation.z)) + .translate(-position.x, -position.y, -position.z); } - + /* public final Matrix4f getOrtho2DProjectionMatrix(float left, float right, float bottom, float top) { return ortho2DMatrix.setOrtho2D(left, right, bottom, top); } */ - - /** - * Create the matrix that describes the object's transformation from model space into world space. + /** Create the matrix that describes the object's transformation from model space into world space. * Stores the result in the classes' {@code modelMatrix} instance. - * @param entity - * @return - */ - public Matrix4f buildModelMatrix(RotatableEntity entity) { + * + * @param entity + * @return */ + public Matrix4f buildModelMatrix(RotatableEntity entity) + { Quaternionf rotation = entity.getRotation(); return modelMatrix.translationRotateScale( - entity.getPosition().x, entity.getPosition().y, entity.getPosition().z, - rotation.x, rotation.y, rotation.z, rotation.w, - entity.getScaleX(), entity.getScaleY(), entity.getScaleZ()); + entity.getPosition().x, entity.getPosition().y, entity.getPosition().z, + rotation.x, rotation.y, rotation.z, rotation.w, + entity.getScaleX(), entity.getScaleY(), entity.getScaleZ()); } - - /** - * Create the matrix that describes the object's translation from model space into world space. + + /** Create the matrix that describes the object's translation from model space into world space. * This model matrix is intended to be a billboard so no rotation or scaling is applied. * Stores the result in the classes' {@code modelMatrix} instance. - * @param entity - * @return - */ - public Matrix4f buildModelBillboardMatrix(Entity entity) { - return modelMatrix.translation(entity.getPosition().x, entity.getPosition().y, entity.getPosition().z); - } - - /** - * Create the matrix that describes the object's transformation from model space into view space. + * + * @param entity + * @return */ + public Matrix4f buildModelBillboardMatrix(Entity entity) + { return modelMatrix.translation(entity.getPosition().x, entity.getPosition().y, entity.getPosition().z); } + + /** Create the matrix that describes the object's transformation from model space into view space. * Stores the result in the classes' {@code modelViewMatrix} instance. - * @param entity - * @param viewMatrix - * @return - */ - public Matrix4f buildModelViewMatrix(RotatableEntity entity, Matrix4f viewMatrix) { - return buildModelViewMatrix(buildModelMatrix(entity), viewMatrix); - } + * + * @param entity + * @param viewMatrix + * @return */ + public Matrix4f buildModelViewMatrix(RotatableEntity entity, Matrix4f viewMatrix) + { return buildModelViewMatrix(buildModelMatrix(entity), viewMatrix); } - /** - * Create the matrix that describes the object's transformation from + /** Create the matrix that describes the object's transformation from * model space into view space as a billboard. * Stores the result in the classes' {@code modelViewMatrix} instance. - * @param entity - * @param viewMatrix - * @return - */ - public Matrix4f buildModelViewBillBoardMatrix(Entity entity, Matrix4f viewMatrix) { + * + * @param entity + * @param viewMatrix + * @return */ + public Matrix4f buildModelViewBillBoardMatrix(Entity entity, Matrix4f viewMatrix) + { Matrix4f modelMatrix = buildModelBillboardMatrix(entity); viewMatrix.transpose3x3(modelMatrix); modelMatrix.scale(entity.getScaleX(), entity.getScaleY(), entity.getScaleZ()); return buildModelViewMatrix(modelMatrix, viewMatrix); } - - /** - * Create the matrix that describes the transformation from model space + + /** Create the matrix that describes the transformation from model space * into view space as specified by the supplied matrices. * Stores the result in the classes' {@code modelViewMatrix} instance. - * @param modelMatrix - * @param viewMatrix - * @return - */ - public Matrix4f buildModelViewMatrix(Matrix4f modelMatrix, Matrix4f viewMatrix) { - return viewMatrix.mulAffine(modelMatrix, modelViewMatrix); - } - + * + * @param modelMatrix + * @param viewMatrix + * @return */ + public Matrix4f buildModelViewMatrix(Matrix4f modelMatrix, Matrix4f viewMatrix) + { return viewMatrix.mulAffine(modelMatrix, modelViewMatrix); } /* public Matrix4f buildModelLightViewMatrix(RotatableEntity entity, Matrix4f lightViewMatrix) { return buildModelViewMatrix(buildModelMatrix(entity), lightViewMatrix); } - + public Matrix4f buildModelLightViewMatrix(Matrix4f modelMatrix, Matrix4f lightViewMatrix) { return lightViewMatrix.mulAffine(modelMatrix, modelLightViewMatrix); } - + public Matrix4f buildOrthoProjModelMatrix(RotatableEntity entity, Matrix4f orthoMatrix) { return orthoMatrix.mulOrthoAffine(buildModelMatrix(entity), orthoModelMatrix); } diff --git a/src/com/bwyap/engine/render3d/entity/Entity.java b/src/com/bwyap/engine/render3d/entity/Entity.java index 200d132..1d022fc 100644 --- a/src/com/bwyap/engine/render3d/entity/Entity.java +++ b/src/com/bwyap/engine/render3d/entity/Entity.java @@ -2,120 +2,115 @@ import org.joml.Vector3f; -/** - * An entity that has a position, velocity and scale. +/** An entity that has a position, velocity and scale. *

- * Implements the following interfaces: + * Implements the following interfaces: *

    - *
  • {@code EntityInterface} to provide methods for positioning the entity
  • - *
  • {@code ScalableInterface} to provide methods for scaling the entity
  • - *
  • {@code MovableInterface} to provide methods for getting and setting the entity's velocity
  • + *
  • {@code EntityInterface} to provide methods for positioning the entity
  • + *
  • {@code ScalableInterface} to provide methods for scaling the entity
  • + *
  • {@code MovableInterface} to provide methods for getting and setting the entity's velocity
  • *
*

- * @author bwyap - * - */ -public class Entity implements EntityInterface, ScalableInterface, MovableInterface { - + * + * @author bwyap */ +public class Entity implements EntityInterface, ScalableInterface, MovableInterface +{ private final Vector3f velocity; private final Vector3f position; private float scaleX, scaleY, scaleZ; - - - public Entity() { + + public Entity() + { velocity = new Vector3f(0, 0, 0); position = new Vector3f(0, 0, 0); scaleX = scaleY = scaleZ = 1; } - + @Override - public Vector3f getPosition() { - return position; - } - + public Vector3f getPosition() + { return position; } + @Override - public void setPosition(float x, float y, float z) { + public void setPosition(float x, float y, float z) + { this.position.x = x; this.position.y = y; this.position.z = z; } @Override - public void setPosition(Vector3f position) { + public void setPosition(Vector3f position) + { this.position.x = position.x; this.position.y = position.y; this.position.z = position.z; } - + @Override - public void movePosition(Vector3f displacement) { + public void movePosition(Vector3f displacement) + { this.position.x += displacement.x; this.position.y += displacement.y; this.position.z += displacement.z; } - + @Override - public void movePosition(float xOffset, float yOffset, float zOffset) { + public void movePosition(float xOffset, float yOffset, float zOffset) + { this.position.x += xOffset; this.position.y += yOffset; this.position.z += zOffset; } - + @Override - public void setVelocity(float x, float y, float z) { + public void setVelocity(float x, float y, float z) + { this.velocity.x = x; this.velocity.y = y; this.velocity.z = z; } - + @Override - public void setVelocity(Vector3f velocity) { + public void setVelocity(Vector3f velocity) + { this.velocity.x = velocity.x; this.velocity.y = velocity.y; this.velocity.z = velocity.z; } - + @Override - public Vector3f getVelocity() { - return velocity; - } - + public Vector3f getVelocity() + { return velocity; } + @Override - public float getScaleX() { - return scaleX; - } - + public float getScaleX() + { return scaleX; } + @Override - public float getScaleY() { - return scaleY; - } - + public float getScaleY() + { return scaleY; } + @Override - public float getScaleZ() { - return scaleZ; - } - + public float getScaleZ() + { return scaleZ; } + @Override - public void setScale(float scale) { + public void setScale(float scale) + { this.scaleX = scale; this.scaleY = scale; this.scaleZ = scale; } - + @Override - public void setScaleX(float scaleX) { - this.scaleX = scaleX; - } - + public void setScaleX(float scaleX) + { this.scaleX = scaleX; } + @Override - public void setScaleY(float scaleY) { - this.scaleY = scaleY; - } - + public void setScaleY(float scaleY) + { this.scaleY = scaleY; } + @Override - public void setScaleZ(float scaleZ) { - this.scaleZ = scaleZ; - } - - + public void setScaleZ(float scaleZ) + { this.scaleZ = scaleZ; } } diff --git a/src/com/bwyap/engine/render3d/entity/EntityInterface.java b/src/com/bwyap/engine/render3d/entity/EntityInterface.java index 5b3a4e8..0eff2a8 100644 --- a/src/com/bwyap/engine/render3d/entity/EntityInterface.java +++ b/src/com/bwyap/engine/render3d/entity/EntityInterface.java @@ -2,46 +2,38 @@ import org.joml.Vector3f; -/** - * Contains methods that an entity with +/** Contains methods that an entity with * a position in a 3D world must implement. - * @author bwyap - * - */ -public interface EntityInterface { - - /** - * Get the position at which the entity is located in the world. - * @return - */ + * + * @author bwyap */ +public interface EntityInterface +{ + /** Get the position at which the entity is located in the world. + * + * @return */ public Vector3f getPosition(); - - /** - * Set the position of the entity in the world. + + /** Set the position of the entity in the world. + * * @param x * @param y - * @param z - */ + * @param z */ public void setPosition(float x, float y, float z); - /** - * Set the position of the entity in the world. - * @param position - */ + /** Set the position of the entity in the world. + * + * @param position */ public void setPosition(Vector3f position); - - /** - * Move the position of the entity by the given displacement - * @param displacement - */ + + /** Move the position of the entity by the given displacement + * + * @param displacement */ public void movePosition(Vector3f displacement); - - /** - * Move the position of the particle + + /** Move the position of the particle + * * @param xOffset * @param yOffset - * @param zOffset - */ + * @param zOffset */ public void movePosition(float xOffset, float yOffset, float zOffset); - } diff --git a/src/com/bwyap/engine/render3d/entity/MovableInterface.java b/src/com/bwyap/engine/render3d/entity/MovableInterface.java index d56b292..1ed2c58 100644 --- a/src/com/bwyap/engine/render3d/entity/MovableInterface.java +++ b/src/com/bwyap/engine/render3d/entity/MovableInterface.java @@ -2,33 +2,26 @@ import org.joml.Vector3f; - -/** - * Contains methods that an entity that can move +/** Contains methods that an entity that can move * over time with some velocity must implement. - * @author bwyap - * - */ -public interface MovableInterface { - - /** - * Set the velocity of the entity + * + * @author bwyap */ +public interface MovableInterface +{ + /** Set the velocity of the entity + * * @param x * @param y - * @param z - */ + * @param z */ public void setVelocity(float x, float y, float z); - /** - * Set the velocity of the entity - * @param velocity - */ + /** Set the velocity of the entity + * + * @param velocity */ public void setVelocity(Vector3f velocity); - - /** - * Get the velocity of the entity - * @return - */ + + /** Get the velocity of the entity + * + * @return */ public Vector3f getVelocity(); - } diff --git a/src/com/bwyap/engine/render3d/entity/RotatableEntity.java b/src/com/bwyap/engine/render3d/entity/RotatableEntity.java index 468186a..29fe2ad 100644 --- a/src/com/bwyap/engine/render3d/entity/RotatableEntity.java +++ b/src/com/bwyap/engine/render3d/entity/RotatableEntity.java @@ -3,65 +3,58 @@ import org.joml.Quaternionf; import org.joml.Vector3f; - -/** - * A movable and scalable entity which has the ability to be rotated. - * Rotation is provided through {@code RotatableInterface} +/** A movable and scalable entity which has the ability to be rotated. + * Rotation is provided through {@code RotatableInterface} * (rotation is stored as a Quaternion). - * @author bwyap - * - */ -public class RotatableEntity extends Entity implements RotatableInterface { - + * + * @author bwyap */ +public class RotatableEntity extends Entity implements RotatableInterface +{ private final Quaternionf rotation; - - - public RotatableEntity() { - rotation = new Quaternionf(0, 0, 0, 1); - } - - + + public RotatableEntity() + { rotation = new Quaternionf(0, 0, 0, 1); } + @Override - public Quaternionf getRotation() { - return rotation; - } - + public Quaternionf getRotation() + { return rotation; } + @Override - public void setRotation(float x, float y, float z, float w) { - this.rotation.x = x * (float) Math.sin(w/2); - this.rotation.y = y * (float) Math.sin(w/2); - this.rotation.z = z * (float) Math.sin(w/2); - this.rotation.w = (float) Math.cos(w/2); + public void setRotation(float x, float y, float z, float w) + { + this.rotation.x = x * (float) Math.sin(w / 2); + this.rotation.y = y * (float) Math.sin(w / 2); + this.rotation.z = z * (float) Math.sin(w / 2); + this.rotation.w = (float) Math.cos(w / 2); } - + @Override - public float getRotationAmount() { - return 2 * (float) Math.acos(rotation.w); - } - + public float getRotationAmount() + { return 2 * (float) Math.acos(rotation.w); } + @Override - public void setRotationAmount(float w) { + public void setRotationAmount(float w) + { Vector3f rotationAxis = getRotationAxis(); setRotation(rotationAxis.x, rotationAxis.y, rotationAxis.z, w % (float) (2 * Math.PI)); } - + @Override - public void setRotationAxisNormalize(float x, float y, float z) { - Vector3f axis = new Vector3f(x, y ,z); + public void setRotationAxisNormalize(float x, float y, float z) + { + Vector3f axis = new Vector3f(x, y, z); axis.normalize(); setRotation(axis.x, axis.y, axis.z, getRotationAmount()); } - + @Override - public void setRotationAxis(float x, float y, float z) { - setRotation(x, y, z, getRotationAmount()); - } + public void setRotationAxis(float x, float y, float z) + { setRotation(x, y, z, getRotationAmount()); } @Override - public Vector3f getRotationAxis() { - return new Vector3f( - rotation.x/(float) Math.sin(getRotationAmount()/2), - rotation.y/(float) Math.sin(getRotationAmount()/2), - rotation.z/(float) Math.sin(getRotationAmount()/2)); - } + public Vector3f getRotationAxis() + { return new Vector3f( + rotation.x / (float) Math.sin(getRotationAmount() / 2), + rotation.y / (float) Math.sin(getRotationAmount() / 2), + rotation.z / (float) Math.sin(getRotationAmount() / 2)); } } diff --git a/src/com/bwyap/engine/render3d/entity/RotatableInterface.java b/src/com/bwyap/engine/render3d/entity/RotatableInterface.java index dfc06d7..585bbc9 100644 --- a/src/com/bwyap/engine/render3d/entity/RotatableInterface.java +++ b/src/com/bwyap/engine/render3d/entity/RotatableInterface.java @@ -3,70 +3,59 @@ import org.joml.Quaternionf; import org.joml.Vector3f; - -/** - * Contains methods that an entity that can be rotated must implement. +/** Contains methods that an entity that can be rotated must implement. * The rotation of the entity should be stored as a Quaternion. - * @author bwyap - * - */ -public interface RotatableInterface { - - /** - * Get the rotation of the entity's model. + * + * @author bwyap */ +public interface RotatableInterface +{ + /** Get the rotation of the entity's model. * Rotation is represented as a quaternion: - * where x,y,z represent the rotation axis and + * where x,y,z represent the rotation axis and * w represents the rotation angle (in radians). - * @return - */ + * + * @return */ public Quaternionf getRotation(); - - /** - * Set the rotation of the object, - * where x,y,z represent the rotation axis (not normalised) + + /** Set the rotation of the object, + * where x,y,z represent the rotation axis (not normalised) * and w represents the rotation amount (in radians). + * * @param x * @param y * @param z - * @param w - */ + * @param w */ public void setRotation(float x, float y, float z, float w); - - /** - * Gets the rotation angle in radians. - * @return - */ + + /** Gets the rotation angle in radians. + * + * @return */ public float getRotationAmount(); - - /** - * Set the amount of rotation around the rotation axis in radians. - * @param w - */ + + /** Set the amount of rotation around the rotation axis in radians. + * + * @param w */ public void setRotationAmount(float w); - - /** - * Set the rotation axis. + + /** Set the rotation axis. * The vector is normalised to ensure there is no distortion. + * * @param x * @param y - * @param z - */ + * @param z */ public void setRotationAxisNormalize(float x, float y, float z); - - /** - * Set the rotation axis (without normalisation). + + /** Set the rotation axis (without normalisation). * If the provided values do not form a normalised vector, * there may be distortion when the object is rotated. + * * @param x * @param y - * @param z - */ + * @param z */ public void setRotationAxis(float x, float y, float z); - - /** - * Get the rotation axis as a vector. - * @return - */ + + /** Get the rotation axis as a vector. + * + * @return */ public Vector3f getRotationAxis(); - } diff --git a/src/com/bwyap/engine/render3d/entity/ScalableInterface.java b/src/com/bwyap/engine/render3d/entity/ScalableInterface.java index 72069d5..31ea2fc 100644 --- a/src/com/bwyap/engine/render3d/entity/ScalableInterface.java +++ b/src/com/bwyap/engine/render3d/entity/ScalableInterface.java @@ -1,53 +1,43 @@ package com.bwyap.engine.render3d.entity; -/** - * Contains methods that an entity that is scalable +/** Contains methods that an entity that is scalable * on the x, y and z axis should implement. - * @author bwyap - * - */ -public interface ScalableInterface { - - /** - * Get the x scale of which the model of the entity will be rendered. - * @return - */ + * + * @author bwyap */ +public interface ScalableInterface +{ + /** Get the x scale of which the model of the entity will be rendered. + * + * @return */ public float getScaleX(); - /** - * Get the y scale of which the model of the entity will be rendered. - * @return - */ + /** Get the y scale of which the model of the entity will be rendered. + * + * @return */ public float getScaleY(); - - /** - * Get the z scale of which the model of the entity will be rendered. - * @return - */ + + /** Get the z scale of which the model of the entity will be rendered. + * + * @return */ public float getScaleZ(); - - /** - * Set the scale at which the model of the entity will be rendered. - * @param scale - */ + + /** Set the scale at which the model of the entity will be rendered. + * + * @param scale */ public void setScale(float scale); - - /** - * Set the x scale at which the model of the entity will be rendered. - * @param scale - */ + + /** Set the x scale at which the model of the entity will be rendered. + * + * @param scale */ public void setScaleX(float xScale); - - /** - * Set the y scale at which the model of the entity will be rendered. - * @param scale - */ + + /** Set the y scale at which the model of the entity will be rendered. + * + * @param scale */ public void setScaleY(float yScale); - - /** - * Set the z scale at which the model of the entity will be rendered. - * @param scale - */ + + /** Set the z scale at which the model of the entity will be rendered. + * + * @param scale */ public void setScaleZ(float zScale); - } diff --git a/src/com/bwyap/engine/resource/JSONResourceLibrary.java b/src/com/bwyap/engine/resource/JSONResourceLibrary.java index d6489c2..2c2b9a7 100644 --- a/src/com/bwyap/engine/resource/JSONResourceLibrary.java +++ b/src/com/bwyap/engine/resource/JSONResourceLibrary.java @@ -6,130 +6,93 @@ import com.bwyap.utility.resource.JSONWrapper; - -/** - * A JSON wrapper that provides access to the resource file +/** A JSON wrapper that provides access to the resource file * paths specified by a Resource library JSON file. - * @author bwyap - * - */ + * + * @author bwyap */ @SuppressWarnings("unchecked") -public class JSONResourceLibrary extends JSONWrapper { - - - /** - * Create a new JSON Resource library with the specified JSON object - * @param object - */ - public JSONResourceLibrary(JSONObject object) { - super(object); - } - - - /** - * Auxillary method for getting internal resource paths - * @param property - * @return - */ - private Map getInternal(String property) { - return (Map) ((JSONObject)object.get("internal")).get(property); - } - - - /** - * Auxillary method for getting external resource paths - * @param property - * @return - */ - private Map getExternal(String property) { - return (Map) ((JSONObject)object.get("external")).get(property); - } - - - +public class JSONResourceLibrary extends JSONWrapper +{ + /** Create a new JSON Resource library with the specified JSON object + * + * @param object */ + public JSONResourceLibrary(JSONObject object) + { super(object); } + + /** Auxillary method for getting internal resource paths + * + * @param property + * @return */ + private Map getInternal(String property) + { return (Map) ((JSONObject) object.get("internal")).get(property); } + + /** Auxillary method for getting external resource paths + * + * @param property + * @return */ + private Map getExternal(String property) + { return (Map) ((JSONObject) object.get("external")).get(property); } + // INTERNAL - - /** - * Get the Map of shader file paths specified by the resource library - * @return - */ - public Map getShaders() { - return getInternal("shaders"); - } - - - /** - * Get the Map of mesh file paths specified by the resource library - * @return - */ - public Map getMeshes() { - return getInternal("meshes"); - } - - - /** - * Get the Map of texture file paths specified by the resource library - * @return - */ - public Map getTextures() { - return getInternal("textures"); - } - - - /** - * Get the Map of font file paths specified by the resource library - * @return - */ - public Map getFonts() { - return getInternal("fonts"); - } - - - + /** Get the Map of shader file paths specified by the resource library + * + * @return */ + public Map getShaders() + { return getInternal("shaders"); } + + /** Get the Map of mesh file paths specified by the resource library + * + * @return */ + public Map getMeshes() + { return getInternal("meshes"); } + + /** Get the Map of texture file paths specified by the resource library + * + * @return */ + public Map getTextures() + { return getInternal("textures"); } + + /** Get the Map of font file paths specified by the resource library + * + * @return */ + public Map getFonts() + { return getInternal("fonts"); } + // EXTERNAL - - /** - * Get the external folder paths specified by the resource library - * @return - */ - public Map getFolders() { - return getExternal("folders"); - } - - - /** - * Get the configuration file paths specified by the resource library - * @return - */ - public Map getConfig() { - return getExternal("config"); - } - - + /** Get the external folder paths specified by the resource library + * + * @return */ + public Map getFolders() + { return getExternal("folders"); } + + /** Get the configuration file paths specified by the resource library + * + * @return */ + public Map getConfig() + { return getExternal("config"); } + // RESOURCE MAPPINGS - - /** - * Get a font from the font library - * @param fontAlias - * @return - */ - public String getFont(String fontAlias) { - return ((JSONObject)((JSONObject)((JSONObject)object).get("mapping")).get("font")).get(fontAlias).toString(); - } - + /** Get a font from the font library + * + * @param fontAlias + * @return */ + public String getFont(String fontAlias) + { return ((JSONObject) ((JSONObject) ((JSONObject) object).get("mapping")).get("font")).get(fontAlias).toString(); } - /** - * Validate the loaded JSON file. - * @return - */ + /** Validate the loaded JSON file. + * + * @return */ @Override - public boolean isValid() { - try { + public boolean isValid() + { + try + { //TODO // // } - catch (Exception e) { + catch (Exception e) + { e.printStackTrace(); return false; } diff --git a/src/com/bwyap/engine/resource/ResourceManagerBase.java b/src/com/bwyap/engine/resource/ResourceManagerBase.java index 951f279..70ed939 100644 --- a/src/com/bwyap/engine/resource/ResourceManagerBase.java +++ b/src/com/bwyap/engine/resource/ResourceManagerBase.java @@ -2,27 +2,19 @@ import com.bwyap.utility.resource.ResourceLoader; -/** - * A base class for a Resource manager. Each implementation +/** A base class for a Resource manager. Each implementation * of this engine should have its own subclass of this class. * The ResourceManager should be implemented as a Singleton. - * @author bwyap - * - */ -public abstract class ResourceManagerBase implements ResourceManagerInterface { - - + * + * @author bwyap */ +public abstract class ResourceManagerBase implements ResourceManagerInterface +{ public final JSONResourceLibrary lib; - - - /** - * Create a new resource manager with the + + /** Create a new resource manager with the * resource library specified at the path - * @param JSONPath - */ - protected ResourceManagerBase(String JSONPath) { - lib = new JSONResourceLibrary(ResourceLoader.loadInternalJSON(JSONPath)); - } - - + * + * @param JSONPath */ + protected ResourceManagerBase(String JSONPath) + { lib = new JSONResourceLibrary(ResourceLoader.loadInternalJSON(JSONPath)); } } diff --git a/src/com/bwyap/engine/resource/ResourceManagerInterface.java b/src/com/bwyap/engine/resource/ResourceManagerInterface.java index 4b76c6e..cfea70d 100644 --- a/src/com/bwyap/engine/resource/ResourceManagerInterface.java +++ b/src/com/bwyap/engine/resource/ResourceManagerInterface.java @@ -1,23 +1,13 @@ package com.bwyap.engine.resource; -/** - * Methods required by a concrete Resource Manager implementation - * @author bwyap - * - */ -public interface ResourceManagerInterface { - - - /** - * Load all non-engine dependent resources - */ +/** Methods required by a concrete Resource Manager implementation + * + * @author bwyap */ +public interface ResourceManagerInterface +{ + /** Load all non-engine dependent resources */ public void loadIndepedentResources() throws Exception; - - - /** - * Load all engine dependent resources - */ + + /** Load all engine dependent resources */ public void loadDependentResources() throws Exception; - - } diff --git a/src/com/bwyap/engine/util/IOUtil.java b/src/com/bwyap/engine/util/IOUtil.java index e847461..51eb171 100644 --- a/src/com/bwyap/engine/util/IOUtil.java +++ b/src/com/bwyap/engine/util/IOUtil.java @@ -18,58 +18,55 @@ import static org.lwjgl.BufferUtils.*; +public final class IOUtil +{ + private IOUtil() + {} -public final class IOUtil { - - private IOUtil() {} - - - private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) { + private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) + { ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity); buffer.flip(); newBuffer.put(buffer); return newBuffer; } - - /** - * Reads the specified resource and returns the raw data as a ByteBuffer. - * - * @param resource the resource to read - * @param bufferSize the initial buffer size + /** Reads the specified resource and returns the raw data as a ByteBuffer. * - * @return the resource data - * - * @throws IOException if an IO error occurs - */ - public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException { + * @param resource the resource to read + * @param bufferSize the initial buffer size + * @return the resource data + * @throws IOException if an IO error occurs */ + public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException + { ByteBuffer buffer; - Path path = Paths.get(resource); - if ( Files.isReadable(path) ) { - try (SeekableByteChannel fc = Files.newByteChannel(path)) { - buffer = BufferUtils.createByteBuffer((int)fc.size() + 1); - while ( fc.read(buffer) != -1 ) ; + if (Files.isReadable(path)) + { + try (SeekableByteChannel fc = Files.newByteChannel(path)) + { + buffer = BufferUtils.createByteBuffer((int) fc.size() + 1); + while (fc.read(buffer) != -1); } - } else { + } + else + { try ( InputStream source = IOUtil.class.getClass().getResourceAsStream(resource); - ReadableByteChannel rbc = Channels.newChannel(source) - ) { + ReadableByteChannel rbc = Channels.newChannel(source)) + { buffer = createByteBuffer(bufferSize); - - while ( true ) { + while (true) + { int bytes = rbc.read(buffer); - if ( bytes == -1 ) + if (bytes == -1) break; - if ( buffer.remaining() == 0 ) + if (buffer.remaining() == 0) buffer = resizeBuffer(buffer, buffer.capacity() * 2); } } } - buffer.flip(); return buffer; } - } \ No newline at end of file diff --git a/src/com/bwyap/engine/window/BoundsInterface.java b/src/com/bwyap/engine/window/BoundsInterface.java index eb5e6e4..04bd554 100644 --- a/src/com/bwyap/engine/window/BoundsInterface.java +++ b/src/com/bwyap/engine/window/BoundsInterface.java @@ -2,60 +2,46 @@ import org.joml.Vector2f; -public interface BoundsInterface { - - /** - * Get the position of the element as a vector, +public interface BoundsInterface +{ + /** Get the position of the element as a vector, * relative to screen space. - * @return - */ + * + * @return */ public Vector2f getPosition(); - - - /** - * Get the absolute position of the element as a vector. + + /** Get the absolute position of the element as a vector. * The absolute position of the element is its assigned position * before any scaling due to screen resizing. - * @return - */ + * + * @return */ public Vector2f getAbsolutePosition(); - - - /** - * Get the X position of the element, + + /** Get the X position of the element, * relative to screen space. - * @return - */ + * + * @return */ public float getPositionX(); - - - /** - * Get the Y position of the element, + + /** Get the Y position of the element, * relative to screen space. - * @return - */ + * + * @return */ public float getPositionY(); - - /** - * Get the bounds of the element - * @return - */ + /** Get the bounds of the element + * + * @return */ public Vector2f getBounds(); - - - /** - * Get the absolute bounds of the element - * @return - */ + + /** Get the absolute bounds of the element + * + * @return */ public Vector2f getAbsoluteBounds(); - - - /** - * Get the original bounds of the element + + /** Get the original bounds of the element * (when the element was first created) - * @return - */ + * + * @return */ public Vector2f getOriginalBounds(); - } diff --git a/src/com/bwyap/engine/window/Window.java b/src/com/bwyap/engine/window/Window.java index 43a7adc..0d1c911 100644 --- a/src/com/bwyap/engine/window/Window.java +++ b/src/com/bwyap/engine/window/Window.java @@ -5,18 +5,15 @@ import com.bwyap.engine.EngineInterface; import com.bwyap.engine.input.InputHandler; - -/** - * An abstract class that specifies an actual window - * that runs an engine. The concrete implementation +/** An abstract class that specifies an actual window + * that runs an engine. The concrete implementation * must handle the intialisation and rendering of the * window, as well as setting up the input handler and * managing the engine itself. - * @author bwyap - * - */ -public abstract class Window implements WindowInterface { - + * + * @author bwyap */ +public abstract class Window implements WindowInterface +{ protected final int absoluteWidth, absoluteHeight; protected int width, height; protected String title; @@ -24,142 +21,110 @@ public abstract class Window implements WindowInterface { protected boolean showFps; protected int targetFPS = 60; protected EngineInterface engine; - protected InputHandler input; - - public Window(int width, int height, String title, boolean showFps) { + public Window(int width, int height, String title, boolean showFps) + { this.width = this.absoluteWidth = width; this.height = this.absoluteHeight = height; this.title = title; this.showFps = showFps; this.resized = false; } - - - /** - * Creates a new EngineInterface object to be run by in the window. + + /** Creates a new EngineInterface object to be run by in the window. + * * @return - * @throws Exception - */ + * @throws Exception */ public abstract EngineInterface createEngine() throws Exception; - - - /** - * Initialise the window - */ + + /** Initialise the window */ public abstract void init(); - - - /** - * Create the window and start the main loop - */ + + /** Create the window and start the main loop */ public abstract void start(); - - - /** - * Clean up resources created and used by the window - */ + + /** Clean up resources created and used by the window */ public abstract void dispose(); - - + @Override - public final InputHandler getInputHandler() { - return input; - } - + public final InputHandler getInputHandler() + { return input; } + @Override - public final int getWidth() { - return width; - } - + public final int getWidth() + { return width; } + @Override - public final int getHeight() { - return height; - } + public final int getHeight() + { return height; } @Override - public final float getAspectRatio() { - return (float)width/(float)height; - } - + public final float getAspectRatio() + { return (float) width / (float) height; } + @Override - public final String getDefaultTitle() { - return title; - } - + public final String getDefaultTitle() + { return title; } + @Override - public final void setDefaultTitle(String title) { - this.title = title; - } - + public final void setDefaultTitle(String title) + { this.title = title; } + @Override - public final void setTitle(String title) { - this.setWindowTitle(title); - } - - /** - * Implementation specific method to set the + public final void setTitle(String title) + { this.setWindowTitle(title); } + + /** Implementation specific method to set the * title displayed on the window. - * @param title - */ + * + * @param title */ protected abstract void setWindowTitle(String title); - + @Override - public void setResized(boolean resized) { - this.resized = resized; - } - + public void setResized(boolean resized) + { this.resized = resized; } + @Override - public boolean isResized() { - return resized; - } - + public boolean isResized() + { return resized; } + @Override - public final float getFPS() { - return engine.getFPS(); - } - + public final float getFPS() + { return engine.getFPS(); } + @Override - public final void setFpsDisplay(float fps) { - if (showFps) { - this.setTitle(title + " (" + (int) fps + " fps)"); - } + public final void setFpsDisplay(float fps) + { + if (showFps) + { this.setTitle(title + " (" + (int) fps + " fps)"); } } - + @Override - public Vector2f getPosition() { - return new Vector2f(0.0f, 0.0f); - } - + public Vector2f getPosition() + { return new Vector2f(0.0f, 0.0f); } + @Override - public Vector2f getAbsolutePosition() { - return getPosition(); - } - + public Vector2f getAbsolutePosition() + { return getPosition(); } + @Override - public float getPositionX() { - return 0.0f; - } - + public float getPositionX() + { return 0.0f; } + @Override - public float getPositionY() { - return 0.0f; - } + public float getPositionY() + { return 0.0f; } @Override - public Vector2f getBounds() { - return new Vector2f(width, height); - } - + public Vector2f getBounds() + { return new Vector2f(width, height); } + @Override - public Vector2f getAbsoluteBounds() { - return new Vector2f(absoluteWidth, absoluteHeight); - } - + public Vector2f getAbsoluteBounds() + { return new Vector2f(absoluteWidth, absoluteHeight); } @Override - public Vector2f getOriginalBounds() { - return getAbsoluteBounds(); - } + public Vector2f getOriginalBounds() + { return getAbsoluteBounds(); } } diff --git a/src/com/bwyap/engine/window/WindowInterface.java b/src/com/bwyap/engine/window/WindowInterface.java index e4dfeda..7c5aed6 100644 --- a/src/com/bwyap/engine/window/WindowInterface.java +++ b/src/com/bwyap/engine/window/WindowInterface.java @@ -2,112 +2,84 @@ import com.bwyap.engine.input.InputHandler; - -/** - * An interface that specifies methods an engine +/** An interface that specifies methods an engine * using a window should be able to access. - * @author bwyap - * - */ -public interface WindowInterface extends BoundsInterface { - - /** - * Check if the window should close - * @return - */ + * + * @author bwyap */ +public interface WindowInterface extends BoundsInterface +{ + /** Check if the window should close + * + * @return */ public boolean shouldClose(); - - /** - * Process events that should be handled - * by the window before the engine is updated. - */ + + /** Process events that should be handled + * by the window before the engine is updated. */ public void processEvents(); - - /** - * Swap the display buffers for rendering the window - */ + + /** Swap the display buffers for rendering the window */ public void swapDisplayBuffers(); - - /** - * Get the input handler for the window - * @return - */ + + /** Get the input handler for the window + * + * @return */ public InputHandler getInputHandler(); - - /** - * Get the width of the window - * @return - */ + + /** Get the width of the window + * + * @return */ public int getWidth(); - - /** - * Get the height of the window - * @return - */ - public int getHeight(); + /** Get the height of the window + * + * @return */ + public int getHeight(); - /** - * Get the current aspect ratio of the screen. - * @return - */ + /** Get the current aspect ratio of the screen. + * + * @return */ public float getAspectRatio(); - - /** - * Get the default title of the window. + /** Get the default title of the window. * The currently displayed title of the window might be different. - * @return - */ + * + * @return */ public String getDefaultTitle(); - - - /** - * Set the default title of the window. + + /** Set the default title of the window. * The currently displayed title of the window might be different. - * @param title - */ + * + * @param title */ public void setDefaultTitle(String title); - - - /** - * Set the title of the window. - * This method will change what is actually + + /** Set the title of the window. + * This method will change what is actually * displayed on the window's title bar. * This does not change the default title of the window, * which can be retrieved using {@code getDefaultTitle()}. - * @param title - */ + * + * @param title */ public void setTitle(String title); - - - /** - * Set whether the window has been resized - * @param resized - */ + + /** Set whether the window has been resized + * + * @param resized */ public void setResized(boolean resized); - - - /** - * Check if the window has been resized - * @return - */ + + /** Check if the window has been resized + * + * @return */ public boolean isResized(); - - /** - * Get the last measured FPS of the game - * @return - */ + /** Get the last measured FPS of the game + * + * @return */ public float getFPS(); - - - /** - * Set the title of the window to show the window's + + /** Set the title of the window to show the window's * default title followed by the last measured FPS rate. * This will only work if showFps has been enabled. - * @param fps - */ + * + * @param fps */ public void setFpsDisplay(float fps); - } diff --git a/src/com/bwyap/enginedriver/EngineLauncherTest.java b/src/com/bwyap/enginedriver/EngineLauncherTest.java index 32ae994..07a6f4d 100644 --- a/src/com/bwyap/enginedriver/EngineLauncherTest.java +++ b/src/com/bwyap/enginedriver/EngineLauncherTest.java @@ -5,18 +5,19 @@ import com.bwyap.enginedriver.window.DriverWindow; import com.bwyap.lwjgl.engine.resource.LWJGLResourceManager; -public class EngineLauncherTest { - - public static void main(String[] args) { +public class EngineLauncherTest +{ + public static void main(String[] args) + { LWJGLResourceManager.initInstance(LWJGLResourceManager.RESOURCE_JSON); - - try { + try + { LWJGLResourceManager.instance().loadIndepedentResources(); - } catch (IOException e) { + } + catch (IOException e) + { e.printStackTrace(); } - new DriverWindow().start(); } - } diff --git a/src/com/bwyap/enginedriver/GameEngine.java b/src/com/bwyap/enginedriver/GameEngine.java index 9d10a79..1f6be12 100644 --- a/src/com/bwyap/enginedriver/GameEngine.java +++ b/src/com/bwyap/enginedriver/GameEngine.java @@ -6,25 +6,16 @@ import com.bwyap.lwjgl.engine.LWJGL3DEngine; import com.bwyap.lwjgl.window.GLFWWindow; +public class GameEngine extends LWJGL3DEngine +{ + public GameEngine(GLFWWindow window, int targetFPS) throws Exception + { super(window, targetFPS); } -public class GameEngine extends LWJGL3DEngine { - - - public GameEngine(GLFWWindow window, int targetFPS) throws Exception { - super(window, targetFPS); - - } - - @Override - public void init() { - setScene(new TestScene(window.getWidth(), window.getHeight())); - } + public void init() + { setScene(new TestScene(window.getWidth(), window.getHeight())); } - @Override - public GUIControllerInterface initGUI() throws Exception { - return new TestGUIController(); - } - + public GUIControllerInterface initGUI() throws Exception + { return new TestGUIController(); } } diff --git a/src/com/bwyap/enginedriver/game/test/TestAnimatedParticle.java b/src/com/bwyap/enginedriver/game/test/TestAnimatedParticle.java index eed9b07..917e8f1 100644 --- a/src/com/bwyap/enginedriver/game/test/TestAnimatedParticle.java +++ b/src/com/bwyap/enginedriver/game/test/TestAnimatedParticle.java @@ -2,22 +2,18 @@ import com.bwyap.lwjgl.engine.particle.AnimatedParticle; -public class TestAnimatedParticle extends AnimatedParticle { +public class TestAnimatedParticle extends AnimatedParticle +{ + TestAnimatedParticle(AnimatedParticle particle) + { super(particle); } + + TestAnimatedParticle(float timeCreated, float lifetime, float textureChangeSpeed) + { super(timeCreated, lifetime, textureChangeSpeed); } - TestAnimatedParticle(AnimatedParticle particle) { - super(particle); - } - - - TestAnimatedParticle(float timeCreated, float lifetime, float textureChangeSpeed) { - super(timeCreated, lifetime, textureChangeSpeed); - } - - @Override - public void update(float timestep) { + public void update(float timestep) + { super.update(timestep); movePosition(getVelocity().x() * timestep, getVelocity().y() * timestep, getVelocity().z() * timestep); } - } diff --git a/src/com/bwyap/enginedriver/game/test/TestAnimatedParticleSystem.java b/src/com/bwyap/enginedriver/game/test/TestAnimatedParticleSystem.java index 949b9f6..b12486a 100644 --- a/src/com/bwyap/enginedriver/game/test/TestAnimatedParticleSystem.java +++ b/src/com/bwyap/enginedriver/game/test/TestAnimatedParticleSystem.java @@ -8,11 +8,11 @@ import com.bwyap.lwjgl.engine.particle.ParticleSystem; import com.bwyap.lwjgl.engine.render3d.LWJGLTexture; -public class TestAnimatedParticleSystem extends ParticleSystem { - - public TestAnimatedParticleSystem(LWJGLTexture texture) throws Exception { +public class TestAnimatedParticleSystem extends ParticleSystem +{ + public TestAnimatedParticleSystem(LWJGLTexture texture) throws Exception + { super(texture, 1000, 10, 0.1f); - this.setActive(true); this.setParticleLifetime(3f, 0); this.setBaseVelocity(new Vector3f(0, 3, 0)); @@ -22,16 +22,14 @@ public TestAnimatedParticleSystem(LWJGLTexture texture) throws Exception { this.setVelocityDirectionVariance(0.5f); this.setEmitRadius(0.5f); } - @Override - protected void setMesh() throws Exception { - this.setMesh("particle"); - } + protected void setMesh() throws Exception + { this.setMesh("particle"); } - @Override - protected AnimatedParticle generateNewParticle(float now) { + protected AnimatedParticle generateNewParticle(float now) + { TestAnimatedParticle p = new TestAnimatedParticle(now, (new Random().nextFloat() * (particleLifetimeMax - particleLifetimeMin)) + particleLifetimeMin, 0.03f); p.setColour(generateColour()); p.setRadius(generateRadius()); @@ -39,5 +37,4 @@ protected AnimatedParticle generateNewParticle(float now) { p.setVelocity(generateStartVelocity()); return p; } - } diff --git a/src/com/bwyap/enginedriver/game/test/TestGUI.java b/src/com/bwyap/enginedriver/game/test/TestGUI.java index f4bf4c9..cbbb2d1 100644 --- a/src/com/bwyap/enginedriver/game/test/TestGUI.java +++ b/src/com/bwyap/enginedriver/game/test/TestGUI.java @@ -27,23 +27,20 @@ import com.bwyap.lwjgl.engine.gui.nanovg.NVGRenderer; import com.bwyap.lwjgl.engine.resource.LWJGLResourceManager; -public class TestGUI extends NVGGUI { - - - public TestGUI() { - super(LWJGLResourceManager.instance().settings().getWidth(), - LWJGLResourceManager.instance().settings().getHeight()); - } - - +public class TestGUI extends NVGGUI +{ + public TestGUI() + { super(LWJGLResourceManager.instance().settings().getWidth(), + LWJGLResourceManager.instance().settings().getHeight()); } + @Override - public void init(NVGRenderer renderer) { - - RectangularButton button = new RectangularButton(5, 5, 100, 30) { + public void init(NVGRenderer renderer) + { + RectangularButton button = new RectangularButton(5, 5, 100, 30) + { @Override - public void onMouseClicked(float x, float y, int mouseButton) { - System.out.println("Pressed rectangle with " + mouseButton); - } + public void onMouseClicked(float x, float y, int mouseButton) + { System.out.println("Pressed rectangle with " + mouseButton); } }; button.colourProperties().setColour(1, 0, 0, 1); button.colourProperties().setMouseoverColour(0, 1, 0, 1); @@ -52,74 +49,63 @@ public void onMouseClicked(float x, float y, int mouseButton) { button.getTextComponent().setFontName(LWJGLResourceManager.instance().lib.getFont("default")); button.getTextComponent().setText("Press me now 123456789"); addElement(button); - - - EllipticalButton ebutton = new EllipticalButton(150, 5, 50f, 15f) { + EllipticalButton ebutton = new EllipticalButton(150, 5, 50f, 15f) + { @Override - public void onMouseClicked(float x, float y, int mouseButton) { - System.out.println("Pressed ellipse with " + mouseButton); - } + public void onMouseClicked(float x, float y, int mouseButton) + { System.out.println("Pressed ellipse with " + mouseButton); } }; ebutton.colourProperties().setHasBorder(true); addElement(ebutton); - - - RoundedRectangularButton rbutton = new RoundedRectangularButton(5, 50, 100f, 30f, 10.0f) { + RoundedRectangularButton rbutton = new RoundedRectangularButton(5, 50, 100f, 30f, 10.0f) + { @Override - public void onMouseClicked(float x, float y, int mouseButton) { - System.out.println("Pressed rounded with " + mouseButton); - } + public void onMouseClicked(float x, float y, int mouseButton) + { System.out.println("Pressed rounded with " + mouseButton); } }; rbutton.colourProperties().setColour(1, 0, 0, 1); rbutton.colourProperties().setMouseoverColour(0, 1, 0, 1); addElement(rbutton); - - - TexturedButton tbutton = new TexturedButton(5, 100, 120, 50) { + TexturedButton tbutton = new TexturedButton(5, 100, 120, 50) + { @Override - public void onMouseClicked(float x, float y, int mouseButton) { - System.out.println("Pressed textured with " + mouseButton); - } + public void onMouseClicked(float x, float y, int mouseButton) + { System.out.println("Pressed textured with " + mouseButton); } }; tbutton.setTexture("test_button"); tbutton.setMouseoverTexture("test_button_mouseover"); tbutton.setPressedTexture("test_button_pressed"); addElement(tbutton); - - - RoundedRectangularTextfield field = new RoundedRectangularTextfield(200, 100, 200, 25, 5) { + RoundedRectangularTextfield field = new RoundedRectangularTextfield(200, 100, 200, 25, 5) + { @Override - public void onSubmit(String text) { - System.out.println("Enter pressed: " + text); - } + public void onSubmit(String text) + { System.out.println("Enter pressed: " + text); } }; field.getTextComponent().setAlignment(ETextAlignment.LEFT); field.getTextComponent().setFontName(LWJGLResourceManager.instance().lib.getFont("default")); field.getTextComponent().setPadding(5, 5, 5, 5); field.colourProperties().setHasBorder(true); addElement(field); - - RoundedRectangularPanel panel = new RoundedRectangularPanel(450, 10, 400, 400, 4); panel.colourProperties().setColour(1, 1, 1, 0.5f); panel.colourProperties().setMouseoverColour(1, 1, 1, 0.5f); panel.colourProperties().setMouseDownColour(1, 1, 1, 0.5f); panel.setSelectable(false); - - - PanelWindow window2 = new RoundedRectangularPanelWindow("Panel", 300, 0, 200, 200, 5) { + PanelWindow window2 = new RoundedRectangularPanelWindow("Panel", 300, 0, 200, 200, 5) + { @Override - protected void initElements() { } + protected void initElements() + {} }; window2.setVisible(true); window2.setSelectable(false); window2.setResizable(true); - - RectangularButton button2 = new RectangularButton(20, 20, 100, 30) { + RectangularButton button2 = new RectangularButton(20, 20, 100, 30) + { @Override - public void onMouseClicked(float x, float y, int mouseButton) { - System.out.println("Pressed rectangle2 with " + mouseButton); - } + public void onMouseClicked(float x, float y, int mouseButton) + { System.out.println("Pressed rectangle2 with " + mouseButton); } }; button2.colourProperties().setColour(1, 0, 0, 1); button2.colourProperties().setMouseoverColour(0, 1, 0, 1); @@ -130,75 +116,60 @@ public void onMouseClicked(float x, float y, int mouseButton) { button2.setPositionAbsolute(true); window2.addElement(button2); panel.addElement(window2); - - addElement(panel); - - RoundedRectangularTextBox textbox = new RoundedRectangularTextBox(0, 0, 300, 100, 5, 5) { + addElement(panel); + RoundedRectangularTextBox textbox = new RoundedRectangularTextBox(0, 0, 300, 100, 5, 5) + { @Override - public void onSubmit(String text) { - System.out.println("Enter pressed on textbox"); - } + public void onSubmit(String text) + { System.out.println("Enter pressed on textbox"); } }; textbox.colourProperties().setColour(0.8f, 0.8f, 0.8f, 0.8f); textbox.getTextComponent().setTextColour(0.1f, 0.0f, 0.0f, 1.0f); textbox.getTextComponent().setFontName(LWJGLResourceManager.instance().lib.getFont("default")); textbox.getTextComponent().setText("" - + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " - + "sed do eiusmod tempor incididunt ut labore et dolore magna."); + + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " + + "sed do eiusmod tempor incididunt ut labore et dolore magna."); // + "aliqua. Ut enim ad minim veniam, quis nostrud exercitation " // + "ullamco laboris nisi ut aliquip ex ea commodo consequat. "); textbox.setEditable(true); textbox.setReactToMouseOver(false); - //panel.addElement(textbox); - - RoundedRectangularScrollArea scroll = new RoundedRectangularScrollArea(10, 10, 300, 200, 25, ScrollDirection.VERTICAL, 4); scroll.colourProperties().setColour(0.5f, 0.5f, 0.5f, 0.5f); scroll.addElement(textbox); //addElement(scroll); - - RectangularCheckBox box1 = new RectangularCheckBox(5, 30, 15, CheckBoxCheckStyle.TICK); RoundedRectangularCheckBox box2 = new RoundedRectangularCheckBox(5, 50, 15, 5, CheckBoxCheckStyle.CROSS); box1.colourProperties().setColour(new Vector4f(0.3f, 0.3f, 0.3f, 1.0f)); box2.colourProperties().setColour(new Vector4f(0.3f, 0.3f, 0.3f, 1.0f)); - RadioButtonGroup group1 = new RadioButtonGroup(); CircularRadioButton radio1 = new CircularRadioButton("test", 5, 70, 7.5f); radio1.colourProperties().setColour(new Vector4f(0.3f, 0.3f, 0.3f, 1.0f)); - CircularRadioButton radio2 = new CircularRadioButton("test2", 5, 90, 7.5f); radio2.colourProperties().setColour(new Vector4f(0.3f, 0.3f, 0.3f, 1.0f)); - CircularRadioButton radio3 = new CircularRadioButton("test3", 5, 110, 7.5f); radio3.colourProperties().setColour(new Vector4f(0.3f, 0.3f, 0.3f, 1.0f)); - group1.add(radio1); group1.add(radio2); group1.add(radio3); - - - RoundedRectangularSolidProgressBar bar1 = new RoundedRectangularSolidProgressBar(340, 5, 5, 200, 3) { - + RoundedRectangularSolidProgressBar bar1 = new RoundedRectangularSolidProgressBar(340, 5, 5, 200, 3) + { @Override - public void update(float timestep) { - this.addProgress(0.1f * timestep); - } + public void update(float timestep) + { this.addProgress(0.1f * timestep); } }; bar1.setFillStyle(ProgressFillStyle.DOWN); - - RectangularSolidProgressBar bar2 = new RectangularSolidProgressBar(5, 240, 340, 5) { + RectangularSolidProgressBar bar2 = new RectangularSolidProgressBar(5, 240, 340, 5) + { @Override - public void update(float timestep) { - this.addProgress(0.1f * timestep); - } + public void update(float timestep) + { this.addProgress(0.1f * timestep); } }; - - - PanelWindow window = new RoundedRectangularPanelWindow("", 5, 300, 350, 250, 5) { + PanelWindow window = new RoundedRectangularPanelWindow("", 5, 300, 350, 250, 5) + { @Override - protected void initElements() { } + protected void initElements() + {} }; window.setVisible(true); window.setSelectable(false); @@ -211,16 +182,11 @@ protected void initElements() { } window.setReactToMouseOver(false); window.setResizable(true); addElement(1, window); - - ImageHolder image = new ImageHolder("test_image", 500, 50, 100, 100); addElement(1, image); } - @Override - public void onUpdate(float timestep) { - - } - + public void onUpdate(float timestep) + {} } diff --git a/src/com/bwyap/enginedriver/game/test/TestGUIController.java b/src/com/bwyap/enginedriver/game/test/TestGUIController.java index c0aca9b..38641fd 100644 --- a/src/com/bwyap/enginedriver/game/test/TestGUIController.java +++ b/src/com/bwyap/enginedriver/game/test/TestGUIController.java @@ -4,20 +4,17 @@ import com.bwyap.lwjgl.engine.gui.nanovg.NVGGUI; import com.bwyap.lwjgl.engine.gui.nanovg.NVGRenderer; - -public class TestGUIController extends GUIController { - +public class TestGUIController extends GUIController +{ private NVGGUI gui; - - - public TestGUIController() throws Exception { + + public TestGUIController() throws Exception + { super(new NVGRenderer()); - //gui = new TestGUI(); //((TestGUI)gui).init((NVGRenderer)renderer); - gui = new TestGUI(); - gui.init((NVGRenderer)renderer); + gui.init((NVGRenderer) renderer); this.setGUI(gui); } } diff --git a/src/com/bwyap/enginedriver/game/test/TestLitSceneObjects.java b/src/com/bwyap/enginedriver/game/test/TestLitSceneObjects.java index ffaf4f2..87cd447 100644 --- a/src/com/bwyap/enginedriver/game/test/TestLitSceneObjects.java +++ b/src/com/bwyap/enginedriver/game/test/TestLitSceneObjects.java @@ -15,31 +15,30 @@ import com.bwyap.lwjgl.engine.render3d.Material; import com.bwyap.lwjgl.engine.render3d.scene.LightedObjectLayer; -public class TestLitSceneObjects extends LightedObjectLayer { - - - public TestLitSceneObjects() throws Exception { +public class TestLitSceneObjects extends LightedObjectLayer +{ + public TestLitSceneObjects() throws Exception + { super(); int sqrt; - sqrt = 3; - for(int i = 0; i < sqrt*sqrt; i++) { + for (int i = 0; i < sqrt * sqrt; i++) + { RenderableEntity cube = new RenderableEntity("cube"); cube.setTexture(LWJGLTexture.getTexture("test")); cube.setMaterial(new Material(new Vector3f(0.7f, 1.0f, 0.7f), 0.1f)); - cube.setPosition(new Vector3f((i % sqrt) * 3 , ((i / sqrt) * -3) - 3, i/5)); + cube.setPosition(new Vector3f((i % sqrt) * 3, ((i / sqrt) * -3) - 3, i / 5)); this.addEntity(cube); } - AnimatedRenderableObject acube = new AnimatedRenderableObject("cube"); LWJGLTexture.getTexture("test_animated_particle").setAlpha(true); acube.setTexture(LWJGLTexture.getTexture("test_animated_particle")); acube.setMaterial(new Material(new Vector3f(0.7f, 1.0f, 0.7f), 0.1f)); acube.setPosition(new Vector3f(-3, 0, 0)); - this.addEntity(acube); - + this.addEntity(acube); sqrt = 16; - for(int i = 0; i < sqrt*sqrt; i++) { + for (int i = 0; i < sqrt * sqrt; i++) + { RenderableEntity icube = new RenderableEntity("icube"); icube.setTexture(LWJGLTexture.getTexture("test")); icube.setMaterial(new Material(new Vector3f(0.7f, 1.0f, 0.7f), 0.1f)); @@ -48,58 +47,43 @@ public TestLitSceneObjects() throws Exception { this.addEntity(icube); } } - - + float cutOff = 0; - + @Override - public void update(float timestep) { + public void update(float timestep) + { super.update(timestep); - - for (RotatableEntity cube : meshMap.get("cube")) { + for (RotatableEntity cube : meshMap.get("cube")) + { cube.setRotationAxisNormalize(0, 1, 1); cube.setRotationAmount(cube.getRotationAmount() + 3 * timestep); } - //cube.setRotationAmount(1.5f); cutOff += 0.01f; lighting.getSpotLights()[0].setCutOff(cutOff); - - for (RotatableEntity cube : instancedMeshMap.get("icube")) { + for (RotatableEntity cube : instancedMeshMap.get("icube")) + { cube.setRotationAxisNormalize(0, 1, 1); cube.setRotationAmount(cube.getRotationAmount() + 1 * timestep); } - } - - + @Override - public void handleInput(InputHandler input, float timestep) { + public void handleInput(InputHandler input, float timestep) + { float speed = 8; - - if (input.isKeyDown(GLFW_KEY_UP) && input.getKeyMods() != 0x1) { - lighting.getSpotLights()[0].movePosition(0, speed * timestep, 0); - } - - if (input.isKeyDown(GLFW_KEY_DOWN) && input.getKeyMods() != 0x1) { - lighting.getSpotLights()[0].movePosition(0, speed * -timestep, 0); - } - - if (input.isKeyDown(GLFW_KEY_LEFT)) { - lighting.getSpotLights()[0].movePosition(speed * -timestep, 0, 0); - } - - if (input.isKeyDown(GLFW_KEY_RIGHT)) { - lighting.getSpotLights()[0].movePosition(speed * timestep, 0, 0); - } - - if (input.isKeyDown(GLFW_KEY_DOWN) && input.getKeyMods() == 0x1) { - lighting.getSpotLights()[0].movePosition(0, 0, speed * timestep); - } - - if (input.isKeyDown(GLFW_KEY_UP) && input.getKeyMods() == 0x1) { - lighting.getSpotLights()[0].movePosition(0, 0, speed * -timestep); - } + if (input.isKeyDown(GLFW_KEY_UP) && input.getKeyMods() != 0x1) + { lighting.getSpotLights()[0].movePosition(0, speed * timestep, 0); } + if (input.isKeyDown(GLFW_KEY_DOWN) && input.getKeyMods() != 0x1) + { lighting.getSpotLights()[0].movePosition(0, speed * -timestep, 0); } + if (input.isKeyDown(GLFW_KEY_LEFT)) + { lighting.getSpotLights()[0].movePosition(speed * -timestep, 0, 0); } + if (input.isKeyDown(GLFW_KEY_RIGHT)) + { lighting.getSpotLights()[0].movePosition(speed * timestep, 0, 0); } + if (input.isKeyDown(GLFW_KEY_DOWN) && input.getKeyMods() == 0x1) + { lighting.getSpotLights()[0].movePosition(0, 0, speed * timestep); } + if (input.isKeyDown(GLFW_KEY_UP) && input.getKeyMods() == 0x1) + { lighting.getSpotLights()[0].movePosition(0, 0, speed * -timestep); } } - } diff --git a/src/com/bwyap/enginedriver/game/test/TestParticle.java b/src/com/bwyap/enginedriver/game/test/TestParticle.java index fb68539..f17c589 100644 --- a/src/com/bwyap/enginedriver/game/test/TestParticle.java +++ b/src/com/bwyap/enginedriver/game/test/TestParticle.java @@ -2,23 +2,15 @@ import com.bwyap.engine.particle.Particle; -public class TestParticle extends Particle { +public class TestParticle extends Particle +{ + TestParticle(float timeCreated, float lifetime) + { super(timeCreated, lifetime); } - - TestParticle(float timeCreated, float lifetime) { - super(timeCreated, lifetime); - } + TestParticle(TestParticle particle) + { super(particle); } - - TestParticle(TestParticle particle) { - super(particle); - } - - @Override - public void update(float timestep) { - movePosition(getVelocity().x() * timestep, getVelocity().y() * timestep, getVelocity().z() * timestep); - - } - + public void update(float timestep) + { movePosition(getVelocity().x() * timestep, getVelocity().y() * timestep, getVelocity().z() * timestep); } } diff --git a/src/com/bwyap/enginedriver/game/test/TestParticleSystem.java b/src/com/bwyap/enginedriver/game/test/TestParticleSystem.java index 4b8f22c..4568250 100644 --- a/src/com/bwyap/enginedriver/game/test/TestParticleSystem.java +++ b/src/com/bwyap/enginedriver/game/test/TestParticleSystem.java @@ -5,12 +5,11 @@ import com.bwyap.lwjgl.engine.particle.ParticleSystem; import com.bwyap.lwjgl.engine.render3d.LWJGLTexture; -public class TestParticleSystem extends ParticleSystem { - - - public TestParticleSystem(LWJGLTexture texture) throws Exception { +public class TestParticleSystem extends ParticleSystem +{ + public TestParticleSystem(LWJGLTexture texture) throws Exception + { super(texture, 2000, 10, 0.01f); - this.setActive(true); this.setParticleLifetime(2f, 0); this.setBaseVelocity(new Vector3f(0, 1f, 0)); @@ -22,16 +21,14 @@ public TestParticleSystem(LWJGLTexture texture) throws Exception { this.setParticleRadius(0.1f, 0.1f); this.setEmitRadius(1f); } - - + @Override - protected void setMesh() throws Exception { - this.setMesh("particle"); - } - - + protected void setMesh() throws Exception + { this.setMesh("particle"); } + @Override - protected TestParticle generateNewParticle(float now) { + protected TestParticle generateNewParticle(float now) + { TestParticle p = new TestParticle(now, (rand.nextFloat() * (particleLifetimeMax - particleLifetimeMin)) + particleLifetimeMin); p.setColour(generateColour()); p.setRadius(generateRadius()); @@ -39,5 +36,4 @@ protected TestParticle generateNewParticle(float now) { p.setVelocity(generateStartVelocity()); return p; } - } diff --git a/src/com/bwyap/enginedriver/game/test/TestScene.java b/src/com/bwyap/enginedriver/game/test/TestScene.java index 9858c46..31629d6 100644 --- a/src/com/bwyap/enginedriver/game/test/TestScene.java +++ b/src/com/bwyap/enginedriver/game/test/TestScene.java @@ -17,14 +17,15 @@ import com.bwyap.lwjgl.engine.render3d.scene.LightedObjectLayer; import com.bwyap.lwjgl.engine.render3d.scene.ParticleSystemLayer; -public class TestScene extends Scene { - - public TestScene(int width, int height) { +public class TestScene extends Scene +{ + public TestScene(int width, int height) + { super(width, height); - LightedObjectLayer element = null; ParticleSystemLayer particles = null; - try { + try + { element = new TestLitSceneObjects(); element.getLighting().createPointLight(new Vector3f(1, 1, 1), new Vector3f(0, 0, 5), 1f).setAttenuation(new Attenuation(1, 0.05f, 0)); //element.getLighting().createDirectionalLight(new Vector3f(1, 1, 1), new Vector3f(0, moveStep, 0), 0f, new Vector3f(1, 1, 1)); @@ -33,76 +34,76 @@ public TestScene(int width, int height) { light.getPointLight().setAttenuation(new Attenuation(1.0f, 0.1f, 0.01f)); light.setCutOff(4); //element.getLighting().createSpotLight(new Vector3f(1, 1, 1), new Vector3f(1, 0, moveStep), 1f, new Vector3f(0, 0, -1), 1rotateStep).getPointLight().setAttenuation(new Attenuation(1.0f, 0.1f, 0.0f)); - TestParticleSystem system = new TestParticleSystem(LWJGLTexture.getTexture("test_particle")); TestAnimatedParticleSystem animatedSystem = new TestAnimatedParticleSystem(LWJGLTexture.getTexture("test_animated_particle")); - particles = new ParticleSystemLayer(); particles.addEntity(animatedSystem); particles.addEntity(system); } - catch (Exception e) { + catch (Exception e) + { e.printStackTrace(); } - element.getLighting().setAmbient(new Vector3f(0.05f, 0.1f, 0.05f)); element.getLighting().setSpecularPower(10f); - this.addLayer(element); this.addLayer(particles); - camera.setPosition(0, 0, 5); } - - + @Override - public void handleInput(InputHandler input, float timestep) { + public void handleInput(InputHandler input, float timestep) + { super.handleInput(input, timestep); - float moveStep = 10; float rotateStep = 50; - - if (input.isKeyDown(GLFW_KEY_W)) { - if ((input.getKeyMods() & 0x1) == 0x1) { + if (input.isKeyDown(GLFW_KEY_W)) + { + if ((input.getKeyMods() & 0x1) == 0x1) + { camera.moveRotation(rotateStep * -timestep, 0, 0); } else camera.movePosition(0, moveStep * timestep, 0); } - - if (input.isKeyDown(GLFW_KEY_S)) { - if ((input.getKeyMods() & 0x1) == 0x1) { + if (input.isKeyDown(GLFW_KEY_S)) + { + if ((input.getKeyMods() & 0x1) == 0x1) + { camera.moveRotation(rotateStep * timestep, 0, 0); } else camera.movePosition(0, moveStep * -timestep, 0); } - - if (input.isKeyDown(GLFW_KEY_A)) { - if ((input.getKeyMods() & 0x1) == 0x1) { + if (input.isKeyDown(GLFW_KEY_A)) + { + if ((input.getKeyMods() & 0x1) == 0x1) + { camera.moveRotation(0, rotateStep * -timestep, 0); } else camera.movePosition(moveStep * -timestep, 0, 0); } - - if (input.isKeyDown(GLFW_KEY_D)) { - if ((input.getKeyMods() & 0x1) == 0x1) { + if (input.isKeyDown(GLFW_KEY_D)) + { + if ((input.getKeyMods() & 0x1) == 0x1) + { camera.moveRotation(0, rotateStep * timestep, 0); } else camera.movePosition(moveStep * timestep, 0, 0); } - - if (input.isKeyDown(GLFW_KEY_E)) { - if ((input.getKeyMods() & 0x1) == 0x1) { + if (input.isKeyDown(GLFW_KEY_E)) + { + if ((input.getKeyMods() & 0x1) == 0x1) + { camera.moveRotation(0, 0, rotateStep * timestep); } else camera.movePosition(0, 0, moveStep * timestep); } - - if (input.isKeyDown(GLFW_KEY_Q)) { - if ((input.getKeyMods() & 0x1) == 0x1) { + if (input.isKeyDown(GLFW_KEY_Q)) + { + if ((input.getKeyMods() & 0x1) == 0x1) + { camera.moveRotation(0, 0, rotateStep * -timestep); } else camera.movePosition(0, 0, moveStep * -timestep); } - } } diff --git a/src/com/bwyap/enginedriver/resource/jsonwrapper/Settings.java b/src/com/bwyap/enginedriver/resource/jsonwrapper/Settings.java index 5889fc6..d52e9e3 100644 --- a/src/com/bwyap/enginedriver/resource/jsonwrapper/Settings.java +++ b/src/com/bwyap/enginedriver/resource/jsonwrapper/Settings.java @@ -4,89 +4,65 @@ import com.bwyap.utility.resource.JSONWrapper; -/** - * A wrapper class for the settings config file. +/** A wrapper class for the settings config file. * Allows easy access to the different properties stored in the config file. - * @author bwyap - * - */ -public class Settings extends JSONWrapper { - - public Settings(JSONObject object) { - super(object); - } + * + * @author bwyap */ +public class Settings extends JSONWrapper +{ + public Settings(JSONObject object) + { super(object); } - - /** - * Gets the target fps - * @return - */ - public int getFPS() { - return getInteger(object, "fps"); - } - - - /** - * Get the default width of the game window - * @return - */ - public int getWidth() { - return getInteger((JSONObject) object.get("window"), "width"); - } - - - /** - * Get the default height of the game window - * @return - */ - public int getHeight() { - return getInteger((JSONObject) object.get("window"), "height"); - } - - - /** - * Check whether the window should enable vsync - * @return - */ - public boolean isVSync() { - return getBoolean(object, "vsync"); - } - - - /** - * Check whether the window should render the GUI using antialiasing - * @return - */ - public boolean isAntiAlias() { - return getBoolean(object, "antialias"); - } - - - /** - * Check whether the renderer should render in polygon mode - * @return - */ - public boolean usePolygonMode() { - return getBoolean(object, "polygon_mode"); - } - - - /** - * Check whether the window should show the fps - * @return - */ - public boolean showFpsWindow() { - return getBoolean(object, "showfps_window"); - } - - - /** - * Validate the loaded settings file. - * @return - */ + /** Gets the target fps + * + * @return */ + public int getFPS() + { return getInteger(object, "fps"); } + + /** Get the default width of the game window + * + * @return */ + public int getWidth() + { return getInteger((JSONObject) object.get("window"), "width"); } + + /** Get the default height of the game window + * + * @return */ + public int getHeight() + { return getInteger((JSONObject) object.get("window"), "height"); } + + /** Check whether the window should enable vsync + * + * @return */ + public boolean isVSync() + { return getBoolean(object, "vsync"); } + + /** Check whether the window should render the GUI using antialiasing + * + * @return */ + public boolean isAntiAlias() + { return getBoolean(object, "antialias"); } + + /** Check whether the renderer should render in polygon mode + * + * @return */ + public boolean usePolygonMode() + { return getBoolean(object, "polygon_mode"); } + + /** Check whether the window should show the fps + * + * @return */ + public boolean showFpsWindow() + { return getBoolean(object, "showfps_window"); } + + /** Validate the loaded settings file. + * + * @return */ @Override - public boolean isValid() { - try { + public boolean isValid() + { + try + { if (getFPS() < 0) throw new Exception("fps must be a positive integer."); getWidth(); getHeight(); @@ -95,12 +71,11 @@ public boolean isValid() { usePolygonMode(); showFpsWindow(); } - catch (Exception e) { + catch (Exception e) + { e.printStackTrace(System.out); return false; } return true; } - - } diff --git a/src/com/bwyap/enginedriver/window/DriverWindow.java b/src/com/bwyap/enginedriver/window/DriverWindow.java index 78ac92e..ba192e7 100644 --- a/src/com/bwyap/enginedriver/window/DriverWindow.java +++ b/src/com/bwyap/enginedriver/window/DriverWindow.java @@ -5,46 +5,40 @@ import com.bwyap.lwjgl.engine.resource.LWJGLResourceManager; import com.bwyap.lwjgl.window.GLFWWindow; - -/** - * A concrete implementation of the GLFWWindow class for Domination. - * @author bwyap - * - */ -public class DriverWindow extends GLFWWindow { - - +/** A concrete implementation of the GLFWWindow class for Domination. + * + * @author bwyap */ +public class DriverWindow extends GLFWWindow +{ public static final String VERSION = "0.3"; - - - public DriverWindow(int width, int height, String title, boolean vSync, boolean polygonMode, boolean showFps) { - super(width, height, title, vSync, polygonMode, showFps); - } - - - public DriverWindow() { + + public DriverWindow(int width, int height, String title, boolean vSync, boolean polygonMode, boolean showFps) + { super(width, height, title, vSync, polygonMode, showFps); } + + public DriverWindow() + { super(LWJGLResourceManager.instance().settings().getWidth(), - LWJGLResourceManager.instance().settings().getHeight(), - "EngineDriver v" + VERSION, - LWJGLResourceManager.instance().settings().isVSync(), - LWJGLResourceManager.instance().settings().usePolygonMode(), - LWJGLResourceManager.instance().settings().showFpsWindow()); + LWJGLResourceManager.instance().settings().getHeight(), + "EngineDriver v" + VERSION, + LWJGLResourceManager.instance().settings().isVSync(), + LWJGLResourceManager.instance().settings().usePolygonMode(), + LWJGLResourceManager.instance().settings().showFpsWindow()); } - - + @Override - public void loadGLRequiredResources() { - try { + public void loadGLRequiredResources() + { + try + { LWJGLResourceManager.instance().loadDependentResources(); - } catch (Exception e) { + } + catch (Exception e) + { e.printStackTrace(); } } - @Override - public EngineInterface createEngine() throws Exception { - return new GameEngine(this, LWJGLResourceManager.instance().settings().getFPS()); - } - + public EngineInterface createEngine() throws Exception + { return new GameEngine(this, LWJGLResourceManager.instance().settings().getFPS()); } } diff --git a/src/com/bwyap/lwjgl/engine/LWJGL3DEngine.java b/src/com/bwyap/lwjgl/engine/LWJGL3DEngine.java index 3f5fd76..f5a4b62 100644 --- a/src/com/bwyap/lwjgl/engine/LWJGL3DEngine.java +++ b/src/com/bwyap/lwjgl/engine/LWJGL3DEngine.java @@ -8,98 +8,86 @@ import com.bwyap.engine.window.WindowInterface; import com.bwyap.lwjgl.engine.render3d.LWJGLRenderer; - -/** - *

+/**

* A fixed timestep engine that uses LWJGL to render a 3D scene. * If no scene is set, the scene rendering call will be skipped. - * This engine also supports a GUI which will be updated and + * This engine also supports a GUI which will be updated and * rendered if set using the {@code initGUI()} method. *

*

* This rendering engine makes use of {@code Scene} objects. * Each tick, the current scene will be updated and rendered. - * The {@code currentScene} is initially null and must be set - * using the {@code setScene} method. + * The {@code currentScene} is initially null and must be set + * using the {@code setScene} method. *

- * @author bwyap - * - */ -public abstract class LWJGL3DEngine extends FixedTimestepEngine { - + * + * @author bwyap */ +public abstract class LWJGL3DEngine extends FixedTimestepEngine +{ private final LWJGLRenderer renderer; private final GUIControllerInterface guiController; - private float fpsPrintTimer = 0; private Scene currentScene; - - - public LWJGL3DEngine(WindowInterface window, int targetFPS) throws Exception { + + public LWJGL3DEngine(WindowInterface window, int targetFPS) throws Exception + { super(window, targetFPS); this.renderer = new LWJGLRenderer(); this.guiController = initGUI(); } - - /** - * Initialise the GUI system used by this engine. + /** Initialise the GUI system used by this engine. * (Return {@code null} if the engine does not require a GUI) - * @throws Exception - */ + * + * @throws Exception */ public abstract GUIControllerInterface initGUI() throws Exception; - @Override - public float getCurrentTime() { - return (float) glfwGetTime(); - } - - - /** - * Set the scene to be rendered. - * @param scene - */ - public void setScene(Scene scene) { - currentScene = scene; - } - - + public float getCurrentTime() + { return (float) glfwGetTime(); } + + /** Set the scene to be rendered. + * + * @param scene */ + public void setScene(Scene scene) + { currentScene = scene; } + @Override - public final void update(float timestep) { - if (currentScene != null) { + public final void update(float timestep) + { + if (currentScene != null) + { currentScene.handleInput(window.getInputHandler(), timestep); currentScene.update(timestep); } - - if (guiController != null) { + if (guiController != null) + { guiController.handleInput(window.getInputHandler()); guiController.update(timestep); } - //Print the FPS to the console. //TODO: remove this later. fpsPrintTimer += timestep; - if (fpsPrintTimer >= 1) { + if (fpsPrintTimer >= 1) + { fpsPrintTimer -= 1; //System.out.println((int)getFPS() + " fps"); } } - - + @Override - public final void render(float timestep) { - if (currentScene != null) { + public final void render(float timestep) + { + if (currentScene != null) + { renderer.startRender3D(window, currentScene.getCamera()); renderer.renderScene(currentScene); } if (guiController != null) guiController.render(window); - renderer.stopRender(); - } - - - @Override - public void cleanup() { - renderer.cleanup(); + renderer.stopRender(); } + @Override + public void cleanup() + { renderer.cleanup(); } } diff --git a/src/com/bwyap/lwjgl/engine/entity/AnimatedRenderableObject.java b/src/com/bwyap/lwjgl/engine/entity/AnimatedRenderableObject.java index 5ea6110..8d11b96 100644 --- a/src/com/bwyap/lwjgl/engine/entity/AnimatedRenderableObject.java +++ b/src/com/bwyap/lwjgl/engine/entity/AnimatedRenderableObject.java @@ -1,58 +1,50 @@ package com.bwyap.lwjgl.engine.entity; - -/** - * A renderable object which supports an animated texture. - * @author bwyap - * - */ -public class AnimatedRenderableObject extends RenderableEntity implements AnimatedTexture { - +/** A renderable object which supports an animated texture. + * + * @author bwyap */ +public class AnimatedRenderableObject extends RenderableEntity implements AnimatedTexture +{ private int texturePosition; private float textureChangeSpeed; private float currentFrameTime; - - public AnimatedRenderableObject(String meshName) { + public AnimatedRenderableObject(String meshName) + { super(meshName); this.texturePosition = 0; this.textureChangeSpeed = 0; this.currentFrameTime = 0; } - - /** - * {@inheritDoc} + /** {@inheritDoc} *

* IMPORTANT: * When overriding this method to implement particle physics * ensure you call {@code super.update(timestep)} to animate the particle. *

- * @param timestep - */ + * + * @param timestep */ @Override - public void update(float timestep) { + public void update(float timestep) + { currentFrameTime += timestep; - if (currentFrameTime >= textureChangeSpeed) { + if (currentFrameTime >= textureChangeSpeed) + { currentFrameTime = 0; texturePosition++; } } - - - @Override - public int getTexturePosition() { - return texturePosition; - } - + @Override - public void setTextureChangeSpeed(float speed) { - this.textureChangeSpeed = speed; - } - + public int getTexturePosition() + { return texturePosition; } + @Override - public float getTextureChangeSpeed() { - return textureChangeSpeed; - } + public void setTextureChangeSpeed(float speed) + { this.textureChangeSpeed = speed; } + @Override + public float getTextureChangeSpeed() + { return textureChangeSpeed; } } diff --git a/src/com/bwyap/lwjgl/engine/entity/AnimatedTexture.java b/src/com/bwyap/lwjgl/engine/entity/AnimatedTexture.java index 4d5a1b2..e17d5a9 100644 --- a/src/com/bwyap/lwjgl/engine/entity/AnimatedTexture.java +++ b/src/com/bwyap/lwjgl/engine/entity/AnimatedTexture.java @@ -1,25 +1,19 @@ package com.bwyap.lwjgl.engine.entity; -public interface AnimatedTexture { - - - /** - * Set the speed at which the texture changes. - * @param speed - */ +public interface AnimatedTexture +{ + /** Set the speed at which the texture changes. + * + * @param speed */ public void setTextureChangeSpeed(float speed); - - - /** - * Get the speed at which the texture changes. - * @return - */ + + /** Get the speed at which the texture changes. + * + * @return */ public float getTextureChangeSpeed(); - - - /** - * Get the texture position at which the entity should be using - * @return - */ + + /** Get the texture position at which the entity should be using + * + * @return */ public int getTexturePosition(); } diff --git a/src/com/bwyap/lwjgl/engine/entity/RenderableEntity.java b/src/com/bwyap/lwjgl/engine/entity/RenderableEntity.java index dd9e11d..c97aef9 100644 --- a/src/com/bwyap/lwjgl/engine/entity/RenderableEntity.java +++ b/src/com/bwyap/lwjgl/engine/entity/RenderableEntity.java @@ -4,98 +4,71 @@ import com.bwyap.lwjgl.engine.render3d.Material; import com.bwyap.lwjgl.engine.render3d.LWJGLTexture; -/** - *

+/**

* A 3D entity that can be rendered to the screen. - * Stores a mesh name, as well as a texture and - * material with which to render the mesh. + * Stores a mesh name, as well as a texture and + * material with which to render the mesh. * Extends {@code RotatableEntity} which provide * methods to move, scale and rotate the entity. *

- *

+ *

* Implements the following interfaces: - * {@code EntityInterface}, + * {@code EntityInterface}, * {@code ScalableInterface}, * {@code MovableInterface} and * {@code RotatableInterface}. *

- * @author bwyap - * - */ -public class RenderableEntity extends RotatableEntity { - + * + * @author bwyap */ +public class RenderableEntity extends RotatableEntity +{ private final String meshName; - private LWJGLTexture texture; private Material material; - - - public RenderableEntity(String meshName) { - this.meshName = meshName; - } - - - /** - * Update the object's state. + + public RenderableEntity(String meshName) + { this.meshName = meshName; } + + /** Update the object's state. * TODO make this method abstract - * @param timestep - */ - public void update(float timestep) { - - } - - - /** - * Get the name of the mesh used by this object - * @return - */ - public String getMeshName() { - return meshName; - } - - - /** - * Get the texture used by this object - * @return - */ - public LWJGLTexture getTexture() { - return texture; - } - - - /** - * Check if the object has a texture to use - * @return - */ - public boolean isTextured() { - return texture != null; - } - - - /** - * Set the texture used by this object - * @param texture - */ - public void setTexture(LWJGLTexture texture) { - this.texture = texture; - } - - - /** - * Get the material used by this object - * @return - */ - public Material getMaterial() { - return material; - } - - - /** - * Set the material used by this object - * @param material - */ - public void setMaterial(Material material) { - this.material = material; - } - + * + * @param timestep */ + public void update(float timestep) + {} + + /** Get the name of the mesh used by this object + * + * @return */ + public String getMeshName() + { return meshName; } + + /** Get the texture used by this object + * + * @return */ + public LWJGLTexture getTexture() + { return texture; } + + /** Check if the object has a texture to use + * + * @return */ + public boolean isTextured() + { return texture != null; } + + /** Set the texture used by this object + * + * @param texture */ + public void setTexture(LWJGLTexture texture) + { this.texture = texture; } + + /** Get the material used by this object + * + * @return */ + public Material getMaterial() + { return material; } + + /** Set the material used by this object + * + * @param material */ + public void setMaterial(Material material) + { this.material = material; } } diff --git a/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGFont.java b/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGFont.java index a71face..4ea624f 100644 --- a/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGFont.java +++ b/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGFont.java @@ -8,103 +8,80 @@ import java.util.HashMap; import java.util.Map; - -/** - * Holds the name and path to a font that can be - * used by NanoVG to render text using a .tff font +/** Holds the name and path to a font that can be + * used by NanoVG to render text using a .tff font * file. The font must be loaded into a byte buffer - * using the {@code load()} command before it can - * be used. - */ -public class NVGFont { - + * using the {@code load()} command before it can + * be used. */ +public class NVGFont +{ private static Map fonts = new HashMap(); - private final String path; private final String fontName; private ByteBuffer fontData; - - - private NVGFont(String fontName, String path) { + + private NVGFont(String fontName, String path) + { this.fontName = fontName; this.path = path; } - - - /** - * Load the font data into a Byte Buffer. - * This is automatically called when the font + + /** Load the font data into a Byte Buffer. + * This is automatically called when the font * is loaded via the static method {@code createFont}. - * @throws IOException - */ - private void load() throws IOException { - fontData = ioResourceToByteBuffer(path, 64*64); - } - - - /** - * Get the name of the font - * @return - */ - public String getName() { - return fontName; - } - - - /** - * Get the buffer containing the loaded font data. + * + * @throws IOException */ + private void load() throws IOException + { fontData = ioResourceToByteBuffer(path, 64 * 64); } + + /** Get the name of the font + * + * @return */ + public String getName() + { return fontName; } + + /** Get the buffer containing the loaded font data. * If the font has not yet been loaded this will be null. * Use the method {@code load()} to load the font data. - * @return - */ - public ByteBuffer getBuffer() { - return fontData; - } - - + * + * @return */ + public ByteBuffer getBuffer() + { return fontData; } + /* ============== * STATIC METHODS * ============== */ - - - /** - * Create a font. - * The font is automatically added to + /** Create a font. + * The font is automatically added to * NanoVGFont's static list of fonts. - * @param fontName - * @param path + * + * @param fontName + * @param path * @return - * @throws IOException - */ - public static NVGFont createFont(String fontName, String path) throws IOException { + * @throws IOException */ + public static NVGFont createFont(String fontName, String path) throws IOException + { NVGFont font = new NVGFont(fontName, path); font.load(); fonts.put(fontName, font); return fonts.get(fontName); } - - - /** - * Gets a font that has been previously created. + + /** Gets a font that has been previously created. * If the font doesn't exist, null will be returned. - * @param fontName - * @return - */ - public static NVGFont getFont(String fontName) { - return fonts.get(fontName); - } - - - /** - * Loads a specified font for the given NanoVG context. - * This must be called before a font can be used by a + * + * @param fontName + * @return */ + public static NVGFont getFont(String fontName) + { return fonts.get(fontName); } + + /** Loads a specified font for the given NanoVG context. + * This must be called before a font can be used by a * NanoVGGUI. + * * @param context - * @param fontName - */ - public static void acquireFont(long context, String fontName) { - nvgCreateFontMem(context, getFont(fontName).getName(), getFont(fontName).getBuffer(), 0); - } - + * @param fontName */ + public static void acquireFont(long context, String fontName) + { nvgCreateFontMem(context, getFont(fontName).getName(), getFont(fontName).getBuffer(), 0); } } \ No newline at end of file diff --git a/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGGUI.java b/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGGUI.java index de2c28d..8a60e3a 100644 --- a/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGGUI.java +++ b/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGGUI.java @@ -2,24 +2,14 @@ import com.bwyap.engine.gui.GUI; - -/** - * A GUI that uses NanoVG for rendering. - * @author bwyap - * - */ -public abstract class NVGGUI extends GUI { - - - public NVGGUI(float width, float height) { - super(width, height); - } - - - /** - * Initialize NVG required objects - */ +/** A GUI that uses NanoVG for rendering. + * + * @author bwyap */ +public abstract class NVGGUI extends GUI +{ + public NVGGUI(float width, float height) + { super(width, height); } + + /** Initialize NVG required objects */ public abstract void init(NVGRenderer renderer); - - } diff --git a/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGRenderer.java b/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGRenderer.java index ddf2617..cf7ba82 100644 --- a/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGRenderer.java +++ b/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGRenderer.java @@ -83,258 +83,233 @@ import com.bwyap.engine.window.WindowInterface; import com.bwyap.lwjgl.engine.resource.LWJGLResourceManager; - -/** - * A GUI renderer that uses LWJGL's included NanoVG library +/** A GUI renderer that uses LWJGL's included NanoVG library * to render 2D vector graphics to the screen. - * @author bwyap - * - */ -public class NVGRenderer extends GUIRenderer { - + * + * @author bwyap */ +public class NVGRenderer extends GUIRenderer +{ protected final long vgID; protected final Set loadedFonts; - private static NVGColor colour = NVGColor.create(); - private boolean resetAlpha = true; - - - public NVGRenderer() throws Exception { + + public NVGRenderer() throws Exception + { // Initialise the GUI if (LWJGLResourceManager.instance().settings().isAntiAlias()) vgID = nvgCreate(NVG_ANTIALIAS | NVG_STENCIL_STROKES); - else + else vgID = nvgCreate(NVG_STENCIL_STROKES); - - if (vgID == NULL) + if (vgID == NULL) throw new Exception("Could not initialise NanoVG"); - // TODO clean this up LWJGLResourceManager.instance().loadNVGResources(getContext()); - - loadedFonts = new HashSet(); - } - - - /** - * Get the ID of the NanoVG context. - * @return - */ - public long getContext() { - return vgID; + loadedFonts = new HashSet(); } - + /** Get the ID of the NanoVG context. + * + * @return */ + public long getContext() + { return vgID; } + @Override - protected final void beginRenderGUI(WindowInterface window) { - nvgBeginFrame(vgID, window.getWidth(), window.getHeight(), 2); - } - - + protected final void beginRenderGUI(WindowInterface window) + { nvgBeginFrame(vgID, window.getWidth(), window.getHeight(), 2); } + @Override - protected void renderGUI(Panel panel, WindowInterface window) { - renderPanel(panel, window, panel.getPosition()); - } - - + protected void renderGUI(Panel panel, WindowInterface window) + { renderPanel(panel, window, panel.getPosition()); } + @Override - protected final void endRenderGUI() { - nvgEndFrame(vgID); - - // Restore state - glEnable(GL_DEPTH_TEST); - glEnable(GL_STENCIL_TEST); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + protected final void endRenderGUI() + { + nvgEndFrame(vgID); + // Restore state + glEnable(GL_DEPTH_TEST); + glEnable(GL_STENCIL_TEST); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } - - + /* ================= * RENDERING METHODS * ================= */ - - @Override - public void renderPanel(Panel panel, WindowInterface window, Vector2f parent) { - if (panel instanceof PanelWindow) { - if (!((PanelWindow)panel).isVisible()) return; + public void renderPanel(Panel panel, WindowInterface window, Vector2f parent) + { + if (panel instanceof PanelWindow) + { if (!((PanelWindow) panel).isVisible()) return; } + if (panel instanceof IFade) + { + if (((IFade) panel).getFade().isFading()) + { nvgGlobalAlpha(getContext(), ((IFade) panel).getFade().getFade()); } } - - if (panel instanceof IFade) { - if (((IFade)panel).getFade().isFading()) { - nvgGlobalAlpha(getContext(), ((IFade)panel).getFade().getFade()); - } - } - panel.updateBounds(window, parent); renderColouredVectorShape(panel, panel); - - if (panel.isClip()) { - pushScissor(getContext(), - panel.getPositionX() + panel.getPaddingLeft(), - panel.getPositionY() + panel.getPaddingTop(), - panel.getBounds().x - panel.getPaddingRight(), - panel.getBounds().y - panel.getPaddingBottom()); - } - + if (panel.isClip()) + { pushScissor(getContext(), + panel.getPositionX() + panel.getPaddingLeft(), + panel.getPositionY() + panel.getPaddingTop(), + panel.getBounds().x - panel.getPaddingRight(), + panel.getBounds().y - panel.getPaddingBottom()); } Iterator it = panel.iterator(); - while (it.hasNext()) { + while (it.hasNext()) + { GUIElementInterface e = it.next(); - // Update the element's bounds e.updateBounds(panel, panel.getPosition()); - // Render element - if (e instanceof Button) renderButton((Button)e); - else if (e instanceof VectorScrollArea) renderVectorScrollArea((VectorScrollArea)e, window); - else if (e instanceof VectorCheckBox) renderVectorCheckBox((VectorCheckBox)e); - else if (e instanceof VectorRadioButton) renderVectorRadioButton((VectorRadioButton)e); - else if (e instanceof RadioButtonGroup) renderRadioButtonGroup((RadioButtonGroup)e, panel); - else if (e instanceof VectorProgressBar) renderVectorProgressBar((VectorProgressBar)e); - else if (e instanceof Label) renderLabel((Label)e); - else if (e instanceof VectorTextBox) renderVectorTextBox((VectorTextBox)e); - else if (e instanceof VectorTextField) renderVectorTextField((VectorTextField)e); - else if (e instanceof ImageHolder) renderImage((ImageHolder)e); - else if (e instanceof Panel) { + if (e instanceof Button) + renderButton((Button) e); + else if (e instanceof VectorScrollArea) + renderVectorScrollArea((VectorScrollArea) e, window); + else if (e instanceof VectorCheckBox) + renderVectorCheckBox((VectorCheckBox) e); + else if (e instanceof VectorRadioButton) + renderVectorRadioButton((VectorRadioButton) e); + else if (e instanceof RadioButtonGroup) + renderRadioButtonGroup((RadioButtonGroup) e, panel); + else if (e instanceof VectorProgressBar) + renderVectorProgressBar((VectorProgressBar) e); + else if (e instanceof Label) + renderLabel((Label) e); + else if (e instanceof VectorTextBox) + renderVectorTextBox((VectorTextBox) e); + else if (e instanceof VectorTextField) + renderVectorTextField((VectorTextField) e); + else if (e instanceof ImageHolder) + renderImage((ImageHolder) e); + else if (e instanceof Panel) + { if (e instanceof PanelWindow) resetAlpha = false; - renderPanel((Panel)e, window, panel.getPosition()); + renderPanel((Panel) e, window, panel.getPosition()); resetAlpha = true; } } - // Render any text it may have - if (panel instanceof ITextDisplay) { - renderText(((ITextDisplay)panel).getTextComponent(), panel); - } - + if (panel instanceof ITextDisplay) + { renderText(((ITextDisplay) panel).getTextComponent(), panel); } popScissor(getContext()); if (resetAlpha) nvgGlobalAlpha(getContext(), 1.0f); } - - + @Override - public void renderVectorTextField(VectorTextField textfield) { + public void renderVectorTextField(VectorTextField textfield) + { renderColouredVectorShape(textfield, textfield); renderText(textfield.getTextComponent(), textfield); } - @Override - public void renderVectorTextBox(VectorTextBox textBox) { + public void renderVectorTextBox(VectorTextBox textBox) + { renderColouredVectorShape(textBox, textBox); renderText(textBox.getTextComponent(), textBox); } - - + @Override - public void renderLabel(Label label) { - renderText(label.getTextComponent(), label); - } - - + public void renderLabel(Label label) + { renderText(label.getTextComponent(), label); } + @Override - public void renderVectorScrollArea(VectorScrollArea scrollArea, WindowInterface window) { + public void renderVectorScrollArea(VectorScrollArea scrollArea, WindowInterface window) + { // Render the panel contents - renderPanel(scrollArea, window, scrollArea.getPosition()); - + renderPanel(scrollArea, window, scrollArea.getPosition()); // Render the scroll bar if (scrollArea.renderScrollBar()) renderColouredVectorShape(scrollArea.getScrollBar(), scrollArea.getScrollBar()); } - - + @Override - public void renderButton(Button button) { + public void renderButton(Button button) + { // Render the button - if (button instanceof TexturedButton) renderTexturedButton((TexturedButton) button); + if (button instanceof TexturedButton) + renderTexturedButton((TexturedButton) button); else if (button instanceof VectorButton) renderVectorButton((VectorButton) button); - // Render any text it may have renderText(button.getTextComponent(), button); } - - + @Override - public void renderVectorProgressBar(VectorProgressBar progressBar) { + public void renderVectorProgressBar(VectorProgressBar progressBar) + { // Render the empty progress bar renderColouredVectorShape(progressBar, progressBar); - // Render the progress by setting a scissor - switch (progressBar.getFillStyle()) { + switch (progressBar.getFillStyle()) + { case DOWN: - pushScissor(getContext(), - progressBar.getPositionX(), - progressBar.getPositionY(), - progressBar.getWidth(), - progressBar.getHeight() * progressBar.getProgress()); + pushScissor(getContext(), + progressBar.getPositionX(), + progressBar.getPositionY(), + progressBar.getWidth(), + progressBar.getHeight() * progressBar.getProgress()); break; case LEFT: - pushScissor(getContext(), - progressBar.getPositionX() + progressBar.getWidth() * (1 - progressBar.getProgress()), - progressBar.getPositionY(), - progressBar.getWidth() * progressBar.getProgress(), - progressBar.getHeight()); + pushScissor(getContext(), + progressBar.getPositionX() + progressBar.getWidth() * (1 - progressBar.getProgress()), + progressBar.getPositionY(), + progressBar.getWidth() * progressBar.getProgress(), + progressBar.getHeight()); break; case RIGHT: - pushScissor(getContext(), - progressBar.getPositionX(), - progressBar.getPositionY(), - progressBar.getWidth() * progressBar.getProgress(), + pushScissor(getContext(), + progressBar.getPositionX(), + progressBar.getPositionY(), + progressBar.getWidth() * progressBar.getProgress(), progressBar.getHeight()); break; case UP: - pushScissor(getContext(), - progressBar.getPositionX(), - progressBar.getPositionY() + progressBar.getHeight() * (1 - progressBar.getProgress()), - progressBar.getWidth(), - progressBar.getHeight()); + pushScissor(getContext(), + progressBar.getPositionX(), + progressBar.getPositionY() + progressBar.getHeight() * (1 - progressBar.getProgress()), + progressBar.getWidth(), + progressBar.getHeight()); break; } - // Render the progress nvgBeginPath(getContext()); - switch (progressBar.getShape()) { + switch (progressBar.getShape()) + { case RECTANGLE: nvgRect(getContext(), progressBar.getPositionX(), progressBar.getPositionY(), progressBar.getWidth(), progressBar.getHeight()); break; case ROUNDED_RECT: - nvgRoundedRect(getContext(), progressBar.getPositionX(), progressBar.getPositionY(), progressBar.getWidth(), progressBar.getHeight(), ((IVectorRoundedRect) progressBar).getRadius()); + nvgRoundedRect(getContext(), progressBar.getPositionX(), progressBar.getPositionY(), progressBar.getWidth(), progressBar.getHeight(), ((IVectorRoundedRect) progressBar).getRadius()); break; - default: + default: break; } - - if (progressBar instanceof SolidVectorProgressBar) { - nvgFillColor(getContext(), rgba(((SolidVectorProgressBar)progressBar).getFillColour())); - } - + if (progressBar instanceof SolidVectorProgressBar) + { nvgFillColor(getContext(), rgba(((SolidVectorProgressBar) progressBar).getFillColour())); } // Render the border (again) - if (progressBar.colourProperties().hasBorder()) { + if (progressBar.colourProperties().hasBorder()) + { nvgStrokeColor(getContext(), rgba(progressBar.colourProperties().getBorderColour())); nvgStrokeWidth(getContext(), progressBar.colourProperties().getBorderWidth()); nvgStroke(getContext()); } nvgFill(getContext()); - popScissor(getContext()); } - - + @Override - public void renderVectorCheckBox(VectorCheckBox checkbox) { + public void renderVectorCheckBox(VectorCheckBox checkbox) + { // Render the check box renderColouredVectorShape(checkbox, checkbox); - if (!checkbox.isSelected() || checkbox.getCheckStyle() == CheckBoxCheckStyle.NONE) return; - float ox = checkbox.getPositionX(); float oy = checkbox.getPositionY(); float w = checkbox.getWidth(); float h = checkbox.getHeight(); float padding = checkbox.getCheckPadding(); - // Render the check mark - switch (checkbox.getCheckStyle()) { + switch (checkbox.getCheckStyle()) + { case CROSS: nvgBeginPath(getContext()); nvgMoveTo(getContext(), ox + padding, oy + padding); @@ -342,321 +317,304 @@ public void renderVectorCheckBox(VectorCheckBox checkbox) { nvgMoveTo(getContext(), ox + w - padding, oy + padding); nvgLineTo(getContext(), ox + padding, oy + h - padding); nvgStrokeWidth(getContext(), checkbox.getCheckStrokeWidth()); - nvgStrokeColor(getContext(), rgba(checkbox.getCheckColour())); + nvgStrokeColor(getContext(), rgba(checkbox.getCheckColour())); nvgStroke(getContext()); break; case DOT: nvgBeginPath(getContext()); - nvgCircle(getContext(), ox + w/2, oy + h/2, w/2 - 4); - nvgFillColor(getContext(), rgba(checkbox.getCheckColour())); + nvgCircle(getContext(), ox + w / 2, oy + h / 2, w / 2 - 4); + nvgFillColor(getContext(), rgba(checkbox.getCheckColour())); nvgFill(getContext()); break; case TICK: nvgBeginPath(getContext()); - nvgMoveTo(getContext(), ox + padding, oy + h/2); - nvgLineTo(getContext(), ox + padding + w/4, oy + h - padding); + nvgMoveTo(getContext(), ox + padding, oy + h / 2); + nvgLineTo(getContext(), ox + padding + w / 4, oy + h - padding); nvgLineTo(getContext(), ox + w - padding, oy + padding); nvgStrokeWidth(getContext(), checkbox.getCheckStrokeWidth()); - nvgStrokeColor(getContext(), rgba(checkbox.getCheckColour())); + nvgStrokeColor(getContext(), rgba(checkbox.getCheckColour())); nvgStroke(getContext()); break; - // This should never be called - case NONE: break; + case NONE: + break; } } - - + @Override - public void renderRadioButtonGroup(RadioButtonGroup group, Panel parentPanel) { + public void renderRadioButtonGroup(RadioButtonGroup group, Panel parentPanel) + { Map buttons = group.getButtonMap(); - // Render each radio button - for (String name : buttons.keySet()) { + for (String name : buttons.keySet()) + { RadioButton b = buttons.get(name); - if (b instanceof VectorRadioButton) { + if (b instanceof VectorRadioButton) + { b.updateBounds(parentPanel, parentPanel.getPosition()); renderVectorRadioButton((VectorRadioButton) b); } } } - - + @Override - protected void renderVectorRadioButton(VectorRadioButton radio) { + protected void renderVectorRadioButton(VectorRadioButton radio) + { // Render the radio button renderColouredVectorShape(radio, radio); - if (!radio.isSelected()) return; - float ox = radio.getPositionX(); float oy = radio.getPositionY(); float r = radio.getWidth(); float padding = radio.getCheckPadding(); - nvgBeginPath(getContext()); nvgCircle(getContext(), ox + r, oy + r, r - padding); - nvgFillColor(getContext(), rgba(radio.getCheckColour())); + nvgFillColor(getContext(), rgba(radio.getCheckColour())); nvgFill(getContext()); } - - + @Override - public void renderImage(ImageHolder holder) { + public void renderImage(ImageHolder holder) + { NVGPaint paint = NVGPaint.create(); nvgImagePattern(getContext(), holder.getImageX(), holder.getImageY(), holder.getImageWidth(), holder.getImageHeight(), 0, NVGTexture.getTexture(holder.getTextureName()), 1, paint); - nvgBeginPath(getContext()); nvgRect(getContext(), holder.getPositionX(), holder.getPositionY(), holder.getWidth(), holder.getHeight()); nvgFillPaint(getContext(), paint); nvgFill(getContext()); } - @Override - public void renderText(TextComponent text, GUIBoundsInterface e) { + public void renderText(TextComponent text, GUIBoundsInterface e) + { // Check there is text to render if (text.getText().equals("")) return; - // Load the font if it isn't already loaded - if (!loadedFonts.contains(text.getFontName())) { + if (!loadedFonts.contains(text.getFontName())) + { NVGFont.acquireFont(getContext(), text.getFontName()); loadedFonts.add(text.getFontName()); } - float scaleFactor = 1.0f; - if (text.scale()) { - float AR = e.getBounds().x/e.getBounds().y; - float originalAR = e.getAbsoluteBounds().x/e.getAbsoluteBounds().y; + if (text.scale()) + { + float AR = e.getBounds().x / e.getBounds().y; + float originalAR = e.getAbsoluteBounds().x / e.getAbsoluteBounds().y; // Wider - if (AR > originalAR) scaleFactor = e.getBounds().y/e.getAbsoluteBounds().y; + if (AR > originalAR) + scaleFactor = e.getBounds().y / e.getAbsoluteBounds().y; // Thinner - else scaleFactor = e.getBounds().x/e.getAbsoluteBounds().x; + else scaleFactor = e.getBounds().x / e.getAbsoluteBounds().x; } nvgFontSize(getContext(), text.getAbsoluteTextSize() * scaleFactor); - nvgFontFace(getContext(), NVGFont.getFont(text.getFontName()).getName()); nvgFillColor(getContext(), rgba(text.getTextColour())); - if (text.isClipText()) pushScissor(getContext(), e.getPositionX(), e.getPositionY(), e.getBounds().x, e.getBounds().y); - float xPos = 0, yPos = 0; - - switch (text.getAlignment()) { - case LEFT: - nvgTextAlign(getContext(), NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); + switch (text.getAlignment()) + { + case LEFT: + nvgTextAlign(getContext(), NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); xPos = e.getPositionX() + text.getPaddingLeft() + text.getOffset().x; yPos = e.getPositionY() + e.getBounds().y / 2 + text.getOffset().y; break; - case CENTER: + case CENTER: nvgTextAlign(getContext(), NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE); xPos = e.getPositionX() + e.getBounds().x / 2 + text.getOffset().x; yPos = e.getPositionY() + e.getBounds().y / 2 + text.getOffset().y; break; - case RIGHT: - nvgTextAlign(getContext(), NVG_ALIGN_RIGHT | NVG_ALIGN_MIDDLE); + case RIGHT: + nvgTextAlign(getContext(), NVG_ALIGN_RIGHT | NVG_ALIGN_MIDDLE); xPos = e.getPositionX() + e.getBounds().x - text.getPaddingRight() + text.getOffset().x; yPos = e.getPositionY() + e.getBounds().y / 2 + text.getOffset().y; break; case BOTTOM_LEFT: - nvgTextAlign(getContext(), NVG_ALIGN_LEFT | NVG_ALIGN_BOTTOM); + nvgTextAlign(getContext(), NVG_ALIGN_LEFT | NVG_ALIGN_BOTTOM); xPos = e.getPositionX() + text.getPaddingLeft() + text.getOffset().x; yPos = e.getPositionY() + e.getBounds().y - text.getPaddingBottom() + text.getOffset().y; break; case BOTTOM_CENTER: - nvgTextAlign(getContext(), NVG_ALIGN_CENTER | NVG_ALIGN_BOTTOM); + nvgTextAlign(getContext(), NVG_ALIGN_CENTER | NVG_ALIGN_BOTTOM); xPos = e.getPositionX() + e.getBounds().x / 2 + text.getOffset().x; yPos = e.getPositionY() + e.getBounds().y - text.getPaddingBottom() + text.getOffset().y; break; case BOTTOM_RIGHT: - nvgTextAlign(getContext(), NVG_ALIGN_RIGHT | NVG_ALIGN_BOTTOM); + nvgTextAlign(getContext(), NVG_ALIGN_RIGHT | NVG_ALIGN_BOTTOM); xPos = e.getPositionX() + e.getBounds().x - text.getPaddingRight() + text.getOffset().x; yPos = e.getPositionY() + e.getBounds().y - text.getPaddingBottom() + text.getOffset().y; break; case TOP_LEFT: - nvgTextAlign(getContext(), NVG_ALIGN_LEFT | NVG_ALIGN_TOP); + nvgTextAlign(getContext(), NVG_ALIGN_LEFT | NVG_ALIGN_TOP); xPos = e.getPositionX() + text.getPaddingLeft() + text.getOffset().x; yPos = e.getPositionY() + text.getPaddingTop() + text.getOffset().y; break; case TOP_CENTER: - nvgTextAlign(getContext(), NVG_ALIGN_CENTER | NVG_ALIGN_TOP); + nvgTextAlign(getContext(), NVG_ALIGN_CENTER | NVG_ALIGN_TOP); xPos = e.getPositionX() + e.getBounds().x / 2 + text.getOffset().x; yPos = e.getPositionY() + text.getPaddingTop() + text.getOffset().y; break; case TOP_RIGHT: - nvgTextAlign(getContext(), NVG_ALIGN_RIGHT | NVG_ALIGN_TOP); + nvgTextAlign(getContext(), NVG_ALIGN_RIGHT | NVG_ALIGN_TOP); xPos = e.getPositionX() + e.getBounds().x - text.getPaddingRight() + text.getOffset().x; yPos = e.getPositionY() + text.getPaddingTop() + text.getOffset().y; break; } - - if (text.isTextBox()) nvgTextBox(getContext(), xPos, yPos, text.getTextBoxWidth(), text.getText()); + if (text.isTextBox()) + nvgTextBox(getContext(), xPos, yPos, text.getTextBoxWidth(), text.getText()); else nvgText(getContext(), xPos, yPos, text.getText()); - if (text.isClipText()) popScissor(getContext()); } - - - + /* =================== * AUXILIARY METHODS * =================== */ - @Override - protected void renderVectorButton(VectorButton button) { - renderColouredVectorShape(button, button); - } - - - /** - * Render a coloured vector shape to the screen (with no offset) - */ - protected void renderColouredVectorShape(IColouredVectorShape shape, GUIBoundsInterface e) { - renderColouredVectorShape(shape, e, 0, 0); - } - - + protected void renderVectorButton(VectorButton button) + { renderColouredVectorShape(button, button); } + + /** Render a coloured vector shape to the screen (with no offset) */ + protected void renderColouredVectorShape(IColouredVectorShape shape, GUIBoundsInterface e) + { renderColouredVectorShape(shape, e, 0, 0); } + @Override - protected void renderColouredVectorShape(IColouredVectorShape shape, GUIBoundsInterface e, float offsetX, float offsetY) { + protected void renderColouredVectorShape(IColouredVectorShape shape, GUIBoundsInterface e, float offsetX, float offsetY) + { if (!shape.renderShape()) return; - nvgBeginPath(getContext()); - // Draw the vector shape - switch (shape.getShape()) { + switch (shape.getShape()) + { case RECTANGLE: nvgRect(getContext(), offsetX + e.getPositionX(), offsetY + e.getPositionY(), e.getWidth(), e.getHeight()); break; case ROUNDED_RECT: - nvgRoundedRect(getContext(), offsetX + e.getPositionX(), offsetY + e.getPositionY(), e.getWidth(), e.getHeight(), ((IVectorRoundedRect) e).getRadius()); + nvgRoundedRect(getContext(), offsetX + e.getPositionX(), offsetY + e.getPositionY(), e.getWidth(), e.getHeight(), ((IVectorRoundedRect) e).getRadius()); break; case ELLIPSE: nvgEllipse(getContext(), offsetX + e.getPositionX() + e.getWidth(), offsetY + e.getPositionY() + e.getHeight(), e.getWidth(), e.getHeight()); break; } - // Render the appropriate colour for the GUI element boolean mouseOver = false; boolean mouseDown = false; boolean selected = false; - - if (e instanceof MouseOverInterface) mouseOver = ((MouseOverInterface)e).isMouseOver() && ((MouseOverInterface)e).mouseOverReact(); - if (e instanceof MouseDownInterface) mouseDown = ((MouseDownInterface)e).isMouseDown(); - if (e instanceof ISelectable) selected = ((ISelectable)e).isSelected(); - - if (selected) { - if (mouseDown) nvgFillColor(getContext(), rgba(shape.colourProperties().getMouseDownColour())); - else nvgFillColor(getContext(), rgba(shape.colourProperties().getSelectedColour())); + if (e instanceof MouseOverInterface) mouseOver = ((MouseOverInterface) e).isMouseOver() && ((MouseOverInterface) e).mouseOverReact(); + if (e instanceof MouseDownInterface) mouseDown = ((MouseDownInterface) e).isMouseDown(); + if (e instanceof ISelectable) selected = ((ISelectable) e).isSelected(); + if (selected) + { + if (mouseDown) + nvgFillColor(getContext(), rgba(shape.colourProperties().getMouseDownColour())); + else nvgFillColor(getContext(), rgba(shape.colourProperties().getSelectedColour())); } - else { - if (mouseOver) { - if (mouseDown) nvgFillColor(getContext(), rgba(shape.colourProperties().getMouseDownColour())); - else nvgFillColor(getContext(), rgba(shape.colourProperties().getMouseoverColour())); + else + { + if (mouseOver) + { + if (mouseDown) + nvgFillColor(getContext(), rgba(shape.colourProperties().getMouseDownColour())); + else nvgFillColor(getContext(), rgba(shape.colourProperties().getMouseoverColour())); } - else nvgFillColor(getContext(), rgba(shape.colourProperties().getColour())); + else nvgFillColor(getContext(), rgba(shape.colourProperties().getColour())); } - // Render the border - if (shape.colourProperties().hasBorder()) { - if (mouseOver) nvgStrokeColor(getContext(), rgba(shape.colourProperties().getBorderMouseoverColour())); + if (shape.colourProperties().hasBorder()) + { + if (mouseOver) + nvgStrokeColor(getContext(), rgba(shape.colourProperties().getBorderMouseoverColour())); else nvgStrokeColor(getContext(), rgba(shape.colourProperties().getBorderColour())); - nvgStrokeWidth(getContext(), shape.colourProperties().getBorderWidth()); nvgStroke(getContext()); } - nvgFill(getContext()); } - - + @Override - protected void renderTexturedButton(TexturedButton button) { + protected void renderTexturedButton(TexturedButton button) + { NVGPaint paint = NVGPaint.create(); - // Render the texture - if (button.isMouseOver()) { - if (button.isMouseDown()) nvgImagePattern(getContext(), button.getPositionX(), button.getPositionY(), button.getWidth(), button.getHeight(), 0, NVGTexture.getTexture(button.getPressedTexture()), 1, paint); + if (button.isMouseOver()) + { + if (button.isMouseDown()) + nvgImagePattern(getContext(), button.getPositionX(), button.getPositionY(), button.getWidth(), button.getHeight(), 0, NVGTexture.getTexture(button.getPressedTexture()), 1, paint); else nvgImagePattern(getContext(), button.getPositionX(), button.getPositionY(), button.getWidth(), button.getHeight(), 0, NVGTexture.getTexture(button.getMouseoverTexture()), 1, paint); } else nvgImagePattern(getContext(), button.getPositionX(), button.getPositionY(), button.getWidth(), button.getHeight(), 0, NVGTexture.getTexture(button.getTexture()), 1, paint); - nvgBeginPath(getContext()); nvgRoundedRect(getContext(), button.getPositionX(), button.getPositionY(), button.getWidth(), button.getHeight(), 5); nvgFillPaint(getContext(), paint); nvgFill(getContext()); } - - - /** - * A class to represent bounds for a scissor rectangle - * @author bwyap - * - */ - private static class ScissorBounds { + + /** A class to represent bounds for a scissor rectangle + * + * @author bwyap */ + private static class ScissorBounds + { final float x, y, w, h; - ScissorBounds(float x, float y, float w, float h) { + + ScissorBounds(float x, float y, float w, float h) + { this.x = x; this.y = y; this.w = w; this.h = h; } } - + private ArrayList scissorBoundsStack = new ArrayList(); - - - /** - * Push a new scissor onto the scissor stack and intersect it with the current scissor + + /** Push a new scissor onto the scissor stack and intersect it with the current scissor + * * @param ctx * @param x * @param y * @param w - * @param h - */ - private void pushScissor(long ctx, float x, float y, float w, float h) { + * @param h */ + private void pushScissor(long ctx, float x, float y, float w, float h) + { scissorBoundsStack.add(new ScissorBounds(x, y, w, h)); nvgIntersectScissor(ctx, x, y, w, h); } - - - /** - * Undo the last applied scissor - * @param ctx - */ - private void popScissor(long ctx) { - if (scissorBoundsStack.size() <= 1) { + + /** Undo the last applied scissor + * + * @param ctx */ + private void popScissor(long ctx) + { + if (scissorBoundsStack.size() <= 1) + { if (scissorBoundsStack.size() == 1) scissorBoundsStack.clear(); nvgResetScissor(ctx); } - else { + else + { scissorBoundsStack.remove(scissorBoundsStack.size() - 1); nvgResetScissor(ctx); - for (ScissorBounds b : scissorBoundsStack) { - nvgIntersectScissor(ctx, b.x, b.y, b.w, b.h); - } - } + for (ScissorBounds b : scissorBoundsStack) + { nvgIntersectScissor(ctx, b.x, b.y, b.w, b.h); } + } } - - - /** - * Static method for converting an RGBA colour + + /** Static method for converting an RGBA colour * value to a NVGColor equivalent. The result * is stored in the given NVGColour object and * it is also returned. - * @param r - * @param g - * @param b - * @param a - * @param colour - * @return - */ - private static NVGColor rgba(Vector4f colour) { + * + * @param r + * @param g + * @param b + * @param a + * @param colour + * @return */ + private static NVGColor rgba(Vector4f colour) + { NVGRenderer.colour.r(colour.x); NVGRenderer.colour.g(colour.y); NVGRenderer.colour.b(colour.z); NVGRenderer.colour.a(colour.w); return NVGRenderer.colour; } - } diff --git a/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGTexture.java b/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGTexture.java index 0d075c2..944a349 100644 --- a/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGTexture.java +++ b/src/com/bwyap/lwjgl/engine/gui/nanovg/NVGTexture.java @@ -10,72 +10,59 @@ import com.bwyap.engine.render.Texture; -/** - *

- * Holds a textureID of a texture loaded for NanoVG. A texture - * can also be used as a texture atlas if its rows and columns - * are set in the constructor (by default it has a row and col - * count of 1, which means the texture is not animated). +/**

+ * Holds a textureID of a texture loaded for NanoVG. A texture + * can also be used as a texture atlas if its rows and columns + * are set in the constructor (by default it has a row and col + * count of 1, which means the texture is not animated). *

*

- * Also provides a static method to load textures into memory - * for rendering by NanoVG. The rendering context must be + * Also provides a static method to load textures into memory + * for rendering by NanoVG. The rendering context must be * provided for the loading process. *

- * @author bwyap - * - */ -public class NVGTexture extends Texture { - + * + * @author bwyap */ +public class NVGTexture extends Texture +{ private static Map loadedTextures = new HashMap(); - public NVGTexture(int textureID) { - super(textureID); - } - - - public NVGTexture(int textureID, int rows, int cols) { - super(textureID, rows, cols); - } - + public NVGTexture(int textureID) + { super(textureID); } - /** - * Loads a texture - * @param name - * @param path - * @param ctx + public NVGTexture(int textureID, int rows, int cols) + { super(textureID, rows, cols); } + + /** Loads a texture + * + * @param name + * @param path + * @param ctx * @return - * @throws IOException - */ - public static NVGTexture loadTexture(String name, String path, long ctx) throws IOException { - ByteBuffer img = ioResourceToByteBuffer(path, 64*64); + * @throws IOException */ + public static NVGTexture loadTexture(String name, String path, long ctx) throws IOException + { + ByteBuffer img = ioResourceToByteBuffer(path, 64 * 64); int textureID = nvgCreateImageMem(ctx, 0, img); loadedTextures.put(name, textureID); return new NVGTexture(textureID); } - - /** - * Loads a texture atlas with the specified number of rows and columns - * @param path - * @param row - * @param col + /** Loads a texture atlas with the specified number of rows and columns + * + * @param path + * @param row + * @param col * @return - * @throws IOException - */ - public static NVGTexture loadTexture(String name, String path, long ctx, int row, int col) throws IOException { - return new NVGTexture(loadTexture(name, path, ctx).getID(), row, col); - } - - - /** - * Get the ID of a loaded texture. - * Returns null if the specified texture has not been loaded. - * @param name - * @return - */ - public static int getTexture(String name) { - return loadedTextures.get(name); - } + * @throws IOException */ + public static NVGTexture loadTexture(String name, String path, long ctx, int row, int col) throws IOException + { return new NVGTexture(loadTexture(name, path, ctx).getID(), row, col); } + /** Get the ID of a loaded texture. + * Returns null if the specified texture has not been loaded. + * + * @param name + * @return */ + public static int getTexture(String name) + { return loadedTextures.get(name); } } diff --git a/src/com/bwyap/lwjgl/engine/particle/AnimatedParticle.java b/src/com/bwyap/lwjgl/engine/particle/AnimatedParticle.java index 754b973..7ffeb0e 100644 --- a/src/com/bwyap/lwjgl/engine/particle/AnimatedParticle.java +++ b/src/com/bwyap/lwjgl/engine/particle/AnimatedParticle.java @@ -3,66 +3,59 @@ import com.bwyap.engine.particle.Particle; import com.bwyap.lwjgl.engine.entity.AnimatedTexture; - -/** - * A particle which supports an animated texture. - * @author bwyap - * - */ -public abstract class AnimatedParticle extends Particle implements AnimatedTexture { - +/** A particle which supports an animated texture. + * + * @author bwyap */ +public abstract class AnimatedParticle extends Particle implements AnimatedTexture +{ private int texturePosition; private float textureChangeSpeed; private float currentFrameTime; - - - protected AnimatedParticle(float timeCreated, float lifetime, float textureChangeSpeed) { + + protected AnimatedParticle(float timeCreated, float lifetime, float textureChangeSpeed) + { super(timeCreated, lifetime); this.texturePosition = 0; this.textureChangeSpeed = textureChangeSpeed; this.currentFrameTime = 0; } - - protected AnimatedParticle(AnimatedParticle particle) { + + protected AnimatedParticle(AnimatedParticle particle) + { super(particle); this.texturePosition = particle.getTexturePosition(); this.textureChangeSpeed = particle.getTextureChangeSpeed(); this.currentFrameTime = particle.currentFrameTime; } - - - /** - * {@inheritDoc} + + /** {@inheritDoc} *

* IMPORTANT: * When overriding this method to implement particle physics * ensure you call {@code super.update(timestep)} to animate the particle. *

- * @param timestep - */ + * + * @param timestep */ @Override - public void update(float timestep) { + public void update(float timestep) + { currentFrameTime += timestep; - if (currentFrameTime >= textureChangeSpeed) { + if (currentFrameTime >= textureChangeSpeed) + { currentFrameTime = 0; texturePosition++; - } - } - - - @Override - public int getTexturePosition() { - return texturePosition; + } } - + @Override - public void setTextureChangeSpeed(float speed) { - this.textureChangeSpeed = speed; - } - + public int getTexturePosition() + { return texturePosition; } + @Override - public float getTextureChangeSpeed() { - return textureChangeSpeed; - } + public void setTextureChangeSpeed(float speed) + { this.textureChangeSpeed = speed; } + @Override + public float getTextureChangeSpeed() + { return textureChangeSpeed; } } diff --git a/src/com/bwyap/lwjgl/engine/particle/ParticleSystem.java b/src/com/bwyap/lwjgl/engine/particle/ParticleSystem.java index bc8764a..c291e67 100644 --- a/src/com/bwyap/lwjgl/engine/particle/ParticleSystem.java +++ b/src/com/bwyap/lwjgl/engine/particle/ParticleSystem.java @@ -14,82 +14,72 @@ import com.bwyap.lwjgl.mesh.InstancedMesh; import com.bwyap.lwjgl.mesh.Mesh; -/** - * An abstract particle system that renders its particles +/** An abstract particle system that renders its particles * using the {@code LWJGLRenderer}. Particles can be assigned - * a mesh and texture. (The mesh should be a quad or it may + * a mesh and texture. (The mesh should be a quad or it may * cause undesirable results) - * system uses a - * @author bwyap - * - * @param the particle type - */ -public abstract class ParticleSystem extends ParticleSystemLogic { - - + * system uses a + * + * @author bwyap + * @param the particle type */ +public abstract class ParticleSystem extends ParticleSystemLogic +{ private String meshName; protected LWJGLTexture texture; - - - public ParticleSystem(LWJGLTexture texture, int maxParticles, int numberToRelease, float releaseInterval) throws Exception { + + public ParticleSystem(LWJGLTexture texture, int maxParticles, int numberToRelease, float releaseInterval) throws Exception + { super(maxParticles, numberToRelease, releaseInterval); this.texture = texture; setMesh(); } - - - /** - * The mesh used by this particle system must be set in this method. + + /** The mesh used by this particle system must be set in this method. * Otherwise, the Particle System will fail to render particles. * This method is automatically called in the Particle System's constructor. - * @throws Exception throws an exception if the given mesh is not an instanced mesh. - */ + * + * @throws Exception throws an exception if the given mesh is not an instanced mesh. */ protected abstract void setMesh() throws Exception; - - - /** - * Set the name of the mesh used by this particle system. + + /** Set the name of the mesh used by this particle system. * The mesh should be an instanced mesh. - * @param meshName - * @throws Exception if the given mesh is not an instanced mesh. - */ - public void setMesh(String meshName) throws Exception { + * + * @param meshName + * @throws Exception if the given mesh is not an instanced mesh. */ + public void setMesh(String meshName) throws Exception + { this.meshName = meshName; - if (!(Mesh.getMesh(meshName) instanceof InstancedMesh)) { - throw new Exception("Given mesh " + meshName + " is not an instanced mesh."); - } + if (!(Mesh.getMesh(meshName) instanceof InstancedMesh)) + { throw new Exception("Given mesh " + meshName + " is not an instanced mesh."); } } - - - /** - * Render the particles in the system + + /** Render the particles in the system + * * @param renderer * @param shader - * @param viewMatrix - */ - public final void render(LWJGLRenderer renderer, Shader shader, Matrix4f viewMatrix) { + * @param viewMatrix */ + public final void render(LWJGLRenderer renderer, Shader shader, Matrix4f viewMatrix) + { shader.setUniform("numRows", texture.getRows()); shader.setUniform("numCols", texture.getCols()); shader.setUniform("textureSampler", 0); renderer.setTexture(texture); - InstancedMesh mesh = (InstancedMesh) Mesh.getMesh(meshName); - // Set up the instance data in the buffer - int chunkSize = mesh.getInstances(); + int chunkSize = mesh.getInstances(); int cycles = activeParticles.size() / chunkSize + (activeParticles.size() % chunkSize == 0 ? 0 : 1); - - for (int c = 0; c < cycles; c++) { + for (int c = 0; c < cycles; c++) + { // Set the instance data buffer for a chunk of entities - for (int i = 0; i < chunkSize && (c * chunkSize + i < activeParticles.size()); i++) { + for (int i = 0; i < chunkSize && (c * chunkSize + i < activeParticles.size()); i++) + { int pos = i + (c * chunkSize); Particle p = activeParticles.get(pos); - Matrix4f modelViewMatrix = renderer.transform.buildModelViewBillBoardMatrix(p, viewMatrix); modelViewMatrix.get(INSTANCE_SIZE_FLOATS * i, mesh.getInstanceDataBuffer()); - int buffPos = INSTANCE_SIZE_FLOATS * i + MATRIX_SIZE_FLOATS * 1; - if (p instanceof AnimatedTexture) { + if (p instanceof AnimatedTexture) + { // If the texture is animated, set the texture co-ordinates AnimatedTexture a = (AnimatedTexture) p; int col = a.getTexturePosition() % texture.getCols(); @@ -99,17 +89,16 @@ public final void render(LWJGLRenderer renderer, Shader shader, Matrix4f viewMat mesh.getInstanceDataBuffer().put(buffPos, textXOffset); mesh.getInstanceDataBuffer().put(buffPos + 1, textYOffset); } - else { + else + { mesh.getInstanceDataBuffer().put(buffPos, 0); mesh.getInstanceDataBuffer().put(buffPos + 1, 0); } } - // Render the instances - int end = Math.min(activeParticles.size(), (c+1) * chunkSize); + int end = Math.min(activeParticles.size(), (c + 1) * chunkSize); renderer.renderMeshListInstanced(mesh, (end - c * chunkSize), true, true, mesh.getInstanceDataBuffer()); mesh.getInstanceDataBuffer().clear(); } } - } diff --git a/src/com/bwyap/lwjgl/engine/render3d/LWJGLRenderer.java b/src/com/bwyap/lwjgl/engine/render3d/LWJGLRenderer.java index 5123d6e..f439349 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/LWJGLRenderer.java +++ b/src/com/bwyap/lwjgl/engine/render3d/LWJGLRenderer.java @@ -38,184 +38,163 @@ import com.bwyap.lwjgl.mesh.InstancedMesh; import com.bwyap.lwjgl.mesh.Mesh; -/** - * Provides the methods for rendering +/** Provides the methods for rendering * graphics to the screen using LWJGL. - * @author bwyap - * - */ -public class LWJGLRenderer extends Renderer3D { - - - public LWJGLRenderer() { - - } - - + * + * @author bwyap */ +public class LWJGLRenderer extends Renderer3D +{ + public LWJGLRenderer() + {} + @Override - public void startRender3D() { + public void startRender3D() + { // Clear OpenGL's buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } - - + @Override - public void startRenderGUI() {} - - + public void startRenderGUI() + {} + @Override - public void stopRender() {} - - + public void stopRender() + {} + @Override - public void cleanup() {} - - + public void cleanup() + {} + /* =========================== * LWJGL RENDERING METHODS * =========================== */ - - /** - * Render a single mesh to the screen. + /** Render a single mesh to the screen. * All shader uniforms must have been set previously. - * @param mesh - */ + * + * @param mesh */ @Deprecated - public void renderMesh(Mesh mesh) { + public void renderMesh(Mesh mesh) + { beginMeshRender(mesh, false, false); glDrawElements(GL_TRIANGLES, mesh.getVertexCount(), GL_UNSIGNED_INT, 0); endMeshRender(); } - - - /** - * Render a list of entities using the provided mesh. + + /** Render a list of entities using the provided mesh. * All entities in the list must use the specified mesh * but may have their own material and texture types. * Each entities' uniforms and necessary buffer data * must be set using the given {@code Consumer} object. + * * @param mesh * @param entities - * @param consumer - */ - public void renderMeshList(Mesh mesh, List entities, Consumer consumer) { + * @param consumer */ + public void renderMeshList(Mesh mesh, List entities, Consumer consumer) + { boolean billboard = !(entities.get(0) instanceof RotatableEntity); beginMeshRender(mesh, billboard, false); - - for (RenderableEntity entity : entities) { + for (RenderableEntity entity : entities) + { consumer.accept(entity); glDrawElements(GL_TRIANGLES, mesh.getVertexCount(), GL_UNSIGNED_INT, 0); } - endMeshRender(); } - - - /** - * Render a list of entities using the provided - * {@code InstancedMesh} and instance data in the - * provided buffer. It is assumed that all required + + /** Render a list of entities using the provided + * {@code InstancedMesh} and instance data in the + * provided buffer. It is assumed that all required * uniforms and instance data have been previously set. - * @param mesh the instanced mesh to render - * @param instances the number of instances to render - * @param billboard flag to indicate a billboard entity (depth mask is disabled) + * + * @param mesh the instanced mesh to render + * @param instances the number of instances to render + * @param billboard flag to indicate a billboard entity (depth mask is disabled) * @param transparent flag to indicate transparent texture (alpha blending is enabled) - * @param buffer the buffer containing the instance data - */ - public void renderMeshListInstanced(InstancedMesh mesh, int instances, boolean billboard, boolean transparent, FloatBuffer buffer) { + * @param buffer the buffer containing the instance data */ + public void renderMeshListInstanced(InstancedMesh mesh, int instances, boolean billboard, boolean transparent, FloatBuffer buffer) + { beginMeshRender(mesh, billboard, transparent); - for (int i = 3; i < 8; i++) { - glEnableVertexAttribArray(i); - } - + for (int i = 3; i < 8; i++) + { glEnableVertexAttribArray(i); } renderChunkInstanced(mesh, instances, buffer); - - for (int i = 3; i < 8; i++) { - glDisableVertexAttribArray(i); - } + for (int i = 3; i < 8; i++) + { glDisableVertexAttribArray(i); } endMeshRender(); } - - /** - * Set the texture that the GPU should use for rendering a mesh - * @param texture - */ - public void setTexture(LWJGLTexture texture) { - if (texture != null) { - // Activate the first texture unit - glActiveTexture(GL_TEXTURE0); - // Bind the texture - glBindTexture(GL_TEXTURE_2D, texture.getID()); - } + /** Set the texture that the GPU should use for rendering a mesh + * + * @param texture */ + public void setTexture(LWJGLTexture texture) + { + if (texture != null) + { + // Activate the first texture unit + glActiveTexture(GL_TEXTURE0); + // Bind the texture + glBindTexture(GL_TEXTURE_2D, texture.getID()); + } } - - - /** - * Render a chunk of instanced meshes. + + /** Render a chunk of instanced meshes. * All instance data must have been previously set up properly. - * @param mesh the instanced mesh to render + * + * @param mesh the instanced mesh to render * @param instances the number of instances to render - * @param buffer the buffer containing the instance data - */ - private void renderChunkInstanced(InstancedMesh mesh, int instances, FloatBuffer buffer) { + * @param buffer the buffer containing the instance data */ + private void renderChunkInstanced(InstancedMesh mesh, int instances, FloatBuffer buffer) + { glBindBuffer(GL_ARRAY_BUFFER, mesh.getInstanceDataVboID()); glBufferData(GL_ARRAY_BUFFER, buffer, GL_DYNAMIC_DRAW); - glDrawElementsInstanced(GL_TRIANGLES, mesh.getVertexCount(), GL_UNSIGNED_INT, 0, instances); - glBindBuffer(GL_ARRAY_BUFFER, 0); } - - - /** - * Set up the resources for rendering the mesh - * @param mesh - */ - private void beginMeshRender(Mesh mesh, boolean transparent, boolean billboard) { + + /** Set up the resources for rendering the mesh + * + * @param mesh */ + private void beginMeshRender(Mesh mesh, boolean transparent, boolean billboard) + { glBindVertexArray(mesh.getVaoID()); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); - if (billboard) glDepthMask(false); - setTransparent(transparent); } - - - /** - * Set the renderer to use transparent blending while rendering - * @param transparent - */ - public void setTransparent(boolean transparent) { - if (transparent) { + + /** Set the renderer to use transparent blending while rendering + * + * @param transparent */ + public void setTransparent(boolean transparent) + { + if (transparent) + { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); } - else { + else + { glDisable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } - - - /** - * Clean up the resources after rendering the mesh - * @param billboard - */ - private void endMeshRender() { + + /** Clean up the resources after rendering the mesh + * + * @param billboard */ + private void endMeshRender() + { glDepthMask(true); glDisable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - // Restore state - glDisableVertexAttribArray(0); - glDisableVertexAttribArray(1); - glDisableVertexAttribArray(2); - glBindVertexArray(0); - glBindTexture(GL_TEXTURE_2D, 0); + glDisableVertexAttribArray(0); + glDisableVertexAttribArray(1); + glDisableVertexAttribArray(2); + glBindVertexArray(0); + glBindTexture(GL_TEXTURE_2D, 0); } - } diff --git a/src/com/bwyap/lwjgl/engine/render3d/LWJGLTexture.java b/src/com/bwyap/lwjgl/engine/render3d/LWJGLTexture.java index 8f65af1..aca38ee 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/LWJGLTexture.java +++ b/src/com/bwyap/lwjgl/engine/render3d/LWJGLTexture.java @@ -21,133 +21,100 @@ import com.bwyap.engine.render.Texture; import com.bwyap.utility.resource.ResourceLoader; - -/** - *

- * Holds a textureID of a texture loaded for LWJGL, and a flag - * to indicate whether the texture has alpha support. A texture - * can also be used as a texture atlas if its rows and columns - * are set in the constructor (by default it has a row and col - * count of 1, which means the texture is not animated). +/**

+ * Holds a textureID of a texture loaded for LWJGL, and a flag + * to indicate whether the texture has alpha support. A texture + * can also be used as a texture atlas if its rows and columns + * are set in the constructor (by default it has a row and col + * count of 1, which means the texture is not animated). *

*

- * The class also provides a static method to load a texture + * The class also provides a static method to load a texture * to the graphics card using {@code PNGDecoder}. *

- * @author bwyap - * - */ -public class LWJGLTexture extends Texture { - + * + * @author bwyap */ +public class LWJGLTexture extends Texture +{ private static Map loadedTextures = new HashMap(); - protected boolean hasAlpha; - - public LWJGLTexture(int textureID, int rows, int cols) { + public LWJGLTexture(int textureID, int rows, int cols) + { super(textureID, rows, cols); this.hasAlpha = false; } - - - public LWJGLTexture(int textureID) { - this(textureID, 1, 1); - } - - /** - * Set the hasAlpha flag for this texture. - * If alpha is supported for this texture, it should be + public LWJGLTexture(int textureID) + { this(textureID, 1, 1); } + + /** Set the hasAlpha flag for this texture. + * If alpha is supported for this texture, it should be * set to true for the renderer render with transparency. * It is set to false by default. - * @param hasAlpha - */ - public void setAlpha(boolean hasAlpha) { - this.hasAlpha = hasAlpha; - } - - - /** - * Check if the texture requires alpha transparency - * @return - */ - public boolean hasAlpha() { - return hasAlpha; - } - - - public void bind() { - glBindTexture(GL_TEXTURE_2D, textureID); - } - - - public void cleanup() { - glDeleteTextures(textureID); - } - + * + * @param hasAlpha */ + public void setAlpha(boolean hasAlpha) + { this.hasAlpha = hasAlpha; } + + /** Check if the texture requires alpha transparency + * + * @return */ + public boolean hasAlpha() + { return hasAlpha; } + + public void bind() + { glBindTexture(GL_TEXTURE_2D, textureID); } - /** - * Loads a texture atlas with the specified number of rows and columns - * @param name - * @param path - * @param row - * @param col + public void cleanup() + { glDeleteTextures(textureID); } + + /** Loads a texture atlas with the specified number of rows and columns + * + * @param name + * @param path + * @param row + * @param col * @return - * @throws IOException - */ - public static LWJGLTexture loadTexture(String name, String path, int row, int col) throws IOException { + * @throws IOException */ + public static LWJGLTexture loadTexture(String name, String path, int row, int col) throws IOException + { PNGDecoder decoder = new PNGDecoder(ResourceLoader.class.getResourceAsStream(path)); - ByteBuffer buf = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight()); decoder.decode(buf, decoder.getWidth() * 4, PNGDecoder.RGBA); buf.flip(); - // Create a new OpenGL texture int textureID = glGenTextures(); - // Bind the textures glBindTexture(GL_TEXTURE_2D, textureID); - // Tell OpenGL how to unpack the RGBA bytes // Each component is 1 byte in size glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - // Upload the texture data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buf); - //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - // Generate mip map glGenerateMipmap(GL_TEXTURE_2D); - // Put the texture in the list of loaded textures LWJGLTexture texture = new LWJGLTexture(textureID, row, col); loadedTextures.put(name, texture); - return texture; } - - /** - * Loads a texture - * @param path + /** Loads a texture + * + * @param path * @return - * @throws IOException - */ - public static LWJGLTexture loadTexture(String name, String path) throws IOException { - return loadTexture(name, path, 1, 1); - } - - - /** - * Get the ID of a loaded texture. - * Returns null if the specified texture has not been loaded. - * @param name - * @return - */ - public static LWJGLTexture getTexture(String name) { - return loadedTextures.get(name); - } + * @throws IOException */ + public static LWJGLTexture loadTexture(String name, String path) throws IOException + { return loadTexture(name, path, 1, 1); } + /** Get the ID of a loaded texture. + * Returns null if the specified texture has not been loaded. + * + * @param name + * @return */ + public static LWJGLTexture getTexture(String name) + { return loadedTextures.get(name); } } diff --git a/src/com/bwyap/lwjgl/engine/render3d/Material.java b/src/com/bwyap/lwjgl/engine/render3d/Material.java index 6260a64..e550286 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/Material.java +++ b/src/com/bwyap/lwjgl/engine/render3d/Material.java @@ -2,51 +2,42 @@ import org.joml.Vector3f; - -/** - * Specifies the colour and reflectance of a material type. - * @author bwyap - * - */ -public class Material { - +/** Specifies the colour and reflectance of a material type. + * + * @author bwyap */ +public class Material +{ private static final Vector3f DEFAULT_COLOUR = new Vector3f(0.5f, 0.5f, 0.5f); - private Vector3f colour; private float reflectance; - - - public Material() { + + public Material() + { this.colour = DEFAULT_COLOUR; this.reflectance = 0; } - - - public Material(Vector3f colour, float reflectance) { + + public Material(Vector3f colour, float reflectance) + { this.colour = colour; this.reflectance = reflectance; } - - public Material(float reflectance) { + public Material(float reflectance) + { this.colour = DEFAULT_COLOUR; this.reflectance = reflectance; } - public Vector3f getColour() { - return colour; - } + public Vector3f getColour() + { return colour; } - public void setColour(Vector3f colour) { - this.colour = colour; - } + public void setColour(Vector3f colour) + { this.colour = colour; } - public float getReflectance() { - return reflectance; - } + public float getReflectance() + { return reflectance; } - public void setReflectance(float reflectance) { - this.reflectance = reflectance; - } - + public void setReflectance(float reflectance) + { this.reflectance = reflectance; } } diff --git a/src/com/bwyap/lwjgl/engine/render3d/light/DirectionalLight.java b/src/com/bwyap/lwjgl/engine/render3d/light/DirectionalLight.java index b50334e..81b3269 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/light/DirectionalLight.java +++ b/src/com/bwyap/lwjgl/engine/render3d/light/DirectionalLight.java @@ -2,36 +2,27 @@ import org.joml.Vector3f; -public class DirectionalLight extends Light { - - +public class DirectionalLight extends Light +{ protected Vector3f direction; - - protected DirectionalLight(int pos, Vector3f colour, Vector3f direction, float intensity) { + protected DirectionalLight(int pos, Vector3f colour, Vector3f direction, float intensity) + { super(pos); this.colour = colour; this.direction = direction; this.intensity = intensity; } - - - public DirectionalLight(DirectionalLight light) { - this(light.getAssignedArrayPos(), new Vector3f(light.getColour()), new Vector3f(light.getDirection()), light.getIntensity()); - } - - public Vector3f getDirection() { - return direction; - } - - - /** - * Set the direction of the light - * @param direction - */ - public void setDirection(Vector3f direction) { - this.direction = direction; - } - + public DirectionalLight(DirectionalLight light) + { this(light.getAssignedArrayPos(), new Vector3f(light.getColour()), new Vector3f(light.getDirection()), light.getIntensity()); } + + public Vector3f getDirection() + { return direction; } + + /** Set the direction of the light + * + * @param direction */ + public void setDirection(Vector3f direction) + { this.direction = direction; } } diff --git a/src/com/bwyap/lwjgl/engine/render3d/light/Light.java b/src/com/bwyap/lwjgl/engine/render3d/light/Light.java index de5c713..4c9898b 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/light/Light.java +++ b/src/com/bwyap/lwjgl/engine/render3d/light/Light.java @@ -2,111 +2,80 @@ import org.joml.Vector3f; - -/** - * Represents a light with a position, colour and intensity. - * @author bwyap - * - */ -public abstract class Light { - +/** Represents a light with a position, colour and intensity. + * + * @author bwyap */ +public abstract class Light +{ private int pos; - protected Vector3f colour; protected float intensity; - - protected Light(int pos) { - this.pos = pos; - } - - - protected Light() { - this(0); - } - - - /** - * Get array position of the light as assigned by SceneLighting (default value is 0). - * @return - */ - public int getAssignedArrayPos() { - return pos; - } - - - /** - * Get the colour of the light - * @return - */ - public Vector3f getColour() { - return colour; - } - - - /** - * Set the colour of the light - * @param colour - */ - public void setColour(Vector3f colour) { - this.colour = colour; - } - - - /** - * Get the intensity of the light - * @return - */ - public float getIntensity() { - return intensity; - } - - - /** - * Set the intensity of the light - * @return - */ - public void setIntensity(float intensity) { - this.intensity = intensity; - } - - - public static class Attenuation { - + protected Light(int pos) + { this.pos = pos; } + + protected Light() + { this(0); } + + /** Get array position of the light as assigned by SceneLighting (default value is 0). + * + * @return */ + public int getAssignedArrayPos() + { return pos; } + + /** Get the colour of the light + * + * @return */ + public Vector3f getColour() + { return colour; } + + /** Set the colour of the light + * + * @param colour */ + public void setColour(Vector3f colour) + { this.colour = colour; } + + /** Get the intensity of the light + * + * @return */ + public float getIntensity() + { return intensity; } + + /** Set the intensity of the light + * + * @return */ + public void setIntensity(float intensity) + { this.intensity = intensity; } + + public static class Attenuation + { private float constant; private float linear; private float exponent; - public Attenuation(float constant, float linear, float exponent) { + public Attenuation(float constant, float linear, float exponent) + { this.constant = constant; this.linear = linear; this.exponent = exponent; } - public float getConstant() { - return constant; - } + public float getConstant() + { return constant; } - public void setConstant(float constant) { - this.constant = constant; - } + public void setConstant(float constant) + { this.constant = constant; } - public float getLinear() { - return linear; - } + public float getLinear() + { return linear; } - public void setLinear(float linear) { - this.linear = linear; - } + public void setLinear(float linear) + { this.linear = linear; } - public float getExponent() { - return exponent; - } + public float getExponent() + { return exponent; } - public void setExponent(float exponent) { - this.exponent = exponent; - } + public void setExponent(float exponent) + { this.exponent = exponent; } } - - } diff --git a/src/com/bwyap/lwjgl/engine/render3d/light/PointLight.java b/src/com/bwyap/lwjgl/engine/render3d/light/PointLight.java index ce869ea..dcd9755 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/light/PointLight.java +++ b/src/com/bwyap/lwjgl/engine/render3d/light/PointLight.java @@ -2,77 +2,59 @@ import org.joml.Vector3f; - -public class PointLight extends Light { - - +public class PointLight extends Light +{ protected Attenuation attenuation; protected Vector3f position; - - - protected PointLight(int pos, Vector3f color, Vector3f position, float intensity) { + + protected PointLight(int pos, Vector3f color, Vector3f position, float intensity) + { super(pos); this.colour = color; this.position = position; this.intensity = intensity; attenuation = new Attenuation(1, 0, 0); } - - - protected PointLight(int pos, Vector3f color, Vector3f position, float intensity, Attenuation attenuation) { + + protected PointLight(int pos, Vector3f color, Vector3f position, float intensity, Attenuation attenuation) + { this(pos, color, position, intensity); this.attenuation = attenuation; } - - public PointLight(PointLight pointLight) { - this(pointLight.getAssignedArrayPos(), new Vector3f(pointLight.getColour()), new Vector3f(pointLight.getPosition()), pointLight.getIntensity(), pointLight.getAttenuation()); - } - + public PointLight(PointLight pointLight) + { this(pointLight.getAssignedArrayPos(), new Vector3f(pointLight.getColour()), new Vector3f(pointLight.getPosition()), pointLight.getIntensity(), pointLight.getAttenuation()); } - /** - * Get the position of the light - * @return - */ - public Vector3f getPosition() { - return position; - } + /** Get the position of the light + * + * @return */ + public Vector3f getPosition() + { return position; } - - /** - * Set the position of the light - * @param position - */ - public void setPosition(Vector3f position) { - this.position = position; - } - - - /** - * move the position of the light relative to its current location + /** Set the position of the light + * + * @param position */ + public void setPosition(Vector3f position) + { this.position = position; } + + /** move the position of the light relative to its current location + * * @param xOffset * @param yOffset - * @param zOffset - */ - public void movePosition(float xOffset, float yOffset, float zOffset) { + * @param zOffset */ + public void movePosition(float xOffset, float yOffset, float zOffset) + { this.position.x += xOffset; this.position.y += yOffset; this.position.z += zOffset; } - - - public Attenuation getAttenuation() { - return attenuation; - } - - public void setAttenuation(Attenuation attenuation) { - this.attenuation = attenuation; - } - + public Attenuation getAttenuation() + { return attenuation; } - public void setAttenuation(float constant, float linear, float exponent) { - this.attenuation = new Attenuation(constant, linear, exponent); - } + public void setAttenuation(Attenuation attenuation) + { this.attenuation = attenuation; } + public void setAttenuation(float constant, float linear, float exponent) + { this.attenuation = new Attenuation(constant, linear, exponent); } } diff --git a/src/com/bwyap/lwjgl/engine/render3d/light/SceneLighting.java b/src/com/bwyap/lwjgl/engine/render3d/light/SceneLighting.java index 1325970..d1b5eb2 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/light/SceneLighting.java +++ b/src/com/bwyap/lwjgl/engine/render3d/light/SceneLighting.java @@ -2,163 +2,128 @@ import org.joml.Vector3f; - -/** - * Holds information about all directional, point and spot lights in a scene. +/** Holds information about all directional, point and spot lights in a scene. * - * @author bwyap - * - */ -public class SceneLighting { - + * @author bwyap */ +public class SceneLighting +{ public static final int MAX_DIR_LIGHTS = 4; public static final int MAX_POINT_LIGHTS = 10; public static final int MAX_SPOT_LIGHTS = 10; - private DirectionalLight[] directionalLights; private PointLight[] pointLights; private SpotLight[] spotLights; - private int pointIndex = 0; private int directionalIndex = 0; private int spotIndex = 0; - private Vector3f ambientLight; private float specularPower; - - - public SceneLighting() { + + public SceneLighting() + { directionalLights = new DirectionalLight[MAX_DIR_LIGHTS]; pointLights = new PointLight[MAX_POINT_LIGHTS]; spotLights = new SpotLight[MAX_SPOT_LIGHTS]; } - - - /** - * Creates a point light. The light is automatically added to the scene. - * There is a maximum number of {@code PointLights} permitted in a scene, - * limited by {@code MAX_POINT_LIGHTS}. - * @param colour - * @param position - * @param intensity + + /** Creates a point light. The light is automatically added to the scene. + * There is a maximum number of {@code PointLights} permitted in a scene, + * limited by {@code MAX_POINT_LIGHTS}. + * + * @param colour + * @param position + * @param intensity * @throws Exception maximum number of point lights exceeded - * @return - */ - public PointLight createPointLight(Vector3f colour, Vector3f position, float intensity) throws Exception { + * @return */ + public PointLight createPointLight(Vector3f colour, Vector3f position, float intensity) throws Exception + { PointLight pointLight = new PointLight(pointIndex, colour, position, intensity); pointLights[pointIndex++] = pointLight; - if (pointIndex == MAX_POINT_LIGHTS) { - throw new Exception("Unable to create new point light: maximum number of PointLights for this scene exceeded."); - } + if (pointIndex == MAX_POINT_LIGHTS) + { throw new Exception("Unable to create new point light: maximum number of PointLights for this scene exceeded."); } return pointLight; } - - - /** - * Creates a directional light. The light is automatically added to the scene. - * There is a maximum number of {@code DirectionalLights} permitted in a scene, - * limited by {@code MAX_DIR_LIGHTS}. - * @param colour - * @param position - * @param intensity - * @param direction + + /** Creates a directional light. The light is automatically added to the scene. + * There is a maximum number of {@code DirectionalLights} permitted in a scene, + * limited by {@code MAX_DIR_LIGHTS}. + * + * @param colour + * @param position + * @param intensity + * @param direction * @return - * @throws Exception maximum number of directional lights exceeded - */ - public DirectionalLight createDirectionalLight(Vector3f colour, Vector3f position, float intensity, Vector3f direction) throws Exception { + * @throws Exception maximum number of directional lights exceeded */ + public DirectionalLight createDirectionalLight(Vector3f colour, Vector3f position, float intensity, Vector3f direction) throws Exception + { DirectionalLight directionalLight = new DirectionalLight(directionalIndex, colour, position, intensity); directionalLight.setDirection(direction); directionalLights[directionalIndex++] = directionalLight; - if (directionalIndex == MAX_DIR_LIGHTS) { - throw new Exception("Unable to create new point light: maximum number of DirectionalLights for this scene exceeded."); - } + if (directionalIndex == MAX_DIR_LIGHTS) + { throw new Exception("Unable to create new point light: maximum number of DirectionalLights for this scene exceeded."); } return directionalLight; } - - - /** - * Creates a spot light. The light is automatically added to the scene. - * There is a maximum number of {@code SpotLights} permitted in a scene, - * limited by {@code MAX_SPOT_LIGHTS}. - * @param colour - * @param position - * @param intensity - * @param coneDirection - * @param cutoffAngle + + /** Creates a spot light. The light is automatically added to the scene. + * There is a maximum number of {@code SpotLights} permitted in a scene, + * limited by {@code MAX_SPOT_LIGHTS}. + * + * @param colour + * @param position + * @param intensity + * @param coneDirection + * @param cutoffAngle * @return - * @throws Exception maximum number of spot lights exceeded - */ - public SpotLight createSpotLight(Vector3f colour, Vector3f position, float intensity, Vector3f coneDirection, float cutOff) throws Exception { + * @throws Exception maximum number of spot lights exceeded */ + public SpotLight createSpotLight(Vector3f colour, Vector3f position, float intensity, Vector3f coneDirection, float cutOff) throws Exception + { PointLight pointLight = new PointLight(spotIndex, colour, position, intensity); SpotLight spotLight = new SpotLight(spotIndex, pointLight, coneDirection, cutOff); spotLights[spotIndex++] = spotLight; - if (spotIndex == MAX_SPOT_LIGHTS) { - throw new Exception("Unable to create new point light: maximum number of SpotLights for this scene exceeded."); - } + if (spotIndex == MAX_SPOT_LIGHTS) + { throw new Exception("Unable to create new point light: maximum number of SpotLights for this scene exceeded."); } return spotLight; } - - - /** - * Set the ambient light of the scene - * @param ambientLight - */ - public void setAmbient(Vector3f ambientLight) { - this.ambientLight = ambientLight; - } - - - /** - * Get the ambient light of the scene - * @return - */ - public Vector3f getAmbientLight() { - return ambientLight; - } - - - /** - * Set the specular power used in the lighting calculations - * @param specularPower - */ - public void setSpecularPower(float specularPower) { - this.specularPower = specularPower; - } - - - /** - * Get the specular power used in the lighting calculations - * @return - */ - public float getSpecularPower() { - return specularPower; - } - - - /** - * Get the array of point lights - * @return - */ - public PointLight[] getPointLights() { - return pointLights; - } - - - /** - * Get the array of directional lights - * @return - */ - public DirectionalLight[] getDirectionalLights() { - return directionalLights; - } - - - /** - * Get the array of spot lights - * @return - */ - public SpotLight[] getSpotLights() { - return spotLights; - } - + + /** Set the ambient light of the scene + * + * @param ambientLight */ + public void setAmbient(Vector3f ambientLight) + { this.ambientLight = ambientLight; } + + /** Get the ambient light of the scene + * + * @return */ + public Vector3f getAmbientLight() + { return ambientLight; } + + /** Set the specular power used in the lighting calculations + * + * @param specularPower */ + public void setSpecularPower(float specularPower) + { this.specularPower = specularPower; } + + /** Get the specular power used in the lighting calculations + * + * @return */ + public float getSpecularPower() + { return specularPower; } + + /** Get the array of point lights + * + * @return */ + public PointLight[] getPointLights() + { return pointLights; } + + /** Get the array of directional lights + * + * @return */ + public DirectionalLight[] getDirectionalLights() + { return directionalLights; } + + /** Get the array of spot lights + * + * @return */ + public SpotLight[] getSpotLights() + { return spotLights; } } diff --git a/src/com/bwyap/lwjgl/engine/render3d/light/SpotLight.java b/src/com/bwyap/lwjgl/engine/render3d/light/SpotLight.java index 6059edb..2e88f77 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/light/SpotLight.java +++ b/src/com/bwyap/lwjgl/engine/render3d/light/SpotLight.java @@ -2,97 +2,69 @@ import org.joml.Vector3f; - -public class SpotLight extends Light { - - +public class SpotLight extends Light +{ private PointLight pointLight; private Vector3f coneDirection; private float cutOff; - - - protected SpotLight(int pos, PointLight pointLight, Vector3f coneDirection, float cutOffAngle) { + + protected SpotLight(int pos, PointLight pointLight, Vector3f coneDirection, float cutOffAngle) + { super(pos); this.pointLight = pointLight; this.coneDirection = coneDirection; - this.cutOff = (float)Math.cos(Math.toRadians(cutOffAngle)); + this.cutOff = (float) Math.cos(Math.toRadians(cutOffAngle)); } - - public SpotLight(SpotLight spotLight) { - this(spotLight.getAssignedArrayPos(), new PointLight(spotLight.getPointLight()), - new Vector3f(spotLight.getConeDirection()), - spotLight.getCutOff()); - } - - - public PointLight getPointLight() { - return pointLight; - } - - - public void setPointLight(PointLight pointLight) { - this.pointLight = pointLight; - } - - - public Vector3f getConeDirection() { - return coneDirection; - } - - - public void setConeDirection(Vector3f coneDirection) { - this.coneDirection = coneDirection; - } - - - public float getCutOff() { - return cutOff; - } - - - public void setCutOff(float cutOff) { - this.cutOff = cutOff; - } - - + public SpotLight(SpotLight spotLight) + { this(spotLight.getAssignedArrayPos(), new PointLight(spotLight.getPointLight()), + new Vector3f(spotLight.getConeDirection()), + spotLight.getCutOff()); } + + public PointLight getPointLight() + { return pointLight; } + + public void setPointLight(PointLight pointLight) + { this.pointLight = pointLight; } + + public Vector3f getConeDirection() + { return coneDirection; } + + public void setConeDirection(Vector3f coneDirection) + { this.coneDirection = coneDirection; } + + public float getCutOff() + { return cutOff; } + + public void setCutOff(float cutOff) + { this.cutOff = cutOff; } + @Override - public Vector3f getColour() { - return pointLight.colour; - } + public Vector3f getColour() + { return pointLight.colour; } @Override - public void setColour(Vector3f colour) { - pointLight.colour = colour; - } + public void setColour(Vector3f colour) + { pointLight.colour = colour; } - - public Vector3f getPosition() { - return pointLight.position; - } + public Vector3f getPosition() + { return pointLight.position; } - - public void setPosition(Vector3f position) { - pointLight.position = position; - } - - - public void movePosition(float xOffset, float yOffset, float zOffset) { + public void setPosition(Vector3f position) + { pointLight.position = position; } + + public void movePosition(float xOffset, float yOffset, float zOffset) + { pointLight.position.x += xOffset; pointLight.position.y += yOffset; pointLight.position.z += zOffset; } - - + @Override - public float getIntensity() { - return pointLight.intensity; - } + public float getIntensity() + { return pointLight.intensity; } - @Override - public void setIntensity(float intensity) { - pointLight.intensity = intensity; - } - + public void setIntensity(float intensity) + { pointLight.intensity = intensity; } } diff --git a/src/com/bwyap/lwjgl/engine/render3d/scene/EntityLayer.java b/src/com/bwyap/lwjgl/engine/render3d/scene/EntityLayer.java index dfae6c0..813cfee 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/scene/EntityLayer.java +++ b/src/com/bwyap/lwjgl/engine/render3d/scene/EntityLayer.java @@ -15,82 +15,79 @@ import com.bwyap.lwjgl.mesh.InstancedMesh; import com.bwyap.lwjgl.mesh.Mesh; - -/** - *

+/**

* A scene layer that holds {@code RenderableEntity} objects. - * All objects in the layer are updated and rendered through + * All objects in the layer are updated and rendered through * the {@code update} and {@code render} methods. *

*

* The {@code RenderableEntity} objects are stored in two {@code Maps}, - * one which holds objects with non-instanced meshes one which + * one which holds objects with non-instanced meshes one which * holds instanced meshes. *

- * @author bwyap - * - */ -public abstract class EntityLayer implements SceneLayer { - + * + * @author bwyap */ +public abstract class EntityLayer implements SceneLayer +{ protected final Map> meshMap; protected final Map> instancedMeshMap; - protected Shader shader; - - - public EntityLayer() { + + public EntityLayer() + { meshMap = new HashMap>(); instancedMeshMap = new HashMap>(); } - - - /** - * Get the map of meshes in this Scene layer and + + /** Get the map of meshes in this Scene layer and * all associated renderable objects. - * @return - */ - public Map> getGameMeshes() { - return meshMap; - } + * + * @return */ + public Map> getGameMeshes() + { return meshMap; } - /** - * Get the map of Instanced meshes in this Scene layer and + /** Get the map of Instanced meshes in this Scene layer and * all associated renderable objects. - * @return - */ - public Map> getGameInstancedMeshes() { - return instancedMeshMap; - } - - - /** - * Add an object to the scene layer. + * + * @return */ + public Map> getGameInstancedMeshes() + { return instancedMeshMap; } + + /** Add an object to the scene layer. * Returns true if the object was added to the scene successfully. - * @param object - */ + * + * @param object */ @Override - public boolean addEntity(RenderableEntity object) { + public boolean addEntity(RenderableEntity object) + { // Check if the mesh exists Mesh mesh = Mesh.getMesh(object.getMeshName()); - if (mesh != null) { - if (mesh instanceof InstancedMesh) { + if (mesh != null) + { + if (mesh instanceof InstancedMesh) + { // Instanced mesh found in mesh map - if (instancedMeshMap.containsKey(object.getMeshName())) { + if (instancedMeshMap.containsKey(object.getMeshName())) + { instancedMeshMap.get(object.getMeshName()).add(object); } // New instanced mesh for this layer - else { + else + { ArrayList list = new ArrayList(); list.add(object); instancedMeshMap.put(object.getMeshName(), list); } } - else { - if (meshMap.containsKey(object.getMeshName())) { + else + { + if (meshMap.containsKey(object.getMeshName())) + { // Mesh found in mesh map meshMap.get(object.getMeshName()).add(object); } - else { + else + { // New mesh for this layer ArrayList list = new ArrayList(); list.add(object); @@ -102,91 +99,79 @@ public boolean addEntity(RenderableEntity object) { // Mesh doesn't exist else return false; } - - - /** - * Remove an entity from the scene layer. - * Returns true if the entity was found and removed from the scene successfully. - */ + + /** Remove an entity from the scene layer. + * Returns true if the entity was found and removed from the scene successfully. */ @Override - public boolean removeEntity(RenderableEntity object) { + public boolean removeEntity(RenderableEntity object) + { // Look through mesh map - for (String m : meshMap.keySet()) { - if (meshMap.get(m).contains(object)) { + for (String m : meshMap.keySet()) + { + if (meshMap.get(m).contains(object)) + { // Object found in one of the lists within the mesh map meshMap.get(m).remove(object); - if (meshMap.get(m).size() == 0) { - meshMap.remove(m); - } + if (meshMap.get(m).size() == 0) + { meshMap.remove(m); } return true; } } // Look through instanced mesh map - for (String m : instancedMeshMap.keySet()) { - if (instancedMeshMap.get(m).contains(object)) { + for (String m : instancedMeshMap.keySet()) + { + if (instancedMeshMap.get(m).contains(object)) + { // Object found in one of the lists within the instanced mesh map instancedMeshMap.get(m).remove(object); - if (instancedMeshMap.get(m).size() == 0) { - instancedMeshMap.remove(m); - } + if (instancedMeshMap.get(m).size() == 0) + { instancedMeshMap.remove(m); } return true; } } return false; } - - - /** - * Update all objects contained in this layer - */ + + /** Update all objects contained in this layer */ @Override - public void update(float timestep) { - for (String m : meshMap.keySet()) { - for (RenderableEntity o : meshMap.get(m)) { - o.update(timestep); - } + public void update(float timestep) + { + for (String m : meshMap.keySet()) + { + for (RenderableEntity o : meshMap.get(m)) + { o.update(timestep); } } - for (String m : instancedMeshMap.keySet()) { - for (RenderableEntity o : instancedMeshMap.get(m)) { - o.update(timestep); - } + for (String m : instancedMeshMap.keySet()) + { + for (RenderableEntity o : instancedMeshMap.get(m)) + { o.update(timestep); } } } - - - /** - * {@inheritDoc} + + /** {@inheritDoc} *

* Requires {@code LWJGLRenderer}. - *

- */ + *

*/ @Override - public final void render(Renderer3D renderer, Matrix4f projectionMatrix, Matrix4f viewMatrix) { + public final void render(Renderer3D renderer, Matrix4f projectionMatrix, Matrix4f viewMatrix) + { beginRender(projectionMatrix, viewMatrix); renderObjects((LWJGLRenderer) renderer, viewMatrix); endRender(); } - - - /** - * Prepare the shader for rendering the entities + + /** Prepare the shader for rendering the entities + * * @param projectionMatrix - * @param viewMatrix - */ + * @param viewMatrix */ protected abstract void beginRender(Matrix4f projectionMatrix, Matrix4f viewMatrix); - - - /** - * Render the entities in scene layer + + /** Render the entities in scene layer + * * @param renderer - * @param viewMatrix - */ + * @param viewMatrix */ protected abstract void renderObjects(LWJGLRenderer renderer, Matrix4f viewMatrix); - - - /** - * Clean up the shader resources after rendering the entities - */ + + /** Clean up the shader resources after rendering the entities */ protected abstract void endRender(); - } diff --git a/src/com/bwyap/lwjgl/engine/render3d/scene/LightedObjectLayer.java b/src/com/bwyap/lwjgl/engine/render3d/scene/LightedObjectLayer.java index d788b01..223d74c 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/scene/LightedObjectLayer.java +++ b/src/com/bwyap/lwjgl/engine/render3d/scene/LightedObjectLayer.java @@ -22,77 +22,70 @@ import com.bwyap.lwjgl.mesh.InstancedMesh; import com.bwyap.lwjgl.mesh.Mesh; - -/** - *

+/**

* A scene layer that can hold renderable entities * that are lit by a Phong lighting shader. - * All objects in the layer are updated and rendered + * All objects in the layer are updated and rendered * through the {@code update} and {@code render} methods. *

*

- * All non-instanced meshes are rendered first, and + * All non-instanced meshes are rendered first, and * all objects with the same mesh are rendered in the * same cycle. *

- * @author bwyap - * - */ -public abstract class LightedObjectLayer extends EntityLayer { - + * + * @author bwyap */ +public abstract class LightedObjectLayer extends EntityLayer +{ protected SceneLighting lighting; - - - public LightedObjectLayer() throws Exception { + + public LightedObjectLayer() throws Exception + { super(); lighting = new SceneLighting(); shader = new PhongLightingShader(); shader.init(); } - - - /** - * Get the {@code SceneLighting} object used to light + + /** Get the {@code SceneLighting} object used to light * the objects in this scene layer - * @return - */ - public SceneLighting getLighting() { - return lighting; - } - - + * + * @return */ + public SceneLighting getLighting() + { return lighting; } + @Override - protected void beginRender(Matrix4f projectionMatrix, Matrix4f viewMatrix) { + protected void beginRender(Matrix4f projectionMatrix, Matrix4f viewMatrix) + { shader.bind(); shader.setUniform("projectionMatrix", projectionMatrix); - shader.setUniform("textureSampler", 0); - calculateLighting(lighting, viewMatrix); + shader.setUniform("textureSampler", 0); + calculateLighting(lighting, viewMatrix); } - - - /** - * {@inheritDoc} + + /** {@inheritDoc} *

* It is assumed that all entities that share the same instanced mesh * also share the same material type and texture. * To have entities with the same instanced mesh but different textures, * use a mesh with a different name (or use non-instanced meshes). - *

- */ + *

*/ @Override - protected void renderObjects(LWJGLRenderer renderer, Matrix4f viewMatrix) { + protected void renderObjects(LWJGLRenderer renderer, Matrix4f viewMatrix) + { // Render non instanced objects shader.setUniform("isInstanced", 0); - // Iterate through each mesh and render each object that has that mesh - for (String meshName : meshMap.keySet()) { + for (String meshName : meshMap.keySet()) + { Mesh mesh = Mesh.getMesh(meshName); - - renderer.renderMeshList(mesh, meshMap.get(meshName), (RenderableEntity o) -> { + renderer.renderMeshList(mesh, meshMap.get(meshName), (RenderableEntity o) -> + { // Set the material information ((PhongLightingShader) shader).setUniform("material", o.getMaterial()); shader.setUniform("useTexture", o.isTextured() ? 1 : 0); - if (o.isTextured()) { + if (o.isTextured()) + { // Set the texture information in the shader shader.setUniform("textureSampler", 0); shader.setUniform("numCols", o.getTexture().getCols()); @@ -101,8 +94,8 @@ protected void renderObjects(LWJGLRenderer renderer, Matrix4f viewMatrix) { renderer.setTexture(o.getTexture()); renderer.setTransparent(o.getTexture().hasAlpha()); } - - if (o instanceof AnimatedTexture) { + if (o instanceof AnimatedTexture) + { // If the texture is animated, set the texture co-ordinates AnimatedTexture a = (AnimatedTexture) o; int col = a.getTexturePosition() % o.getTexture().getCols(); @@ -111,56 +104,53 @@ protected void renderObjects(LWJGLRenderer renderer, Matrix4f viewMatrix) { float texYOffset = (float) row / o.getTexture().getRows(); shader.setUniform("nonInstancedTexOffset", new Vector2f(texXOffset, texYOffset)); } - // Set the model view matrix uniform Matrix4f modelViewMatrix; if (o instanceof RotatableEntity) modelViewMatrix = renderer.transform.buildModelViewMatrix(o, viewMatrix); else modelViewMatrix = renderer.transform.buildModelBillboardMatrix(o); - shader.setUniform("modelViewNonInstancedMatrix", modelViewMatrix); + shader.setUniform("modelViewNonInstancedMatrix", modelViewMatrix); }); } - // Render instanced objects shader.setUniform("isInstanced", 1); - // Iterate through each mesh and render each object that has that mesh - for (String meshName : instancedMeshMap.keySet()) { + for (String meshName : instancedMeshMap.keySet()) + { InstancedMesh mesh = (InstancedMesh) Mesh.getMesh(meshName); - // Set up the instance data in the buffer List list = instancedMeshMap.get(meshName); - int chunkSize = mesh.getInstances(); + int chunkSize = mesh.getInstances(); int cycles = list.size() / chunkSize + (list.size() % chunkSize == 0 ? 0 : 1); boolean billboard = !(list.get(0) instanceof RotatableEntity); boolean transparent = list.get(0).isTextured() ? (list.get(0).getTexture().hasAlpha()) : false; - - for (int c = 0; c < cycles; c++) { + for (int c = 0; c < cycles; c++) + { // It is expected that all meshes of the same instance in this // layer are textured in the same way with the same material RenderableEntity object = instancedMeshMap.get(meshName).get(c); ((PhongLightingShader) shader).setUniform("material", object.getMaterial()); shader.setUniform("useTexture", object.isTextured() ? 1 : 0); - if (object.isTextured()) { + if (object.isTextured()) + { // Set the texture information shader.setUniform("textureSampler", 0); shader.setUniform("numCols", object.getTexture().getCols()); shader.setUniform("numRows", object.getTexture().getRows()); renderer.setTexture(object.getTexture()); } - // Set the instance data buffer for a chunk of entities - for (int i = 0; i < chunkSize && (c * chunkSize + i < list.size()); i++) { + for (int i = 0; i < chunkSize && (c * chunkSize + i < list.size()); i++) + { int pos = i + (c * chunkSize); RenderableEntity o = list.get(pos); - Matrix4f modelViewMatrix; - if (billboard) modelViewMatrix = renderer.transform.buildModelBillboardMatrix(o); + if (billboard) + modelViewMatrix = renderer.transform.buildModelBillboardMatrix(o); else modelViewMatrix = renderer.transform.buildModelViewMatrix(o, viewMatrix); - modelViewMatrix.get(INSTANCE_SIZE_FLOATS * i, mesh.getInstanceDataBuffer()); - - if (o instanceof AnimatedTexture) { + if (o instanceof AnimatedTexture) + { // If the texture is animated, set the texture co-ordinates AnimatedTexture a = (AnimatedTexture) o; int col = a.getTexturePosition() % o.getTexture().getCols(); @@ -172,44 +162,40 @@ protected void renderObjects(LWJGLRenderer renderer, Matrix4f viewMatrix) { mesh.getInstanceDataBuffer().put(buffPos + 1, textYOffset); } } - // Render the instances - int end = Math.min(list.size(), (c+1) * chunkSize); + int end = Math.min(list.size(), (c + 1) * chunkSize); renderer.renderMeshListInstanced(mesh, end - (c * chunkSize), billboard, transparent, mesh.getInstanceDataBuffer()); mesh.getInstanceDataBuffer().clear(); } } } - - + @Override - protected void endRender() { - shader.unbind(); - } - - - /** - * Calculate the lighting for the objects and set the shader uniforms + protected void endRender() + { shader.unbind(); } + + /** Calculate the lighting for the objects and set the shader uniforms + * * @param lighting - * @param viewMatrix - */ - protected void calculateLighting(SceneLighting lighting, Matrix4f viewMatrix) { + * @param viewMatrix */ + protected void calculateLighting(SceneLighting lighting, Matrix4f viewMatrix) + { // Calculate lighting - shader.setUniform("ambientLight", lighting.getAmbientLight()); + shader.setUniform("ambientLight", lighting.getAmbientLight()); shader.setUniform("specularPower", lighting.getSpecularPower()); - // Get a copy of the directional light object and transform its position to view coordinates - for (int i = 0; i < SceneLighting.MAX_DIR_LIGHTS; i++) { + for (int i = 0; i < SceneLighting.MAX_DIR_LIGHTS; i++) + { if (lighting.getDirectionalLights()[i] == null) continue; DirectionalLight currDirLight = new DirectionalLight(lighting.getDirectionalLights()[i]); Vector4f dir = new Vector4f(currDirLight.getDirection(), 0); dir.mul(viewMatrix); currDirLight.setDirection(new Vector3f(dir.x, dir.y, dir.z)); - ((PhongLightingShader)shader).setUniform("directionalLights", currDirLight, i); + ((PhongLightingShader) shader).setUniform("directionalLights", currDirLight, i); } - // Get a copy of the point light object and transform its position to view coordinates - for (int i = 0; i < SceneLighting.MAX_POINT_LIGHTS; i++) { + for (int i = 0; i < SceneLighting.MAX_POINT_LIGHTS; i++) + { if (lighting.getPointLights()[i] == null) continue; PointLight currPointLight = new PointLight(lighting.getPointLights()[i]); Vector3f lightPos = currPointLight.getPosition(); @@ -218,25 +204,23 @@ protected void calculateLighting(SceneLighting lighting, Matrix4f viewMatrix) { lightPos.x = aux.x; lightPos.y = aux.y; lightPos.z = aux.z; - ((PhongLightingShader)shader).setUniform("pointLights", currPointLight, i); + ((PhongLightingShader) shader).setUniform("pointLights", currPointLight, i); } - // Get a copy of the spot light object and transform its position and cone direction to view coordinates - for (int i = 0; i < SceneLighting.MAX_SPOT_LIGHTS; i++) { + for (int i = 0; i < SceneLighting.MAX_SPOT_LIGHTS; i++) + { if (lighting.getSpotLights()[i] == null) continue; SpotLight currSpotLight = new SpotLight(lighting.getSpotLights()[i]); Vector4f dir = new Vector4f(currSpotLight.getConeDirection(), 0); dir.mul(viewMatrix); currSpotLight.setConeDirection(new Vector3f(dir.x, dir.y, dir.z)); - Vector3f spotLightPos = currSpotLight.getPointLight().getPosition(); Vector4f auxSpot = new Vector4f(spotLightPos, 1); auxSpot.mul(viewMatrix); spotLightPos.x = auxSpot.x; spotLightPos.y = auxSpot.y; spotLightPos.z = auxSpot.z; - ((PhongLightingShader)shader).setUniform("spotLights", currSpotLight, i); + ((PhongLightingShader) shader).setUniform("spotLights", currSpotLight, i); } } - } diff --git a/src/com/bwyap/lwjgl/engine/render3d/scene/ParticleSystemLayer.java b/src/com/bwyap/lwjgl/engine/render3d/scene/ParticleSystemLayer.java index 868da6c..1eb9174 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/scene/ParticleSystemLayer.java +++ b/src/com/bwyap/lwjgl/engine/render3d/scene/ParticleSystemLayer.java @@ -12,82 +12,64 @@ import com.bwyap.lwjgl.engine.render3d.LWJGLRenderer; import com.bwyap.lwjgl.engine.render3d.shader.ParticleShader; -/** - * A scene layer which holds particle systems. +/** A scene layer which holds particle systems. * All systems within this layer should use the * same shader. - * @author bwyap - * - */ -public class ParticleSystemLayer implements SceneLayer> { - + * + * @author bwyap */ +public class ParticleSystemLayer implements SceneLayer> +{ protected List> particleSystems; protected ParticleShader shader; - - - public ParticleSystemLayer() throws Exception { + + public ParticleSystemLayer() throws Exception + { particleSystems = new ArrayList>(); shader = new ParticleShader(); shader.init(); } - - - /** - * Add a particle system to the scene. - * @param system - */ - public boolean addEntity(ParticleSystem system) { - return particleSystems.add(system); - } - - - /** - * Remove a particle system from the scene. + + /** Add a particle system to the scene. + * + * @param system */ + public boolean addEntity(ParticleSystem system) + { return particleSystems.add(system); } + + /** Remove a particle system from the scene. * Returns true if the system was removed. - * @param system - * @return - */ + * + * @param system + * @return */ @Override - public boolean removeEntity(ParticleSystem system) { - return particleSystems.remove(system); - } + public boolean removeEntity(ParticleSystem system) + { return particleSystems.remove(system); } - - /** - * Update the particle systems in this scene layer. - * @param timestep - */ + /** Update the particle systems in this scene layer. + * + * @param timestep */ @Override - public void update(float timestep) { - for (ParticleSystem system : particleSystems) { - system.update(timestep); - } + public void update(float timestep) + { + for (ParticleSystem system : particleSystems) + { system.update(timestep); } } - - + @Override - public void handleInput(InputHandler input, float timestep) { - - } - - - /** - * {@inheritDoc} + public void handleInput(InputHandler input, float timestep) + {} + + /** {@inheritDoc} *

* Requires {@code LWJGLRenderer}. - *

- */ + *

*/ @Override - public void render(Renderer3D renderer, Matrix4f projectionMatrix, Matrix4f viewMatrix) { + public void render(Renderer3D renderer, Matrix4f projectionMatrix, Matrix4f viewMatrix) + { shader.bind(); shader.setUniform("textureSampler", 0); shader.setUniform("projectionMatrix", projectionMatrix); - - for(ParticleSystem system : particleSystems) { - system.render((LWJGLRenderer)renderer, shader, viewMatrix); - } - + for (ParticleSystem system : particleSystems) + { system.render((LWJGLRenderer) renderer, shader, viewMatrix); } shader.unbind(); } - } diff --git a/src/com/bwyap/lwjgl/engine/render3d/shader/ParticleShader.java b/src/com/bwyap/lwjgl/engine/render3d/shader/ParticleShader.java index fe5ea57..6759218 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/shader/ParticleShader.java +++ b/src/com/bwyap/lwjgl/engine/render3d/shader/ParticleShader.java @@ -1,27 +1,21 @@ package com.bwyap.lwjgl.engine.render3d.shader; +public class ParticleShader extends Shader +{ + public ParticleShader() throws Exception + { super(); } -public class ParticleShader extends Shader { - - - public ParticleShader() throws Exception { - super(); - } - - @Override - public void init() throws Exception { - createVertexShader(Shader.getSource("particle_vertex")); - createFragmentShader(Shader.getSource("particle_fragment")); - link(); - + public void init() throws Exception + { + createVertexShader(Shader.getSource("particle_vertex")); + createFragmentShader(Shader.getSource("particle_fragment")); + link(); // Create uniforms for modelView and projection matrices and texture - createUniform("projectionMatrix"); - createUniform("textureSampler"); - - // Create uniforms for animated particle support - createUniform("numRows"); - createUniform("numCols"); + createUniform("projectionMatrix"); + createUniform("textureSampler"); + // Create uniforms for animated particle support + createUniform("numRows"); + createUniform("numCols"); } - } diff --git a/src/com/bwyap/lwjgl/engine/render3d/shader/PhongLightingShader.java b/src/com/bwyap/lwjgl/engine/render3d/shader/PhongLightingShader.java index 1ad0a4d..03627a2 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/shader/PhongLightingShader.java +++ b/src/com/bwyap/lwjgl/engine/render3d/shader/PhongLightingShader.java @@ -6,56 +6,47 @@ import com.bwyap.lwjgl.engine.render3d.light.SceneLighting; import com.bwyap.lwjgl.engine.render3d.light.SpotLight; -/** - * Phong lighting model shader. - * Provides methods to create uniforms for directional lights, point lights and spot lights. - * @author bwyap - * - */ -public class PhongLightingShader extends Shader { - - - public PhongLightingShader() throws Exception { - super(); - } - +/** Phong lighting model shader. + * Provides methods to create uniforms for directional lights, point lights and spot lights. + * + * @author bwyap */ +public class PhongLightingShader extends Shader +{ + public PhongLightingShader() throws Exception + { super(); } - /** - * Initialise the uniforms required for Phong lighting - * @throws Exception - */ + /** Initialise the uniforms required for Phong lighting + * + * @throws Exception */ @Override - public void init() throws Exception { + public void init() throws Exception + { createVertexShader(Shader.getSource("vertex")); createFragmentShader(Shader.getSource("fragment")); link(); - // Create uniforms for modelView and projection matrices and texture createUniform("projectionMatrix"); createUniform("modelViewNonInstancedMatrix"); createUniform("textureSampler"); - createUniform("isInstanced"); createUniform("numCols"); createUniform("numRows"); createUniform("nonInstancedTexOffset"); - createMaterialUniform("material"); createUniform("useTexture"); createUniform("specularPower"); createUniform("ambientLight"); createDirectionalLightListUniform("directionalLights", SceneLighting.MAX_DIR_LIGHTS); createPointLightListUniform("pointLights", SceneLighting.MAX_POINT_LIGHTS); - createSpotLightListUniform("spotLights", SceneLighting.MAX_SPOT_LIGHTS); + createSpotLightListUniform("spotLights", SceneLighting.MAX_SPOT_LIGHTS); } - - - /** - * Create the uniform for a point light - * @param uniformName - * @throws Exception - */ - public void createPointLightUniform(String uniformName) throws Exception { + + /** Create the uniform for a point light + * + * @param uniformName + * @throws Exception */ + public void createPointLightUniform(String uniformName) throws Exception + { createUniform(uniformName + ".colour"); createUniform(uniformName + ".position"); createUniform(uniformName + ".intensity"); @@ -63,203 +54,176 @@ public void createPointLightUniform(String uniformName) throws Exception { createUniform(uniformName + ".att.linear"); createUniform(uniformName + ".att.exponent"); } - - - /** - * Create the uniform for a directional light - * @param uniformName - * @throws Exception - */ - public void createDirectionalLightUniform(String uniformName) throws Exception { + + /** Create the uniform for a directional light + * + * @param uniformName + * @throws Exception */ + public void createDirectionalLightUniform(String uniformName) throws Exception + { createUniform(uniformName + ".colour"); createUniform(uniformName + ".direction"); createUniform(uniformName + ".intensity"); } - - - /** - * Create the uniform for a spot light - * @param uniformName - * @throws Exception - */ - public void createSpotLightUniform(String uniformName) throws Exception { - createPointLightUniform(uniformName + ".pl"); + + /** Create the uniform for a spot light + * + * @param uniformName + * @throws Exception */ + public void createSpotLightUniform(String uniformName) throws Exception + { + createPointLightUniform(uniformName + ".pl"); createUniform(uniformName + ".coneDir"); createUniform(uniformName + ".cutoff"); } - - - /** - * Create the uniform for a material - * @param uniformName - * @throws Exception - */ - public void createMaterialUniform(String uniformName) throws Exception { + + /** Create the uniform for a material + * + * @param uniformName + * @throws Exception */ + public void createMaterialUniform(String uniformName) throws Exception + { createUniform(uniformName + ".colour"); createUniform(uniformName + ".reflectance"); } - - - /** - * Create the uniform for a list of directional lights - * @param uniformName - * @param size - * @throws Exception - */ - public void createDirectionalLightListUniform(String uniformName, int size) throws Exception { - for (int i = 0; i < size; i++) { - createDirectionalLightUniform(uniformName + "[" + i + "]"); - } - } - - - /** - * Create the uniform for a list of point lights - * @param uniformName - * @param size - * @throws Exception - */ - public void createPointLightListUniform(String uniformName, int size) throws Exception { - for (int i = 0; i < size; i++) { - createPointLightUniform(uniformName + "[" + i + "]"); - } + + /** Create the uniform for a list of directional lights + * + * @param uniformName + * @param size + * @throws Exception */ + public void createDirectionalLightListUniform(String uniformName, int size) throws Exception + { + for (int i = 0; i < size; i++) + { createDirectionalLightUniform(uniformName + "[" + i + "]"); } } - - /** - * Create the uniform for a list of spot lights - * @param uniformName - * @param size - * @throws Exception - */ - public void createSpotLightListUniform(String uniformName, int size) throws Exception { - for (int i = 0; i < size; i++) { - createSpotLightUniform(uniformName + "[" + i + "]"); - } - } - - - /** - * Sets the uniforms for a point light. - * @param uniformName - * @param pointLight - */ - public void setUniform(String uniformName, PointLight pointLight) { - setUniform(uniformName + ".colour", pointLight.getColour()); - setUniform(uniformName + ".position", pointLight.getPosition()); - setUniform(uniformName + ".intensity", pointLight.getIntensity()); - PointLight.Attenuation att = pointLight.getAttenuation(); - setUniform(uniformName + ".att.constant", att.getConstant()); - setUniform(uniformName + ".att.linear", att.getLinear()); + /** Create the uniform for a list of point lights + * + * @param uniformName + * @param size + * @throws Exception */ + public void createPointLightListUniform(String uniformName, int size) throws Exception + { + for (int i = 0; i < size; i++) + { createPointLightUniform(uniformName + "[" + i + "]"); } + } + + /** Create the uniform for a list of spot lights + * + * @param uniformName + * @param size + * @throws Exception */ + public void createSpotLightListUniform(String uniformName, int size) throws Exception + { + for (int i = 0; i < size; i++) + { createSpotLightUniform(uniformName + "[" + i + "]"); } + } + + /** Sets the uniforms for a point light. + * + * @param uniformName + * @param pointLight */ + public void setUniform(String uniformName, PointLight pointLight) + { + setUniform(uniformName + ".colour", pointLight.getColour()); + setUniform(uniformName + ".position", pointLight.getPosition()); + setUniform(uniformName + ".intensity", pointLight.getIntensity()); + PointLight.Attenuation att = pointLight.getAttenuation(); + setUniform(uniformName + ".att.constant", att.getConstant()); + setUniform(uniformName + ".att.linear", att.getLinear()); setUniform(uniformName + ".att.exponent", att.getExponent()); } - - - /** - * Sets the uniforms for a directional light. - * @param uniformName - * @param dirLight - * @throws Exception - */ - public void setUniform(String uniformName, DirectionalLight dirLight) { - setUniform(uniformName + ".colour", dirLight.getColour()); - setUniform(uniformName + ".direction", dirLight.getDirection()); + + /** Sets the uniforms for a directional light. + * + * @param uniformName + * @param dirLight + * @throws Exception */ + public void setUniform(String uniformName, DirectionalLight dirLight) + { + setUniform(uniformName + ".colour", dirLight.getColour()); + setUniform(uniformName + ".direction", dirLight.getDirection()); setUniform(uniformName + ".intensity", dirLight.getIntensity()); } - - - /** - * Sets the uniforms for a spot light. - * @param uniformName - * @param spotLight - * @throws Exception - */ - public void setUniform(String uniformName, SpotLight spotLight) { + + /** Sets the uniforms for a spot light. + * + * @param uniformName + * @param spotLight + * @throws Exception */ + public void setUniform(String uniformName, SpotLight spotLight) + { setUniform(uniformName + ".pl", spotLight.getPointLight()); setUniform(uniformName + ".coneDir", spotLight.getConeDirection()); setUniform(uniformName + ".cutoff", spotLight.getCutOff()); } - - /** - * Sets the uniforms for a material. - * @param uniformName - * @param material - * @throws Exception - */ - public void setUniform(String uniformName, Material material) { - setUniform(uniformName + ".colour", material.getColour()); + + /** Sets the uniforms for a material. + * + * @param uniformName + * @param material + * @throws Exception */ + public void setUniform(String uniformName, Material material) + { + setUniform(uniformName + ".colour", material.getColour()); setUniform(uniformName + ".reflectance", material.getReflectance()); } - - /** - * Sets the uniforms for a list of directional lights + /** Sets the uniforms for a list of directional lights + * * @param uniformName - * @param directionalLights - */ - public void setUniform(String uniformName, DirectionalLight[] directionalLights) { - int numLights = directionalLights != null ? directionalLights.length : 0; - for (int i = 0; i < numLights; i++) { - setUniform(uniformName, directionalLights[i], i); - } + * @param directionalLights */ + public void setUniform(String uniformName, DirectionalLight[] directionalLights) + { + int numLights = directionalLights != null ? directionalLights.length : 0; + for (int i = 0; i < numLights; i++) + { setUniform(uniformName, directionalLights[i], i); } } - - - /** - * Sets the uniforms for a directional light in an array at the specified position. + + /** Sets the uniforms for a directional light in an array at the specified position. + * * @param uniformName * @param directionalLight - * @param pos - */ - public void setUniform(String uniformName, DirectionalLight directionalLight, int pos) { - setUniform(uniformName + "[" + pos + "]", directionalLight); - } - - - /** - * Sets the uniforms for a list of point lights + * @param pos */ + public void setUniform(String uniformName, DirectionalLight directionalLight, int pos) + { setUniform(uniformName + "[" + pos + "]", directionalLight); } + + /** Sets the uniforms for a list of point lights + * * @param uniformName - * @param pointLights - */ - public void setUniform(String uniformName, PointLight[] pointLights) { - int numLights = pointLights != null ? pointLights.length : 0; - for (int i = 0; i < numLights; i++) { - setUniform(uniformName, pointLights[i], i); - } + * @param pointLights */ + public void setUniform(String uniformName, PointLight[] pointLights) + { + int numLights = pointLights != null ? pointLights.length : 0; + for (int i = 0; i < numLights; i++) + { setUniform(uniformName, pointLights[i], i); } } - - /** - * Sets the uniforms for a point light in an array at the specified position. + + /** Sets the uniforms for a point light in an array at the specified position. + * * @param uniformName * @param pointLight - * @param pos - */ - public void setUniform(String uniformName, PointLight pointLight, int pos) { - setUniform(uniformName + "[" + pos + "]", pointLight); - } - - - /** - * Sets the uniforms for a list of spot lights + * @param pos */ + public void setUniform(String uniformName, PointLight pointLight, int pos) + { setUniform(uniformName + "[" + pos + "]", pointLight); } + + /** Sets the uniforms for a list of spot lights + * * @param uniformName - * @param spotLights - */ - public void setUniform(String uniformName, SpotLight[] spotLights) { + * @param spotLights */ + public void setUniform(String uniformName, SpotLight[] spotLights) + { int numLights = spotLights != null ? spotLights.length : 0; - for (int i = 0; i < numLights; i++) { - setUniform(uniformName, spotLights[i], i); - } + for (int i = 0; i < numLights; i++) + { setUniform(uniformName, spotLights[i], i); } } - - - /** - * Sets the uniforms for a spot light in an array at the specified position. + + /** Sets the uniforms for a spot light in an array at the specified position. + * * @param uniformName * @param spotLight - * @param pos - */ - public void setUniform(String uniformName, SpotLight spotLight, int pos) { - setUniform(uniformName + "[" + pos + "]", spotLight); - } - + * @param pos */ + public void setUniform(String uniformName, SpotLight spotLight, int pos) + { setUniform(uniformName + "[" + pos + "]", spotLight); } } diff --git a/src/com/bwyap/lwjgl/engine/render3d/shader/Shader.java b/src/com/bwyap/lwjgl/engine/render3d/shader/Shader.java index 645c624..5b0a804 100644 --- a/src/com/bwyap/lwjgl/engine/render3d/shader/Shader.java +++ b/src/com/bwyap/lwjgl/engine/render3d/shader/Shader.java @@ -35,236 +35,175 @@ import org.joml.Vector3f; import org.lwjgl.BufferUtils; -/** - * Responsible for initialising a vertex and fragment shader in the rendering pipeline. +/** Responsible for initialising a vertex and fragment shader in the rendering pipeline. * Contains methods to pass uniform data to the shaders when rendering a scene. - * @author bwyap - * - */ -public abstract class Shader { - - + * + * @author bwyap */ +public abstract class Shader +{ private static final Map sources = new HashMap(); - - - /** - * Get the source code of the shader with the given name + + /** Get the source code of the shader with the given name * from the static Map of loaded shader sources. - * If the specified shader has not been loaded, this - * method will return {@code null}. - * @param shaderName - * @return - */ - public static String getSource(String shaderName) { - return sources.get(shaderName); - } - - - /** - * Add the source code of the shader with the given name + * If the specified shader has not been loaded, this + * method will return {@code null}. + * + * @param shaderName + * @return */ + public static String getSource(String shaderName) + { return sources.get(shaderName); } + + /** Add the source code of the shader with the given name * to the static Map of shader sources. This will allow * the source code of the shader to be retrieved by name. + * * @param shaderName - * @param sourceCode - */ - public static void addSource(String shaderName, String sourceCode) { - sources.put(shaderName, sourceCode); - } - - - + * @param sourceCode */ + public static void addSource(String shaderName, String sourceCode) + { sources.put(shaderName, sourceCode); } + protected final int programID; protected final Map uniforms; - protected int vertexShaderID; protected int fragmentShaderID; - - - public Shader() throws Exception { + + public Shader() throws Exception + { programID = glCreateProgram(); - if (programID == 0) { - throw new Exception("Could not create shader."); - } - - uniforms = new HashMap<>(); + if (programID == 0) + { throw new Exception("Could not create shader."); } + uniforms = new HashMap<>(); } - - - /** - * Initialise the shader - * @throws Exception - */ + + /** Initialise the shader + * + * @throws Exception */ public abstract void init() throws Exception; - - - /** - * Get the ID of the shader program - * @return - */ - public int getID() { - return programID; - } - - - /** - * Create a uniform for the shader - * @param uniformName - * @throws Exception - */ - public void createUniform(String uniformName) throws Exception { + + /** Get the ID of the shader program + * + * @return */ + public int getID() + { return programID; } + + /** Create a uniform for the shader + * + * @param uniformName + * @throws Exception */ + public void createUniform(String uniformName) throws Exception + { int uniformLocation = glGetUniformLocation(programID, uniformName); - - if (uniformLocation < 0) { - throw new Exception("Could not find uniform:" + uniformName); - } - - uniforms.put(uniformName, uniformLocation); + if (uniformLocation < 0) + { throw new Exception("Could not find uniform:" + uniformName); } + uniforms.put(uniformName, uniformLocation); } - - - /** - * Set the specified uniform to the value of a 4x4 matrix + + /** Set the specified uniform to the value of a 4x4 matrix + * * @param uniformName - * @param value - */ - public void setUniform(String uniformName, Matrix4f value) { + * @param value */ + public void setUniform(String uniformName, Matrix4f value) + { // Dump the matrix into a float buffer FloatBuffer fb = BufferUtils.createFloatBuffer(16); value.get(fb); glUniformMatrix4fv(uniforms.get(uniformName), false, fb); } - - /** - * Set the specified uniform to the value of a Vector3f + /** Set the specified uniform to the value of a Vector3f + * * @param uniformName - * @param value - */ - public void setUniform(String uniformName, Vector3f value) { - glUniform3f(uniforms.get(uniformName), value.x, value.y, value.z ); - } - + * @param value */ + public void setUniform(String uniformName, Vector3f value) + { glUniform3f(uniforms.get(uniformName), value.x, value.y, value.z); } + public void setUniform(String uniformName, Vector2f value) + { glUniform2f(uniforms.get(uniformName), value.x, value.y); } - public void setUniform(String uniformName, Vector2f value) { - glUniform2f(uniforms.get(uniformName), value.x, value.y); - } - - - /** - * Set the specified uniform to the value of an integer + /** Set the specified uniform to the value of an integer + * * @param uniformName - * @param value - */ - public void setUniform(String uniformName, int value) { - glUniform1i(uniforms.get(uniformName), value); - } + * @param value */ + public void setUniform(String uniformName, int value) + { glUniform1i(uniforms.get(uniformName), value); } - - /** - * Set the specified uniform to the value of an float + /** Set the specified uniform to the value of an float + * * @param uniformName - * @param value - */ - public void setUniform(String uniformName, float value) { - glUniform1f(uniforms.get(uniformName), value); - } - - - /** - * Create a vertex shader and attach it to the program - * @param shaderCode - * @throws Exception - */ - public void createVertexShader(String shaderCode) throws Exception { - vertexShaderID = createShader(shaderCode, GL_VERTEX_SHADER); - } - + * @param value */ + public void setUniform(String uniformName, float value) + { glUniform1f(uniforms.get(uniformName), value); } - /** - * Create a fragment shader and attach it to the program - * @param shaderCode - * @throws Exception - */ - public void createFragmentShader(String shaderCode) throws Exception { - fragmentShaderID = createShader(shaderCode, GL_FRAGMENT_SHADER); - } - - - /** - * Create a shader of the specified type and attach it to the program - * @param shaderCode - * @param shaderType + /** Create a vertex shader and attach it to the program + * + * @param shaderCode + * @throws Exception */ + public void createVertexShader(String shaderCode) throws Exception + { vertexShaderID = createShader(shaderCode, GL_VERTEX_SHADER); } + + /** Create a fragment shader and attach it to the program + * + * @param shaderCode + * @throws Exception */ + public void createFragmentShader(String shaderCode) throws Exception + { fragmentShaderID = createShader(shaderCode, GL_FRAGMENT_SHADER); } + + /** Create a shader of the specified type and attach it to the program + * + * @param shaderCode + * @param shaderType * @return - * @throws Exception - */ - protected int createShader(String shaderCode, int shaderType) throws Exception { + * @throws Exception */ + protected int createShader(String shaderCode, int shaderType) throws Exception + { int shaderID = glCreateShader(shaderType); - - if (shaderID == 0) { - throw new Exception("Error creating shader. "); - } - + if (shaderID == 0) + { throw new Exception("Error creating shader. "); } glShaderSource(shaderID, shaderCode); glCompileShader(shaderID); - - if (glGetShaderi(shaderID, GL_COMPILE_STATUS) == 0) { + if (glGetShaderi(shaderID, GL_COMPILE_STATUS) == 0) + { //System.out.println(shaderCode); throw new Exception("Error compiling shader code: " + glGetShaderInfoLog(shaderID, 1024)); } - glAttachShader(programID, shaderID); - return shaderID; } - - - /** - * Links the shaders to the program - * @throws Exception - */ - public void link() throws Exception { + + /** Links the shaders to the program + * + * @throws Exception */ + public void link() throws Exception + { glLinkProgram(programID); - - if (glGetProgrami(programID, GL_LINK_STATUS) == 0) { - throw new Exception("Error linking shader code: " + glGetProgramInfoLog(programID, 1024)); - } - + 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)); - } + if (glGetProgrami(programID, GL_VALIDATE_STATUS) == 0) + { System.err.println("Warning validating shader code: " + glGetProgramInfoLog(programID, 1024)); } } - - + /** * */ - public void bind() { - glUseProgram(programID); - } - - + public void bind() + { glUseProgram(programID); } + /** * */ - public void unbind() { - glUseProgram(0); - } - - - /** - * Clean up the shaders - */ - public void cleanUp() { + public void unbind() + { glUseProgram(0); } + + /** Clean up the shaders */ + public void cleanUp() + { unbind(); - - if (programID != 0) { + if (programID != 0) + { if (vertexShaderID != 0) glDetachShader(programID, vertexShaderID); if (fragmentShaderID != 0) glDetachShader(programID, fragmentShaderID); } - glDeleteProgram(programID); } - } diff --git a/src/com/bwyap/lwjgl/engine/resource/LWJGLResourceManager.java b/src/com/bwyap/lwjgl/engine/resource/LWJGLResourceManager.java index f377dfd..bfbff62 100644 --- a/src/com/bwyap/lwjgl/engine/resource/LWJGLResourceManager.java +++ b/src/com/bwyap/lwjgl/engine/resource/LWJGLResourceManager.java @@ -13,196 +13,155 @@ import com.bwyap.lwjgl.mesh.OBJLoader; import com.bwyap.utility.resource.ResourceLoader; - -/** - * A resource manager for the LWJGL engine. +/** A resource manager for the LWJGL engine. * This class is a Singleton and its instance should be called using the method {@code instance()}. * The instance must first be initialised through the method {@code initInstance()}. - * @author bwyap - * - */ -public class LWJGLResourceManager extends ResourceManagerBase { - + * + * @author bwyap */ +public class LWJGLResourceManager extends ResourceManagerBase +{ public static final String RESOURCE_JSON = "/com/bwyap/engine/resource/resources.json"; public static final String DEFAULT_INTERNAL_PATH = "/com/bwyap/enginedriver/resource/defaultcontent/"; - private static LWJGLResourceManager instance; - - private Settings settings; private InputMapping inputMapping; - - - /** - * Get the resource manager instance - * @return - */ - public static LWJGLResourceManager instance() { - return instance; - } - - - /** - * Initialise the resource manager instance with + + /** Get the resource manager instance + * + * @return */ + public static LWJGLResourceManager instance() + { return instance; } + + /** Initialise the resource manager instance with * the resource library at the given path - * @param JSONPath - */ - public static void initInstance(String JSONPath) { - instance = new LWJGLResourceManager(JSONPath); - } - - - protected LWJGLResourceManager(String JSONPath) { - super(JSONPath); - } - - + * + * @param JSONPath */ + public static void initInstance(String JSONPath) + { instance = new LWJGLResourceManager(JSONPath); } + + protected LWJGLResourceManager(String JSONPath) + { super(JSONPath); } + @Override - public void loadIndepedentResources() throws IOException { + public void loadIndepedentResources() throws IOException + { loadFolders(); loadConfig(); loadShaders(); } - - - /** - * {@inheritDoc} + + /** {@inheritDoc} *

* This method requires that LWJGL's {@code GL.createCapabilities()} method be called. - *

- */ + *

*/ @Override - public void loadDependentResources() throws Exception { + public void loadDependentResources() throws Exception + { loadMeshes(); loadLWJGLTextures(); } - - - /** - * Load resources for the GUI renderer (through NanoVG) - * @param ctx - * @throws IOException - */ - public void loadNVGResources(long ctx) throws IOException { + + /** Load resources for the GUI renderer (through NanoVG) + * + * @param ctx + * @throws IOException */ + public void loadNVGResources(long ctx) throws IOException + { loadNVGFonts(); loadNVGTextures(ctx); } - - - /** - * Get the settings object - * @return - */ - public Settings settings() { - return settings; - } - - - /** - * Get the input mapping object - * @return - */ - public InputMapping inputMapping() { - return inputMapping; - } - - - + + /** Get the settings object + * + * @return */ + public Settings settings() + { return settings; } + + /** Get the input mapping object + * + * @return */ + public InputMapping inputMapping() + { return inputMapping; } /* * =============== * PRIVATE METHODS * =============== */ - - + // EXTERNAL - - /** - * Load folders for local data - */ - private void loadFolders() { + /** Load folders for local data */ + private void loadFolders() + { ResourceLoader.loadFolder(new File(lib.getFolders().get("data_folder"))); ResourceLoader.loadFolder(new File(lib.getFolders().get("config_folder"))); } - - - /** - * Load configuration files - */ - private void loadConfig() { + + /** Load configuration files */ + private void loadConfig() + { File configFile = new File(lib.getConfig().get("config_file")); settings = new Settings(ResourceLoader.loadJSON(configFile)); - if (!settings.isValid()) { + if (!settings.isValid()) + { ResourceLoader.copyFileFromJar(configFile, null); settings = new Settings(ResourceLoader.loadJSON(configFile)); } - File inputMappingFile = new File(lib.getConfig().get("input_file")); inputMapping = new InputMapping(ResourceLoader.loadJSON(inputMappingFile)); - if (!inputMapping.isValid()) { + if (!inputMapping.isValid()) + { ResourceLoader.copyFileFromJar(inputMappingFile, null); inputMapping = new InputMapping(ResourceLoader.loadJSON(inputMappingFile)); } } - - - + // INTERNAL - - /** - * Load shader code into memory. The shader code can be retrieved - * from the {@code Shader} class to create and link the shader. - */ - private void loadShaders() { + /** Load shader code into memory. The shader code can be retrieved + * from the {@code Shader} class to create and link the shader. */ + private void loadShaders() + { Shader.addSource("vertex", ResourceLoader.loadShaderFile(lib.getShaders().get("vertex"))); Shader.addSource("fragment", ResourceLoader.loadShaderFile(lib.getShaders().get("fragment"))); Shader.addSource("particle_vertex", ResourceLoader.loadShaderFile(lib.getShaders().get("particle_vertex"))); Shader.addSource("particle_fragment", ResourceLoader.loadShaderFile(lib.getShaders().get("particle_fragment"))); } - - - /** - * Load meshes from their OBJ files into memory - * @throws Exception - */ - private void loadMeshes() throws Exception { + + /** Load meshes from their OBJ files into memory + * + * @throws Exception */ + private void loadMeshes() throws Exception + { OBJLoader.loadInstancedMesh("particle", lib.getMeshes().get("particle"), 2000); OBJLoader.loadInstancedMesh("icube", lib.getMeshes().get("cube"), 64); OBJLoader.loadMesh("bunny", lib.getMeshes().get("bunny")); OBJLoader.loadMesh("cube", lib.getMeshes().get("cube")); } - - - /** - * Load mesh textures - * @throws IOException - */ - private void loadLWJGLTextures() throws IOException { + + /** Load mesh textures + * + * @throws IOException */ + private void loadLWJGLTextures() throws IOException + { LWJGLTexture.loadTexture("test", lib.getTextures().get("test")); LWJGLTexture.loadTexture("test_particle", lib.getTextures().get("test_particle")); LWJGLTexture.loadTexture("test_animated_particle", lib.getTextures().get("test_animated_particle"), 4, 4); } - - - /** - * Load fonts for GUI rendering - * @throws IOException - */ - private void loadNVGFonts() throws IOException { - NVGFont.createFont("aeromatics_reg", lib.getFonts().get("aeromatics_reg")); - } - - - /** - * Load textures for GUI rendering - * @param ctx - * @throws IOException - */ - private void loadNVGTextures(long ctx) throws IOException{ + + /** Load fonts for GUI rendering + * + * @throws IOException */ + private void loadNVGFonts() throws IOException + { NVGFont.createFont("aeromatics_reg", lib.getFonts().get("aeromatics_reg")); } + + /** Load textures for GUI rendering + * + * @param ctx + * @throws IOException */ + private void loadNVGTextures(long ctx) throws IOException + { NVGTexture.loadTexture("test_button", lib.getTextures().get("test_button"), ctx); NVGTexture.loadTexture("test_button_mouseover", lib.getTextures().get("test_button_mouseover"), ctx); NVGTexture.loadTexture("test_button_pressed", lib.getTextures().get("test_button_pressed"), ctx); NVGTexture.loadTexture("test_image", lib.getTextures().get("test_image"), ctx); } - } diff --git a/src/com/bwyap/lwjgl/mesh/InstancedMesh.java b/src/com/bwyap/lwjgl/mesh/InstancedMesh.java index e6587a2..e387505 100644 --- a/src/com/bwyap/lwjgl/mesh/InstancedMesh.java +++ b/src/com/bwyap/lwjgl/mesh/InstancedMesh.java @@ -12,77 +12,60 @@ import org.lwjgl.BufferUtils; - -public class InstancedMesh extends Mesh { - +public class InstancedMesh extends Mesh +{ public static final int FLOAT_SIZE_BYTES = 4; public static final int VECTOR4F_SIZE_BYTES = 4 * FLOAT_SIZE_BYTES; public static final int MATRIX_SIZE_FLOATS = 4 * 4; public static final int MATRIX_SIZE_BYTES = MATRIX_SIZE_FLOATS * FLOAT_SIZE_BYTES; public static final int INSTANCE_SIZE_BYTES = MATRIX_SIZE_BYTES * 1 + FLOAT_SIZE_BYTES * 2; public static final int INSTANCE_SIZE_FLOATS = MATRIX_SIZE_FLOATS * 1 + 2; - private final int instances; private final int instanceDataVbo; - private final FloatBuffer instanceDataBuffer; - - protected InstancedMesh(String name, float[] positions, float[] texCoords, float[] normals, int[] indices, int instances) { + protected InstancedMesh(String name, float[] positions, float[] texCoords, float[] normals, int[] indices, int instances) + { super(name, positions, texCoords, normals, indices); this.instances = instances; this.instanceDataBuffer = BufferUtils.createFloatBuffer(instances * INSTANCE_SIZE_FLOATS); - glBindVertexArray(getVaoID()); - //Model view matrix instanceDataVbo = glGenBuffers(); vboIDs.add(instanceDataVbo); glBindBuffer(GL_ARRAY_BUFFER, instanceDataVbo); int start = 3; int strideStart = 0; - for (int i = 0; i < 4; i++) { + for (int i = 0; i < 4; i++) + { glVertexAttribPointer(start, 4, GL_FLOAT, false, INSTANCE_SIZE_BYTES, strideStart); glVertexAttribDivisor(start, 1); start++; strideStart += VECTOR4F_SIZE_BYTES; } - // Texture offsets glVertexAttribPointer(start, 2, GL_FLOAT, false, INSTANCE_SIZE_BYTES, strideStart); glVertexAttribDivisor(start, 1); - glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } - - - /** - * Get the maximum number of instances which can be rendered - * @return - */ - public int getInstances() { - return instances; - } - - - - /** - * Get the ID of the VBO for the instance data - * @return - */ - public int getInstanceDataVboID() { - return instanceDataVbo; - } - - - /** - * Get the float buffer with the instance data for this mesh. + + /** Get the maximum number of instances which can be rendered + * + * @return */ + public int getInstances() + { return instances; } + + /** Get the ID of the VBO for the instance data + * + * @return */ + public int getInstanceDataVboID() + { return instanceDataVbo; } + + /** Get the float buffer with the instance data for this mesh. * Created with the appropriate size when this mesh was instantiated. - * @return - */ - public FloatBuffer getInstanceDataBuffer() { - return instanceDataBuffer; - } - + * + * @return */ + public FloatBuffer getInstanceDataBuffer() + { return instanceDataBuffer; } } diff --git a/src/com/bwyap/lwjgl/mesh/Mesh.java b/src/com/bwyap/lwjgl/mesh/Mesh.java index 27563f4..5bcee95 100644 --- a/src/com/bwyap/lwjgl/mesh/Mesh.java +++ b/src/com/bwyap/lwjgl/mesh/Mesh.java @@ -23,80 +23,65 @@ import org.joml.Vector3f; import org.lwjgl.BufferUtils; -/** - *

- * A mesh holds the vertices, indices, normals and texture co-ordinates +/**

+ * A mesh holds the vertices, indices, normals and texture co-ordinates * necessary to render a 3D model using LWJGL. Meshes should be loaded * from OBJ files using the {@code OBJLoader} class. *

- * *

* A mesh must be given a texture using the {@code setTexture} method, * and the texture must have been previously loaded. By default a mesh - * without a texture will be rendered using a default colour. A mesh - * also be rendered with a colour which can be assigned using the + * without a texture will be rendered using a default colour. A mesh + * also be rendered with a colour which can be assigned using the * {@code setColour} method if no texture has been previously assigned. *

* - * @author bwyap - * - */ -public class Mesh { - + * @author bwyap */ +public class Mesh +{ private static final Map loadedMeshes = new HashMap(); - - /** - * Get the mesh with the specified name. + + /** Get the mesh with the specified name. * If no such mesh is found, null is returned. - * @param name - * @return - */ - public static Mesh getMesh(String name) { - return loadedMeshes.get(name); - } - - /** - * Add a mesh to the map of loaded meshes. + * + * @param name + * @return */ + public static Mesh getMesh(String name) + { return loadedMeshes.get(name); } + + /** Add a mesh to the map of loaded meshes. * Returns the mesh with the given name previously if overriding. * Null otherwise. - * @param name - * @param mesh - * @return - */ - protected static Mesh addMesh(String name, Mesh mesh) { - return loadedMeshes.put(name, mesh); - } - - - private static final Vector3f DEFAULT_COLOUR = new Vector3f(0.5f, 0.5f, 0.5f); + * + * @param name + * @param mesh + * @return */ + protected static Mesh addMesh(String name, Mesh mesh) + { return loadedMeshes.put(name, mesh); } + private static final Vector3f DEFAULT_COLOUR = new Vector3f(0.5f, 0.5f, 0.5f); private final String name; private final int vaoID; private final int vertexCount; protected final ArrayList vboIDs; - private Vector3f colour; - - - /** - * Creates a mesh with the given vertices, indices, normals and texture co-ordinates. + + /** Creates a mesh with the given vertices, indices, normals and texture co-ordinates. * This constructor should only be used by the {@code OBJLoader} class. * The required vertex buffer objects and vertex array objects will be created for use by the graphics card. + * * @param positions * @param texCoords * @param normals - * @param indices - */ - protected Mesh(String name, float[] positions, float[] texCoords, float[] normals, int[] indices) { + * @param indices */ + protected Mesh(String name, float[] positions, float[] texCoords, float[] normals, int[] indices) + { this.name = name; this.vertexCount = indices.length; this.colour = DEFAULT_COLOUR; - vboIDs = new ArrayList(); - vaoID = glGenVertexArrays(); glBindVertexArray(vaoID); - // Position VBO int vboID = glGenBuffers(); vboIDs.add(vboID); @@ -105,113 +90,87 @@ protected Mesh(String name, float[] positions, float[] texCoords, float[] normal glBindBuffer(GL_ARRAY_BUFFER, vboID); glBufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); - // Tex coord VBO vboID = glGenBuffers(); vboIDs.add(vboID); - FloatBuffer textureBuffer = BufferUtils.createFloatBuffer(texCoords.length); + FloatBuffer textureBuffer = BufferUtils.createFloatBuffer(texCoords.length); textureBuffer.put(texCoords).flip(); - glBindBuffer(GL_ARRAY_BUFFER, vboID); - glBufferData(GL_ARRAY_BUFFER, textureBuffer, GL_STATIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, vboID); + glBufferData(GL_ARRAY_BUFFER, textureBuffer, GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0); - // Vertex normals VBO vboID = glGenBuffers(); vboIDs.add(vboID); - FloatBuffer vecNormalsBuffer = BufferUtils.createFloatBuffer(normals.length); + FloatBuffer vecNormalsBuffer = BufferUtils.createFloatBuffer(normals.length); vecNormalsBuffer.put(normals).flip(); glBindBuffer(GL_ARRAY_BUFFER, vboID); - glBufferData(GL_ARRAY_BUFFER, vecNormalsBuffer, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, vecNormalsBuffer, GL_STATIC_DRAW); glVertexAttribPointer(2, 3, GL_FLOAT, false, 0, 0); - // Index VBO vboID = glGenBuffers(); vboIDs.add(vboID); - IntBuffer indicesBuffer = BufferUtils.createIntBuffer(indices.length); - indicesBuffer.put(indices).flip(); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboID); + IntBuffer indicesBuffer = BufferUtils.createIntBuffer(indices.length); + indicesBuffer.put(indices).flip(); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } - - - /** - * Get the name assigned to the mesh - * @return - */ - public String getName() { - return name; - } - - - /** - * Clean up the resources when the mesh was created. - */ - public void cleanup() { + + /** Get the name assigned to the mesh + * + * @return */ + public String getName() + { return name; } + + /** Clean up the resources when the mesh was created. */ + public void cleanup() + { glDisableVertexAttribArray(0); - // Delete the VBO glBindBuffer(GL_ARRAY_BUFFER, 0); - for (int id : vboIDs) { - glDeleteBuffers(id); - } - + for (int id : vboIDs) + { glDeleteBuffers(id); } // Delete the VAO glBindVertexArray(0); - glDeleteVertexArrays(vaoID); + glDeleteVertexArrays(vaoID); } - - - /** - * Set the colour for this mesh. + + /** Set the colour for this mesh. * The model will be rendered with this colour if no texture has been set. + * * @param r * @param g - * @param b - */ - public void setColour(float r, float g, float b) { + * @param b */ + public void setColour(float r, float g, float b) + { colour.x = r; colour.y = g; colour.z = b; } - - - /** - * Set the colour for this mesh. + + /** Set the colour for this mesh. * The model will be rendered with this colour if no texture has been set. - * @param colour - */ - public void setColour(Vector3f colour) { - this.colour = colour; - } - - - /** - * Get the assigned colour of this mesh. - * @return - */ - public Vector3f getColour() { - return colour; - } - - - /** - * Get the ID of the vertex array object for this mesh. - * @return - */ - public int getVaoID() { - return vaoID; - } - - - /** - * Get the vertex count of this mesh's model. - * @return - */ - public int getVertexCount() { - return vertexCount; - } - + * + * @param colour */ + public void setColour(Vector3f colour) + { this.colour = colour; } + + /** Get the assigned colour of this mesh. + * + * @return */ + public Vector3f getColour() + { return colour; } + + /** Get the ID of the vertex array object for this mesh. + * + * @return */ + public int getVaoID() + { return vaoID; } + + /** Get the vertex count of this mesh's model. + * + * @return */ + public int getVertexCount() + { return vertexCount; } } diff --git a/src/com/bwyap/lwjgl/mesh/MeshOld.java b/src/com/bwyap/lwjgl/mesh/MeshOld.java index 4207b4b..d0657cb 100644 --- a/src/com/bwyap/lwjgl/mesh/MeshOld.java +++ b/src/com/bwyap/lwjgl/mesh/MeshOld.java @@ -28,24 +28,21 @@ import org.lwjgl.BufferUtils; - @Deprecated -public class MeshOld { - +public class MeshOld +{ private final int vaoID; private final int vertexCount; private final ArrayList vboIDs; private final int textureID; - - - public MeshOld(float[] positions, float[] texCoords, int[] indices, int textureID) { + + public MeshOld(float[] positions, float[] texCoords, int[] indices, int textureID) + { this.vertexCount = indices.length; this.textureID = textureID; vboIDs = new ArrayList(); - vaoID = glGenVertexArrays(); glBindVertexArray(vaoID); - int positionVboID = glGenBuffers(); vboIDs.add(positionVboID); FloatBuffer verticesBuffer = BufferUtils.createFloatBuffer(positions.length); @@ -54,74 +51,57 @@ public MeshOld(float[] positions, float[] texCoords, int[] indices, int textureI glBufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); - int textureVboID = glGenBuffers(); vboIDs.add(textureVboID); - FloatBuffer textureBuffer = BufferUtils.createFloatBuffer(texCoords.length); + FloatBuffer textureBuffer = BufferUtils.createFloatBuffer(texCoords.length); textureBuffer.put(texCoords).flip(); - glBindBuffer(GL_ARRAY_BUFFER, textureVboID); - glBufferData(GL_ARRAY_BUFFER, textureBuffer, GL_STATIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, textureVboID); + glBufferData(GL_ARRAY_BUFFER, textureBuffer, GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0); - int indexVboID = glGenBuffers(); vboIDs.add(indexVboID); - IntBuffer indicesBuffer = BufferUtils.createIntBuffer(indices.length); - indicesBuffer.put(indices).flip(); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVboID); + IntBuffer indicesBuffer = BufferUtils.createIntBuffer(indices.length); + indicesBuffer.put(indices).flip(); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVboID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_STATIC_DRAW); - - glBindVertexArray(0); } - - - public void render() { - // Activate first texture unit - glActiveTexture(GL_TEXTURE0); - // Bind the texture - glBindTexture(GL_TEXTURE_2D, getTextureID()); - - // Draw the mesh + + public void render() + { + // Activate first texture unit + glActiveTexture(GL_TEXTURE0); + // Bind the texture + glBindTexture(GL_TEXTURE_2D, getTextureID()); + // Draw the mesh glBindVertexArray(getVaoID()); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); - glDrawElements(GL_TRIANGLES, getVertexCount(), GL_UNSIGNED_INT, 0); - // Restore state - glDisableVertexAttribArray(0); - glDisableVertexAttribArray(1); - glBindVertexArray(0); + glDisableVertexAttribArray(0); + glDisableVertexAttribArray(1); + glBindVertexArray(0); } - - - public void cleanup() { + + public void cleanup() + { glDisableVertexAttribArray(0); - // Delete the VBO glBindBuffer(GL_ARRAY_BUFFER, 0); - for (int id : vboIDs) { - glDeleteBuffers(id); - } - + for (int id : vboIDs) + { glDeleteBuffers(id); } // Delete the VAO glBindVertexArray(0); - glDeleteVertexArrays(vaoID); + glDeleteVertexArrays(vaoID); } - - public int getTextureID() { - return textureID; - } - - - public int getVaoID() { - return vaoID; - } - - - public int getVertexCount() { - return vertexCount; - } - + public int getTextureID() + { return textureID; } + + public int getVaoID() + { return vaoID; } + + public int getVertexCount() + { return vertexCount; } } diff --git a/src/com/bwyap/lwjgl/mesh/OBJLoader.java b/src/com/bwyap/lwjgl/mesh/OBJLoader.java index ead433c..3fe2d25 100644 --- a/src/com/bwyap/lwjgl/mesh/OBJLoader.java +++ b/src/com/bwyap/lwjgl/mesh/OBJLoader.java @@ -8,79 +8,74 @@ import com.bwyap.utility.resource.ResourceLoader; - -/** - * A helper class for parsing an OBJ file and loading it as a mesh. - * @author bwyap - * - */ -public class OBJLoader { - - - /** - * Loads an {@code OBJ} model as a mesh with the vertex array object initialised. - * @param fileName - * @param i number of instances +/** A helper class for parsing an OBJ file and loading it as a mesh. + * + * @author bwyap */ +public class OBJLoader +{ + /** Loads an {@code OBJ} model as a mesh with the vertex array object initialised. + * + * @param fileName + * @param i number of instances * @return - * @throws Exception - */ - public static InstancedMesh loadInstancedMesh(String name, String fileName, int i) throws Exception { + * @throws Exception */ + public static InstancedMesh loadInstancedMesh(String name, String fileName, int i) throws Exception + { MeshProperties p = decodeMesh(fileName); Mesh.addMesh(name, new InstancedMesh(name, p.posArr, p.textCoordArr, p.normArr, p.indicesArr, i)); - return (InstancedMesh)Mesh.getMesh(name); + return (InstancedMesh) Mesh.getMesh(name); } - - /** - * Loads an {@code OBJ} model as an instanced mesh with the vertex array object initialised. - * @param fileName + /** Loads an {@code OBJ} model as an instanced mesh with the vertex array object initialised. + * + * @param fileName * @return - * @throws Exception - */ - public static Mesh loadMesh(String name, String fileName) throws Exception { + * @throws Exception */ + public static Mesh loadMesh(String name, String fileName) throws Exception + { MeshProperties p = decodeMesh(fileName); Mesh.addMesh(name, new Mesh(name, p.posArr, p.textCoordArr, p.normArr, p.indicesArr)); return Mesh.getMesh(name); } - - - /** - * Load and decode the {@code OBJ} specified by {@code filename}. - * @param fileName + + /** Load and decode the {@code OBJ} specified by {@code filename}. + * + * @param fileName * @return - * @throws Exception - */ - private static MeshProperties decodeMesh(String fileName) throws Exception { + * @throws Exception */ + private static MeshProperties decodeMesh(String fileName) throws Exception + { List lines = ResourceLoader.loadInternalTextFileAsList(fileName); List vertices = new ArrayList<>(); List textures = new ArrayList<>(); List normals = new ArrayList<>(); List faces = new ArrayList<>(); - - for (String line : lines) { + for (String line : lines) + { String[] tokens = line.split("\\s+"); - switch (tokens[0]) { + switch (tokens[0]) + { case "v": // Geometric vertex Vector3f vec3f = new Vector3f( - Float.parseFloat(tokens[1]), - Float.parseFloat(tokens[2]), - Float.parseFloat(tokens[3])); + Float.parseFloat(tokens[1]), + Float.parseFloat(tokens[2]), + Float.parseFloat(tokens[3])); vertices.add(vec3f); break; case "vt": // Texture coordinate Vector2f vec2f = new Vector2f( - Float.parseFloat(tokens[1]), - Float.parseFloat(tokens[2])); + Float.parseFloat(tokens[1]), + Float.parseFloat(tokens[2])); textures.add(vec2f); break; case "vn": // Vertex normal Vector3f vec3fNorm = new Vector3f( - Float.parseFloat(tokens[1]), - Float.parseFloat(tokens[2]), - Float.parseFloat(tokens[3])); + Float.parseFloat(tokens[1]), + Float.parseFloat(tokens[2]), + Float.parseFloat(tokens[3])); normals.add(vec3fNorm); break; case "f": @@ -92,53 +87,50 @@ private static MeshProperties decodeMesh(String fileName) throws Exception { break; } } - return reorderLists(vertices, textures, normals, faces); } - - - private static MeshProperties reorderLists(List posList, List textCoordList, List normList, List facesList) { + + private static MeshProperties reorderLists(List posList, List textCoordList, List normList, List facesList) + { List indices = new ArrayList(); // Create position array in the order it has been declared float[] posArr = new float[posList.size() * 3]; int i = 0; - for (Vector3f pos : posList) { + for (Vector3f pos : posList) + { posArr[i * 3] = pos.x; posArr[i * 3 + 1] = pos.y; posArr[i * 3 + 2] = pos.z; i++; } - float[] textCoordArr = new float[posList.size() * 2]; float[] normArr = new float[posList.size() * 3]; - - for (Face face : facesList) { + for (Face face : facesList) + { IndexGroup[] faceVertexIndices = face.getFaceVertexIndices(); - for (IndexGroup indValue : faceVertexIndices) { - processFaceVertex(indValue, textCoordList, normList, - indices, textCoordArr, normArr); - } + for (IndexGroup indValue : faceVertexIndices) + { processFaceVertex(indValue, textCoordList, normList, + indices, textCoordArr, normArr); } } - int[] indicesArr = new int[indices.size()]; indicesArr = indices.stream().mapToInt((Integer v) -> v).toArray(); - return new MeshProperties(posArr, textCoordArr, normArr, indicesArr); } - - private static void processFaceVertex(IndexGroup indices, List textCoordList, List normList, List indicesList, float[] texCoordArr, float[] normArr) { + private static void processFaceVertex(IndexGroup indices, List textCoordList, List normList, List indicesList, float[] texCoordArr, float[] normArr) + { // Set index for vertex coordinates int posIndex = indices.idxPos; indicesList.add(posIndex); - // Reorder texture coordinates - if (indices.idxTextCoord >= 0) { + if (indices.idxTextCoord >= 0) + { Vector2f textCoord = textCoordList.get(indices.idxTextCoord); texCoordArr[posIndex * 2] = textCoord.x; texCoordArr[posIndex * 2 + 1] = 1 - textCoord.y; } - if (indices.idxVecNormal >= 0) { + if (indices.idxVecNormal >= 0) + { // Reorder vector normals Vector3f vecNorm = normList.get(indices.idxVecNormal); normArr[posIndex * 3] = vecNorm.x; @@ -146,78 +138,71 @@ private static void processFaceVertex(IndexGroup indices, List textCoo normArr[posIndex * 3 + 2] = vecNorm.z; } } - - - /** - * Represents an Index Group in the OBJ file for a vertex. - * @author bwyap - * - */ - protected static class IndexGroup { - + + /** Represents an Index Group in the OBJ file for a vertex. + * + * @author bwyap */ + protected static class IndexGroup + { public static final int NO_VALUE = -1; public int idxPos; public int idxTextCoord; public int idxVecNormal; - - public IndexGroup() { + + public IndexGroup() + { idxPos = NO_VALUE; idxTextCoord = NO_VALUE; idxVecNormal = NO_VALUE; } } - - - protected static class Face { - /** - * List of idxGroup groups for a face triangle (3 vertices per face). - */ + + protected static class Face + { + /** List of idxGroup groups for a face triangle (3 vertices per face). */ private IndexGroup[] idxGroups = new IndexGroup[3]; - - public Face(String v1, String v2, String v3) { + + public Face(String v1, String v2, String v3) + { idxGroups = new IndexGroup[3]; // Parse the lines idxGroups[0] = parseLine(v1); idxGroups[1] = parseLine(v2); idxGroups[2] = parseLine(v3); } - - private IndexGroup parseLine(String line) { + + private IndexGroup parseLine(String line) + { IndexGroup idxGroup = new IndexGroup(); String[] lineTokens = line.split("/"); int length = lineTokens.length; idxGroup.idxPos = Integer.parseInt(lineTokens[0]) - 1; - - if (length > 1) { + if (length > 1) + { // It can be empty if the obj does not define texture coords String textCoord = lineTokens[1]; idxGroup.idxTextCoord = textCoord.length() > 0 ? Integer.parseInt(textCoord) - 1 : IndexGroup.NO_VALUE; - if (length > 2) { - idxGroup.idxVecNormal = Integer.parseInt(lineTokens[2]) - 1; - } + if (length > 2) + { idxGroup.idxVecNormal = Integer.parseInt(lineTokens[2]) - 1; } } return idxGroup; } - - public IndexGroup[] getFaceVertexIndices() { - return idxGroups; - } - + + public IndexGroup[] getFaceVertexIndices() + { return idxGroups; } } - - protected static class MeshProperties { - + protected static class MeshProperties + { float[] posArr, textCoordArr, normArr; int[] indicesArr; - - MeshProperties(float[] posArr, float[] textCoordArr, float[] normArr, int[] indicesArr) { + + MeshProperties(float[] posArr, float[] textCoordArr, float[] normArr, int[] indicesArr) + { this.posArr = posArr; this.textCoordArr = textCoordArr; this.normArr = normArr; this.indicesArr = indicesArr; } } - - } diff --git a/src/com/bwyap/lwjgl/window/GLFWWindow.java b/src/com/bwyap/lwjgl/window/GLFWWindow.java index 54c9739..4ea1e8a 100644 --- a/src/com/bwyap/lwjgl/window/GLFWWindow.java +++ b/src/com/bwyap/lwjgl/window/GLFWWindow.java @@ -60,54 +60,47 @@ import com.bwyap.lwjgl.window.input.GLFWKeyboardHandler; import com.bwyap.lwjgl.window.input.GLFWMouseHandler; -/** - * A GLFW window with input handlers. - * The {@code start()} method will start a loop which call the +/** A GLFW window with input handlers. + * The {@code start()} method will start a loop which call the * {@code update} and {@code render} methods on a {@GLFWGame} object. *

* The method {@code createGame()} method should be overridden to * load a more specific and concrete implementation of GLFWGame. * - * @author bwyap - * - */ -public abstract class GLFWWindow extends Window { - + * @author bwyap */ +public abstract class GLFWWindow extends Window +{ private long window; private boolean vSync; private boolean polygonMode; - private GLFWKeyboardHandler keyboardHandler; private GLFWMouseHandler mouseHandler; - // Callbacks - GLFWErrorCallback errorCallback; - GLFWWindowSizeCallback windowSizeCallback; - GLFWKeyCallback keyCallback; + GLFWErrorCallback errorCallback; + GLFWWindowSizeCallback windowSizeCallback; + GLFWKeyCallback keyCallback; GLFWMouseButtonCallback mouseButtonCallback; - GLFWCursorPosCallback cursorPosCallback; - GLFWScrollCallback scrollCallback; - GLFWCursorEnterCallback cursorEnterCallback; - - - /** - * A GLFW window. + GLFWCursorPosCallback cursorPosCallback; + GLFWScrollCallback scrollCallback; + GLFWCursorEnterCallback cursorEnterCallback; + + /** A GLFW window. + * * @param width - * @param height - */ - public GLFWWindow(int width, int height, String title, boolean vSync, boolean polygonMode, boolean showFps) { + * @param height */ + public GLFWWindow(int width, int height, String title, boolean vSync, boolean polygonMode, boolean showFps) + { super(width, height, title, showFps); this.vSync = vSync; this.polygonMode = polygonMode; } - - + @Override - public void init() { + public void init() + { // Initialize GLFW. Most GLFW functions will not work before doing this. - if (!glfwInit()) + if (!glfwInit()) throw new IllegalStateException("Unable to initialize GLFW"); - //Configure the window glfwDefaultWindowHints(); // optional, the current window hints are already the default glfwWindowHint(GLFW_SAMPLES, 4); @@ -117,196 +110,156 @@ public void init() { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); - //Create the window window = glfwCreateWindow(width, height, title, NULL, NULL); - if (window == NULL) + if (window == NULL) throw new RuntimeException("Failed to create the GLFW window"); - // Initialise the callbacks for the window initCallbacks(); - // Get the resolution of the primary monitor GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); - // Center our window glfwSetWindowPos(window, (vidmode.width() - width) / 2, - (vidmode.height() - height) / 2 - ); - - glfwMakeContextCurrent(window); // Make the OpenGL context current - - if (vSync) { - glfwSwapInterval(1); // Enable v-sync + (vidmode.height() - height) / 2); + glfwMakeContextCurrent(window); // Make the OpenGL context current + if (vSync) + { + glfwSwapInterval(1); // Enable v-sync } - - glfwShowWindow(window); // Make the window visible + glfwShowWindow(window); // Make the window visible GL.createCapabilities(); loadGLRequiredResources(); - //Create a new engine to run - try { + try + { engine = createEngine(); - } catch (Exception e) { + } + catch (Exception e) + { e.printStackTrace(); } - setClearColour(0, 0, 0, 0); glEnable(GL_DEPTH_TEST); glEnable(GL_STENCIL_TEST); - if (polygonMode) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } - - + @Override - public boolean shouldClose() { - return glfwWindowShouldClose(this.getID()); - } - - + public boolean shouldClose() + { return glfwWindowShouldClose(this.getID()); } + @Override - public void processEvents() { - glfwPollEvents(); - } - - + public void processEvents() + { glfwPollEvents(); } + @Override - public void swapDisplayBuffers() { - glfwSwapBuffers(this.getID()); - } - - - /** - * Load resources which require GL capabilities to be initialised first. - * This method is automatically called. - */ + public void swapDisplayBuffers() + { glfwSwapBuffers(this.getID()); } + + /** Load resources which require GL capabilities to be initialised first. + * This method is automatically called. */ public abstract void loadGLRequiredResources(); - - - /** - * Initialise the callbacks used by this window. - */ - protected void initCallbacks() { + + /** Initialise the callbacks used by this window. */ + protected void initCallbacks() + { // Setup an error callback. // The default implementation will print the error message in System.err. errorCallback = GLFWErrorCallback.createPrint(System.err).set(); - // Setup window callback - glfwSetWindowSizeCallback(window, windowSizeCallback = new GLFWWindowSizeCallback() { + glfwSetWindowSizeCallback(window, windowSizeCallback = new GLFWWindowSizeCallback() + { @Override - public void invoke(long window, int width, int height) { + public void invoke(long window, int width, int height) + { GLFWWindow.this.width = width; GLFWWindow.this.height = height; GLFWWindow.this.setResized(true); glfwSetWindowAspectRatio(window, LWJGLResourceManager.instance().settings().getWidth(), LWJGLResourceManager.instance().settings().getHeight()); } }); - // Create input handlers keyboardHandler = new GLFWKeyboardHandler(); mouseHandler = new GLFWMouseHandler(); input = new InputHandler(keyboardHandler, mouseHandler); - // Setup key callback - glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() { + glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() + { @Override - public void invoke(long window, int key, int scancode, int action, int mods) { - keyboardHandler.invoke(window, key, scancode, action, mods); - } + public void invoke(long window, int key, int scancode, int action, int mods) + { keyboardHandler.invoke(window, key, scancode, action, mods); } }); - // Setup mouse callbacks - glfwSetMouseButtonCallback(window, mouseButtonCallback = new GLFWMouseButtonCallback() { + glfwSetMouseButtonCallback(window, mouseButtonCallback = new GLFWMouseButtonCallback() + { @Override - public void invoke(long window, int button, int action, int mods) { - mouseHandler.invokeMouseButtonCallback(window, button, action, mods); - } + public void invoke(long window, int button, int action, int mods) + { mouseHandler.invokeMouseButtonCallback(window, button, action, mods); } }); - - glfwSetScrollCallback(window, scrollCallback = new GLFWScrollCallback() { + glfwSetScrollCallback(window, scrollCallback = new GLFWScrollCallback() + { @Override - public void invoke(long window, double xoffset, double yoffset) { - mouseHandler.invokeScrollCallback(window, xoffset, yoffset); - } + public void invoke(long window, double xoffset, double yoffset) + { mouseHandler.invokeScrollCallback(window, xoffset, yoffset); } }); - - glfwSetCursorPosCallback(window, cursorPosCallback = new GLFWCursorPosCallback() { + glfwSetCursorPosCallback(window, cursorPosCallback = new GLFWCursorPosCallback() + { @Override - public void invoke(long window, double xpos, double ypos) { - mouseHandler.invokeCursorPosCallback(window, xpos, ypos); - } + public void invoke(long window, double xpos, double ypos) + { mouseHandler.invokeCursorPosCallback(window, xpos, ypos); } }); - - glfwSetCursorEnterCallback(window, cursorEnterCallback = new GLFWCursorEnterCallback() { + glfwSetCursorEnterCallback(window, cursorEnterCallback = new GLFWCursorEnterCallback() + { @Override - public void invoke(long window, boolean entered) { - mouseHandler.invokeCursorEnterCallback(window, entered); - } + public void invoke(long window, boolean entered) + { mouseHandler.invokeCursorEnterCallback(window, entered); } }); - } - - + @Override - public final void start() { + public final void start() + { // Initialise the window init(); - // Run the engine engine.run(); - // Dispose the window dispose(); } - @Override - public void dispose() { + public void dispose() + { glfwFreeCallbacks(window); glfwSetErrorCallback(null).free(); - // Destroy the window glfwDestroyWindow(window); - glfwTerminate(); } - - - /** - * Sets the clear colour for the window + + /** Sets the clear colour for the window + * * @param r * @param g * @param b - * @param alpha - */ - public void setClearColour(float r, float g, float b, float alpha) { - glClearColor(r, g, b, alpha); - } - - - /** - * Get the window handle - * @return - */ - public long getID() { - return window; - } - - + * @param alpha */ + public void setClearColour(float r, float g, float b, float alpha) + { glClearColor(r, g, b, alpha); } + + /** Get the window handle + * + * @return */ + public long getID() + { return window; } + @Override - protected void setWindowTitle(String title) { - glfwSetWindowTitle(window, title); - } - - - /** - * Checks if vSync is enabled for this window - * @return - */ - public boolean isVSync() { - return vSync; - } - + protected void setWindowTitle(String title) + { glfwSetWindowTitle(window, title); } + + /** Checks if vSync is enabled for this window + * + * @return */ + public boolean isVSync() + { return vSync; } } diff --git a/src/com/bwyap/lwjgl/window/input/GLFWKeyboardHandler.java b/src/com/bwyap/lwjgl/window/input/GLFWKeyboardHandler.java index 3c9157d..f3262f5 100644 --- a/src/com/bwyap/lwjgl/window/input/GLFWKeyboardHandler.java +++ b/src/com/bwyap/lwjgl/window/input/GLFWKeyboardHandler.java @@ -12,137 +12,117 @@ import com.bwyap.engine.input.KeyboardHandlerInterface; -/** - * Handles keyboard input through GLFWKeyCallbacks. - * @author bwyap - * - */ -public class GLFWKeyboardHandler implements KeyboardHandlerInterface { - +/** Handles keyboard input through GLFWKeyCallbacks. + * + * @author bwyap */ +public class GLFWKeyboardHandler implements KeyboardHandlerInterface +{ private static final boolean DEBUG = false; - private boolean[] keys = new boolean[65535]; private int keyMods = 0x0; private int keysDown = 0; private char typedChar = 0; - private Map acceptedKeys; private Map acceptedShiftKeys; - - - public GLFWKeyboardHandler() { + + public GLFWKeyboardHandler() + { acceptedKeys = new HashMap(); acceptedShiftKeys = new HashMap(); initAcceptedKeys(); } - - - /** - * For GLFWKeyCallback + + /** For GLFWKeyCallback + * * @param window * @param key * @param scancode * @param action - * @param mods - */ - public void invoke(long window, int key, int scancode, int action, int mods) { - if (key != GLFW_KEY_UNKNOWN) { + * @param mods */ + public void invoke(long window, int key, int scancode, int action, int mods) + { + if (key != GLFW_KEY_UNKNOWN) + { keys[key] = action != GLFW_RELEASE; keyMods = mods; - if (action != GLFW_RELEASE) typedChar = convertKey(key, mods); - - if (action == GLFW_PRESS) keysDown++; + if (action == GLFW_PRESS) + keysDown++; else if (action == GLFW_RELEASE) keysDown--; - if (DEBUG) if (action == GLFW_PRESS) System.out.println(key + " pressed with mods " + mods); if (DEBUG) if (action == GLFW_REPEAT) System.out.println(key + " holding with mods " + mods); if (DEBUG) if (action == GLFW_RELEASE) System.out.println(key + " released with mods " + mods); - } + } } - - + @Override - public char consumeLastTypedChar() { + public char consumeLastTypedChar() + { char c = typedChar; typedChar = 0; return c; } - - + @Override - public boolean isKeyDown(int keycode) { - return keys[keycode]; - } - - - /** - * {@inheritDoc} + public boolean isKeyDown(int keycode) + { return keys[keycode]; } + + /** {@inheritDoc} *

* In the GLFW system, the following bits will be set if - *

+ *

*

* {@code GLFW_MOD_SHIFT: 0x1}
* {@code GLFW_MOD_CONTROL: 0x2}
* {@code GLFW_MOD_ALT: 0x4}
* {@code GLFW_MOD_SUPER: 0x8} (Command on macOS) - *

- */ + *

*/ @Override - public int getKeyMods() { - return keyMods; - } - - - @Override - public int getKeysDown() { - return keysDown; - } - - - /** - * Converts an accepted GLFW keycode into a character - * @param key - * @param mods - * @return - */ - public char convertKey(int key, int mods) { - if ((mods & 0x1) == 0x1) { - if (acceptedShiftKeys.get(key) != null) return acceptedShiftKeys.get(key); - } - if (acceptedKeys.get(key) == null) return 0; + public int getKeyMods() + { return keyMods; } + + @Override + public int getKeysDown() + { return keysDown; } + + /** Converts an accepted GLFW keycode into a character + * + * @param key + * @param mods + * @return */ + public char convertKey(int key, int mods) + { + if ((mods & 0x1) == 0x1) + { if (acceptedShiftKeys.get(key) != null) return acceptedShiftKeys.get(key); } + if (acceptedKeys.get(key) == null) + return 0; else return acceptedKeys.get(key); } - - - /** - * Initialise the HashMaps holding the mappings from GLFW_KEY codes to characters - */ - private void initAcceptedKeys() { + + /** Initialise the HashMaps holding the mappings from GLFW_KEY codes to characters */ + private void initAcceptedKeys() + { String lowercase = "abcdefghijklmnopqrstuvwxyz"; String uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - String special1Lower = " ??????'????,-./0123456789?;?="; String special1Upper = " ??????\"????<_>?)!@#$%^&*(?:?+"; - String special2Lower = "[\\]`"; String special2Upper = "{|}~"; - - for (int i = 0; i < 26; i++) { + for (int i = 0; i < 26; i++) + { acceptedKeys.put(i + GLFW_KEY_A, lowercase.charAt(i)); acceptedShiftKeys.put(i + GLFW_KEY_A, uppercase.charAt(i)); } - - for (int i = 0; i < special1Lower.length(); i++) { + for (int i = 0; i < special1Lower.length(); i++) + { acceptedKeys.put(i + GLFW_KEY_SPACE, special1Lower.charAt(i)); acceptedShiftKeys.put(i + GLFW_KEY_SPACE, special1Upper.charAt(i)); } - - for (int i = 0; i < special2Lower.length(); i++) { + for (int i = 0; i < special2Lower.length(); i++) + { acceptedKeys.put(i + GLFW_KEY_LEFT_BRACKET, special2Lower.charAt(i)); acceptedShiftKeys.put(i + GLFW_KEY_LEFT_BRACKET, special2Upper.charAt(i)); } - acceptedKeys.put(GLFW_KEY_BACKSPACE, '\b'); acceptedKeys.put(GLFW_KEY_ENTER, '\n'); /* @@ -155,5 +135,4 @@ private void initAcceptedKeys() { } */ } - } diff --git a/src/com/bwyap/lwjgl/window/input/GLFWMouseHandler.java b/src/com/bwyap/lwjgl/window/input/GLFWMouseHandler.java index a293d25..555a3ae 100644 --- a/src/com/bwyap/lwjgl/window/input/GLFWMouseHandler.java +++ b/src/com/bwyap/lwjgl/window/input/GLFWMouseHandler.java @@ -4,133 +4,116 @@ import com.bwyap.engine.input.MouseHandlerInterface; -/** - * Handles mouse input through GLFW Callbacks. - * @author bwyap - * - */ -public class GLFWMouseHandler implements MouseHandlerInterface { - +/** Handles mouse input through GLFW Callbacks. + * + * @author bwyap */ +public class GLFWMouseHandler implements MouseHandlerInterface +{ private static final boolean DEBUG = false; - private boolean[] buttons = new boolean[1024]; private double mouseX, mouseY; private double scrollX, scrollY; private double mouseScrollTime; private boolean mouseEntered; - - - /** - * For GLFWMouseButtonCallback + + /** For GLFWMouseButtonCallback + * * @param window * @param button * @param action - * @param mods - */ - public void invokeMouseButtonCallback(long window, int button, int action, int mods) { + * @param mods */ + public void invokeMouseButtonCallback(long window, int button, int action, int mods) + { buttons[button] = action != GLFW_RELEASE; - if (DEBUG) if (action == GLFW_PRESS) System.out.println("Mouse " + button + " pressed."); if (DEBUG) if (action == GLFW_REPEAT) System.out.println("Mouse " + button + " holding."); if (DEBUG) if (action == GLFW_RELEASE) System.out.println("Mouse " + button + " released."); } - - - /** - * For GLFWScrollCallback + + /** For GLFWScrollCallback + * * @param window * @param xoffset - * @param yoffset - */ - public void invokeScrollCallback(long window, double xoffset, double yoffset) { + * @param yoffset */ + public void invokeScrollCallback(long window, double xoffset, double yoffset) + { mouseScrollTime = glfwGetTime(); scrollX = xoffset; scrollY = yoffset; - if (DEBUG) System.out.println("Mouse scrolled: " + xoffset + ", " + yoffset); } - - /** - * For GLFWCursorPosCallback + /** For GLFWCursorPosCallback + * * @param window * @param xpos - * @param ypos - */ - public void invokeCursorPosCallback(long window, double xpos, double ypos) { + * @param ypos */ + public void invokeCursorPosCallback(long window, double xpos, double ypos) + { mouseX = xpos; mouseY = ypos; - if (DEBUG) System.out.println("Mouse moved to " + xpos + ", " + ypos); } - - /** - * For GLFWCursorEnterCallback + /** For GLFWCursorEnterCallback + * * @param window - * @param entered - */ - public void invokeCursorEnterCallback(long window, boolean entered) { + * @param entered */ + public void invokeCursorEnterCallback(long window, boolean entered) + { mouseEntered = entered; - if (DEBUG) System.out.println("Mouse entered: " + entered); } - - + @Override - public boolean isMouseDown(int mouseButton) { - return buttons[mouseButton]; - } - + public boolean isMouseDown(int mouseButton) + { return buttons[mouseButton]; } + @Override - public boolean isMouseDown() { - for (boolean down : buttons) { - if (down) return true; - } + public boolean isMouseDown() + { + for (boolean down : buttons) + { if (down) return true; } return false; } @Override - public double getMouseX() { - return mouseX; - } + public double getMouseX() + { return mouseX; } @Override - public double getMouseY() { - return mouseY; - } + public double getMouseY() + { return mouseY; } @Override - public boolean isMouseEntered() { - return mouseEntered; - } + public boolean isMouseEntered() + { return mouseEntered; } @Override - public double getMouseScrollX() { - return scrollX; - } - + public double getMouseScrollX() + { return scrollX; } + @Override - public double consumeMouseScrollX() { + public double consumeMouseScrollX() + { double x = scrollX; scrollX = 0; return x; } @Override - public double getMouseScrollY() { - return scrollY; - } - + public double getMouseScrollY() + { return scrollY; } + @Override - public double consumeMouseScrollY() { + public double consumeMouseScrollY() + { double y = scrollY; scrollY = 0; return y; } @Override - public double getLastMouseScrollTime() { - return mouseScrollTime; - } + public double getLastMouseScrollTime() + { return mouseScrollTime; } } diff --git a/src/com/bwyap/utility/StreamLogger.java b/src/com/bwyap/utility/StreamLogger.java index 14cd1df..c8aad87 100644 --- a/src/com/bwyap/utility/StreamLogger.java +++ b/src/com/bwyap/utility/StreamLogger.java @@ -2,195 +2,173 @@ import java.io.PrintStream; -/** - * A wrapper for a collection of methods that print to a PrintStream. +/** A wrapper for a collection of methods that print to a PrintStream. * The logger specifies a name and a line level at the start of each line. - * Line levels are one of: + * Line levels are one of: * {@code RECEIVE}, {@code SEND}, {@code INFO}, {@code MESSAGE} or {@code ERROR}. - * @author bwyap - * - */ -public class StreamLogger { - - - static enum LineLevel { + * + * @author bwyap */ +public class StreamLogger +{ + static enum LineLevel + { RECEIVE, SEND, INFO, MESSAGE, ERROR, CONNECTION, RESOURCE; - @Override - public String toString() { - switch (this) { - case ERROR: return "ERR"; - case INFO: return "INF"; - case CONNECTION:return "CON"; - case MESSAGE: return "MSG"; - case RECEIVE: return "RCV"; - case SEND: return "SND"; - case RESOURCE: return "RES"; + public String toString() + { + switch (this) + { + case ERROR: + return "ERR"; + case INFO: + return "INF"; + case CONNECTION: + return "CON"; + case MESSAGE: + return "MSG"; + case RECEIVE: + return "RCV"; + case SEND: + return "SND"; + case RESOURCE: + return "RES"; } return null; } } - - static enum DebugLevel { + static enum DebugLevel + { DEBUG, NORMAL; } - + private String name; private PrintStream printStream; private DebugLevel debugLevel; - - - private static LineLevel[] LEVEL_DEBUG = { - LineLevel.ERROR, - LineLevel.INFO, - LineLevel.CONNECTION, - LineLevel.MESSAGE, - LineLevel.RECEIVE, - LineLevel.SEND, - LineLevel.RESOURCE + private static LineLevel[] LEVEL_DEBUG = + { + LineLevel.ERROR, + LineLevel.INFO, + LineLevel.CONNECTION, + LineLevel.MESSAGE, + LineLevel.RECEIVE, + LineLevel.SEND, + LineLevel.RESOURCE }; - - - private static LineLevel[] LEVEL_NORMAL = { - LineLevel.ERROR, - LineLevel.INFO, - LineLevel.CONNECTION, - LineLevel.MESSAGE, - LineLevel.RESOURCE + private static LineLevel[] LEVEL_NORMAL = + { + LineLevel.ERROR, + LineLevel.INFO, + LineLevel.CONNECTION, + LineLevel.MESSAGE, + LineLevel.RESOURCE }; - - public StreamLogger(String name, PrintStream printStream) { + public StreamLogger(String name, PrintStream printStream) + { this.name = name; this.printStream = printStream; this.debugLevel = DebugLevel.NORMAL; } - - - /** - * Gets the stream the logger is outputting to - * @return - */ - public PrintStream getStream() { - return printStream; - } - - /** - * Push a receive line - * @param message - */ - public void pushReceive(String message) { - pushLine(LineLevel.RECEIVE, message); - } - - /** - * Push an error line - * @param message - */ - public void pushError(String message) { - pushLine(LineLevel.ERROR, message); - } - /** - * Push an info line - * @param message - */ - public void pushInfo(String message) { - pushLine(LineLevel.INFO, message); - } - - /** - * Push a connection line - * @param message - */ - public void pushCon(String message) { - pushLine(LineLevel.CONNECTION, message); - } - - /** - * Push a message line - * @param message - */ - public void pushMessage(String message) { - pushLine(LineLevel.MESSAGE, message); - } - - /** - * Push a send line - * @param message - */ - public void pushSend(String message) { - pushLine(LineLevel.SEND, message); - } - - /** - * Push a resource line - * @param message - */ - public void pushResource(String message) { - pushLine(LineLevel.RESOURCE, message); - } + /** Gets the stream the logger is outputting to + * + * @return */ + public PrintStream getStream() + { return printStream; } + + /** Push a receive line + * + * @param message */ + public void pushReceive(String message) + { pushLine(LineLevel.RECEIVE, message); } + + /** Push an error line + * + * @param message */ + public void pushError(String message) + { pushLine(LineLevel.ERROR, message); } + + /** Push an info line + * + * @param message */ + public void pushInfo(String message) + { pushLine(LineLevel.INFO, message); } + + /** Push a connection line + * + * @param message */ + public void pushCon(String message) + { pushLine(LineLevel.CONNECTION, message); } - /** - * Push a line to the server console at the specified level + /** Push a message line + * + * @param message */ + public void pushMessage(String message) + { pushLine(LineLevel.MESSAGE, message); } + + /** Push a send line + * + * @param message */ + public void pushSend(String message) + { pushLine(LineLevel.SEND, message); } + + /** Push a resource line + * + * @param message */ + public void pushResource(String message) + { pushLine(LineLevel.RESOURCE, message); } + + /** Push a line to the server console at the specified level + * * @param level - * @param message - */ - public void pushLine(LineLevel level, String message) { - + * @param message */ + public void pushLine(LineLevel level, String message) + { LineLevel[] acceptedLevels = null; - - switch (debugLevel) { - case NORMAL: acceptedLevels = LEVEL_NORMAL; break; - case DEBUG: acceptedLevels = LEVEL_DEBUG; break; + switch (debugLevel) + { + case NORMAL: + acceptedLevels = LEVEL_NORMAL; + break; + case DEBUG: + acceptedLevels = LEVEL_DEBUG; + break; } - //Check accepted levels filter - for (int i = 0; i < acceptedLevels.length; i++) { - if (acceptedLevels[i] == level) { + for (int i = 0; i < acceptedLevels.length; i++) + { + if (acceptedLevels[i] == level) + { String header = "[" + Thread.currentThread().getName() + "] "; - String tail = " " + name + "> " + message; - + String tail = " " + name + "> " + message; printStream.println(header + level + tail); return; } } } - - - /** - * Set the name of the logger - * @param name - */ - public void setName(String name) { - this.name = name; - } - - - /** - * Get the name of the logger - * @return - */ - public String getName() { - return name; - } - - - /** - * Set the debug level of the logger. - * @param level - */ - public void setDebugLevel(DebugLevel level) { - this.debugLevel = level; - } - - - /** - * Get the current debug level of the logger. - * @return - */ - public DebugLevel getDebugLevel() { - return debugLevel; - } + + /** Set the name of the logger + * + * @param name */ + public void setName(String name) + { this.name = name; } + + /** Get the name of the logger + * + * @return */ + public String getName() + { return name; } + + /** Set the debug level of the logger. + * + * @param level */ + public void setDebugLevel(DebugLevel level) + { this.debugLevel = level; } + + /** Get the current debug level of the logger. + * + * @return */ + public DebugLevel getDebugLevel() + { return debugLevel; } } diff --git a/src/com/bwyap/utility/resource/JSONWrapper.java b/src/com/bwyap/utility/resource/JSONWrapper.java index e7cfe59..fab6092 100644 --- a/src/com/bwyap/utility/resource/JSONWrapper.java +++ b/src/com/bwyap/utility/resource/JSONWrapper.java @@ -2,62 +2,46 @@ import org.json.simple.JSONObject; -/** - * A wrapper for a JSONObject. +/** A wrapper for a JSONObject. * Provides methods to extract specific data types from a JSONObject. - * @author bwyap - * - */ -public class JSONWrapper { - + * + * @author bwyap */ +public class JSONWrapper +{ protected JSONObject object; - - - public JSONWrapper(JSONObject object) { - this.object = object; - } - - - /** - * A helper function for extracting a boolean value from a JSON object - * @param o - * @param key - * @return - */ - protected static boolean getBoolean(JSONObject o, String key) { - return Boolean.parseBoolean(o.get(key).toString()); - } - - /** - * A helper function for extracting an integer value from a JSON object - * @param o - * @param key - * @return - */ - protected static int getInteger(JSONObject o, String key) { - return Integer.parseInt(o.get(key).toString()); - } - - - /** - * A helper function for extracting a String value from a JSON object - * @param o - * @param key - * @return - */ - protected static String getString(JSONObject o, String key) { - return o.get(key).toString(); - } - - - /** - * Validates the contents of the loaded JSON object. + public JSONWrapper(JSONObject object) + { this.object = object; } + + /** A helper function for extracting a boolean value from a JSON object + * + * @param o + * @param key + * @return */ + protected static boolean getBoolean(JSONObject o, String key) + { return Boolean.parseBoolean(o.get(key).toString()); } + + /** A helper function for extracting an integer value from a JSON object + * + * @param o + * @param key + * @return */ + protected static int getInteger(JSONObject o, String key) + { return Integer.parseInt(o.get(key).toString()); } + + /** A helper function for extracting a String value from a JSON object + * + * @param o + * @param key + * @return */ + protected static String getString(JSONObject o, String key) + { return o.get(key).toString(); } + + /** Validates the contents of the loaded JSON object. *

* This method should be overridden so that the loaded object can be checked for validity. - * @return - */ - public boolean isValid() { - return true; - } + * + * @return */ + public boolean isValid() + { return true; } } diff --git a/src/com/bwyap/utility/resource/ResourceLoader.java b/src/com/bwyap/utility/resource/ResourceLoader.java index 39a8d28..242cc4a 100644 --- a/src/com/bwyap/utility/resource/ResourceLoader.java +++ b/src/com/bwyap/utility/resource/ResourceLoader.java @@ -19,266 +19,252 @@ import com.bwyap.lwjgl.engine.resource.LWJGLResourceManager; import com.bwyap.utility.StreamLogger; -public class ResourceLoader { - +public class ResourceLoader +{ private static StreamLogger logger = null; - - - /** - * Loads a JSON object from a file on disk. + + /** Loads a JSON object from a file on disk. * If the file is not found on disk, a default version will be copied from the jar. - * @param file File which describes the location of the physical file - * @return - */ - public static JSONObject loadJSON(File file) { + * + * @param file File which describes the location of the physical file + * @return */ + public static JSONObject loadJSON(File file) + { JSONObject jsonObject = null; - - if (!file.exists()) { + if (!file.exists()) + { log("Config file <" + file.getName() + "> not found. Using default config."); copyFileFromJar(file, null); } - JSONParser parser = new JSONParser(); - try { + try + { Object o = parser.parse(new FileReader(file)); jsonObject = (JSONObject) o; } - catch (IOException e) { + catch (IOException e) + { printStackTrace(e); } - catch (ParseException e) { + catch (ParseException e) + { log("An error occurred while trying to parse JSON file <" + file.getName() + ">."); printStackTrace(e); } - return jsonObject; } - - - /** - * Loads a JSON object from an internal file. - * @param path the internal path of the JSON file - * @return - */ - public static JSONObject loadInternalJSON(String path) { + + /** Loads a JSON object from an internal file. + * + * @param path the internal path of the JSON file + * @return */ + public static JSONObject loadInternalJSON(String path) + { JSONObject jsonObject = null; - JSONParser parser = new JSONParser(); - try { + try + { String config = loadInternalTextFileAsString(path); Object o = parser.parse(config); jsonObject = (JSONObject) o; } - catch (ParseException e) { + catch (ParseException e) + { log("An error occurred while trying to parse internal JSON file <" + path + ">."); printStackTrace(e); } - return jsonObject; } - - - /** - * Reads an internal CSV file from within the jar and loads the data into a hash map. - * @param path - * @return - */ - public static HashMap loadInternalCSV(String path) { + + /** Reads an internal CSV file from within the jar and loads the data into a hash map. + * + * @param path + * @return */ + public static HashMap loadInternalCSV(String path) + { log("Loading internal CSV @ " + path); - BufferedReader txtReader = new BufferedReader(new InputStreamReader(ResourceLoader.class.getResourceAsStream(path))); HashMap data = new HashMap(); - - try { - for(String line; (line = txtReader.readLine()) != null; ) { + try + { + for (String line; (line = txtReader.readLine()) != null;) + { String[] args = line.split(","); - - if (args.length > 0) { - if (args[0].substring(0, 1).equals("#")) { + if (args.length > 0) + { + if (args[0].substring(0, 1).equals("#")) + { //Line is a comment so it does not need to be loaded } - else { + else + { data.put(args[0], args); } } - } - } - catch (IOException e) { + } + } + catch (IOException e) + { printStackTrace(e); } - log("CSV file load complete."); return data; } - - - /** - * Loads a shader code file. - * @param file - * @return - */ - public static String loadShaderFile(String path) { + + /** Loads a shader code file. + * + * @param file + * @return */ + public static String loadShaderFile(String path) + { log("Loading shader @ " + path); return loadInternalTextFileAsString(path); } - - /** - * Loads a text file as a string from within the jar file. - * @param file - * @return - */ - public static List loadInternalTextFileAsList(String path) { + /** Loads a text file as a string from within the jar file. + * + * @param file + * @return */ + public static List loadInternalTextFileAsList(String path) + { //log("Loading internal text file @ " + file.getPath()); List lines = new ArrayList(); - try ( - InputStream in = ResourceLoader.class.getClass().getResourceAsStream(path); - BufferedReader br = new BufferedReader(new InputStreamReader(in)); - ) { - - String line = null; - - while (true) { - line = br.readLine(); - if (line != null) lines.add(line); - else break; - } - - } catch (IOException e) { - e.printStackTrace(); + InputStream in = ResourceLoader.class.getClass().getResourceAsStream(path); + BufferedReader br = new BufferedReader(new InputStreamReader(in));) + { + String line = null; + while (true) + { + line = br.readLine(); + if (line != null) + lines.add(line); + else break; } - + } + catch (IOException e) + { + e.printStackTrace(); + } return lines; } - - - /** - * Loads a text file as a string from within the jar file. - * @param file - * @return - */ - public static String loadInternalTextFileAsString(String path) { + + /** Loads a text file as a string from within the jar file. + * + * @param file + * @return */ + public static String loadInternalTextFileAsString(String path) + { //log("Loading internal text file @ " + file.getPath()); String s = ""; - - for (String line : loadInternalTextFileAsList(path)) { - s += line + "\n"; - } - + for (String line : loadInternalTextFileAsList(path)) + { s += line + "\n"; } return s; } - - - /** - * Loads a text file as a string. - * @param file - * @return - */ - public static String loadTextFile(File file) { + + /** Loads a text file as a string. + * + * @param file + * @return */ + public static String loadTextFile(File file) + { //log("Loading text file @ " + file.getPath()); String s = ""; - try ( FileReader fr = new FileReader(file); - BufferedReader br = new BufferedReader(fr); - ) { - + BufferedReader br = new BufferedReader(fr);) + { String line = null; - - while (true) { + while (true) + { line = br.readLine(); - if (line != null) s += line + "\n"; + if (line != null) + s += line + "\n"; else break; } - - } catch (IOException e) { + } + catch (IOException e) + { e.printStackTrace(); } - return s; } - - - /** - * Copy an internal file to an external location. - * If the parameter {@code internalPath} is {@code null} - * the path of {@code file} will be used to search within the the + + /** Copy an internal file to an external location. + * If the parameter {@code internalPath} is {@code null} + * the path of {@code file} will be used to search within the the * {@code IN_RESPATH} folder for the specified file. *

* WARNING: this will overwrite anything that is in {@code file}. - * @param file the external file to copy the internal file to - * @param internalPath the path of the internal file. This can be null. - */ - public static void copyFileFromJar(File file, String internalPath) { + * + * @param file the external file to copy the internal file to + * @param internalPath the path of the internal file. This can be null. */ + public static void copyFileFromJar(File file, String internalPath) + { InputStream in = null; - - try (PrintWriter out = new PrintWriter(file.getPath(), "UTF-8"); - FileOutputStream outStream = new FileOutputStream(file)) { - - if (internalPath == null) { + try (PrintWriter out = new PrintWriter(file.getPath(), "UTF-8"); + FileOutputStream outStream = new FileOutputStream(file)) + { + if (internalPath == null) + { in = ResourceLoader.class.getClass().getResourceAsStream(LWJGLResourceManager.DEFAULT_INTERNAL_PATH + file.getPath()); } - else { + else + { in = ResourceLoader.class.getClass().getResourceAsStream(internalPath); } - log("Copying file <" + file.getName() + ">"); - while (in.available() > 0) { - out.write(in.read()); - } + while (in.available() > 0) + { out.write(in.read()); } log("File <" + file.getName() + "> copy complete."); } - catch (Exception e) { + catch (Exception e) + { log("ERROR occured when writing <" + file.getName() + "> to file."); printStackTrace(e); } } - - /** - * Creates a folder if it is valid - * @param file the File representing the directory - */ - public static void loadFolder(File file) { - if(!file.isDirectory() | !file.exists()) { + /** Creates a folder if it is valid + * + * @param file the File representing the directory */ + public static void loadFolder(File file) + { + if (!file.isDirectory() | !file.exists()) + { log("Directory <" + file.getPath() + "> not found."); file.mkdirs(); log("<" + file.getPath() + "> created."); } } - - /** - * Sets the logger for the resource loader to use - * @param logger - */ - public static void setLogger(StreamLogger logger) { - ResourceLoader.logger = logger; - } - - - /** - * Log a message to the logger if it has been initialised. + /** Sets the logger for the resource loader to use + * + * @param logger */ + public static void setLogger(StreamLogger logger) + { ResourceLoader.logger = logger; } + + /** Log a message to the logger if it has been initialised. * Otherwise, the message is printed to the {@code System.out} stream - * @param message - */ - private static void log(String message) { - if (logger != null) { + * + * @param message */ + private static void log(String message) + { + if (logger != null) + { logger.pushResource(message); } else System.out.println("RES >> " + message); } - - - /** - * A private method for printing stack traces to a logger if it exists. + + /** A private method for printing stack traces to a logger if it exists. * If a custom logger has not been assigned, traces are printed to their default location. - * @param e - */ - private static void printStackTrace(Exception e) { - if (logger != null) e.printStackTrace(logger.getStream()); + * + * @param e */ + private static void printStackTrace(Exception e) + { + if (logger != null) + e.printStackTrace(logger.getStream()); else e.printStackTrace(); } - }