diff --git a/.checkstyle b/.checkstyle index 34ed486..428926e 100644 --- a/.checkstyle +++ b/.checkstyle @@ -1,7 +1,7 @@ - + diff --git a/.classpath b/.classpath index 6f1d0cc..a1b8fa1 100644 --- a/.classpath +++ b/.classpath @@ -5,6 +5,7 @@ + diff --git a/gale.iml b/gale.iml new file mode 100644 index 0000000..0ad39d6 --- /dev/null +++ b/gale.iml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/resources/gale/data/simple3D.frag b/resources/resources/gale/data/simple3D.frag new file mode 100644 index 0000000..4bf4c15 --- /dev/null +++ b/resources/resources/gale/data/simple3D.frag @@ -0,0 +1,16 @@ +#version 400 core + +#ifdef GL_ES +precision mediump float; +precision mediump int; +#endif + +in vec4 io_color; + +// output: +out vec4 out_Color; + +void main(void) { + out_Color = io_color; +} + diff --git a/resources/resources/gale/data/simple3D.vert b/resources/resources/gale/data/simple3D.vert new file mode 100644 index 0000000..985abb4 --- /dev/null +++ b/resources/resources/gale/data/simple3D.vert @@ -0,0 +1,21 @@ +#version 400 core + +#ifdef GL_ES +precision mediump float; +precision mediump int; +#endif + +// Input : +in vec3 in_position; +uniform vec4 in_colors; +uniform mat4 in_matrixTransformation; +uniform mat4 in_matrixProjection; +uniform mat4 in_matrixView; + +// output : +out vec4 io_color; + +void main(void) { + gl_Position = in_matrixProjection * in_matrixView * in_matrixTransformation * vec4(in_position, 1.0); + io_color = vec4(in_colors.xyz, 0.3); +} diff --git a/src/module-info.java b/src/module-info.java index 1c5b4fc..d960b4e 100644 --- a/src/module-info.java +++ b/src/module-info.java @@ -1,37 +1,39 @@ -/** Basic module interface. +/** + * Basic module interface. * - * @author Edouard DUPIN */ + * @author Edouard DUPIN + */ open module org.atriasoft.gale { exports org.atriasoft.gale; exports org.atriasoft.gale.backend3d; exports org.atriasoft.gale.context; - //exports org.atriasoft.gale.context.JOGL; + // exports org.atriasoft.gale.context.JOGL; exports org.atriasoft.gale.context.LWJG_AWT; exports org.atriasoft.gale.key; exports org.atriasoft.gale.resource; - + requires transitive org.atriasoft.etk; - - //requires transitive vecmath; + + // requires transitive vecmath; requires transitive org.lwjgl; requires transitive org.lwjgl.natives; requires transitive org.lwjgl.glfw; requires transitive org.lwjgl.glfw.natives; requires transitive org.lwjgl.assimp; requires transitive org.lwjgl.assimp.natives; - // requires transitive org.lwjgl.openal; - // requires transitive org.lwjgl.openal.natives; + // requires transitive org.lwjgl.openal; + // requires transitive org.lwjgl.openal.natives; requires transitive org.lwjgl.stb; requires transitive org.lwjgl.stb.natives; requires transitive org.lwjgl.jawt; - //requires transitive org.lwjgl.opengl.awt; + // requires transitive org.lwjgl.opengl.awt; requires transitive org.lwjgl.opengl; requires transitive org.lwjgl.opengl.natives; - //requires org.lwjgl.openvr; - - //requires transitive jogamp.fat; - + // requires org.lwjgl.openvr; + + // requires transitive jogamp.fat; + requires transitive java.desktop; requires transitive pngdecoder; requires transitive lwjgl3.awt; diff --git a/src/org/atriasoft/gale/Application.java b/src/org/atriasoft/gale/Application.java index 4b18165..0a4b79c 100644 --- a/src/org/atriasoft/gale/Application.java +++ b/src/org/atriasoft/gale/Application.java @@ -15,278 +15,296 @@ public class Application { public boolean canDraw = false; private boolean needRedraw = true; private String title = "gale"; - private Uri iconName = new Uri(""); - private Cursor cursor = Cursor.arrow; + private Uri iconName = null; + private final Cursor cursor = Cursor.arrow; private Orientation orientation = Orientation.screenAuto; - Vector2f windowsSize = new Vector2f(800,600); + Vector2f windowsSize = new Vector2f(800, 600); public Application() { Log.verbose("Constructor Gale Application"); } + /** - * @brief The application is created. - * @param context Current gale context. - */ - public void onCreate(Context context) { - Log.verbose("Create Gale Application"); - } - /** - * @brief The application is started. - * @param context Current gale context. - */ - public void onStart(Context context){ - Log.verbose("Start Gale Application"); - } - /** - * @brief The application is resumed (now visible). - * @param context Current gale context. - */ - public void onResume(Context context){ - Log.verbose("Start Gale Application"); - } - /** - * @brief call application to precalculate drawing. - * @param context Current gale context. - */ - public void onRegenerateDisplay(Context context) { - //Log.verbose("Regenerate Gale Application"); - markDrawingIsNeeded(); - } - - /** - * @brief Real draw of the application - * @param context Current gale context. - */ - public void onDraw(Context context) { - Log.verbose("draw Gale Application"); - } - /** - * @brief The application is Hide / not visible. - * @param context Current gale context. - */ - public void onPause(Context context) { - Log.verbose("Pause Gale Application"); - } - /** - * @brief The application is stopped. - * @param context Current gale context. - */ - public void onStop(Context context) { - Log.verbose("Stop Gale Application"); - } - /** - * @brief The application is removed (call destructor just adter it.). - * @param context Current gale context. - */ - public void onDestroy(Context context) { - Log.verbose("Destroy Gale Application"); - } - /** - * @brief The user request application removing. - * @param context Current gale context. - */ - public void onKillDemand(Context context) { - Log.info("Gale request auto destroy ==> no applification specification"); - System.exit(0); - } - /** - * @brief Exit the application (not availlable on IOs, ==> the user will not understand the comportement. He will think the application has crashed (Apple philosophie)) + * Exit the application (not availlable on IOs, ==> the user will not understand the comportement. He will think the application has crashed (Apple philosophie)) * @param value value to return on the program */ - public void exit(int value) { + public void exit(final int value) { Log.verbose("Exit Requested " + value); Gale.getContext().stop(); } - - public void markDrawingIsNeeded() { - this.needRedraw = true; - } - public boolean isDrawingNeeded() { - boolean tmp = this.needRedraw; - this.needRedraw = false; - return tmp; - } - /** - * @brief Get touch/mouse/... event. - * @param type Type of pointer event - * @param pointerID Pointer id of the touch event. - * @param pos Position of the event (can be <0 if out of window). - * @param state Key state (up/down/move) - */ - public void onPointer(KeySpecial special, - KeyType type, - int pointerID, - Vector2f pos, - KeyStatus state) { - - } - /** - * @brief Get keyborad value input. - * @param special Current special key status (ctrl/alt/shift ...). - * @param type Type of the event. - * @param value Unicode value of the char pushed (viable only if type==gale::key::keyboard::character). - * @param state State of the key (up/down/upRepeate/downRepeate) - */ - public void onKeyboard(KeySpecial special, - KeyKeyboard type, - Character value, - KeyStatus state) { - - } - /** - * @brief Show the virtal keyboard (if possible : only on iOs/Android) - */ - public void keyboardShow() { - Context context = Gale.getContext(); - if (context == null) { - return; - } - context.keyboardShow(); - } - /** - * @brief Hide the virtal keyboard (if possible : only on iOs/Android) - */ - public void keyboardHide() { - Context context = Gale.getContext(); - if (context == null) { - return; - } - context.keyboardHide(); - } - /** - * @brief Event generated when user change the size of the window. - * @param size New size of the window. - */ - public void onResize(Vector2f size) { - if (size == null) { - Log.error("Try to set a null size ..."); - return; - } - windowsSize = size; - } - /** - * @brief Set the size of the window (if possible: Android and Ios does not support it) - * @param size New size of the window. - * @return - */ - public void setSize(Vector2f size) { - windowsSize = size; - Context context = Gale.getContext(); - if (context == null) { - return; - } - context.setSize(size); - } - /** - * @brief Get the size of the window. - * @return Current size of the window. - */ - public Vector2f getSize() { - return windowsSize; - } public float getAspectRatio() { - return windowsSize.x/windowsSize.y; + return this.windowsSize.x() / this.windowsSize.y(); } - + /** - * @brief Event generated when user change the position of the window. - * @param size New position of the window. - */ - public void onMovePosition(Vector2f size) { - - } - /** - * @brief Set the position of the window (if possible: Android and Ios does not support it) - * @param size New position of the window. - */ - public void setPosition(Vector2f size) { - - } - /** - * @brief Get the position of the window. - * @return Current position of the window. - */ - public Vector2f getPosition() { - return new Vector2f(0,0); - } - - /** - * @brief Set the title of the application - * @param title New title to set at the application (if possible: Android and Ios does not support it) - */ - public void setTitle(String title) { - this.title = title; - Context context = Gale.getContext(); - if (context == null) { - return; - } - context.setTitle(this.title); - } - /** - * @brief Get the current title of the application - * @return Current title - */ - public String getTitle() { - return this.title; - } - /** - * @brief set the Icon of the application. - * @param iconFile File name icon (.bmp/.png). - */ - public void setIcon(Uri iconFile) { - this.iconName = iconFile; - Gale.getContext().setIcon(this.iconName); - } - /** - * @brief Get the current filename of the application. - * @return Filename of the icon. - */ - public Uri getIcon() { - return this.iconName; - } - - /** - * @brief Set the cursor type. - * @param newCursor Selected cursor. - */ - public void setCursor(Cursor newCursor) { - Gale.getContext().setCursor(this.cursor); - } - /** - * @brief Get the cursor type. + * Get the cursor type. * @return the current cursor. */ public Cursor getCursor() { return this.cursor; } + /** - * @brief set the screen orientation (if possible : only on iOs/Android) - * @param orientation New orientation. + * Get the current filename of the application. + * @return Filename of the icon. */ - public void setOrientation(Orientation orientation) { - this.orientation = orientation; - Gale.getContext().forceOrientation(this.orientation); + public Uri getIcon() { + return this.iconName; } + /** - * @brief get the screen orientation (if possible : only on iOs/Android) + * get the screen orientation (if possible : only on iOs/Android) * @return Current orientation. */ public Orientation getOrientation() { return this.orientation; } - + /** - * @brief A clipboard data is back (apear after a request of a new clipboard). + * Get the position of the window. + * @return Current position of the window. + */ + public Vector2f getPosition() { + return new Vector2f(0, 0); + } + + /** + * Get the size of the window. + * @return Current size of the window. + */ + public Vector2f getSize() { + return this.windowsSize; + } + + /** + * Get the current title of the application + * @return Current title + */ + public String getTitle() { + return this.title; + } + + public boolean isDrawingNeeded() { + final boolean tmp = this.needRedraw; + this.needRedraw = false; + return tmp; + } + + /** + * Hide the virtal keyboard (if possible : only on iOs/Android) + */ + public void keyboardHide() { + final Context context = Gale.getContext(); + if (context == null) { + return; + } + context.keyboardHide(); + } + + /** + * Show the virtal keyboard (if possible : only on iOs/Android) + */ + public void keyboardShow() { + final Context context = Gale.getContext(); + if (context == null) { + return; + } + context.keyboardShow(); + } + + public void markDrawingIsNeeded() { + this.needRedraw = true; + } + + /** + * A clipboard data is back (apear after a request of a new clipboard). * @param clipboardId Id of the clipboard. */ - public void onClipboardEvent(ClipboardList clipboardId) { + public void onClipboardEvent(final ClipboardList clipboardId) { } - + /** - * @brief Call every time a draw is called (not entirely periodic, but faster at we can ... + * The application is created. + * @param context Current gale context. + */ + public void onCreate(final Context context) { + Log.verbose("Create Gale Application"); + } + + /** + * The application is removed (call destructor just adter it.). + * @param context Current gale context. + */ + public void onDestroy(final Context context) { + Log.verbose("Destroy Gale Application"); + } + + /** + * Real draw of the application + * @param context Current gale context. + */ + public void onDraw(final Context context) { + Log.verbose("draw Gale Application"); + } + + /** + * Get keyborad value input. + * @param special Current special key status (ctrl/alt/shift ...). + * @param type Type of the event. + * @param value Unicode value of the char pushed (viable only if type==gale::key::keyboard::character). + * @param state State of the key (up/down/upRepeate/downRepeate) + */ + public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) { + + } + + /** + * The user request application removing. + * @param context Current gale context. + */ + public void onKillDemand(final Context context) { + Log.info("Gale request auto destroy ==> no applification specification"); + System.exit(0); + } + + /** + * Event generated when user change the position of the window. + * @param size New position of the window. + */ + public void onMovePosition(final Vector2f size) { + + } + + /** + * The application is Hide / not visible. + * @param context Current gale context. + */ + public void onPause(final Context context) { + Log.verbose("Pause Gale Application"); + } + + /** + * Call every time a draw is called (not entirely periodic, but faster at we can ... * @param time Current time of the call; */ - public void onPeriod(long time) {}; + public void onPeriod(final long time) {} + + /** + * Get touch/mouse/... event. + * @param type Type of pointer event + * @param pointerID Pointer id of the touch event. + * @param pos Position of the event (can be <0 if out of window). + * @param state Key state (up/down/move) + */ + public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) { + + } + + /** + * call application to precalculate drawing. + * @param context Current gale context. + */ + public void onRegenerateDisplay(final Context context) { + //Log.verbose("Regenerate Gale Application"); + markDrawingIsNeeded(); + } + + /** + * Event generated when user change the size of the window. + * @param size New size of the window. + */ + public void onResize(final Vector2f size) { + if (size == null) { + Log.error("Try to set a null size ..."); + return; + } + this.windowsSize = size; + } + + /** + * The application is resumed (now visible). + * @param context Current gale context. + */ + public void onResume(final Context context) { + Log.verbose("Start Gale Application"); + } + + /** + * The application is started. + * @param context Current gale context. + */ + public void onStart(final Context context) { + Log.verbose("Start Gale Application"); + } + + /** + * The application is stopped. + * @param context Current gale context. + */ + public void onStop(final Context context) { + Log.verbose("Stop Gale Application"); + } + + /** + * Set the cursor type. + * @param newCursor Selected cursor. + */ + public void setCursor(final Cursor newCursor) { + Gale.getContext().setCursor(this.cursor); + } + + /** + * set the Icon of the application. + * @param iconFile File name icon (.bmp/.png). + */ + public void setIcon(final Uri iconFile) { + this.iconName = iconFile; + Gale.getContext().setIcon(this.iconName); + } + + /** + * set the screen orientation (if possible : only on iOs/Android) + * @param orientation New orientation. + */ + public void setOrientation(final Orientation orientation) { + this.orientation = orientation; + Gale.getContext().forceOrientation(this.orientation); + } + + /** + * Set the position of the window (if possible: Android and Ios does not support it) + * @param size New position of the window. + */ + public void setPosition(final Vector2f size) { + + } + + /** + * Set the size of the window (if possible: Android and Ios does not support it) + * @param size New size of the window. + * @return + */ + public void setSize(final Vector2f size) { + this.windowsSize = size; + final Context context = Gale.getContext(); + if (context == null) { + return; + } + context.setSize(size); + } + + /** + * Set the title of the application + * @param title New title to set at the application (if possible: Android and Ios does not support it) + */ + public void setTitle(final String title) { + this.title = title; + final Context context = Gale.getContext(); + if (context == null) { + return; + } + context.setTitle(this.title); + }; } diff --git a/src/org/atriasoft/gale/Dimension.java b/src/org/atriasoft/gale/Dimension.java index 24bade2..43123b2 100644 --- a/src/org/atriasoft/gale/Dimension.java +++ b/src/org/atriasoft/gale/Dimension.java @@ -6,340 +6,275 @@ package org.atriasoft.gale; import org.atriasoft.etk.math.Vector2f; +import org.atriasoft.etk.math.Vector2i; import org.atriasoft.gale.internal.Log; /** - * @brief in the dimention class we store the data as the more usefull unit (pixel) + * in the dimension class we store the data as the more usefull unit (pixel) * but one case need to be dynamic the %, then when requested in % the register the % value */ -public class Dimension { - private final static Vector2f ratio = new Vector2f(9999999, 888888); - private final static Vector2f invRatio = new Vector2f(1, 1); - private final static Dimension windowsSize = new Dimension(new Vector2f(9999999, 888888), Distance.PIXEL); +@SuppressWarnings("preview") +public record Dimension( + Vector2f size, + Distance type) { + public static final Dimension ZERO = new Dimension(Vector2f.ZERO, Distance.PIXEL); + private static Vector2f ratio = new Vector2f(9999999, 888888); + private static Vector2f invRatio = new Vector2f(1, 1); + private static Dimension windowsSize = new Dimension(Vector2f.MAX_VALUE, Distance.PIXEL); - public final static float INCH_TO_MILLIMETER = 1.0f / 25.4f; - public final static float FOOT_TO_MILLIMETER = 1.0f / 304.8f; - public final static float METER_TO_MILLIMETER = 1.0f / 1000.0f; - public final static float CENTIMETER_TO_MILLIMETER = 1.0f / 10.0f; - public final static float KILOMETER_TO_MILLIMETER = 1.0f / 1000000.0f; - public final static float MILLIMETER_TO_INCH = 25.4f; - public final static float MILLIMETER_TO_FOOT = 304.8f; - public final static float MILLIMETER_TO_METER = 1000.0f; - public final static float MILLIMETER_TO_CENTIMETER = 10.0f; - public final static float MILLIMETER_TO_KILOMETER = 1000000.0f; + public static final float INCH_TO_MILLIMETER = 1.0f / 25.4f; + public static final float FOOT_TO_MILLIMETER = 1.0f / 304.8f; + public static final float METER_TO_MILLIMETER = 1.0f / 1000.0f; + public static final float CENTIMETER_TO_MILLIMETER = 1.0f / 10.0f; + public static final float KILOMETER_TO_MILLIMETER = 1.0f / 1000000.0f; + public static final float MILLIMETER_TO_INCH = 25.4f; + public static final float MILLIMETER_TO_FOOT = 304.8f; + public static final float MILLIMETER_TO_METER = 1000.0f; + public static final float MILLIMETER_TO_CENTIMETER = 10.0f; + public static final float MILLIMETER_TO_KILOMETER = 1000000.0f; /** - * @brief basic init + * basic init */ static { final Dimension conversion = new Dimension(new Vector2f(72, 72), Distance.INCH); - ratio.set(conversion.getMillimeter()); - invRatio.setValue(1.0f / ratio.x, 1.0f / ratio.y); - windowsSize.set(new Vector2f(200, 200), Distance.PIXEL); + ratio = conversion.getMillimeter(); + invRatio = new Vector2f(1.0f / ratio.x(), 1.0f / ratio.y()); + windowsSize = new Dimension(new Vector2f(200, 200), Distance.PIXEL); } /** - * @brief get the Windows diagonal size in the request unit - * @param[in] type Unit type requested. + * get the Windows diagonal size in the request unit + * @param type Unit type requested. * @return the requested size */ - public static float getWindowsDiag(final Distance _type) { - final Vector2f size = getWindowsSize(_type); + public static float getWindowsDiag(final Distance type) { + final Vector2f size = getWindowsSize(type); return size.length(); } /** - * @brief get the Windows size in the request unit - * @param[in] type Unit type requested. + * get the Windows size in the request unit + * @param type Unit type requested. * @return the requested size */ - public static Vector2f getWindowsSize(final Distance _type) { - return windowsSize.get(_type); + public static Vector2f getWindowsSize(final Distance type) { + return windowsSize.get(type); } /** - * @brief set the Milimeter ratio for calculation - * @param[in] Ratio Milimeter ration for the screen calculation interpolation - * @param[in] type Unit type requested. + * set the Milimeter ratio for calculation + * @param ratio Milimeter ration for the screen calculation interpolation + * @param type Unit type requested. * @note: same as @ref setPixelPerInch (internal manage convertion) */ - public static void setPixelRatio(final Vector2f _ratio, final Distance _type) { - Log.info("Set a new screen ratio for the screen : ratio=" + _ratio + " type=" + _type); - final Dimension conversion = new Dimension(_ratio, _type); + public static void setPixelRatio(final Vector2f ratio, final Distance type) { + Log.info("Set a new screen ratio for the screen : ratio=" + ratio + " type=" + type); + final Dimension conversion = new Dimension(ratio, type); Log.info(" == > " + conversion); - ratio.set(conversion.getMillimeter()); - invRatio.setValue(1.0f / ratio.x, 1.0f / ratio.y); - Log.info("Set a new screen ratio for the screen : ratioMm=" + ratio); + Dimension.ratio = conversion.getMillimeter(); + invRatio = new Vector2f(1.0f / Dimension.ratio.x(), 1.0f / Dimension.ratio.y()); + Log.info("Set a new screen ratio for the screen : ratioMm=" + Dimension.ratio); } /** - * @brief set the current Windows size - * @param[in] size size of the current windows in pixel. + * set the current Windows size + * @param size size of the current windows in pixel. */ - public static void setPixelWindowsSize(final Vector2f _size) { - windowsSize.set(_size); + public static void setPixelWindowsSize(final Vector2f size) { + windowsSize = new Dimension(size); Log.verbose("Set a new Windows property size " + windowsSize + "px"); } - private Vector2f size = new Vector2f(0, 0); - private Distance type = Distance.PIXEL; - /** - * @brief Constructor (default :0,0 mode pixel) + * Constructor (default :0,0 mode pixel) */ public Dimension() { - + this(Vector2f.ZERO, Distance.PIXEL); } /** - * @brief Constructor - * @param[in] _config dimension configuration. + * Constructor + * @param size Requested dimension */ - public Dimension(final String _config) { - set(_config); + public Dimension(final Vector2f size) { + this(size, Distance.PIXEL); + } + + public Dimension(final Vector2f size, final Distance type) { + this.size = size; + this.type = type; } /** - * @brief Constructor - * @param[in] _size Requested dimension - * @param[in] _type Unit of the Dimension + * get the current dimension in requested type + * @param type Type of unit requested. + * @return dimension requested. */ - public Dimension(final Vector2f _size) { - set(_size, Distance.PIXEL); - } - - public Dimension(final Vector2f _size, final Distance _type) { - set(_size, _type); - } - - /***************************************************** - * isEqual - *****************************************************/ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof Dimension)) { - return false; - } - final Dimension other = (Dimension) obj; - return this.size.equals(other.size) && this.type == other.type; + public Vector2f get(final Distance type) { + return switch (type) { + case POURCENT -> getPourcent(); + case PIXEL -> getPixel(); + case METER -> getMeter(); + case CENTIMETER -> getCentimeter(); + case MILLIMETER -> getMillimeter(); + case KILOMETER -> getKilometer(); + case INCH -> getInch(); + case FOOT -> getFoot(); + }; } /** - * @brief get the current dimention in requested type - * @param[in] _type Type of unit requested. - * @return dimention requested. - */ - public Vector2f get(final Distance _type) { - switch (_type) { - case POURCENT: - return getPourcent(); - case PIXEL: - return getPixel(); - case METER: - return getMeter(); - case CENTIMETER: - return getCentimeter(); - case MILLIMETER: - return getMillimeter(); - case KILOMETER: - return getKilometer(); - case INCH: - return getInch(); - case FOOT: - return getFoot(); - } - return new Vector2f(0, 0); - } - - /** - * @brief get the current dimention in Centimeter - * @return dimention in Centimeter + * get the current dimension in Centimeter + * @return dimension in Centimeter */ public Vector2f getCentimeter() { - return getMillimeter().multiplyNew(MILLIMETER_TO_CENTIMETER); + return getMillimeter().multiply(MILLIMETER_TO_CENTIMETER); } /** - * @brief get the current dimention in Foot - * @return dimention in Foot + * get the current dimension in Foot + * @return dimension in Foot */ public Vector2f getFoot() { - return getMillimeter().multiplyNew(MILLIMETER_TO_FOOT); + return getMillimeter().multiply(MILLIMETER_TO_FOOT); } /** - * @brief get the current dimention in Inch - * @return dimention in Inch + * get the current dimension in Inch + * @return dimension in Inch */ public Vector2f getInch() { - return getMillimeter().multiplyNew(MILLIMETER_TO_INCH); + return getMillimeter().multiply(MILLIMETER_TO_INCH); } /** - * @brief get the current dimention in Kilometer - * @return dimention in Kilometer + * get the current dimension in Kilometer + * @return dimension in Kilometer */ public Vector2f getKilometer() { - return getMillimeter().multiplyNew(MILLIMETER_TO_KILOMETER); + return getMillimeter().multiply(MILLIMETER_TO_KILOMETER); } /** - * @brief get the current dimention in Meter - * @return dimention in Meter + * get the current dimension in Meter + * @return dimension in Meter */ public Vector2f getMeter() { - return getMillimeter().multiplyNew(MILLIMETER_TO_METER); + return getMillimeter().multiply(MILLIMETER_TO_METER); } /** - * @brief get the current dimention in Millimeter - * @return dimention in Millimeter + * get the current dimension in Millimeter + * @return dimension in Millimeter */ public Vector2f getMillimeter() { - return new Vector2f(getPixel().x * invRatio.x, getPixel().y * invRatio.y); + return new Vector2f(getPixel().x() * invRatio.x(), getPixel().y() * invRatio.y()); } /** - * @brief get the current dimention in pixel - * @return dimention in Pixel + * get the current dimension in pixel + * @return dimension in Pixel */ public Vector2f getPixel() { if (this.type != Distance.POURCENT) { return this.size; - } else { - final Vector2f windDim = windowsSize.getPixel(); - final Vector2f res = new Vector2f(windDim.x * this.size.x, windDim.y * this.size.y); - //GALE_DEBUG("Get % : " + m_data + " / " + windDim + " == > " + res); - return res; } + final Vector2f windDim = windowsSize.getPixel(); + final Vector2f res = new Vector2f(windDim.x() * this.size.x(), windDim.y() * this.size.y()); + //GALE_DEBUG("Get % : " + m_data + " / " + windDim + " == > " + res); + return res; + } + + public Vector2i getPixeli() { + if (this.type != Distance.POURCENT) { + return new Vector2i((int) this.size.x(), (int) this.size.y()); + } + final Vector2f windDim = windowsSize.getPixel(); + final Vector2i res = new Vector2i((int) (windDim.x() * this.size.x()), (int) (windDim.y() * this.size.y())); + //GALE_DEBUG("Get % : " + m_data + " / " + windDim + " == > " + res); + return res; } /** - * @brief get the current dimention in Pourcent - * @return dimention in Pourcent + * get the current dimension in Pourcent + * @return dimension in Pourcent */ public Vector2f getPourcent() { if (this.type != Distance.POURCENT) { final Vector2f windDim = windowsSize.getPixel(); - //GALE_DEBUG(" windows dimention : " /*+ windowsSize*/ + " == > " + windDim + "px"); // ==> infinite loop ... - //printf(" windows dimention : %f,%f", windDim.x(),windDim.y()); + //GALE_DEBUG(" windows dimension : " /*+ windowsSize*/ + " == > " + windDim + "px"); // ==> infinite loop ... + //printf(" windows dimension : %f,%f", windDim.x(),windDim.y()); //printf(" data : %f,%f", m_data.x(),m_data.y()); - return new Vector2f((this.size.x / windDim.x) * 100.0f, (this.size.y / windDim.y) * 100.0f); + return new Vector2f((this.size.x() / windDim.x()) * 100.0f, (this.size.y() / windDim.y()) * 100.0f); } - return new Vector2f(this.size.x * 100.0f, this.size.y * 100.0f); + return new Vector2f(this.size.x() * 100.0f, this.size.y() * 100.0f); }; /** - * @breif get the dimension type + * get the dimension type * @return the type */ public Distance getType() { return this.type; } - /***************************************************** - * assigment - *****************************************************/ - public Dimension set(final Dimension _obj) { - if (this != _obj) { - this.size = _obj.size; - this.type = _obj.type; - } - return this; - } - /** - * @brief set the current dimention in requested type - * @param[in] _config dimension configuration. + * set the current dimension in requested type + * @param config dimension configuration. */ - private void set(String _config) { - this.size.setValue(0, 0); - this.type = Distance.PIXEL; + public static Dimension valueOf(String config) { + final Vector2f size = Vector2f.ZERO; Distance type = Distance.PIXEL; - if (_config.endsWith("%") == true) { + if (config.endsWith("%")) { type = Distance.POURCENT; - _config = _config.substring(0, _config.length() - 1); - } else if (_config.endsWith("px") == true) { + config = config.substring(0, config.length() - 1); + } else if (config.endsWith("px")) { type = Distance.PIXEL; - _config = _config.substring(0, _config.length() - 2); - } else if (_config.endsWith("ft") == true) { + config = config.substring(0, config.length() - 2); + } else if (config.endsWith("ft")) { type = Distance.FOOT; - _config = _config.substring(0, _config.length() - 2); - } else if (_config.endsWith("in") == true) { + config = config.substring(0, config.length() - 2); + } else if (config.endsWith("in")) { type = Distance.INCH; - _config = _config.substring(0, _config.length() - 2); - } else if (_config.endsWith("km") == true) { + config = config.substring(0, config.length() - 2); + } else if (config.endsWith("km")) { type = Distance.KILOMETER; - _config = _config.substring(0, _config.length() - 2); - } else if (_config.endsWith("mm") == true) { + config = config.substring(0, config.length() - 2); + } else if (config.endsWith("mm")) { type = Distance.MILLIMETER; - _config = _config.substring(0, _config.length() - 2); - } else if (_config.endsWith("cm") == true) { + config = config.substring(0, config.length() - 2); + } else if (config.endsWith("cm")) { type = Distance.CENTIMETER; - _config = _config.substring(0, _config.length() - 2); - } else if (_config.endsWith("m") == true) { + config = config.substring(0, config.length() - 2); + } else if (config.endsWith("m")) { type = Distance.METER; - _config = _config.substring(0, _config.length() - 1); + config = config.substring(0, config.length() - 1); } else { - Log.critical("Can not parse dimention : '" + _config + "'"); - return; + Log.critical("Can not parse dimension : '" + config + "'"); + return null; } - final Vector2f tmp = Vector2f.valueOf(_config); - set(tmp, type); - Log.verbose(" config dimention : \"" + _config + "\" == > " + this); - } - - public void set(final Vector2f _size) { - this.size = _size; - this.type = Distance.PIXEL; + final Vector2f tmp = Vector2f.valueOf(config); + final Dimension ret = new Dimension(tmp, type); + Log.verbose(" config dimension : '" + config + "' == > " + ret.toString()); + return ret; } /** - * @brief set the current dimention in requested type - * @param[in] _size Dimention to set - * @param[in] _type Type of unit requested. - */ - public void set(final Vector2f _size, final Distance _type) { - this.size = _size; - this.type = _type; - } - - /** - * @brief string cast : + * string cast : */ @Override public String toString() { String str = get(getType()).toString(); switch (getType()) { - case POURCENT: - str += "%"; - break; - case PIXEL: - str += "px"; - break; - case METER: - str += "m"; - break; - case CENTIMETER: - str += "cm"; - break; - case MILLIMETER: - str += "mm"; - break; - case KILOMETER: - str += "km"; - break; - case INCH: - str += "in"; - break; - case FOOT: - str += "ft"; - break; + case POURCENT -> str += "%"; + case PIXEL -> str += "px"; + case METER -> str += "m"; + case CENTIMETER -> str += "cm"; + case MILLIMETER -> str += "mm"; + case KILOMETER -> str += "km"; + case INCH -> str += "in"; + case FOOT -> str += "ft"; + default -> str += ""; } return str; } diff --git a/src/org/atriasoft/gale/Gale.java b/src/org/atriasoft/gale/Gale.java index f1f8ca6..67be412 100644 --- a/src/org/atriasoft/gale/Gale.java +++ b/src/org/atriasoft/gale/Gale.java @@ -1,5 +1,6 @@ package org.atriasoft.gale; +import org.atriasoft.etk.Uri; import org.atriasoft.gale.context.Context; //import org.atriasoft.gale.context.JOGL.ContextJOGL; import org.atriasoft.gale.context.LWJG_AWT.ContextLWJGLAWT; @@ -7,9 +8,25 @@ import org.atriasoft.gale.context.LWJG_AWT.ContextLWJGLAWT; import org.atriasoft.gale.internal.Log; public class Gale { - private Gale() {} + public static Context getContext() { + // TODO Auto-generated method stub + return Context.getContext(); + } + /** - * @brief This is the only one things the User might done in his main(); + * get GALE version + * @return The string that describe gale version + */ + public static String getVersion() { + return "J-0.5"; + } + + public static void init() { + Uri.addLibrary("gale", Gale.class, "/resources/gale/"); + } + + /** + * This is the only one things the User might done in his main(); * @note To answare you before you ask the question, this is really simple: * Due to the fect that the current system is multiple-platform, you "main" * Does not exist in the android platform, then gale call other start @@ -20,7 +37,8 @@ public class Gale { * @param _argv Standard argv * @return normal error int for the application error management */ - public static int run(Application application, String[] arg) { + public static int run(final Application application, final String[] arg) { + init(); //etk::init(_argc, _argv); Context context = null; String request = ""; @@ -34,17 +52,6 @@ public class Gale { } return context.run(); } - - /** - * @brief get GALE version - * @return The string that describe gale version - */ - public static String getVersion() { - return "J-0.5"; - } - - public static Context getContext() { - // TODO Auto-generated method stub - return Context.getContext(); - } + + private Gale() {} } diff --git a/src/org/atriasoft/gale/backend3d/OpenGL.java b/src/org/atriasoft/gale/backend3d/OpenGL.java index cfcce02..a6be4d8 100644 --- a/src/org/atriasoft/gale/backend3d/OpenGL.java +++ b/src/org/atriasoft/gale/backend3d/OpenGL.java @@ -3,15 +3,21 @@ package org.atriasoft.gale.backend3d; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.atriasoft.etk.Color; +import org.atriasoft.etk.Uri; import org.atriasoft.etk.math.Matrix4f; import org.atriasoft.etk.math.Vector2f; import org.atriasoft.etk.math.Vector2i; @@ -28,64 +34,112 @@ import org.lwjgl.opengl.GL40; public class OpenGL { public static enum ClearFlag { - clearFlag_colorBuffer, //!< Indicates the buffers currently enabled for color writing. - clearFlag_depthBuffer, //!< Indicates the depth buffer. - clearFlag_stencilBuffer //!< Indicates the stencil buffer. + clearFlag_colorBuffer, // !< Indicates the buffers currently enabled for color writing. + clearFlag_depthBuffer, // !< Indicates the depth buffer. + clearFlag_stencilBuffer // !< Indicates the stencil buffer. } // We map all the flag, but not all is supported by all platform... public static enum Flag { - flag_blend, //!< If enabled, blend the computed fragment color values with the values in the color buffers. - //See glBlendFunc. - flag_clipDistanceI, //!< If enabled, clip geometry against user-defined half space i. - flag_colorLogigOP, //!< If enabled, apply the currently selected logical operation to the computed fragment color and color buffer values. See glLogicOp. - flag_cullFace, //!< If enabled, cull polygons based on their winding in window coordinates. See glCullFace. - flag_debugOutput, //!< If enabled, debug messages are produced by a debug context. When disabled, the debug message log is silenced. Note that in a non-debug context, very few, if any messages might be produced, even when GLDEBUGOUTPUT is enabled. - flag_debugOutputSynchronous, //!< If enabled, debug messages are produced synchronously by a debug context. If disabled, debug messages may be produced asynchronously. In particular, they may be delayed relative to the execution of GL commands, and the debug callback function may be called from a thread other than that in which the commands are executed. See glDebugMessageCallback. - flag_depthClamp, //!< If enabled, the -wcdzcdwc plane equation is ignored by view volume clipping (effectively, there is no near or far plane clipping). See glDepthRange. - flag_depthTest, //!< If enabled, do depth comparisons and update the depth buffer. Note that even if the depth buffer exists and the depth mask is non-zero, the depth buffer is not updated if the depth test is disabled. See glDepthFunc and glDepthRange. - flag_dither, //!< If enabled, dither color components or indices before they are written to the color buffer. - flag_framebufferSRGB, //!< If enabled and the value of GLFRAMEBUFFERATTACHMENTCOLORENCODING for the framebuffer attachment corresponding to the destination buffer is GLSRGB, the R, G, and B destination color values (after conversion from fixed-point to floating-point) are considered to be encoded for the sRGB color space and hence are linearized prior to their use in blending. - flag_lineSmooth, //!< If enabled, draw lines with correct filtering. Otherwise, draw aliased lines. See glLineWidth. - flag_multisample, //!< If enabled, use multiple fragment samples in computing the final color of a pixel. See glSampleCoverage. - flag_polygonOffsetFill, //!< If enabled, and if the polygon is rendered in GLFILL mode, an offset is added to depth values of a polygon's fragments before the depth comparison is performed. See glPolygonOffset. - flag_polygonOffsetLine, //!< If enabled, and if the polygon is rendered in GLLINE mode, an offset is added to depth values of a polygon's fragments before the depth comparison is performed. See glPolygonOffset. - flag_polygonOffsetPoint, //!< If enabled, an offset is added to depth values of a polygon's fragments before the depth comparison is performed, if the polygon is rendered in GLPOINT mode. See glPolygonOffset. - flag_polygonSmooth, //!< If enabled, draw polygons with proper filtering. Otherwise, draw aliased polygons. For correct antialiased polygons, an alpha buffer is needed and the polygons must be sorted front to back. - flag_primitiveRestart, //!< enables primitive restarting. If enabled, any one of the draw commands which transfers a set of generic attribute array elements to the GL will restart the primitive when the index of the vertex is equal to the primitive restart index. See glPrimitiveRestartIndex. - flag_primitiveRestartFixedIndex, //!< enables primitive restarting with a fixed index. If enabled, any one of the draw commands which transfers a set of generic attribute array elements to the GL will restart the primitive when the index of the vertex is equal to the fixed primitive index for the specified index type. The fixed index is equal to 2n1 where n is equal to 8 for GLUNSIGNEDBYTE, 16 for GLUNSIGNEDSHORT and 32 for GLUNSIGNEDINT. - flag_sampleAlphaToCoverage, //!< If enabled, compute a temporary coverage value where each bit is determined by the alpha value at the corresponding sample location. The temporary coverage value is then ANDed with the fragment coverage value. - flag_sampleAlphaToOne, //!< If enabled, each sample alpha value is replaced by the maximum representable alpha value. - flag_sampleCoverage, //!< If enabled, the fragment's coverage is ANDed with the temporary coverage value. If GLSAMPLECOVERAGEINVERT is set to GLTRUE, invert the coverage value. See glSampleCoverage. - flag_sampleShading, //!< If enabled, the active fragment shader is run once for each covered sample, or at fraction of this rate as determined by the current value of GLMINSAMPLESHADINGVALUE. See glMinSampleShading. - flag_sampleMask, //!< If enabled, the sample coverage mask generated for a fragment during rasterization will be ANDed with the value of GLSAMPLEMASKVALUE before shading occurs. See glSampleMaski. - flag_scissorTest, //!< If enabled, discard fragments that are outside the scissor rectangle. See glScissor. - flag_stencilTest, //!< If enabled, do stencil testing and update the stencil buffer. See glStencilFunc and glStencilOp. GLTEXTURECUBEMAPSEAMLESS = 1+0, //!< If enabled, cubemap textures are sampled such that when linearly sampling from the border between two adjacent faces, texels from both faces are used to generate the final sample value. When disabled, texels from only a single face are used to ruct the final sample value. - flag_programPointSize, //!< If enabled and a vertex or geometry shader is active, then the derived point size is taken from the (potentially clipped) shader builtin gthis.PointSize and clamped to the implementation-dependent point size range. - flag_texture2D, //!< - flag_alphaTest, //!< - flag_fog, - flag_back + flag_blend, // !< If enabled, blend the computed fragment color values with the values in + // the color buffers. + // See glBlendFunc. + flag_clipDistanceI, // !< If enabled, clip geometry against user-defined half space i. + flag_colorLogigOP, // !< If enabled, apply the currently selected logical operation to the computed + // fragment color and color buffer values. See glLogicOp. + flag_cullFace, // !< If enabled, cull polygons based on their winding in window coordinates. + // See glCullFace. + flag_debugOutput, // !< If enabled, debug messages are produced by a debug context. When disabled, + // the debug message log is silenced. Note that in a non-debug context, very + // few, if any messages might be produced, even when GLDEBUGOUTPUT is enabled. + flag_debugOutputSynchronous, // !< If enabled, debug messages are produced synchronously by a debug context. + // If disabled, debug messages may be produced asynchronously. In particular, + // they may be delayed relative to the execution of GL commands, and the debug + // callback function may be called from a thread other than that in which the + // commands are executed. See glDebugMessageCallback. + flag_depthClamp, // !< If enabled, the -wcdzcdwc plane equation is ignored by view volume + // clipping (effectively, there is no near or far plane clipping). See + // glDepthRange. + flag_depthTest, // !< If enabled, do depth comparisons and update the depth buffer. Note that + // even if the depth buffer exists and the depth mask is non-zero, the depth + // buffer is not updated if the depth test is disabled. See glDepthFunc and + // glDepthRange. + flag_dither, // !< If enabled, dither color components or indices before they are written to + // the color buffer. + flag_framebufferSRGB, // !< If enabled and the value of GLFRAMEBUFFERATTACHMENTCOLORENCODING for the + // framebuffer attachment corresponding to the destination buffer is GLSRGB, the + // R, G, and B destination color values (after conversion from fixed-point to + // floating-point) are considered to be encoded for the sRGB color space and + // hence are linearized prior to their use in blending. + flag_lineSmooth, // !< If enabled, draw lines with correct filtering. Otherwise, draw aliased + // lines. See glLineWidth. + flag_multisample, // !< If enabled, use multiple fragment samples in computing the final color of + // a pixel. See glSampleCoverage. + flag_polygonOffsetFill, // !< If enabled, and if the polygon is rendered in GLFILL mode, an offset is + // added to depth values of a polygon's fragments before the depth comparison is + // performed. See glPolygonOffset. + flag_polygonOffsetLine, // !< If enabled, and if the polygon is rendered in GLLINE mode, an offset is + // added to depth values of a polygon's fragments before the depth comparison is + // performed. See glPolygonOffset. + flag_polygonOffsetPoint, // !< If enabled, an offset is added to depth values of a polygon's fragments + // before the depth comparison is performed, if the polygon is rendered in + // GLPOINT mode. See glPolygonOffset. + flag_polygonSmooth, // !< If enabled, draw polygons with proper filtering. Otherwise, draw aliased + // polygons. For correct antialiased polygons, an alpha buffer is needed and the + // polygons must be sorted front to back. + flag_primitiveRestart, // !< enables primitive restarting. If enabled, any one of the draw commands + // which transfers a set of generic attribute array elements to the GL will + // restart the primitive when the index of the vertex is equal to the primitive + // restart index. See glPrimitiveRestartIndex. + flag_primitiveRestartFixedIndex, // !< enables primitive restarting with a fixed index. If enabled, any one of + // the draw commands which transfers a set of generic attribute array + // elements to the GL will restart the primitive when the index of the + // vertex is equal to the fixed primitive index for the specified index + // type. The fixed index is equal to 2n1 where n is equal to 8 for + // GLUNSIGNEDBYTE, 16 for GLUNSIGNEDSHORT and 32 for GLUNSIGNEDINT. + flag_sampleAlphaToCoverage, // !< If enabled, compute a temporary coverage value where each bit is + // determined by the alpha value at the corresponding sample location. The + // temporary coverage value is then ANDed with the fragment coverage value. + flag_sampleAlphaToOne, // !< If enabled, each sample alpha value is replaced by the maximum + // representable alpha value. + flag_sampleCoverage, // !< If enabled, the fragment's coverage is ANDed with the temporary coverage + // value. If GLSAMPLECOVERAGEINVERT is set to GLTRUE, invert the coverage value. + // See glSampleCoverage. + flag_sampleShading, // !< If enabled, the active fragment shader is run once for each covered + // sample, or at fraction of this rate as determined by the current value of + // GLMINSAMPLESHADINGVALUE. See glMinSampleShading. + flag_sampleMask, // !< If enabled, the sample coverage mask generated for a fragment during + // rasterization will be ANDed with the value of GLSAMPLEMASKVALUE before + // shading occurs. See glSampleMaski. + flag_scissorTest, // !< If enabled, discard fragments that are outside the scissor rectangle. See + // glScissor. + flag_stencilTest, // !< If enabled, do stencil testing and update the stencil buffer. See + // glStencilFunc and glStencilOp. GLTEXTURECUBEMAPSEAMLESS = 1+0, //!< If + // enabled, cubemap textures are sampled such that when linearly sampling from + // the border between two adjacent faces, texels from both faces are used to + // generate the final sample value. When disabled, texels from only a single + // face are used to ruct the final sample value. + flag_programPointSize, // !< If enabled and a vertex or geometry shader is active, then the derived + // point size is taken from the (potentially clipped) shader builtin + // gthis.PointSize and clamped to the implementation-dependent point size range. + flag_texture2D, // !< + flag_alphaTest, // !< + flag_fog, flag_back } public enum RenderMode { - point, - line, - lineStrip, //!< Not supported in GALE (TODO Later) - lineLoop, - triangle, - triangleStrip, //!< Not supported in GALE (TODO Later) - triangleFan, //!< Not supported in GALE (TODO Later) - quad, //!< Not supported in OpenGL-ES2 - quadStrip, //!< Not supported in OpenGL-ES2 - polygon //!< Not supported in OpenGL-ES2 + point, line, lineStrip, // !< Not supported in GALE (TODO Later) + lineLoop, triangle, triangleStrip, // !< Not supported in GALE (TODO Later) + triangleFan, // !< Not supported in GALE (TODO Later) + quad, // !< Not supported in OpenGL-ES2 + quadStrip, // !< Not supported in OpenGL-ES2 + polygon // !< Not supported in OpenGL-ES2 } /* Shader wrapping : */ public static enum ShaderType { - vertex, - fragment - } + vertex, fragment + }; public static class StateFlag { public boolean current = false; @@ -93,14 +147,17 @@ public class OpenGL { } public enum Usage { - streamDraw, - staticDraw, - dynamicDraw + streamDraw, staticDraw, dynamicDraw } - public static final int GL_RGB = GL11.GL_RGB; - public static final int GL_RGBA = GL11.GL_RGBA; + private static final int[] TEXTURE_ID_BINDING = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2, GL13.GL_TEXTURE3, GL13.GL_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7, + GL13.GL_TEXTURE8, GL13.GL_TEXTURE9, GL13.GL_TEXTURE10, GL13.GL_TEXTURE11, GL13.GL_TEXTURE12, GL13.GL_TEXTURE13, GL13.GL_TEXTURE14, GL13.GL_TEXTURE15, GL13.GL_TEXTURE16, GL13.GL_TEXTURE17, + GL13.GL_TEXTURE18, GL13.GL_TEXTURE19, GL13.GL_TEXTURE20, GL13.GL_TEXTURE21, GL13.GL_TEXTURE22, GL13.GL_TEXTURE23, GL13.GL_TEXTURE24, GL13.GL_TEXTURE25, GL13.GL_TEXTURE26, + GL13.GL_TEXTURE27, GL13.GL_TEXTURE28, GL13.GL_TEXTURE29, GL13.GL_TEXTURE30, GL13.GL_TEXTURE31 }; + public static final int GL_RGB = GL11.GL_RGB; + + public static final int GL_RGBA = GL11.GL_RGBA; public static final int GL_UNSIGNED_BYTE = GL11.GL_UNSIGNED_BYTE; public static final int GL_TEXTURE_2D = GL11.GL_TEXTURE_2D; @@ -111,170 +168,176 @@ public class OpenGL { static final boolean DIRECT_MODE = false; // TODO externalize this ...; - private static List matrixList = new ArrayList<>(); + private static final List MATRIX_LIST = new ArrayList<>(); + + private static Matrix4f matrixCamera = Matrix4f.IDENTITY; - private static Matrix4f matrixCamera = new Matrix4f(); private static int programId = 0; - private static final Map CONVERT_RENDER_MODE = Map.of(RenderMode.point, GL11.GL_POINTS, RenderMode.line, GL11.GL_LINES, RenderMode.lineStrip, GL11.GL_LINE_STRIP, RenderMode.lineLoop, GL11.GL_LINE_LOOP, RenderMode.triangle, GL11.GL_TRIANGLES, RenderMode.triangleStrip, GL11.GL_TRIANGLE_STRIP, RenderMode.triangleFan, GL11.GL_TRIANGLE_FAN, RenderMode.quad, GL11.GL_QUADS, RenderMode.quadStrip, GL11.GL_QUAD_STRIP, RenderMode.polygon, GL11.GL_POLYGON); - private static Map basicFlag;; + private static final Map BASIC_FLAG; private static boolean flagsStatesChange = false; - private static Map flagsStates = new HashMap<>(); + + private static final Map FLAGS_STATES = new HashMap<>(); public static Map convertUsage; static { - flagsStates.put(Flag.flag_blend, new StateFlag()); - flagsStates.put(Flag.flag_clipDistanceI, new StateFlag()); - flagsStates.put(Flag.flag_colorLogigOP, new StateFlag()); - flagsStates.put(Flag.flag_cullFace, new StateFlag()); - flagsStates.put(Flag.flag_debugOutput, new StateFlag()); - flagsStates.put(Flag.flag_debugOutputSynchronous, new StateFlag()); - flagsStates.put(Flag.flag_depthClamp, new StateFlag()); - flagsStates.put(Flag.flag_depthTest, new StateFlag()); - flagsStates.put(Flag.flag_dither, new StateFlag()); - flagsStates.put(Flag.flag_framebufferSRGB, new StateFlag()); - flagsStates.put(Flag.flag_lineSmooth, new StateFlag()); - flagsStates.put(Flag.flag_multisample, new StateFlag()); - flagsStates.put(Flag.flag_polygonOffsetFill, new StateFlag()); - flagsStates.put(Flag.flag_polygonOffsetLine, new StateFlag()); - flagsStates.put(Flag.flag_polygonOffsetPoint, new StateFlag()); - flagsStates.put(Flag.flag_polygonSmooth, new StateFlag()); - flagsStates.put(Flag.flag_primitiveRestart, new StateFlag()); - flagsStates.put(Flag.flag_primitiveRestartFixedIndex, new StateFlag()); - flagsStates.put(Flag.flag_sampleAlphaToCoverage, new StateFlag()); - flagsStates.put(Flag.flag_sampleAlphaToOne, new StateFlag()); - flagsStates.put(Flag.flag_sampleCoverage, new StateFlag()); - flagsStates.put(Flag.flag_sampleShading, new StateFlag()); - flagsStates.put(Flag.flag_sampleMask, new StateFlag()); - flagsStates.put(Flag.flag_scissorTest, new StateFlag()); - flagsStates.put(Flag.flag_stencilTest, new StateFlag()); - flagsStates.put(Flag.flag_programPointSize, new StateFlag()); - flagsStates.put(Flag.flag_texture2D, new StateFlag()); - flagsStates.put(Flag.flag_alphaTest, new StateFlag()); - flagsStates.put(Flag.flag_fog, new StateFlag()); - flagsStates.put(Flag.flag_back, new StateFlag()); - basicFlag = new HashMap<>(); - basicFlag.put(Flag.flag_blend, GL11.GL_BLEND); - // basicFlag.put(Flag.flag_clipDistanceI, GL_CLIP_DISTANCE0); - // basicFlag.put(Flag.flag_colorLogigOP, GL_COLOR_LOGIC_OP); - basicFlag.put(Flag.flag_cullFace, GL11.GL_CULL_FACE); - // basicFlag.put(Flag.flag_debugOutput, GLDEBUGOUTPUT); - // basicFlag.put(Flag.flag_debugOutputSynchronous, GLDEBUGOUTPUTSYNCHRONOUS); - // basicFlag.put(Flag.flag_depthClamp, GLDEPTHCLAMP); - basicFlag.put(Flag.flag_depthTest, GL11.GL_DEPTH_TEST); - basicFlag.put(Flag.flag_dither, GL11.GL_DITHER); - // basicFlag.put(Flag.flag_framebufferSRGB, GLFRAMEBUFFERSRGB); - // basicFlag.put(Flag.flag_lineSmooth, GLLINESMOOTH); - // basicFlag.put(Flag.flag_multisample, GLMULTISAMPLE); - basicFlag.put(Flag.flag_polygonOffsetFill, GL11.GL_POLYGON_OFFSET_FILL); - // basicFlag.put(Flag.flag_polygonOffsetLine, GLPOLYGONOFFSETLINE); - // basicFlag.put(Flag.flag_polygonOffsetPoint, GLPOLYGONOFFSETPOINT); - // basicFlag.put(Flag.flag_polygonSmooth, GLPOLYGONSMOOTH); - // basicFlag.put(Flag.flag_primitiveRestart, GLPRIMITIVERESTART); - // basicFlag.put(Flag.flag_primitiveRestartFixedIndex, GLPRIMITIVERESTARTFIXEDINDEX); - basicFlag.put(Flag.flag_sampleAlphaToCoverage, GL20.GL_SAMPLE_ALPHA_TO_COVERAGE); - // basicFlag.put(Flag.flag_sampleAlphaToOne, GLSAMPLEALPHATOONE); - basicFlag.put(Flag.flag_sampleCoverage, GL30.GL_SAMPLE_COVERAGE); - // basicFlag.put(Flag.flag_sampleShading, GLSAMPLESHADING); - // basicFlag.put(Flag.flag_sampleMask, GLSAMPLEMASK); - basicFlag.put(Flag.flag_scissorTest, GL11.GL_SCISSOR_TEST); - basicFlag.put(Flag.flag_stencilTest, GL30.GL_STENCIL_TEST); - // basicFlag.put(Flag.flag_programPointSize, GLPROGRAMPOINTSIZE); - basicFlag.put(Flag.flag_texture2D, GL11.GL_TEXTURE_2D); - // basicFlag.put(Flag.flag_alphaTest, GLALPHATEST); - // basicFlag.put(Flag.flag_fog, GLFOG); - basicFlag.put(Flag.flag_back, GL11.GL_BACK); + FLAGS_STATES.put(Flag.flag_blend, new StateFlag()); + FLAGS_STATES.put(Flag.flag_clipDistanceI, new StateFlag()); + FLAGS_STATES.put(Flag.flag_colorLogigOP, new StateFlag()); + FLAGS_STATES.put(Flag.flag_cullFace, new StateFlag()); + FLAGS_STATES.put(Flag.flag_debugOutput, new StateFlag()); + FLAGS_STATES.put(Flag.flag_debugOutputSynchronous, new StateFlag()); + FLAGS_STATES.put(Flag.flag_depthClamp, new StateFlag()); + FLAGS_STATES.put(Flag.flag_depthTest, new StateFlag()); + FLAGS_STATES.put(Flag.flag_dither, new StateFlag()); + FLAGS_STATES.put(Flag.flag_framebufferSRGB, new StateFlag()); + FLAGS_STATES.put(Flag.flag_lineSmooth, new StateFlag()); + FLAGS_STATES.put(Flag.flag_multisample, new StateFlag()); + FLAGS_STATES.put(Flag.flag_polygonOffsetFill, new StateFlag()); + FLAGS_STATES.put(Flag.flag_polygonOffsetLine, new StateFlag()); + FLAGS_STATES.put(Flag.flag_polygonOffsetPoint, new StateFlag()); + FLAGS_STATES.put(Flag.flag_polygonSmooth, new StateFlag()); + FLAGS_STATES.put(Flag.flag_primitiveRestart, new StateFlag()); + FLAGS_STATES.put(Flag.flag_primitiveRestartFixedIndex, new StateFlag()); + FLAGS_STATES.put(Flag.flag_sampleAlphaToCoverage, new StateFlag()); + FLAGS_STATES.put(Flag.flag_sampleAlphaToOne, new StateFlag()); + FLAGS_STATES.put(Flag.flag_sampleCoverage, new StateFlag()); + FLAGS_STATES.put(Flag.flag_sampleShading, new StateFlag()); + FLAGS_STATES.put(Flag.flag_sampleMask, new StateFlag()); + FLAGS_STATES.put(Flag.flag_scissorTest, new StateFlag()); + FLAGS_STATES.put(Flag.flag_stencilTest, new StateFlag()); + FLAGS_STATES.put(Flag.flag_programPointSize, new StateFlag()); + FLAGS_STATES.put(Flag.flag_texture2D, new StateFlag()); + FLAGS_STATES.put(Flag.flag_alphaTest, new StateFlag()); + FLAGS_STATES.put(Flag.flag_fog, new StateFlag()); + FLAGS_STATES.put(Flag.flag_back, new StateFlag()); + BASIC_FLAG = new HashMap<>(); + BASIC_FLAG.put(Flag.flag_blend, GL11.GL_BLEND); + // basicFlag.put(Flag.flag_clipDistanceI, GL_CLIP_DISTANCE0); + // basicFlag.put(Flag.flag_colorLogigOP, GL_COLOR_LOGIC_OP); + BASIC_FLAG.put(Flag.flag_cullFace, GL11.GL_CULL_FACE); + // basicFlag.put(Flag.flag_debugOutput, GLDEBUGOUTPUT); + // basicFlag.put(Flag.flag_debugOutputSynchronous, GLDEBUGOUTPUTSYNCHRONOUS); + // basicFlag.put(Flag.flag_depthClamp, GLDEPTHCLAMP); + BASIC_FLAG.put(Flag.flag_depthTest, GL11.GL_DEPTH_TEST); + BASIC_FLAG.put(Flag.flag_dither, GL11.GL_DITHER); + // basicFlag.put(Flag.flag_framebufferSRGB, GLFRAMEBUFFERSRGB); + // basicFlag.put(Flag.flag_lineSmooth, GLLINESMOOTH); + // basicFlag.put(Flag.flag_multisample, GLMULTISAMPLE); + BASIC_FLAG.put(Flag.flag_polygonOffsetFill, GL11.GL_POLYGON_OFFSET_FILL); + // basicFlag.put(Flag.flag_polygonOffsetLine, GLPOLYGONOFFSETLINE); + // basicFlag.put(Flag.flag_polygonOffsetPoint, GLPOLYGONOFFSETPOINT); + // basicFlag.put(Flag.flag_polygonSmooth, GLPOLYGONSMOOTH); + // basicFlag.put(Flag.flag_primitiveRestart, GLPRIMITIVERESTART); + // basicFlag.put(Flag.flag_primitiveRestartFixedIndex, + // GLPRIMITIVERESTARTFIXEDINDEX); + BASIC_FLAG.put(Flag.flag_sampleAlphaToCoverage, GL20.GL_SAMPLE_ALPHA_TO_COVERAGE); + // basicFlag.put(Flag.flag_sampleAlphaToOne, GLSAMPLEALPHATOONE); + BASIC_FLAG.put(Flag.flag_sampleCoverage, GL30.GL_SAMPLE_COVERAGE); + // basicFlag.put(Flag.flag_sampleShading, GLSAMPLESHADING); + // basicFlag.put(Flag.flag_sampleMask, GLSAMPLEMASK); + BASIC_FLAG.put(Flag.flag_scissorTest, GL11.GL_SCISSOR_TEST); + BASIC_FLAG.put(Flag.flag_stencilTest, GL30.GL_STENCIL_TEST); + // basicFlag.put(Flag.flag_programPointSize, GLPROGRAMPOINTSIZE); + BASIC_FLAG.put(Flag.flag_texture2D, GL11.GL_TEXTURE_2D); + // basicFlag.put(Flag.flag_alphaTest, GLALPHATEST); + // basicFlag.put(Flag.flag_fog, GLFOG); + BASIC_FLAG.put(Flag.flag_back, GL11.GL_BACK); convertUsage = new HashMap<>(); convertUsage.put(Usage.streamDraw, GL20.GL_STREAM_DRAW); convertUsage.put(Usage.staticDraw, GL20.GL_STATIC_DRAW); convertUsage.put(Usage.dynamicDraw, GL20.GL_DYNAMIC_DRAW); } - private static Map threadHasContext = new HashMap<>(); - + private static final Map THREAD_HAS_CONTEXT = new HashMap<>(); private static final Map BASIC_FLAG_CLEAR = Map.of(ClearFlag.clearFlag_colorBuffer, GL11.GL_COLOR_BUFFER_BIT, ClearFlag.clearFlag_depthBuffer, GL11.GL_DEPTH_BUFFER_BIT, ClearFlag.clearFlag_stencilBuffer, GL11.GL_STENCIL_BUFFER_BIT); /** - * @brief enable Texture on the system - * @param flagID The flag requested + * enable Texture on the system + * @param textureID Id of the texture 0 .. 13 */ - public static void activeTexture(final int flagID) { + public static void activeTexture(final int textureID) { if (programId >= 0) { - GL13.glActiveTexture(flagID); + GL13.glActiveTexture(TEXTURE_ID_BINDING[textureID]); checkGlError("glActiveTexture"); } else if (DEBUG) { Log.error("try to bind texture with no program set"); } } - public static boolean bindBuffer(final int bufferId) { + public static void bindBuffer(final int bufferId) { GL20.glBindBuffer(GL20.GL_ARRAY_BUFFER, bufferId); checkGlError("glBindBuffer"); - return true; } public static void bindTexture2D(final int texId) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId); } - public static boolean bufferData(final Color[] data, final Usage usage) { + public static void blendFuncAuto() { + GL40.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + } + + public static void bufferData(final Color[] data, final Usage usage) { final FloatBuffer buffer = storeDataInFloatBuffer(data); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage)); checkGlError("glBufferData"); - return true; } - public static boolean bufferData(final float[] data, final Usage usage) { + public static void bufferData(final float[] data, final Usage usage) { final FloatBuffer buffer = storeDataInFloatBuffer(data); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage)); checkGlError("glBufferData"); - return true; } - public static boolean bufferData(final int[] data, final Usage usage) { + public static void bufferData(final int[] data, final Usage usage) { final IntBuffer buffer = storeDataInFloatBuffer(data); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage)); checkGlError("glBufferData"); - return true; } - public static boolean bufferData(final Vector2f[] data, final Usage usage) { + public static void bufferData(final Vector2f[] data, final Usage usage) { final FloatBuffer buffer = storeDataInFloatBuffer(data); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage)); checkGlError("glBufferData"); - return true; } - public static boolean bufferData(final Vector3f[] data, final Usage usage) { + public static void bufferData(final Vector3f[] data, final Usage usage) { final FloatBuffer buffer = storeDataInFloatBuffer(data); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage)); checkGlError("glBufferData"); - return true; } public static void checkGlError(final String op) { - // int localLine = Thread.currentThread().getStackTrace()[2].getLineNumber(); - // if (CHECKERROROPENGL == true) { - // boolean hasError = false; - // for (int error = GL11.glGetError(); error!=null; error = GL11.glGetError()) { - // Log.error("after " + op + "():" + localLine + " glError(" + error + ")"); - // hasError = true; - // } - // if (hasError == true) { - // Log.critical("plop"); - // } - // for (GLint error = glGetError(); error; error = glGetError()) { - // Log.error("after " + op + "() glError (" + error + ")"); - // } - // } + // int localLine = Thread.currentThread().getStackTrace()[2].getLineNumber(); + // if (CHECKERROROPENGL == true) { + // boolean hasError = false; + // for (int error = GL11.glGetError(); error!=null; error = GL11.glGetError()) { + // Log.error("after " + op + "():" + localLine + " glError(" + error + ")"); + // hasError = true; + // } + // if (hasError == true) { + // Log.critical("plop"); + // } + // for (GLint error = glGetError(); error; error = glGetError()) { + // Log.error("after " + op + "() glError (" + error + ")"); + // } + // } } /** - * @brief clear sets the bitplane area of the window to values previously selected by clearColor, clearDepth, and clearStencil. Multiple color buffers can be cleared simultaneously by selecting more than one buffer at a time using drawBuffer. - * The pixel ownership test, the scissor test, dithering, and the buffer writemasks affect the operation of clear. The scissor box bounds the cleared region. Alpha function, blend function, logical operation, stenciling, texture mapping, and depth-buffering are ignored by clear. - * @param flags This is the bitwise OR of several values indicating which buffer is to be cleared. + * clear sets the bitplane area of the window to values previously + * selected by clearColor, clearDepth, and clearStencil. Multiple color + * buffers can be cleared simultaneously by selecting more than one + * buffer at a time using drawBuffer. The pixel ownership test, the + * scissor test, dithering, and the buffer writemasks affect the + * operation of clear. The scissor box bounds the cleared region. Alpha + * function, blend function, logical operation, stenciling, texture + * mapping, and depth-buffering are ignored by clear. + * @param flag This is the bitwise OR of several values indicating which buffer + * is to be cleared. */ public static void clear(final ClearFlag flag) { GL11.glClear(BASIC_FLAG_CLEAR.get(flag)); @@ -282,16 +345,17 @@ public class OpenGL { } /** - * @brief Specifies the clear color value When clear is requested - * @param value to set [0..1] + * Specifies the clear color value When clear is requested + * @param color cleear color of the screen */ public static void clearColor(final Color color) { - GL11.glClearColor(color.r, color.g, color.b, color.a); + GL11.glClearColor(color.r(), color.g(), color.b(), color.a()); checkGlError("glClearColor"); } /** - * @brief Specifies the depth value used when the depth buffer is cleared. The initial value is 1. + * Specifies the depth value used when the depth buffer is cleared. The + * initial value is 1. * @param value to set [0..1] */ public static void clearDepth(final float value) { @@ -300,15 +364,17 @@ public class OpenGL { } private static void clearFlagState() { - for (final Map.Entry elem : flagsStates.entrySet()) { + for (final Map.Entry elem : FLAGS_STATES.entrySet()) { elem.getValue().current = false; elem.getValue().mustBeSet = false; } } /** - * @brief Specifies the index used by clear to clear the stencil buffer. s is masked with 2 m - 1 , where m is the number of bits in the stencil buffer. - * @param value + * Specifies the index used by clear to clear the stencil buffer. s is + * masked with 2 m - 1 , where m is the number of bits in the stencil + * buffer. + * @param value */ public static void clearStencil(final int value) { GL11.glClearStencil(value); @@ -330,35 +396,35 @@ public class OpenGL { } /** - * @brief disable Texture on the system + * disable Texture on the system * @param flagID The flag requested */ - // TODO rename Disable + // TODO rename Disable public static void desActiveTexture(final int flagID) { - // if (this.programId >= 0) { - // - // } + // if (this.programId >= 0) { + // + // } } /** - * @brief disable a flag on the system + * disable a flag on the system * @param flagID The flag requested */ public static void disable(final Flag flagID) { - //Log.info("Disable : " + flagID); + // Log.info("Disable : " + flagID); if (DIRECT_MODE) { - GL11.glDisable(basicFlag.get(flagID)); + GL11.glDisable(BASIC_FLAG.get(flagID)); checkGlError("glDisable"); } else { - //Log.debug("Disable FLAGS = " + this.flagsStates); - flagsStates.get(flagID).mustBeSet = false; + // Log.debug("Disable FLAGS = " + this.flagsStates); + FLAGS_STATES.get(flagID).mustBeSet = false; flagsStatesChange = true; - //Log.debug(" == >" + this.flagsStates); + // Log.debug(" == >" + this.flagsStates); } } /** - * @brief draw a specific array == > this enable mode difference ... + * draw a specific array == > this enable mode difference ... */ public static void drawArrays(final RenderMode mode, final int first, final int count) { if (programId >= 0) { @@ -373,39 +439,39 @@ public class OpenGL { } /** - * @brief enable a flag on the system + * enable a flag on the system * @param flagID The flag requested */ public static void enable(final Flag flagID) { - //Log.info("Enable : " + flagID); + // Log.info("Enable : " + flagID); if (DIRECT_MODE) { - GL11.glEnable(basicFlag.get(flagID)); + GL11.glEnable(BASIC_FLAG.get(flagID)); checkGlError("glEnable"); } else { - //Log.debug("Enable FLAGS = " + this.flagsStates); - flagsStates.get(flagID).mustBeSet = true; + // Log.debug("Enable FLAGS = " + this.flagsStates); + FLAGS_STATES.get(flagID).mustBeSet = true; flagsStatesChange = true; - //Log.debug(" == >" + this.flagsStates); + // Log.debug(" == >" + this.flagsStates); } } /** - * @brief + * */ public static void finish() { programId = -1; } /** - * @brief + * */ public static void flush() { programId = -1; GL11.glFlush(); - //checkGlError("glFlush"); - //Log.info("========================" ); - //Log.info("== FLUSH OPEN GL ==" ); - //Log.info("========================"); + // checkGlError("glFlush"); + // Log.info("========================" ); + // Log.info("== FLUSH OPEN GL ==" ); + // Log.info("========================"); } public static int genBuffers() { @@ -431,7 +497,8 @@ public class OpenGL { } /** - * @brief get a reference on the current matrix camera destinate to opengl renderer. + * get a reference on the current matrix camera destinate to opengl + * renderer. * @return The requested matrix. */ public static Matrix4f getCameraMatrix() { @@ -439,15 +506,15 @@ public class OpenGL { } /** - * @brief get a reference on the current matrix destinate to opengl renderer. + * get a reference on the current matrix destinate to opengl renderer. * @return The requested matrix. */ public static Matrix4f getMatrix() { - if (matrixList.size() == 0) { - Log.error("set matrix list is not corect size in the stack : " + matrixList.size()); - matrixList.add(Matrix4f.identity()); + if (MATRIX_LIST.size() == 0) { + Log.error("set matrix list is not corect size in the stack: 0"); + MATRIX_LIST.add(Matrix4f.IDENTITY); } - return matrixList.get(matrixList.size() - 1); + return MATRIX_LIST.get(MATRIX_LIST.size() - 1); } public static void glDeleteTextures(final int textureId) { @@ -477,43 +544,46 @@ public class OpenGL { } /** - * @brief Get the current thread context status. - * @return true The threflagsStates.putn acces to openGL.flagsStates.put(Flag.@return false The Thread Can not acces to OpenGL. + * Get the current thread context status. + * @return true The threflagsStates.putn acces to + * openGL.flagsStates.put(Flag.@return false The Thread Can not acces to + * OpenGL. */ public static boolean hasContext() { final long curentThreadId = Thread.currentThread().getId(); - if (threadHasContext.containsKey(curentThreadId) == false) { + if (!THREAD_HAS_CONTEXT.containsKey(curentThreadId)) { return false; } - return threadHasContext.get(curentThreadId); + return THREAD_HAS_CONTEXT.get(curentThreadId); } /** - * @brief Lock the openGL context for one user only == > better to keep flags and other things ... + * Lock the openGL context for one user only == > better to keep flags + * and other things ... */ public static void lock() { - //mutexOpenGl().lock(); - matrixList.clear(); - final Matrix4f tmpMat = Matrix4f.identity(); - matrixList.add(tmpMat); - matrixCamera.setIdentity(); + // mutexOpenGl().lock(); + MATRIX_LIST.clear(); + final Matrix4f tmpMat = Matrix4f.IDENTITY; + MATRIX_LIST.add(tmpMat); + matrixCamera = Matrix4f.IDENTITY; clearFlagState(); programId = -1; } /** - * @brief remove the current matrix and get the last one from the matrix stack. + * remove the current matrix and get the last one from the matrix stack. */ public static void pop() { - if (matrixList.size() <= 1) { - Log.error("set matrix list is not corect size in the stack : " + matrixList.size()); - matrixList.clear(); - matrixList.add(Matrix4f.identity()); - matrixCamera.setIdentity(); + if (MATRIX_LIST.size() <= 1) { + Log.error("set matrix list is not corect size in the stack : " + MATRIX_LIST.size()); + MATRIX_LIST.clear(); + MATRIX_LIST.add(Matrix4f.IDENTITY); + matrixCamera = Matrix4f.IDENTITY; return; } - matrixList.remove(matrixList.size() - 1); - matrixCamera.setIdentity(); + MATRIX_LIST.remove(MATRIX_LIST.size() - 1); + matrixCamera = Matrix4f.IDENTITY; } public static boolean programAttach(final int prog, final int shader) { @@ -547,43 +617,44 @@ public class OpenGL { checkGlError("glLinkProgram"); GL20.glValidateProgram(prog); - // GLint linkStatus = GLFALSE; - // glGetProgramiv(GLint(prog), GLLINKSTATUS, linkStatus); - // checkGlError("glGetProgramiv"); - // if (linkStatus != GLTRUE) { - // GLint bufLength = 0; - // this.bufferDisplayError[0] = '\0'; - // glGetProgramInfoLog(GLint(prog), LOGOGLINTERNALBUFFERLEN, bufLength, this.bufferDisplayError); - // char tmpLog[256]; - // int idOut=0; - // Log.error("Could not compile 'PROGRAM':"); - // for (sizet iii=0; iii= 256) { - // tmpLog[idOut] = '\0'; - // Log.error(" == > " + tmpLog); - // idOut=0; - // } else { - // idOut++; - // } - // if (this.bufferDisplayError[iii] == '\0') { - // break; - // } - // } - // if (idOut != 0) { - // tmpLog[idOut] = '\0'; - // Log.error(" == > " + tmpLog); - // } - // return false; - // } + // GLint linkStatus = GLFALSE; + // glGetProgramiv(GLint(prog), GLLINKSTATUS, linkStatus); + // checkGlError("glGetProgramiv"); + // if (linkStatus != GLTRUE) { + // GLint bufLength = 0; + // this.bufferDisplayError[0] = '\0'; + // glGetProgramInfoLog(GLint(prog), LOGOGLINTERNALBUFFERLEN, bufLength, + // this.bufferDisplayError); + // char tmpLog[256]; + // int idOut=0; + // Log.error("Could not compile 'PROGRAM':"); + // for (sizet iii=0; iii= 256) { + // tmpLog[idOut] = '\0'; + // Log.error(" == > " + tmpLog); + // idOut=0; + // } else { + // idOut++; + // } + // if (this.bufferDisplayError[iii] == '\0') { + // break; + // } + // } + // if (idOut != 0) { + // tmpLog[idOut] = '\0'; + // Log.error(" == > " + tmpLog); + // } + // return false; + // } return true; } // ------------------------------------------------------------------------------------ - // -- Open GL program ... - // ------------------------------------------------------------------------------------ + // -- Open GL program ... + // ------------------------------------------------------------------------------------ public static int programCreate() { final int programId = GL20.glCreateProgram(); if (programId == 0) { @@ -651,12 +722,12 @@ public class OpenGL { } public static void programLoadUniformBoolean(final int location, final boolean value) { - //System.out.println("set value " + value + " " + (value==true?1.0f:0.0f)); - GL20.glUniform1f(location, value == true ? 1.0f : 0.0f); + // System.out.println("set value " + value + " " + (value==true?1.0f:0.0f)); + GL20.glUniform1f(location, value ? 1.0f : 0.0f); } public static void programLoadUniformColor(final int location, final Color value) { - GL20.glUniform4f(location, value.r, value.g, value.b, value.a); + GL20.glUniform4f(location, value.r(), value.g(), value.b(), value.a()); } public static void programLoadUniformFloat(final int location, final float value) { @@ -689,30 +760,30 @@ public class OpenGL { public static void programLoadUniformInt(final int location, final int value, final int value2, final int value3, final int value4) { GL20.glUniform4i(location, value, value2, value3, value4); - } - - public static void programLoadUniformMatrix(final int location, final Matrix4f value) { - GL20.glUniformMatrix4fv(location, true, value.getTable()); }; + public static void programLoadUniformMatrix(final int location, final Matrix4f value) { + GL20.glUniformMatrix4fv(location, true, value.asArray()); + } + public static void programLoadUniformMatrix(final int location, final Matrix4f value, final boolean transpose) { - GL20.glUniformMatrix4fv(location, transpose, value.getTable()); + GL20.glUniformMatrix4fv(location, transpose, value.asArray()); } public static void programLoadUniformVector(final int location, final Vector2f value) { - GL20.glUniform2f(location, value.x, value.y); + GL20.glUniform2f(location, value.x(), value.y()); } public static void programLoadUniformVector(final int location, final Vector2i value) { - GL20.glUniform2i(location, value.x, value.y); + GL20.glUniform2i(location, value.x(), value.y()); } public static void programLoadUniformVector(final int location, final Vector3f value) { - GL20.glUniform3f(location, value.x, value.y, value.z); + GL20.glUniform3f(location, value.x(), value.y(), value.z()); } public static void programLoadUniformVector(final int location, final Vector3i value) { - GL20.glUniform3i(location, value.x, value.y, value.z); + GL20.glUniform3i(location, value.x(), value.y(), value.z()); } public static void programRemove(final int prog) { @@ -728,39 +799,45 @@ public class OpenGL { // nothing to do ... } - // public static void drawElements(RenderMode mode, List indices) { - // if (this.programId >= 0) { - // updateAllFlags(); - // //Log.debug("Request draw of " + indices.size() + "elements"); - // GL15.glDrawElements(convertRenderMode.get(mode), indices.size(), GL11.GL_UNSIGNED_INT);//, &indices[0]); - // checkGlError("glDrawElements"); - // } - // } - // public static void drawElements16(RenderMode mode, List indices) { - // if (this.programId >= 0) { - // updateAllFlags(); - // GL20.glDrawElements(convertRenderMode.get(mode), indices.size(), GLUNSIGNEDSHORT, &indices[0]); - // checkGlError("glDrawElements"); - // } - // } - // public static void drawElements8 (enum renderMode mode, List indices) { - // if (this.programId >= 0) { - // updateAllFlags(); - // GL20.glDrawElements(convertRenderMode[int(mode)], indices.size(), GLUNSIGNEDBYTE, &indices[0]); - // checkGlError("glDrawElements"); - // } - // } + // public static void drawElements(RenderMode mode, List indices) { + // if (this.programId >= 0) { + // updateAllFlags(); + // //Log.debug("Request draw of " + indices.size() + "elements"); + // GL15.glDrawElements(convertRenderMode.get(mode), indices.size(), + // GL11.GL_UNSIGNED_INT);//, &indices[0]); + // checkGlError("glDrawElements"); + // } + // } + // public static void drawElements16(RenderMode mode, List indices) { + // if (this.programId >= 0) { + // updateAllFlags(); + // GL20.glDrawElements(convertRenderMode.get(mode), indices.size(), + // GLUNSIGNEDSHORT, &indices[0]); + // checkGlError("glDrawElements"); + // } + // } + // public static void drawElements8 (enum renderMode mode, List indices) { + // if (this.programId >= 0) { + // updateAllFlags(); + // GL20.glDrawElements(convertRenderMode[int(mode)], indices.size(), + // GLUNSIGNEDBYTE, &indices[0]); + // checkGlError("glDrawElements"); + // } + // } /** - * @brief Use openGL program + * Use openGL program * @param id Id of the program that might be used */ public static void programUse(final int id) { - //Log.verbose("USE prog : " + id); - // note : In normal openGL case, the system might call with the program ID and at the end with 0, - // here, we wrap this use to prevent over call of glUseProgram == > then we set -1 when the - // user no more use this program, and just stop grnerating. (chen 0 == > this is an errored program ... + // Log.verbose("USE prog : " + id); + // note : In normal openGL case, the system might call with the program ID and + // at the end with 0, + // here, we wrap this use to prevent over call of glUseProgram == > then we set + // -1 when the + // user no more use this program, and just stop grnerating. (chen 0 == > this is + // an errored program ... if (id == -1) { - // not used == > because it is unneded + // not used == > because it is unneded return; } if (programId != id) { @@ -771,16 +848,16 @@ public class OpenGL { } /** - * @brief store current matrix in the matrix stack. + * store current matrix in the matrix stack. */ public static void push() { - if (matrixList.size() == 0) { - Log.error("set matrix list is not corect size in the stack : " + matrixList.size()); - matrixList.add(Matrix4f.identity()); + if (MATRIX_LIST.size() == 0) { + Log.error("set matrix list is not corect size in the stack : " + MATRIX_LIST.size()); + MATRIX_LIST.add(Matrix4f.IDENTITY); return; } - final Matrix4f tmp = matrixList.get(matrixList.size() - 1); - matrixList.add(tmp); + final Matrix4f tmp = MATRIX_LIST.get(MATRIX_LIST.size() - 1); + MATRIX_LIST.add(tmp); } protected static StringBuilder readLocalFile(final String name) { @@ -800,6 +877,27 @@ public class OpenGL { return fileSource; } + protected static StringBuilder readLocalFile(final Uri name) { + final StringBuilder fileSource = new StringBuilder(); + try { + final InputStream inputStream = Uri.getStream(name); + if (inputStream == null) { + Log.error("Could not read the file! " + name); + System.exit(-1); + } + final Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name()))); + int c = 0; + while ((c = reader.read()) != -1) { + fileSource.append((char) c); + } + } catch (final IOException e) { + Log.error("Could not read the file! " + name); + e.printStackTrace(); + System.exit(-1); + } + return fileSource; + } + public static void reset() { if (DIRECT_MODE) { Log.error("TODO ..."); @@ -808,29 +906,32 @@ public class OpenGL { programId = -1; updateAllFlags(); } - } + }; public static void resetFlagState() { - for (final Map.Entry elem : flagsStates.entrySet()) { + for (final Map.Entry elem : FLAGS_STATES.entrySet()) { elem.getValue().mustBeSet = false; } flagsStatesChange = true; - }; - - /** - * @brief When you will done an opengl rendering, you might call this reset matrix first. It remove all the stach of the matrix pushed. - * @param newOne the default matrix that might be set for the graphic card for renderer. if too more pop will be done, this is the last that mmight survived - */ - public static void setBasicMatrix(final Matrix4f newOne) { - if (matrixList.size() != 1) { - Log.error("matrix is not corect size in the stack : " + matrixList.size()); - } - matrixList.clear(); - matrixList.add(newOne); } /** - * @brief set a reference on the current camera to opengl renderer. + * When you will done an opengl rendering, you might call this reset + * matrix first. It remove all the stach of the matrix pushed. + * @param newOne the default matrix that might be set for the graphic card for + * renderer. if too more pop will be done, this is the last that + * mmight survived + */ + public static void setBasicMatrix(final Matrix4f newOne) { + if (MATRIX_LIST.size() != 1) { + Log.error("matrix is not corect size in the stack : " + MATRIX_LIST.size()); + } + MATRIX_LIST.clear(); + MATRIX_LIST.add(newOne); + } + + /** + * set a reference on the current camera to opengl renderer. * @param newOne The requested matrix. */ public static void setCameraMatrix(final Matrix4f newOne) { @@ -842,17 +943,19 @@ public class OpenGL { } /** - * @brief this funtion configure the current use matrix for the renderer (call @ref Push before, and @ref Pop when no more needed). + * this funtion configure the current use matrix for the renderer + * (call @ref Push before, and @ref Pop when no more needed). * @param newOne The new current matrix use for the render. - * @note We did not use opengl standard system, due to the fact that is not supported in opengl ES-2 + * @note We did not use opengl standard system, due to the fact that is not + * supported in opengl ES-2 */ public static void setMatrix(final Matrix4f newOne) { - if (matrixList.size() == 0) { - Log.error("set matrix list is not corect size in the stack : " + matrixList.size()); - matrixList.add(newOne); + if (MATRIX_LIST.size() == 0) { + Log.error("set matrix list is not corect size in the stack : " + MATRIX_LIST.size()); + MATRIX_LIST.add(newOne); return; } - matrixList.set(matrixList.size() - 1, newOne); + MATRIX_LIST.set(MATRIX_LIST.size() - 1, newOne); } public static void setTexture2DFilterLinear() { @@ -876,14 +979,14 @@ public class OpenGL { } public static void setViewPort(final Vector2f start, final Vector2f stop) { - //Log.info("setViewport " + start + " " + stop); - GL11.glViewport((int) start.x, (int) start.y, (int) stop.x, (int) stop.y); + // Log.info("setViewport " + start + " " + stop); + GL11.glViewport((int) start.x(), (int) start.y(), (int) stop.x(), (int) stop.y()); checkGlError("glViewport"); } public static void setViewPort(final Vector2i start, final Vector2i stop) { - //Log.info("setViewport " + start + " " + stop); - GL11.glViewport(start.x, start.y, stop.x, stop.y); + // Log.info("setViewport " + start + " " + stop); + GL11.glViewport(start.x(), start.y(), stop.x(), stop.y()); checkGlError("glViewport"); } @@ -908,7 +1011,7 @@ public class OpenGL { return shaderId; } - public static int shaderLoad(final String file, final ShaderType type) { + public static int shaderLoad(final Uri file, final ShaderType type) { System.out.println("Load shader: '" + file + "'"); final StringBuilder shaderSource = readLocalFile(file); final int shaderID = shaderCreate(type); @@ -934,10 +1037,10 @@ public class OpenGL { public static FloatBuffer storeDataInFloatBuffer(final Color[] data) { final FloatBuffer buffer = FloatBuffer.allocate(data.length * 4); for (int iii = 0; iii < data.length; iii++) { - buffer.put(iii * 4, data[iii].r); - buffer.put(iii * 4 + 1, data[iii].g); - buffer.put(iii * 4 + 2, data[iii].b); - buffer.put(iii * 4 + 3, data[iii].a); + buffer.put(iii * 4, data[iii].r()); + buffer.put(iii * 4 + 1, data[iii].g()); + buffer.put(iii * 4 + 2, data[iii].b()); + buffer.put(iii * 4 + 3, data[iii].a()); } buffer.flip(); return buffer; @@ -960,8 +1063,8 @@ public class OpenGL { public static FloatBuffer storeDataInFloatBuffer(final Vector2f[] data) { final FloatBuffer buffer = FloatBuffer.allocate(data.length * 2); for (int iii = 0; iii < data.length; iii++) { - buffer.put(iii * 2, data[iii].x); - buffer.put(iii * 2 + 1, data[iii].y); + buffer.put(iii * 2, data[iii].x()); + buffer.put(iii * 2 + 1, data[iii].y()); } buffer.flip(); return buffer; @@ -970,36 +1073,38 @@ public class OpenGL { public static FloatBuffer storeDataInFloatBuffer(final Vector3f[] data) { final FloatBuffer buffer = FloatBuffer.allocate(data.length * 3); for (int iii = 0; iii < data.length; iii++) { - buffer.put(iii * 3, data[iii].x); - buffer.put(iii * 3 + 1, data[iii].y); - buffer.put(iii * 3 + 2, data[iii].z); + buffer.put(iii * 3, data[iii].x()); + buffer.put(iii * 3 + 1, data[iii].y()); + buffer.put(iii * 3 + 2, data[iii].z()); } buffer.flip(); return buffer; } /** - * @brief + * */ public static void swap() { } /** - * @brief must be called by the thread that has openGl context to notify the system + * must be called by the thread that has openGl context to notify the + * system * @note Call @ref gale::openGL::threadHasNoMoreContext when ended */ public static void threadHasContext() { final long curentThreadId = Thread.currentThread().getId(); - threadHasContext.put(curentThreadId, true); + THREAD_HAS_CONTEXT.put(curentThreadId, true); } /** - * @brief At the end of the thread exection, set the thead has no more openGL cotext + * At the end of the thread exection, set the thead has no more openGL + * cotext */ public static void threadHasNoMoreContext() { final long curentThreadId = Thread.currentThread().getId(); - threadHasContext.remove(curentThreadId); + THREAD_HAS_CONTEXT.remove(curentThreadId); } public static boolean unbindBuffer() { @@ -1009,36 +1114,37 @@ public class OpenGL { } /** - * @brief Un-lock the openGL context for an other user... + * Un-lock the openGL context for an other user... */ public static void unLock() { - //mutexOpenGl().unLock(); + // mutexOpenGl().unLock(); } /** - * @brieg update all the internal flag needed to be set from tre previous element set ... + * @brieg update all the internal flag needed to be set from tre previous + * element set ... */ public static void updateAllFlags() { if (DIRECT_MODE) { return; } // check if flags has change : - if (flagsStatesChange == false) { + if (!flagsStatesChange) { return; } flagsStatesChange = false; - for (final Map.Entry elem : flagsStates.entrySet()) { + for (final Map.Entry elem : FLAGS_STATES.entrySet()) { final StateFlag value = elem.getValue(); if (value.current != value.mustBeSet) { value.current = value.mustBeSet; - if (value.current == true) { - GL11.glEnable(basicFlag.get(elem.getKey())); + if (value.current) { + GL11.glEnable(BASIC_FLAG.get(elem.getKey())); checkGlError("glEnable"); - //Log.info(" enable : " + elem.getKey() + " " + basicFlag.get(elem.getKey())); + // Log.info(" enable : " + elem.getKey() + " " + basicFlag.get(elem.getKey())); } else { - GL11.glDisable(basicFlag.get(elem.getKey())); + GL11.glDisable(BASIC_FLAG.get(elem.getKey())); checkGlError("glDisable"); - //Log.info(" disable : " + elem.getKey()); + // Log.info(" disable : " + elem.getKey()); } } } diff --git a/src/org/atriasoft/gale/context/ClipBoard.java b/src/org/atriasoft/gale/context/ClipBoard.java index 9fbb679..296c6cd 100644 --- a/src/org/atriasoft/gale/context/ClipBoard.java +++ b/src/org/atriasoft/gale/context/ClipBoard.java @@ -3,14 +3,14 @@ package org.atriasoft.gale.context; public class ClipBoard { private ClipBoard() {} /** - * @brief set the string data on a specific clipboard. The Gui system is notify that the clipboard "SELECTION" and "COPY" are change + * set the string data on a specific clipboard. The Gui system is notify that the clipboard "SELECTION" and "COPY" are change * @param _clipboardID Select the specific ID of the clipboard * @param _data The string that might be send to the clipboard */ public static void set(ClipboardList clipboardID, String data) { } /** - * @brief Call system to request the current clipboard. + * Call system to request the current clipboard. * @note Due to some system that manage the clipboard request asynchronous (like X11) and gale managing the system with only one thread, * we need the call the system to send us the buffer, this is really ambigous, but the widget (who has focus) receive the * notification of the arrival of this buffer id @@ -19,7 +19,7 @@ public class ClipBoard { public static void request(ClipboardList clipboardID) { } /** - * @brief set the gale internal buffer (no notification at the GUI). This fuction might be use by the + * set the gale internal buffer (no notification at the GUI). This fuction might be use by the * Gui abstraction to set the buffer we receive. The end user must not use it. * @param _clipboardID selected clipboard ID * @param _data new buffer data @@ -27,7 +27,7 @@ public class ClipBoard { public static void setSystem(ClipboardList clipboardID, String data) { } /** - * @brief get the gale internal buffer of the curent clipboard. The end user can use it when he receive the event in + * get the gale internal buffer of the curent clipboard. The end user can use it when he receive the event in * the widget : @ref onEventClipboard == > we can nothe this function is the only one which permit it. * @note if we call this fuction withoutcallin @ref gale::context::clipBoard::Request, we only get the previous clipboard * @param _clipboardID selected clipboard ID diff --git a/src/org/atriasoft/gale/context/Context.java b/src/org/atriasoft/gale/context/Context.java index 42355ac..c9b9d5c 100644 --- a/src/org/atriasoft/gale/context/Context.java +++ b/src/org/atriasoft/gale/context/Context.java @@ -28,7 +28,7 @@ public abstract class Context { private static int countMemeCheck = 0; /** - * @brief From everyware in the program, we can get the context inteface. + * From everyware in the program, we can get the context inteface. * @return current reference on the instance. */ public static Context getContext() { @@ -78,13 +78,13 @@ public abstract class Context { // this.displayFps=true; // } else if ( this.commandLine.get(iii) == "-h" // || this.commandLine.get(iii) == "--help" - // || start_with(this.commandLine.get(iii), "--gale")) { + // || startwith(this.commandLine.get(iii), "--gale")) { // Log.print("gale - help : "); // Log.print(" --gale-fps"); // Log.print(" Display the current fps of the display"); // Log.print(" -h/--help"); // Log.print(" Display this help"); - // if (start_with(this.commandLine.get(iii), "--gale")) { + // if (startwith(this.commandLine.get(iii), "--gale")) { // Log.error("gale unknow element in parameter: '" << this.commandLine.get(iii) << "'"); // // remove parameter ... // } else { @@ -101,14 +101,14 @@ public abstract class Context { Log.info("GALE v:" + Gale.getVersion()); forceOrientation(Orientation.screenAuto); - postAction((_context) -> { - final Application appl = _context.getApplication(); + postAction((context) -> { + final Application appl = context.getApplication(); if (appl == null) { return; } - appl.onCreate(_context); - appl.onStart(_context); - appl.onResume(_context); + appl.onCreate(context); + appl.onStart(context); + appl.onResume(context); appl.canDraw = true; }); @@ -118,8 +118,8 @@ public abstract class Context { } /** - * @brief Inform the Gui that we want to have a copy of the clipboard - * @param _clipboardID ID of the clipboard (STD/SELECTION) only apear here + * Inform the Gui that we want to have a copy of the clipboard + * @param clipboardID ID of the clipboard (STD/SELECTION) only apear here */ public void clipBoardGet(final ClipboardList clipboardID) { // just transmit an event , we have the data in the system @@ -127,21 +127,21 @@ public abstract class Context { } /** - * @brief Inform the Gui that we are the new owner of the clipboard - * @param _clipboardID ID of the clipboard (STD/SELECTION) only apear here + * Inform the Gui that we are the new owner of the clipboard + * @param clipboardID ID of the clipboard (STD/SELECTION) only apear here */ public void clipBoardSet(final ClipboardList clipboardID) { // nothing to do, data is already copyed in the GALE clipborad center } /** - * @brief force the screen orientation (availlable on portable elements ... - * @param _orientation Selected orientation. + * force the screen orientation (availlable on portable elements ... + * @param orientation Selected orientation. */ public void forceOrientation(final Orientation orientation) {} /** - * @brief Redraw all the windows + * Redraw all the windows */ public void forceRedrawAll() { if (this.application == null) { @@ -180,7 +180,7 @@ public abstract class Context { } /** - * @brief The Application request the current position of the windows. + * The Application request the current position of the windows. * @return Turrent position of the Windows. */ public Vector2f getPos() { @@ -192,7 +192,7 @@ public abstract class Context { } /** - * @brief get the current windows size + * get the current windows size * @return the current size ... */ public Vector2f getSize() { @@ -200,20 +200,20 @@ public abstract class Context { } /** - * @brief get all Keyboard event from the X system (like many time use of META) - * @param _status "true" if all the event will be get, false if we want only ours. + * get all Keyboard event from the X system (like many time use of META) + * @param status "true" if all the event will be get, false if we want only ours. */ public void grabKeyboardEvents(final boolean status) {} /** - * @brief get all Mouse/Touch events from the X system - * @param _status "true" if all the event will be get, false if we want only ours. - * @param _forcedPosition the position where the mouse might be reset at every events ... + * get all Mouse/Touch events from the X system + * @param status "true" if all the event will be get, false if we want only ours. + * @param forcedPosition the position where the mouse might be reset at every events ... */ public void grabPointerEvents(final boolean status, final Vector2f forcedPosition) {} /** - * @brief The Application request that the Windows will be Hidden. + * The Application request that the Windows will be Hidden. */ public void hide() { Log.info("hide: NOT implemented ..."); @@ -224,14 +224,14 @@ public abstract class Context { } /** - * @brief Hide the virtal keyboard (for touch system only) + * Hide the virtal keyboard (for touch system only) */ public void keyboardHide() { Log.info("keyboardHide: NOT implemented ..."); } /** - * @brief display the virtal keyboard (for touch system only) + * display the virtal keyboard (for touch system only) */ public void keyboardShow() { Log.info("keyboardShow: NOT implemented ..."); @@ -242,13 +242,13 @@ public abstract class Context { } /** - * @brief Open an URL on an eternal brother. - * @param _url URL to open. + * Open an URL on an eternal brother. + * @param url URL to open. */ public void openURL(final String url) {} /** - * @brief The current context is set in background (framerate is slowing down (max fps)/5 # 4fps) + * The current context is set in background (framerate is slowing down (max fps)/5 # 4fps) */ public void operatingSystemBackground() { // set the current interface : @@ -262,8 +262,8 @@ public abstract class Context { } /** - * @brief Call by the OS when a clipboard arrive to US (previously requested by a widget) - * @param Id of the clipboard + * Call by the OS when a clipboard arrive to US (previously requested by a widget) + * @param clipboardID of the clipboard */ public void operatingSystemClipBoardArrive(final ClipboardList clipboardID) { postAction((context) -> { @@ -297,7 +297,7 @@ public abstract class Context { OpenGL.threadHasContext(); OpenGL.resetFlagState(); // process the events - if (this.displayFps == true) { + if (this.displayFps) { this.fpsSystemEvent.tic(); } boolean needRedraw = false; @@ -333,52 +333,52 @@ public abstract class Context { { // Lock openGl context: OpenGL.lock(); - if (this.displayFps == true) { + if (this.displayFps) { this.fpsSystemContext.tic(); } - if (needRedraw = true || displayEveryTime == true) { + if (needRedraw || displayEveryTime) { //Log.debug(" ==> real Draw"); lockContext(); this.resourceManager.updateContext(); unLockContext(); - if (this.displayFps == true) { + if (this.displayFps) { this.fpsSystemContext.incrementCounter(); } } - if (this.displayFps == true) { + if (this.displayFps) { this.fpsSystemContext.toc(); this.fpsSystem.tic(); } if (this.application != null) { - if (needRedraw == true || displayEveryTime == true) { + if (needRedraw || displayEveryTime) { this.fpsSystem.incrementCounter(); // set the current interface : lockContext(); - if (this.application.canDraw == true) { + if (this.application.canDraw) { this.application.onDraw(this); } unLockContext(); hasDisplayDone = true; } } - if (this.displayFps == true) { + if (this.displayFps) { this.fpsSystem.toc(); this.fpsFlush.tic(); } - if (hasDisplayDone == true) { - //Log.info("lklklklklk " << _displayEveryTime); - if (this.displayFps == true) { + if (hasDisplayDone) { + //Log.info("lklklklklk " << displayEveryTime); + if (this.displayFps) { this.fpsFlush.incrementCounter(); } OpenGL.flush(); } - if (this.displayFps == true) { + if (this.displayFps) { this.fpsFlush.toc(); } // release open GL Context OpenGL.unLock(); } - if (this.displayFps == true) { + if (this.displayFps) { this.fpsSystemEvent.draw(); this.fpsSystemContext.draw(); this.fpsSystem.draw(); @@ -403,7 +403,7 @@ public abstract class Context { }; /** - * @brief The current context is set in foreground (framerate is maximum speed) + * The current context is set in foreground (framerate is maximum speed) */ public void operatingSystemForeground() { // set the current interface : @@ -418,35 +418,35 @@ public abstract class Context { } /** - * @brief The OS inform that the Windows is now Hidden. + * The OS inform that the Windows is now Hidden. */ public void operatingSystemHide() { postAction((context) -> { /* - Application> appl = _context.getApplication(); + Application> appl = context.getApplication(); if (appl == null) { return; } - appl.onKeyboard(_special, - _type, - _char, - _state); + appl.onKeyboard(special, + type, + char, + state); */ Log.todo("HIDE ... "); }); }; /** - * @brief The OS inform that the current windows has change his position. - * @param _pos New position of the Windows. + * The OS inform that the current windows has change his position. + * @param pos New position of the Windows. */ - public void operatingSystemMove(final Vector2f _pos) { - if (this.windowsPos.isEqual(_pos)) { + public void operatingSystemMove(final Vector2f pos) { + if (this.windowsPos.isEqual(pos)) { return; } postAction((context) -> { - Log.debug("Receive MSG : THREAD_MOVE : " + context.windowsPos + " ==> " + _pos); - context.windowsPos = _pos; + Log.debug("Receive MSG : THREADMOVE : " + context.windowsPos + " ==> " + pos); + context.windowsPos = pos; final Application appl = context.getApplication(); if (appl == null) { return; @@ -456,26 +456,26 @@ public abstract class Context { } /** - * @brief The OS inform that the openGL ext has been destroy == > use to automaticly reload the texture and other thinks ... + * The OS inform that the openGL ext has been destroy == > use to automaticly reload the texture and other thinks ... */ public void operatingSystemOpenGlContextDestroy() { this.resourceManager.contextHasBeenDestroyed(); }; /** - * @brief The OS inform that the current windows has change his size. - * @param _size new size of the windows. + * The OS inform that the current windows has change his size. + * @param size new size of the windows. */ - public void operatingSystemResize(final Vector2f _size) { - if (this.windowsSize == _size) { + public void operatingSystemResize(final Vector2f size) { + if (this.windowsSize == size) { return; } // TODO Better in the thread ... ==> but generate some init error ... - //gale::Dimension::setPixelWindowsSize(_size); + //gale::Dimension::setPixelWindowsSize(size); postAction((context) -> { - Log.debug("Receive MSG : THREAD_RESIZE : " + context.windowsSize + " ==> " + _size); - context.windowsSize = _size; - //gale::Dimension::setPixelWindowsSize(_context.windowsSize); + Log.debug("Receive MSG : THREADRESIZE : " + context.windowsSize + " ==> " + size); + context.windowsSize = size; + //gale::Dimension::setPixelWindowsSize(context.windowsSize); final Application tmpAppl = context.getApplication(); if (tmpAppl != null) { tmpAppl.onResize(context.windowsSize); @@ -486,7 +486,7 @@ public abstract class Context { }; /** - * @brief The current context is resumed + * The current context is resumed */ public void operatingSystemResume() { // set the current interface : @@ -517,11 +517,11 @@ public abstract class Context { public void operatingSystemsetKeyboard(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final boolean isARepeateKey, final Character charValue) { KeyStatus tmpState = state; - if (isARepeateKey == true) { + if (isARepeateKey) { if (tmpState == KeyStatus.down) { - tmpState = KeyStatus.downRepeate; + tmpState = KeyStatus.downRepeat; } else { - tmpState = KeyStatus.upRepeate; + tmpState = KeyStatus.upRepeat; } } operatingSystemsetKeyboard2(special, type, state, charValue); @@ -538,26 +538,26 @@ public abstract class Context { } /** - * @brief The OS inform that the Windows is now visible. + * The OS inform that the Windows is now visible. */ public void operatingSystemShow() { postAction((context) -> { /* - Application> appl = _context.getApplication(); + Application> appl = context.getApplication(); if (appl == null) { return; } - appl.onKeyboard(_special, - _type, - _char, - _state); + appl.onKeyboard(special, + type, + char, + state); */ Log.todo("SHOW ... "); }); }; /** - * @brief The OS Inform that the Window has been killed + * The OS Inform that the Window has been killed */ public void operatingSystemStop() { // set the current interface : @@ -573,7 +573,7 @@ public abstract class Context { } /** - * @brief The current context is suspended + * The current context is suspended */ public void operatingSystemSuspend() { // set the current interface : @@ -595,7 +595,7 @@ public abstract class Context { } /** - * @brief Processing all the event arrived ... (commoly called in draw function) + * Processing all the event arrived ... (commoly called in draw function) */ public void processEvents() { int nbEvent = 0; @@ -648,63 +648,63 @@ public abstract class Context { // } public void requestUpdateSize() { postAction((context) -> { - //Log.debug("Receive MSG : THREAD_RESIZE"); + //Log.debug("Receive MSG : THREADRESIZE"); context.forceRedrawAll(); }); } /** - * @brief reset event management for the IO like Input ou Mouse or keyborad + * reset event management for the IO like Input ou Mouse or keyborad */ public void resetIOEvent() { // TODO this.input.newLayerSet(); } /** - * @brief Internal API to run the processing of the event loop ... + * Internal API to run the processing of the event loop ... * @return The Exit value of the program * @note INTERNAL API */ public abstract int run(); /** - * @brief set the cursor display type. - * @param NewCursor selected new cursor. + * set the cursor display type. + * @param newCursor selected new cursor. */ public void setCursor(final Cursor newCursor) {} /** - * @brief The application request a change of his current size force the fullscreen mode. - * @param _status status of the fullscreen mode. + * The application request a change of his current size force the fullscreen mode. + * @param status status of the fullscreen mode. */ public void setFullScreen(final boolean status) { this.fullscreen = status; } /** - * @brief set the Icon of the program - * @param _inputFile new filename icon of the current program. + * set the Icon of the program + * @param inputFile new filename icon of the current program. */ public void setIcon(final Uri inputFile) {}; /** - * @brief The Application request that the current windows will change his position. - * @param _pos New position of the Windows requested. + * The Application request that the current windows will change his position. + * @param pos New position of the Windows requested. */ public void setPos(final Vector2f pos) { Log.info("setPos: NOT implemented ..."); }; /** - * @brief The application request a change of his current size. - * @param _size new Requested size of the windows. + * The application request a change of his current size. + * @param size new Requested size of the windows. */ public void setSize(final Vector2f size) { Log.info("setSize: NOT implemented ..."); } /** - * @brief set the new title of the windows + * set the new title of the windows * @param title New desired title */ public void setTitle(final String title) { @@ -712,20 +712,20 @@ public abstract class Context { }; /** - * @brief Enable or Disable the decoration on the Windows (availlable only on Desktop) - * @param _status "true" to enable decoration / false otherwise + * Enable or Disable the decoration on the Windows (availlable only on Desktop) + * @param status "true" to enable decoration / false otherwise */ public void setWindowsDecoration(final boolean status) {}; /** - * @brief The Application request that the Windows will be visible. + * The Application request that the Windows will be visible. */ public void show() { Log.info("show: NOT implemented ..."); }; /** - * @brief StartProcessing (2nd thread). + * StartProcessing (2nd thread). * @note to call when all the Context is started */ public void start2ndThreadProcessing() { @@ -743,7 +743,7 @@ public abstract class Context { }; /** - * @brief The application request that the Window will be killed + * The application request that the Window will be killed */ public void stop() { Log.warning("stop: NOT implemented for this platform..."); diff --git a/src/org/atriasoft/gale/context/LWJG_AWT/ContextLWJGLAWT.java b/src/org/atriasoft/gale/context/LWJG_AWT/ContextLWJGLAWT.java index b9afefb..fc8b963 100644 --- a/src/org/atriasoft/gale/context/LWJG_AWT/ContextLWJGLAWT.java +++ b/src/org/atriasoft/gale/context/LWJG_AWT/ContextLWJGLAWT.java @@ -1,5 +1,8 @@ package org.atriasoft.gale.context.LWJG_AWT; +import static org.lwjgl.opengl.GL.createCapabilities; +import static org.lwjgl.opengl.GL11.glClearColor; + import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Cursor; @@ -7,6 +10,7 @@ import java.awt.Dimension; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; +import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; @@ -18,7 +22,6 @@ import java.awt.event.MouseWheelListener; import java.awt.image.MemoryImageSource; import java.util.ArrayList; import java.util.List; -import java.awt.Robot; import javax.swing.JFrame; import javax.swing.SwingUtilities; @@ -29,11 +32,11 @@ import org.atriasoft.gale.Application; import org.atriasoft.gale.DisplayManagerDraw; import org.atriasoft.gale.Fps; import org.atriasoft.gale.context.Context; +import org.atriasoft.gale.internal.Log; import org.atriasoft.gale.key.KeyKeyboard; import org.atriasoft.gale.key.KeySpecial; import org.atriasoft.gale.key.KeyStatus; import org.atriasoft.gale.key.KeyType; -import org.atriasoft.gale.internal.Log; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.awt.AWTGLCanvas; //import org.lwjgl.Version; @@ -43,220 +46,67 @@ import org.lwjgl.opengl.awt.AWTGLCanvas; //import org.lwjgl.system.MemoryStack; import org.lwjgl.opengl.awt.GLData; -import static org.lwjgl.opengl.GL.createCapabilities; -import static org.lwjgl.opengl.GL11.glClearColor; - public class ContextLWJGLAWT extends Context implements MouseListener, MouseMotionListener, KeyListener, MouseWheelListener { - private boolean[] inputIsPressed = new boolean[MAX_MANAGE_INPUT]; - private Vector2f decoratedWindowsSize = new Vector2f(0, 0); - private Vector2f cursorPos = new Vector2f(0, 0); - private Vector2f cursorSize = new Vector2f(0, 0); private static final int WIDTH = 800; private static final int HEIGHT = 600; + private static final int MAX_MANAGE_INPUT = 15; private static final String TITLE = "Gale basic UI"; - private static long lastFrameTime; private static float delta; - - private Fps fps = new Fps("Main Loop", true); - - private DisplayManagerDraw drawer = null; private static double whellOffsetY; private static double whellOffsetX; + private static boolean rightButtonStateDown = false; private static boolean leftButtonStateDown = false; + private static double lastMousePositionX = 0; + private static double lastMousePositionY = 0; private static double currentMousePositionX = 0; private static double currentMousePositionY = 0; - - // The window handle - private long window = 0; - private KeySpecial guiKeyBoardMode = new KeySpecial(); + public static Context create(final Application application, final String[] arg) { + // TODO Auto-generated method stub + return new ContextLWJGLAWT(application, arg); + } + + private static long getCurrentTime() { + return System.currentTimeMillis(); + } + + public static float getFrameTimeSecconds() { + return delta; + } + + private final boolean[] inputIsPressed = new boolean[MAX_MANAGE_INPUT]; + private Vector2f decoratedWindowsSize = Vector2f.ZERO; + private Vector2f cursorPos = Vector2f.ZERO; + + private final Vector2f cursorSize = Vector2f.ZERO; + private final Fps fps = new Fps("Main Loop", true); + + private DisplayManagerDraw drawer = null; + // The window handle + private final long window = 0; + private final KeySpecial guiKeyBoardMode = new KeySpecial(); // Generic UI properties private JFrame frame; private GLData glData; + private AWTGLCanvas canvas; + private Robot robot = null; - public ContextLWJGLAWT(Application application, String[] args) { + + private final List pressedKey = new ArrayList<>(); + + public ContextLWJGLAWT(final Application application, final String[] args) { super(application, args); System.out.println("Hello JOGL !"); initWindows(); start2ndThreadProcessing(); } - - public void setDrawer(DisplayManagerDraw drawer) { - this.drawer = drawer; - } - - public void unInit() { - - } - - @SuppressWarnings("serial") - private void initWindows() { - frame = new JFrame("Gale base"); - frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - frame.setLayout(new BorderLayout()); - frame.setPreferredSize(new Dimension(800, 600)); - glData = new GLData(); - glData.samples = 4; - glData.swapInterval = 0; - frame.add(canvas = new AWTGLCanvas(glData) { - public void initGL() { - System.out.println("OpenGL version: " + effective.majorVersion + "." + effective.minorVersion + " (Profile: " + effective.profile + ")"); - createCapabilities(); - glClearColor(0.3f, 0.4f, 0.5f, 1); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - } - public void paintGL() { - //Log.warning("Draw ... "); - int w = getWidth(); - int h = getHeight(); - if (decoratedWindowsSize.x != w || decoratedWindowsSize.y != h) { - decoratedWindowsSize.x = w; - decoratedWindowsSize.y = h; - Rectangle bounds = canvas.getBounds(); - windowsSize.x = bounds.width; - windowsSize.y = bounds.height; - operatingSystemResize(windowsSize); - } - operatingSystemDraw(true); - swapBuffers(); - } - }, BorderLayout.CENTER); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - canvas.requestFocus(); - canvas.addMouseListener(this); - canvas.addMouseMotionListener(this); - canvas.addKeyListener(this); - canvas.addMouseWheelListener(this); - frame.transferFocus(); - - lastFrameTime = getCurrentTime(); - - } - @Override - public void mouseClicked(MouseEvent e) { -// System.out.println(e.getX()); -// System.out.println(e.getY()); - Log.info("Mouse clicked:" + e.getX() + " " + e.getY()); - } - @Override - public void mouseEntered(MouseEvent e) { - // TODO Auto-generated method stub - //Log.info("Mouse entered:" + e.getX() + " " + e.getY()); - cursorPos.x = e.getX(); - cursorPos.y = e.getY(); - operatingSystemSetInput(guiKeyBoardMode, - KeyType.mouse, - KeyStatus.enter, - 0, - cursorPos); - } - @Override - public void mouseExited(MouseEvent e) { - // TODO Auto-generated method stub - //Log.info("Mouse exited:" + e.getX() + " " + e.getY()); - cursorPos.x = e.getX(); - cursorPos.y = e.getY(); - operatingSystemSetInput(guiKeyBoardMode, - KeyType.mouse, - KeyStatus.leave, - 0, - cursorPos); - //this.frame.mouseMove(e, 200, 200); - } - @Override - public void mousePressed(MouseEvent e) { - Log.info("Mouse pressed:" + e.getX() + " " + e.getY()); - int button = e.getButton(); - cursorPos.x = e.getX(); - cursorPos.y = e.getY(); - if (button < MAX_MANAGE_INPUT) { - inputIsPressed[button] = true; - } - operatingSystemSetInput(guiKeyBoardMode, - KeyType.mouse, - KeyStatus.down, - button, - cursorPos); - } - @Override - public void mouseReleased(MouseEvent e) { - //Log.info("Mouse release:" + e.getX() + " " + e.getY()); -// Log.info("mouse value: GLFW_RELEASE" + action + " bt=" + button); - int button = e.getButton(); - cursorPos.x = e.getX(); - cursorPos.y = e.getY(); - if (button < MAX_MANAGE_INPUT) { - inputIsPressed[button] = false; - } - operatingSystemSetInput(guiKeyBoardMode, - KeyType.mouse, - KeyStatus.up, - button, - cursorPos); - } - - @Override - public void mouseDragged(MouseEvent e) { - //Log.error("mouse drag ... " + e); - mouseMoved(e); - } - public void mouseMoved(MouseEvent e) { - //Log.info("Mouse moved:" + e.getX() + " " + e.getY() + " " + e); - if (this.robot != null) { - Rectangle bounds = frame.getBounds(); - //Log.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize); - float refPosX = bounds.x + bounds.width/2; - float refPosY = bounds.y + bounds.height/2; - if (e.getXOnScreen() == (int)refPosX - && e.getYOnScreen() == (int)refPosY) { - cursorPos.x = 0; - cursorPos.y = 0; - return; - } else { - //Log.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize); - cursorPos.x = -((float)e.getXOnScreen() - refPosX); - cursorPos.y = (float)e.getYOnScreen() - refPosY; - robot.mouseMove((int)refPosX, (int)refPosY); - } - Log.info("delta moved:" + cursorPos); - } else { - // TODO use real size ... !!!! - cursorPos.x = (float)e.getX(); - cursorPos.y = cursorSize.y - (float)e.getY(); - } - // For compatibility of the Android system : - boolean findOne = false; - for (int iii=0; iii pressedKey = new ArrayList(); - - private int getUniqueIndex(KeyEvent e) { + private int getUniqueIndex(final KeyEvent e) { int internalKeyValue = e.getKeyCode(); if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { internalKeyValue += 100000000; @@ -269,323 +119,14 @@ public class ContextLWJGLAWT extends Context implements MouseListener, MouseMoti } return internalKeyValue; } - public void keyPressed(KeyEvent e) { - int internalKeyValue = getUniqueIndex(e); - int index = pressedKey.indexOf(internalKeyValue); - if (index == -1) { - pressedKey.add(internalKeyValue); - } - keyEvent(e, true, index != -1); - } - public void keyReleased(KeyEvent e) { - int internalKeyValue = getUniqueIndex(e); - int index = pressedKey.indexOf(internalKeyValue); - if (index == -1) { - pressedKey.remove(internalKeyValue); - } - keyEvent(e, false, false); - } - public void keyEvent(KeyEvent e, boolean pressed, boolean thisIsAReapeateKey) { - //Log.info("event " + thisIsAReapeateKey + " " + e.getKeyCode() + " " + e); - boolean find = true; - KeyKeyboard keyInput = KeyKeyboard.unknow; - //Log.error("keyboard input " + e.getWhen() + " " + e.getKeyCode() + " " + e.getKeyLocation()); - switch (e.getKeyCode()) { - //case 328: // keypad - case KeyEvent.VK_UP: keyInput = KeyKeyboard.up; break; - //case 324: // keypad - case KeyEvent.VK_LEFT: keyInput = KeyKeyboard.left; break; - //case 326: // keypad - case KeyEvent.VK_RIGHT: keyInput = KeyKeyboard.right; break; - //case 323: // keypad - case KeyEvent.VK_DOWN: keyInput = KeyKeyboard.down; break; - //case 329: // keypad - case KeyEvent.VK_PAGE_UP: keyInput = KeyKeyboard.pageUp; break; - //case 323: // keypad - case KeyEvent.VK_PAGE_DOWN: keyInput = KeyKeyboard.pageDown; break; - //case 327: // keypad - case KeyEvent.VK_HOME: keyInput = KeyKeyboard.start; break; - //case 321: // keypad - case KeyEvent.VK_END: keyInput = KeyKeyboard.end; break; - case KeyEvent.VK_PRINTSCREEN:keyInput = KeyKeyboard.stopDefil; break; - case KeyEvent.VK_PAUSE: keyInput = KeyKeyboard.wait; break; - //case 320: // keypad - case KeyEvent.VK_INSERT: - keyInput = KeyKeyboard.insert; - if(pressed == false) { - if (guiKeyBoardMode.getInsert() == true) { - guiKeyBoardMode.setInsert(false); - } else { - guiKeyBoardMode.setInsert(true); - } - } - break; - //case 84: keyInput = KeyboardCenter; break; // Keypad - case KeyEvent.VK_F1: keyInput = KeyKeyboard.f1; break; - case KeyEvent.VK_F2: keyInput = KeyKeyboard.f2; break; - case KeyEvent.VK_F3: keyInput = KeyKeyboard.f3; break; - case KeyEvent.VK_F4: keyInput = KeyKeyboard.f4; break; - case KeyEvent.VK_F5: keyInput = KeyKeyboard.f5; break; - case KeyEvent.VK_F6: keyInput = KeyKeyboard.f6; break; - case KeyEvent.VK_F7: keyInput = KeyKeyboard.f7; break; - case KeyEvent.VK_F8: keyInput = KeyKeyboard.f8; break; - case KeyEvent.VK_F9: keyInput = KeyKeyboard.f9; break; - case KeyEvent.VK_F10: keyInput = KeyKeyboard.f10; break; - case KeyEvent.VK_F11: keyInput = KeyKeyboard.f11; break; - case KeyEvent.VK_F12: keyInput = KeyKeyboard.f12; break; - case KeyEvent.VK_CAPS_LOCK: - keyInput = KeyKeyboard.capLock; - guiKeyBoardMode.setCapsLock(pressed == true); - break; - case KeyEvent.VK_SHIFT: - if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { - keyInput = KeyKeyboard.shiftLeft; guiKeyBoardMode.setShiftLeft (pressed == true); break; - } else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) { - keyInput = KeyKeyboard.shiftLeft; guiKeyBoardMode.setShiftRight (pressed == true); break; - } - case KeyEvent.VK_CONTROL: - if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { - keyInput = KeyKeyboard.ctrlLeft; guiKeyBoardMode.setCtrlLeft (pressed == true); break; - } else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) { - keyInput = KeyKeyboard.ctrlRight; guiKeyBoardMode.setCtrlRight (pressed == true); break; - } - case KeyEvent.VK_META: - if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { - keyInput = KeyKeyboard.metaLeft; guiKeyBoardMode.setMetaLeft (pressed == true); break; - } else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) { - keyInput = KeyKeyboard.metaRight; guiKeyBoardMode.setMetaRight (pressed == true); break; - } - case KeyEvent.VK_ALT: - keyInput = KeyKeyboard.altLeft; - guiKeyBoardMode.setAltLeft(pressed == true); - break; - case KeyEvent.VK_ALT_GRAPH: - keyInput = KeyKeyboard.altRight; - guiKeyBoardMode.setAltRight(pressed == true); - break; - case KeyEvent.VK_CONTEXT_MENU: - keyInput = KeyKeyboard.contextMenu; - break; - case KeyEvent.VK_NUM_LOCK: - keyInput = KeyKeyboard.numLock; - guiKeyBoardMode.setNumLock(pressed == true); - break; - case KeyEvent.VK_DELETE: // Suppr on keypad - find = false; - if(guiKeyBoardMode.getNumLock() == true){ - if (thisIsAReapeateKey == true) { - operatingSystemsetKeyboard(guiKeyBoardMode, - KeyKeyboard.character, - (pressed != true?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey, - '.'); - } - operatingSystemsetKeyboard(guiKeyBoardMode, - KeyKeyboard.character, - (pressed == true?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey, - '.'); - } else { - if (thisIsAReapeateKey == true) { - operatingSystemsetKeyboard(guiKeyBoardMode, - KeyKeyboard.character, - (pressed != true?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey, - (char)0x7F); - } - operatingSystemsetKeyboard(guiKeyBoardMode, - KeyKeyboard.character, - (pressed == true?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey, - (char)0x7F); - } - break; - case KeyEvent.VK_TAB: // special case for TAB - find = false; - if (thisIsAReapeateKey == true) { - operatingSystemsetKeyboard(guiKeyBoardMode, - KeyKeyboard.character, - (pressed==false?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey, - (char)0x09); - } - operatingSystemsetKeyboard(guiKeyBoardMode, - KeyKeyboard.character, - (pressed == true?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey, - (char)0x09); - break; - default: - find = false; - if (thisIsAReapeateKey == true) { - operatingSystemsetKeyboard(guiKeyBoardMode, - KeyKeyboard.character, - (pressed==false?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey, - e.getKeyChar()); - } - operatingSystemsetKeyboard(guiKeyBoardMode, - KeyKeyboard.character, - (pressed==true?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey, - e.getKeyChar()); - } - if (find == true) { - if (thisIsAReapeateKey == true) { - operatingSystemsetKeyboard(guiKeyBoardMode, - keyInput, - (pressed==false?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey); - } - operatingSystemsetKeyboard(guiKeyBoardMode, - keyInput, - (pressed == true?KeyStatus.down:KeyStatus.up), - thisIsAReapeateKey); - } - } - - public void keyTyped(KeyEvent e) { - // not needed with my model ... - //Log.info(" typed " + e.getKeyChar() + " " + e); - } - - - - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - //Log.info("wheel_event : " + e); - cursorPos.x = e.getX(); - cursorPos.y = e.getY(); - if (e.getWheelRotation()<0) { - inputIsPressed[5] = true; - operatingSystemSetInput(guiKeyBoardMode, - KeyType.mouse, - KeyStatus.down, - 5, - cursorPos); - inputIsPressed[5] = false; - operatingSystemSetInput(guiKeyBoardMode, - KeyType.mouse, - KeyStatus.up, - 5, - cursorPos); - } else if (e.getWheelRotation()>0) { - inputIsPressed[4] = true; - operatingSystemSetInput(guiKeyBoardMode, - KeyType.mouse, - KeyStatus.down, - 4, - cursorPos); - inputIsPressed[4] = false; - operatingSystemSetInput(guiKeyBoardMode, - KeyType.mouse, - KeyStatus.up, - 4, - cursorPos); - } - } - public static float getFrameTimeSecconds() { - return delta; - } - private static long getCurrentTime() { - return System.currentTimeMillis(); - } - @Override - public int run() { - Runnable renderLoop = new Runnable() { - public void run() { -// fps.tic(); - if (!canvas.isValid()) { - System.exit(0); - return; - } - canvas.render(); -// fps.toc(); -// fps.draw(); - SwingUtilities.invokeLater(this); - } - }; - SwingUtilities.invokeLater(renderLoop); - - -// while (canvas != null && canvas.isValid()) { -// canvas.render(); -// try { -// Thread.sleep(10); -// } catch (InterruptedException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - // Run the rendering loop until the user has attempted to close - // the window or has pressed the ESCAPE key. -// while ( !glfwWindowShouldClose(window) ) { -// /* -// fps.tic(); -// long currentFrameTime = getCurrentTime(); -// delta = (currentFrameTime-lastFrameTime)/1000f; -// lastFrameTime = currentFrameTime; -// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer -// if (this.drawer != null) { -// fps.incrementCounter(); -// this.drawer.draw(); -// } -// lastMousePositionX = currentMousePositionX; -// lastMousePositionY = currentMousePositionY; -// whellOffsetY = 0; -// whellOffsetY = 0; -// glfwSwapBuffers(window); // swap the color buffers -// // Poll for window events. The key callback above will only be -// // invoked during this call. -// glfwPollEvents(); -// fps.toc(); -// fps.draw(); -// */ -// -// glfwSwapBuffers(window); // swap the color buffers -// glfwPollEvents(); -// /* -// if (specialEventThatNeedARedraw) { -// X11_INFO("specialEventThatNeedARedraw = " << specialEventThatNeedARedraw); -// } -// hasDisplay = operatingSystemDraw(specialEventThatNeedARedraw); -// if (hasDisplay) { -// // need to request it every time needed to have a redrawing (this can take some time if the application filter the drfaw periodicity) -// specialEventThatNeedARedraw = false; -// } -// */ -// } - //System.exit(0); - return 0; - } - /****************************************************************************************/ - @Override - public void setTitle(String title) { - this.frame.setTitle(title); - } - @Override - public void setIcon(Uri inputFile) { - - } - private void hideCursor() { - int[] pixels = new int[16 * 16]; - Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16)); - Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor"); - frame.setCursor(transparentCursor); - } - private void showCursor() { - frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - @Override - public void grabPointerEvents(boolean _status, Vector2f _forcedPosition) { - if (_status == true) { + public void grabPointerEvents(final boolean status, final Vector2f forcedPosition) { + if (status) { try { this.robot = new Robot(); hideCursor(); - } catch (AWTException e) { + } catch (final AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -593,26 +134,478 @@ public class ContextLWJGLAWT extends Context implements MouseListener, MouseMoti this.robot = null; showCursor(); } - }; + } + + private void hideCursor() { + final int[] pixels = new int[16 * 16]; + final Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16)); + final Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor"); + this.frame.setCursor(transparentCursor); + } + + private void initWindows() { + this.frame = new JFrame("Gale base"); + this.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + this.frame.setLayout(new BorderLayout()); + this.frame.setPreferredSize(new Dimension(800, 600)); + this.glData = new GLData(); + this.glData.samples = 4; + this.glData.swapInterval = 0; + this.frame.add(this.canvas = new AWTGLCanvas(this.glData) { + @Override + public void initGL() { + System.out.println("OpenGL version: " + this.effective.majorVersion + "." + this.effective.minorVersion + " (Profile: " + this.effective.profile + ")"); + createCapabilities(); + glClearColor(0.3f, 0.4f, 0.5f, 1); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + } + + @Override + public void paintGL() { + //Log.warning("Draw ... "); + final int w = getWidth(); + final int h = getHeight(); + if (ContextLWJGLAWT.this.decoratedWindowsSize.x() != w || ContextLWJGLAWT.this.decoratedWindowsSize.y() != h) { + ContextLWJGLAWT.this.decoratedWindowsSize = new Vector2f(w, h); + final Rectangle bounds = ContextLWJGLAWT.this.canvas.getBounds(); + ContextLWJGLAWT.this.windowsSize = new Vector2f(bounds.width, bounds.height); + operatingSystemResize(ContextLWJGLAWT.this.windowsSize); + } + operatingSystemDraw(true); + swapBuffers(); + } + }, BorderLayout.CENTER); + this.frame.pack(); + this.frame.setLocationRelativeTo(null); + this.frame.setVisible(true); + this.canvas.requestFocus(); + this.canvas.addMouseListener(this); + this.canvas.addMouseMotionListener(this); + this.canvas.addKeyListener(this); + this.canvas.addMouseWheelListener(this); + this.frame.transferFocus(); + + lastFrameTime = getCurrentTime(); + + } + @Override - public boolean isGrabPointerEvents() { return this.robot != null; }; - @Override - public void setFullScreen(boolean status){ - super.setFullScreen(status); - if (status == true) { - frame.setExtendedState(JFrame.MAXIMIZED_BOTH); - frame.setUndecorated(true); - } else { - frame.setExtendedState(JFrame.NORMAL); - frame.setUndecorated(false); + public boolean isGrabPointerEvents() { + return this.robot != null; + } + + public void keyEvent(final KeyEvent e, final boolean pressed, final boolean thisIsAReapeateKey) { + //Log.info("event " + thisIsAReapeateKey + " " + e.getKeyCode() + " " + e); + boolean find = true; + KeyKeyboard keyInput = KeyKeyboard.unknow; + //Log.error("keyboard input " + e.getWhen() + " " + e.getKeyCode() + " " + e.getKeyLocation()); + switch (e.getKeyCode()) { + //case 328: // keypad + case KeyEvent.VK_UP: + keyInput = KeyKeyboard.up; + break; + //case 324: // keypad + case KeyEvent.VK_LEFT: + keyInput = KeyKeyboard.left; + break; + //case 326: // keypad + case KeyEvent.VK_RIGHT: + keyInput = KeyKeyboard.right; + break; + //case 323: // keypad + case KeyEvent.VK_DOWN: + keyInput = KeyKeyboard.down; + break; + //case 329: // keypad + case KeyEvent.VK_PAGE_UP: + keyInput = KeyKeyboard.pageUp; + break; + //case 323: // keypad + case KeyEvent.VK_PAGE_DOWN: + keyInput = KeyKeyboard.pageDown; + break; + //case 327: // keypad + case KeyEvent.VK_HOME: + keyInput = KeyKeyboard.start; + break; + //case 321: // keypad + case KeyEvent.VK_END: + keyInput = KeyKeyboard.end; + break; + case KeyEvent.VK_PRINTSCREEN: + keyInput = KeyKeyboard.stopDefil; + break; + case KeyEvent.VK_PAUSE: + keyInput = KeyKeyboard.wait; + break; + //case 320: // keypad + case KeyEvent.VK_INSERT: + keyInput = KeyKeyboard.insert; + if (!pressed) { + if (this.guiKeyBoardMode.getInsert()) { + this.guiKeyBoardMode.setInsert(false); + } else { + this.guiKeyBoardMode.setInsert(true); + } + } + break; + //case 84: keyInput = KeyboardCenter; break; // Keypad + case KeyEvent.VK_F1: + keyInput = KeyKeyboard.f1; + break; + case KeyEvent.VK_F2: + keyInput = KeyKeyboard.f2; + break; + case KeyEvent.VK_F3: + keyInput = KeyKeyboard.f3; + break; + case KeyEvent.VK_F4: + keyInput = KeyKeyboard.f4; + break; + case KeyEvent.VK_F5: + keyInput = KeyKeyboard.f5; + break; + case KeyEvent.VK_F6: + keyInput = KeyKeyboard.f6; + break; + case KeyEvent.VK_F7: + keyInput = KeyKeyboard.f7; + break; + case KeyEvent.VK_F8: + keyInput = KeyKeyboard.f8; + break; + case KeyEvent.VK_F9: + keyInput = KeyKeyboard.f9; + break; + case KeyEvent.VK_F10: + keyInput = KeyKeyboard.f10; + break; + case KeyEvent.VK_F11: + keyInput = KeyKeyboard.f11; + break; + case KeyEvent.VK_F12: + keyInput = KeyKeyboard.f12; + break; + case KeyEvent.VK_CAPS_LOCK: + keyInput = KeyKeyboard.capLock; + this.guiKeyBoardMode.setCapsLock(pressed); + break; + case KeyEvent.VK_SHIFT: + if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { + keyInput = KeyKeyboard.shiftLeft; + this.guiKeyBoardMode.setShiftLeft(pressed); + break; + } else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) { + keyInput = KeyKeyboard.shiftLeft; + this.guiKeyBoardMode.setShiftRight(pressed); + break; + } + case KeyEvent.VK_CONTROL: + if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { + keyInput = KeyKeyboard.ctrlLeft; + this.guiKeyBoardMode.setCtrlLeft(pressed); + break; + } else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) { + keyInput = KeyKeyboard.ctrlRight; + this.guiKeyBoardMode.setCtrlRight(pressed); + break; + } + case KeyEvent.VK_META: + if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { + keyInput = KeyKeyboard.metaLeft; + this.guiKeyBoardMode.setMetaLeft(pressed); + break; + } else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) { + keyInput = KeyKeyboard.metaRight; + this.guiKeyBoardMode.setMetaRight(pressed); + break; + } + case KeyEvent.VK_ALT: + keyInput = KeyKeyboard.altLeft; + this.guiKeyBoardMode.setAltLeft(pressed); + break; + case KeyEvent.VK_ALT_GRAPH: + keyInput = KeyKeyboard.altRight; + this.guiKeyBoardMode.setAltRight(pressed); + break; + case KeyEvent.VK_CONTEXT_MENU: + keyInput = KeyKeyboard.contextMenu; + break; + case KeyEvent.VK_NUM_LOCK: + keyInput = KeyKeyboard.numLock; + this.guiKeyBoardMode.setNumLock(pressed); + break; + case KeyEvent.VK_DELETE: // Suppr on keypad + find = false; + if (this.guiKeyBoardMode.getNumLock()) { + if (thisIsAReapeateKey) { + operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.character, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.'); + } + operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.character, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.'); + } else { + if (thisIsAReapeateKey) { + operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.character, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F); + } + operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.character, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F); + } + break; + case KeyEvent.VK_TAB: // special case for TAB + find = false; + if (thisIsAReapeateKey) { + operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.character, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09); + } + operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.character, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09); + break; + default: + find = false; + if (thisIsAReapeateKey) { + operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.character, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar()); + } + operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.character, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar()); } + if (find) { + if (thisIsAReapeateKey) { + operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey); + } + operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey); + } + } + + @Override + public void keyPressed(final KeyEvent e) { + final int internalKeyValue = getUniqueIndex(e); + final int index = this.pressedKey.indexOf(internalKeyValue); + if (index == -1) { + this.pressedKey.add(internalKeyValue); + } + keyEvent(e, true, index != -1); + } + + @Override + public void keyReleased(final KeyEvent e) { + final int internalKeyValue = getUniqueIndex(e); + final int index = this.pressedKey.indexOf(internalKeyValue); + if (index == -1) { + this.pressedKey.remove(internalKeyValue); + } + keyEvent(e, false, false); + } + + @Override + public void keyTyped(final KeyEvent e) { + // not needed with my model ... + //Log.info(" typed " + e.getKeyChar() + " " + e); + } + + @Override + public void mouseClicked(final MouseEvent e) { + // System.out.println(e.getX()); + // System.out.println(e.getY()); + Log.info("Mouse clicked:" + e.getX() + " " + e.getY()); + } + + @Override + public void mouseDragged(final MouseEvent e) { + //Log.error("mouse drag ... " + e); + mouseMoved(e); + } + + @Override + public void mouseEntered(final MouseEvent e) { + // TODO Auto-generated method stub + //Log.info("Mouse entered:" + e.getX() + " " + e.getY()); + this.cursorPos = new Vector2f(e.getX(), e.getY()); + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.enter, 0, this.cursorPos); + } + + @Override + public void mouseExited(final MouseEvent e) { + // TODO Auto-generated method stub + //Log.info("Mouse exited:" + e.getX() + " " + e.getY()); + this.cursorPos = new Vector2f(e.getX(), e.getY()); + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.leave, 0, this.cursorPos); + //this.frame.mouseMove(e, 200, 200); + } + + @Override + public void mouseMoved(final MouseEvent e) { + //Log.info("Mouse moved:" + e.getX() + " " + e.getY() + " " + e); + if (this.robot != null) { + final Rectangle bounds = this.frame.getBounds(); + //Log.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize); + final float refPosX = bounds.x + bounds.width / 2.0f; + final float refPosY = bounds.y + bounds.height / 2.0f; + if (e.getXOnScreen() == (int) refPosX && e.getYOnScreen() == (int) refPosY) { + this.cursorPos = Vector2f.ZERO; + return; + } else { + //Log.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize); + this.cursorPos = new Vector2f(-(e.getXOnScreen() - refPosX), e.getYOnScreen() - refPosY); + this.robot.mouseMove((int) refPosX, (int) refPosY); + } + Log.info("delta moved:" + this.cursorPos); + } else { + // TODO use real size ... !!!! + this.cursorPos = new Vector2f(e.getX(), this.cursorSize.y() - e.getY()); + } + // For compatibility of the Android system : + boolean findOne = false; + for (int iii = 0; iii < MAX_MANAGE_INPUT; iii++) { + if (this.inputIsPressed[iii]) { + //Log.debug("X11 event: bt=" << iii << " " << event.type << " = \"MotionNotify\" (" << m_cursorEventX << "," << m_cursorEventY << ")"); + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.move, iii, this.cursorPos); + findOne = true; + } + } + if (!findOne) { + //X11_DEBUG("X11 event: bt=" << 0 << " " << event.type << " = \"MotionNotify\" (" << m_cursorEventX << "," << m_cursorEventY << ")"); + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.move, 0, this.cursorPos); + } + } + + @Override + public void mousePressed(final MouseEvent e) { + Log.info("Mouse pressed:" + e.getX() + " " + e.getY()); + final int button = e.getButton(); + this.cursorPos = new Vector2f(e.getX(), e.getY()); + if (button < MAX_MANAGE_INPUT) { + this.inputIsPressed[button] = true; + } + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.down, button, this.cursorPos); + } + + @Override + public void mouseReleased(final MouseEvent e) { + //Log.info("Mouse release:" + e.getX() + " " + e.getY()); + // Log.info("mouse value: GLFW_RELEASE" + action + " bt=" + button); + final int button = e.getButton(); + this.cursorPos = new Vector2f(e.getX(), e.getY()); + if (button < MAX_MANAGE_INPUT) { + this.inputIsPressed[button] = false; + } + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, button, this.cursorPos); + } + + @Override + public void mouseWheelMoved(final MouseWheelEvent e) { + //Log.info("wheel_event : " + e); + this.cursorPos = new Vector2f(e.getX(), e.getY()); + if (e.getWheelRotation() < 0) { + this.inputIsPressed[5] = true; + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.down, 5, this.cursorPos); + this.inputIsPressed[5] = false; + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, 5, this.cursorPos); + } else if (e.getWheelRotation() > 0) { + this.inputIsPressed[4] = true; + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.down, 4, this.cursorPos); + this.inputIsPressed[4] = false; + operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, 4, this.cursorPos); + } + } + + @Override + public int run() { + final Runnable renderLoop = new Runnable() { + @Override + public void run() { + // fps.tic(); + if (!ContextLWJGLAWT.this.canvas.isValid()) { + System.exit(0); + return; + } + ContextLWJGLAWT.this.canvas.render(); + // fps.toc(); + // fps.draw(); + SwingUtilities.invokeLater(this); + } + }; + SwingUtilities.invokeLater(renderLoop); + + // while (canvas != null && canvas.isValid()) { + // canvas.render(); + // try { + // Thread.sleep(10); + // } catch (InterruptedException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // } + // } + + // Run the rendering loop until the user has attempted to close + // the window or has pressed the ESCAPE key. + // while ( !glfwWindowShouldClose(window) ) { + // /* + // fps.tic(); + // long currentFrameTime = getCurrentTime(); + // delta = (currentFrameTime-lastFrameTime)/1000f; + // lastFrameTime = currentFrameTime; + // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer + // if (this.drawer != null) { + // fps.incrementCounter(); + // this.drawer.draw(); + // } + // lastMousePositionX = currentMousePositionX; + // lastMousePositionY = currentMousePositionY; + // whellOffsetY = 0; + // whellOffsetY = 0; + // glfwSwapBuffers(window); // swap the color buffers + // // Poll for window events. The key callback above will only be + // // invoked during this call. + // glfwPollEvents(); + // fps.toc(); + // fps.draw(); + // */ + // + // glfwSwapBuffers(window); // swap the color buffers + // glfwPollEvents(); + // /* + // if (specialEventThatNeedARedraw) { + // X11_INFO("specialEventThatNeedARedraw = " << specialEventThatNeedARedraw); + // } + // hasDisplay = operatingSystemDraw(specialEventThatNeedARedraw); + // if (hasDisplay) { + // // need to request it every time needed to have a redrawing (this can take some time if the application filter the drfaw periodicity) + // specialEventThatNeedARedraw = false; + // } + // */ + // } + //System.exit(0); + return 0; + } + + public void setDrawer(final DisplayManagerDraw drawer) { + this.drawer = drawer; + } + + @Override + public void setFullScreen(final boolean status) { + super.setFullScreen(status); + if (status) { + this.frame.setExtendedState(JFrame.MAXIMIZED_BOTH); + this.frame.setUndecorated(true); + } else { + this.frame.setExtendedState(JFrame.NORMAL); + this.frame.setUndecorated(false); + } + } + + @Override + public void setIcon(final Uri inputFile) { + }; - public static Context create(Application application, String[] arg) { - // TODO Auto-generated method stub - return new ContextLWJGLAWT(application, arg); + /****************************************************************************************/ + @Override + public void setTitle(final String title) { + this.frame.setTitle(title); + }; + + private void showCursor() { + this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + }; + + public void unInit() { + } - - - + } diff --git a/src/org/atriasoft/gale/key/KeySpecial.java b/src/org/atriasoft/gale/key/KeySpecial.java index 63e9f6e..68ea7d2 100644 --- a/src/org/atriasoft/gale/key/KeySpecial.java +++ b/src/org/atriasoft/gale/key/KeySpecial.java @@ -13,209 +13,209 @@ public class KeySpecial { private boolean valueNumLock = false; private boolean valueInsert = false; /** - * @brief Main ructor + * Main ructor */ public KeySpecial() { } /** - * @brief get the current CapLock Status + * get the current CapLock Status * @return The CapLock value */ public boolean getCapsLock() { return valueCapLock; } /** - * @brief set the current CapLock Status + * set the current CapLock Status * @param value The new CapLock value */ public void setCapsLock(boolean value) { valueCapLock = value; } /** - * @brief Get the current Shift key status + * Get the current Shift key status * @return The Shift value */ public boolean getShift() { return valueShiftLeft || valueShiftRight; } /** - * @brief Get the current Shift left key status + * Get the current Shift left key status * @return The Shift value */ public boolean getShiftLeft() { return valueShiftLeft; } /** - * @brief Get the current Shift right key status + * Get the current Shift right key status * @return The Shift value */ public boolean getShiftRight() { return valueShiftRight; } /** - * @brief Set the current Shift left key status + * Set the current Shift left key status * @param value The new Shift value */ public void setShiftLeft(boolean value) { valueShiftLeft = value; } /** - * @brief Set the current Shift right key status + * Set the current Shift right key status * @param value The new Shift value */ public void setShiftRight(boolean value) { valueShiftRight = value; } /** - * @brief Get the Current Control key status + * Get the Current Control key status * @return The Control value */ public boolean getCtrl() { return valueCtrlLeft || valueCtrlRight; } /** - * @brief Get the Current Control left key status + * Get the Current Control left key status * @return The Control value */ public boolean getCtrlLeft() { return valueCtrlLeft; } /** - * @brief Get the Current Control right key status + * Get the Current Control right key status * @return The Control value */ public boolean getCtrlRight() { return valueCtrlRight; } /** - * @brief Set the Current Control left key status + * Set the Current Control left key status * @param value The new Control value */ public void setCtrlLeft(boolean value){ valueCtrlLeft = value; } /** - * @brief Set the Current Control right key status + * Set the Current Control right key status * @param value The new Control value */ public void setCtrlRight(boolean value) { valueCtrlRight = value; } /** - * @brief Get the current Meta key status (also named windows or apple key) + * Get the current Meta key status (also named windows or apple key) * @return The Meta value (name Windows key, apple key, command key ...) */ public boolean getMeta() { return valueMetaLeft || valueMetaRight; } /** - * @brief Get the current Meta left key status (also named windows or apple key) + * Get the current Meta left key status (also named windows or apple key) * @return The Meta value (name Windows key, apple key, command key ...) */ public boolean getMetaLeft() { return valueMetaLeft; } /** - * @brief Get the current Meta right key status (also named windows or apple key) + * Get the current Meta right key status (also named windows or apple key) * @return The Meta value (name Windows key, apple key, command key ...) */ public boolean getMetaRight() { return valueMetaRight; } /** - * @brief Set the current Meta left key status (also named windows or apple key) + * Set the current Meta left key status (also named windows or apple key) * @param value The new Meta value (name Windows key, apple key, command key ...) */ public void setMetaLeft(boolean value) { valueMetaLeft = value; } /** - * @brief Set the current Meta right key status (also named windows or apple key) + * Set the current Meta right key status (also named windows or apple key) * @param value The new Meta value (name Windows key, apple key, command key ...) */ public void setMetaRight(boolean value) { valueMetaRight = value; } /** - * @brief Get the current Alt key status + * Get the current Alt key status * @return The Alt value */ public boolean getAlt() { return valueAltLeft || valueAltRight; } /** - * @brief Get the current Alt left key status + * Get the current Alt left key status * @return The Alt value */ public boolean getAltLeft() { return valueAltLeft; } /** - * @brief Get the current Alt right key status (alt-gr) + * Get the current Alt right key status (alt-gr) * @return The Alt value */ public boolean getAltRight() { return valueAltRight; } /** - * @brief Set the current Alt left key status + * Set the current Alt left key status * @param value The new Alt value */ public void setAltLeft(boolean value) { valueAltLeft = value; } /** - * @brief Set the current Alt right key status (alt-gr) + * Set the current Alt right key status (alt-gr) * @param value The new Alt value */ public void setAltRight(boolean value) { valueAltRight = value; } /** - * @brief Get the current Alt-Gr key status + * Get the current Alt-Gr key status * @return The Alt-gr value (does not exist on MacOs) */ public boolean getAltGr() { return getAltRight(); } /** - * @brief Set the current Alt-Gr key status + * Set the current Alt-Gr key status * @param value The new Alt-gr value (does not exist on MacOs) */ public void setAltGr(boolean value) { setAltRight(value); } /** - * @brief Get the current Ver-num key status + * Get the current Ver-num key status * @return The Numerical Lock value */ public boolean getNumLock() { return valueNumLock; } /** - * @brief Set the current Ver-num key status + * Set the current Ver-num key status * @param value The new Numerical Lock value */ public void setNumLock(boolean value) { valueNumLock = value; } /** - * @brief Get the current Intert key status + * Get the current Intert key status * @return The Insert value */ public boolean getInsert() { return valueInsert; } /** - * @brief Set the current Intert key status + * Set the current Intert key status * @param value The new Insert value */ public void setInsert(boolean value) { valueInsert = value; } /** - * @brief Update the internal value with the input moving key. + * Update the internal value with the input moving key. * @param move Moving key. * @param isDown The key is pressed or not. */ @@ -259,7 +259,7 @@ public class KeySpecial { } } /** - * @brief Get the value with the input moving key. + * Get the value with the input moving key. * @param move Moving key. * @return true The key is pressed. * @return false The key is released. diff --git a/src/org/atriasoft/gale/key/KeyStatus.java b/src/org/atriasoft/gale/key/KeyStatus.java index 08dd37a..fe6756f 100644 --- a/src/org/atriasoft/gale/key/KeyStatus.java +++ b/src/org/atriasoft/gale/key/KeyStatus.java @@ -1,37 +1,32 @@ package org.atriasoft.gale.key; public enum KeyStatus { - unknow, - down, // availlable on Keyboard too - downRepeate, // availlable on Keyboard too: the down event us in repeate cycle + unknown, + down, // available on Keyboard too + downRepeat, // available on Keyboard too: the down event us in repeate cycle move, pressSingle, pressDouble, pressTriple, pressQuad, - pressQuinte, - up, // availlable on Keyboard too - upRepeate, // availlable on Keyboard too: the up event us in repeate cycle + pressQuint, + up, // available on Keyboard too + upRepeat, // available on Keyboard too: the up event us in repeate cycle upAfter, // mouse input & finger input this appear after the single event (depending on some case...) enter, leave, - abort, // Appeare when an event is tranfert betwwen widgets (the widget which receive this has lost the events) - transfert // Appeare when an event is tranfert betwwen widgets (the widget which receive this has receive the transfert of the event) + abort, // Appear when an event is tranfert betwwen widgets (the widget which receive this has lost the events) + transfer // Appear when an event is tranfert betwwen widgets (the widget which receive this has receive the transfert of the event) ; public static KeyStatus pressCount(final int i) { - switch (i) { - case 1: - return pressSingle; - case 2: - return pressDouble; - case 3: - return pressTriple; - case 4: - return pressQuad; - case 5: - return pressQuinte; - } - return unknow; + return switch (i) { + case 1 -> pressSingle; + case 2 -> pressDouble; + case 3 -> pressTriple; + case 4 -> pressQuad; + case 5 -> pressQuint; + default -> unknown; + }; } } diff --git a/src/org/atriasoft/gale/resource/Resource.java b/src/org/atriasoft/gale/resource/Resource.java index a6052fc..a72c3e3 100644 --- a/src/org/atriasoft/gale/resource/Resource.java +++ b/src/org/atriasoft/gale/resource/Resource.java @@ -10,7 +10,7 @@ public abstract class Resource { private static int idGenerated = 10; /** - * @brief Get the current resource Manager + * Get the current resource Manager */ protected static ResourceManager getManager() { return Context.getContext().getResourcesManager(); @@ -22,7 +22,7 @@ public abstract class Resource { protected String name = NO_NAME_RESOURCE; //!< name of the resource ... /** - * @brief generic protected contructor (use factory to create this class) + * generic protected contructor (use factory to create this class) */ protected Resource() { this.uid = idGenerated++; @@ -50,7 +50,7 @@ public abstract class Resource { } /** - * @brief get the resource name + * get the resource name * @return The requested name */ public String getName() { @@ -58,7 +58,7 @@ public abstract class Resource { } /** - * @brief Get the current resource level; + * Get the current resource level; * @return value in [0..5] */ public int getResourceLevel() { @@ -77,21 +77,21 @@ public abstract class Resource { } /** - * @brief User request the reload of all resources (usefull when the file depend on DATA:GUI:xxx ... + * User request the reload of all resources (usefull when the file depend on DATA:GUI:xxx ... */ public void reload() { Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)"); }; /** - * @brief The current OpenGl context is removing ==> remove yout own system data + * The current OpenGl context is removing ==> remove yout own system data */ public void removeContext() { Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)"); } /** - * @brief The notification of the Context removing is too late, we have no more acces on the OpenGl context (thank you Android). + * The notification of the Context removing is too late, we have no more acces on the OpenGl context (thank you Android). * Just update your internal state */ public void removeContextToLate() { @@ -99,7 +99,7 @@ public abstract class Resource { } /** - * @brief get the resource name + * get the resource name * @param name The name to set. */ public void setName(final String name) { @@ -107,7 +107,7 @@ public abstract class Resource { } /** - * @brief Call when need to send data on the harware (openGL) + * Call when need to send data on the harware (openGL) * @note This is done asynchronously with the create of the Resource. * @return true The context is updated * @return false The context is not updated diff --git a/src/org/atriasoft/gale/resource/ResourceColored3DObject.java b/src/org/atriasoft/gale/resource/ResourceColored3DObject.java index 6174947..4ccf724 100644 --- a/src/org/atriasoft/gale/resource/ResourceColored3DObject.java +++ b/src/org/atriasoft/gale/resource/ResourceColored3DObject.java @@ -30,7 +30,7 @@ public class ResourceColored3DObject extends Resource { super(); // get the shader resource : this.oGLPosition = 0; - this.program = ResourceProgram.create(new Uri("DATA_EGE", "simple3D.vert"), new Uri("DATA_EGE", "simple3D.frag")); + this.program = ResourceProgram.create(new Uri("DATA", "simple3D.vert", "gale"), new Uri("DATA", "simple3D.frag", "gale")); if (this.program != null) { this.oGLMatrixTransformation = this.program.getUniform("in_matrixTransformation"); this.oGLMatrixProjection = this.program.getUniform("in_matrixProjection"); @@ -49,9 +49,9 @@ public class ResourceColored3DObject extends Resource { private float[] convertInFloat(final List data) { final float[] out = new float[data.size() * 3]; for (int iii = 0; iii < data.size(); iii++) { - out[iii * 3] = data.get(iii).x; - out[iii * 3 + 1] = data.get(iii).y; - out[iii * 3 + 2] = data.get(iii).z; + out[iii * 3] = data.get(iii).x(); + out[iii * 3 + 1] = data.get(iii).y(); + out[iii * 3 + 2] = data.get(iii).z(); } return out; } @@ -64,9 +64,9 @@ public class ResourceColored3DObject extends Resource { Log.error("No shader ..."); return; } - if (true == depthtest) { + if (depthtest) { OpenGL.enable(OpenGL.Flag.flag_depthTest); - if (false == updateDepthBuffer) { + if (!updateDepthBuffer) { OpenGL.setDeathMask(false); } } @@ -74,7 +74,7 @@ public class ResourceColored3DObject extends Resource { this.program.use(); final Matrix4f projectionMatrix = OpenGL.getMatrix(); final Matrix4f viewMatrix = OpenGL.getCameraMatrix(); - final Matrix4f transformationMatrix = Matrix4f.identity(); + final Matrix4f transformationMatrix = Matrix4f.IDENTITY; this.program.uniformMatrix(this.oGLMatrixView, viewMatrix); this.program.uniformMatrix(this.oGLMatrixProjection, projectionMatrix); this.program.uniformMatrix(this.oGLMatrixTransformation, transformationMatrix); @@ -83,20 +83,20 @@ public class ResourceColored3DObject extends Resource { // position : final FloatBuffer buffer = storeDataInFloatBuffer(convertInFloat(vertices)); this.program.sendAttribute(this.oGLPosition, 3, buffer, 3); - if (color.a < 1.0f) { + if (color.a() < 1.0f) { OpenGL.enable(OpenGL.Flag.flag_blend); } // Request the draw of the elements: OpenGL.drawArrays(OpenGL.RenderMode.triangle, 0, vertices.size()); - if (color.a < 1.0f) { + if (color.a() < 1.0f) { OpenGL.disable(OpenGL.Flag.flag_blend); } this.program.unUse(); // Request the draw od the elements: //glDrawArrays(oGLLINES, 0, vertices.size()); //this.oGLprogram.UnUse(); - if (true == depthtest) { - if (false == updateDepthBuffer) { + if (depthtest) { + if (!updateDepthBuffer) { OpenGL.setDeathMask(true); } OpenGL.disable(OpenGL.Flag.flag_depthTest); @@ -111,9 +111,9 @@ public class ResourceColored3DObject extends Resource { Log.error("No shader ..."); return; } - if (true == depthtest) { + if (depthtest) { OpenGL.enable(OpenGL.Flag.flag_depthTest); - if (false == updateDepthBuffer) { + if (!updateDepthBuffer) { OpenGL.setDeathMask(false); } } @@ -131,17 +131,17 @@ public class ResourceColored3DObject extends Resource { // color : //Log.info("color= " + color + " " + this.oGLPosition); this.program.uniformColor(this.oGLColor, color); - if (color.a < 1.0f) { + if (color.a() < 1.0f) { OpenGL.enable(OpenGL.Flag.flag_blend); } // Request the draw of the elements: OpenGL.drawArrays(OpenGL.RenderMode.triangle, 0, vertices.size()); - if (color.a < 1.0f) { + if (color.a() < 1.0f) { OpenGL.disable(OpenGL.Flag.flag_blend); } this.program.unUse(); - if (true == depthtest) { - if (false == updateDepthBuffer) { + if (depthtest) { + if (!updateDepthBuffer) { OpenGL.setDeathMask(true); } OpenGL.disable(OpenGL.Flag.flag_depthTest); @@ -286,41 +286,41 @@ public class ResourceColored3DObject extends Resource { public void drawCubeLine(final Vector3f min, final Vector3f max, final Color color, final Matrix4f transformationMatrix, final boolean updateDepthBuffer, final boolean depthtest) { final List vertices = new ArrayList<>(); - vertices.add(new Vector3f(min.x, min.y, min.z)); - vertices.add(new Vector3f(max.x, min.y, min.z)); + vertices.add(new Vector3f(min.x(), min.y(), min.z())); + vertices.add(new Vector3f(max.x(), min.y(), min.z())); - vertices.add(new Vector3f(max.x, min.y, min.z)); - vertices.add(new Vector3f(max.x, min.y, max.z)); + vertices.add(new Vector3f(max.x(), min.y(), min.z())); + vertices.add(new Vector3f(max.x(), min.y(), max.z())); - vertices.add(new Vector3f(max.x, min.y, max.z)); - vertices.add(new Vector3f(min.x, min.y, max.z)); + vertices.add(new Vector3f(max.x(), min.y(), max.z())); + vertices.add(new Vector3f(min.x(), min.y(), max.z())); - vertices.add(new Vector3f(min.x, min.y, max.z)); - vertices.add(new Vector3f(min.x, min.y, min.z)); + vertices.add(new Vector3f(min.x(), min.y(), max.z())); + vertices.add(new Vector3f(min.x(), min.y(), min.z())); - vertices.add(new Vector3f(min.x, max.y, min.z)); - vertices.add(new Vector3f(max.x, max.y, min.z)); + vertices.add(new Vector3f(min.x(), max.y(), min.z())); + vertices.add(new Vector3f(max.x(), max.y(), min.z())); - vertices.add(new Vector3f(max.x, max.y, min.z)); - vertices.add(new Vector3f(max.x, max.y, max.z)); + vertices.add(new Vector3f(max.x(), max.y(), min.z())); + vertices.add(new Vector3f(max.x(), max.y(), max.z())); - vertices.add(new Vector3f(max.x, max.y, max.z)); - vertices.add(new Vector3f(min.x, max.y, max.z)); + vertices.add(new Vector3f(max.x(), max.y(), max.z())); + vertices.add(new Vector3f(min.x(), max.y(), max.z())); - vertices.add(new Vector3f(min.x, max.y, max.z)); - vertices.add(new Vector3f(min.x, max.y, min.z)); + vertices.add(new Vector3f(min.x(), max.y(), max.z())); + vertices.add(new Vector3f(min.x(), max.y(), min.z())); - vertices.add(new Vector3f(min.x, min.y, min.z)); - vertices.add(new Vector3f(min.x, max.y, min.z)); + vertices.add(new Vector3f(min.x(), min.y(), min.z())); + vertices.add(new Vector3f(min.x(), max.y(), min.z())); - vertices.add(new Vector3f(max.x, min.y, min.z)); - vertices.add(new Vector3f(max.x, max.y, min.z)); + vertices.add(new Vector3f(max.x(), min.y(), min.z())); + vertices.add(new Vector3f(max.x(), max.y(), min.z())); - vertices.add(new Vector3f(max.x, min.y, max.z)); - vertices.add(new Vector3f(max.x, max.y, max.z)); + vertices.add(new Vector3f(max.x(), min.y(), max.z())); + vertices.add(new Vector3f(max.x(), max.y(), max.z())); - vertices.add(new Vector3f(min.x, min.y, max.z)); - vertices.add(new Vector3f(min.x, max.y, max.z)); + vertices.add(new Vector3f(min.x(), min.y(), max.z())); + vertices.add(new Vector3f(min.x(), max.y(), max.z())); drawLine(vertices, color, transformationMatrix, updateDepthBuffer, depthtest); } @@ -402,9 +402,9 @@ public class ResourceColored3DObject extends Resource { Log.error("No shader ..."); return; } - if (true == depthtest) { + if (depthtest) { OpenGL.enable(OpenGL.Flag.flag_depthTest); - if (false == updateDepthBuffer) { + if (!updateDepthBuffer) { OpenGL.setDeathMask(false); } } @@ -421,17 +421,17 @@ public class ResourceColored3DObject extends Resource { this.program.sendAttribute(this.oGLPosition, 3, buffer, 3); // color : this.program.uniformColor(this.oGLColor, color); - if (color.a < 1.0f) { + if (color.a() < 1.0f) { OpenGL.enable(OpenGL.Flag.flag_blend); } // Request the draw od the elements: OpenGL.drawArrays(OpenGL.RenderMode.line, 0, vertices.size()); - if (color.a < 1.0f) { + if (color.a() < 1.0f) { OpenGL.disable(OpenGL.Flag.flag_blend); } this.program.unUse(); - if (true == depthtest) { - if (false == updateDepthBuffer) { + if (depthtest) { + if (!updateDepthBuffer) { OpenGL.setDeathMask(true); } OpenGL.disable(OpenGL.Flag.flag_depthTest); @@ -477,8 +477,9 @@ public class ResourceColored3DObject extends Resource { public void drawSquare(final Vector3f size, final Matrix4f transformationMatrix, final Color tmpColor) { final List tmpVertices = new ArrayList<>(); final int[] indices = { 0, 1, 2, 3, 2, 1, 4, 0, 6, 6, 0, 2, 5, 1, 4, 4, 1, 0, 7, 3, 1, 7, 1, 5, 5, 4, 7, 7, 4, 6, 7, 2, 3, 7, 6, 2 }; - final Vector3f[] vertices = { new Vector3f(size.x, size.y, size.z), new Vector3f(-size.x, size.y, size.z), new Vector3f(size.x, -size.y, size.z), new Vector3f(-size.x, -size.y, size.z), - new Vector3f(size.x, size.y, -size.z), new Vector3f(-size.x, size.y, -size.z), new Vector3f(size.x, -size.y, -size.z), new Vector3f(-size.x, -size.y, -size.z) }; + final Vector3f[] vertices = { new Vector3f(size.x(), size.y(), size.z()), new Vector3f(-size.x(), size.y(), size.z()), new Vector3f(size.x(), -size.y(), size.z()), + new Vector3f(-size.x(), -size.y(), size.z()), new Vector3f(size.x(), size.y(), -size.z()), new Vector3f(-size.x(), size.y(), -size.z()), new Vector3f(size.x(), -size.y(), -size.z()), + new Vector3f(-size.x(), -size.y(), -size.z()) }; tmpVertices.clear(); for (int iii = 0; iii < 36; iii += 3) { // normal calculation : @@ -498,9 +499,9 @@ public class ResourceColored3DObject extends Resource { public void drawTriangles(final List vertex, final List indice, final Matrix4f transformationMatrix, final Color tmpColor, final Vector3f offset) { final List tmpVertices = new ArrayList<>(); for (int iii = 0; iii < indice.size() / 3; ++iii) { - tmpVertices.add(vertex.get(indice.get(iii * 3 + 0)).addNew(offset)); - tmpVertices.add(vertex.get(indice.get(iii * 3 + 1)).addNew(offset)); - tmpVertices.add(vertex.get(indice.get(iii * 3 + 2)).addNew(offset)); + tmpVertices.add(vertex.get(indice.get(iii * 3 + 0)).add(offset)); + tmpVertices.add(vertex.get(indice.get(iii * 3 + 1)).add(offset)); + tmpVertices.add(vertex.get(indice.get(iii * 3 + 2)).add(offset)); //Log.info(" indices " << indice[iii*3 + 0] << " " << indice[iii*3 + 1] << " " << indice[iii*3 + 2]); //Log.info(" triangle " << vertex[indice[iii*3 + 0]] << " " << vertex[indice[iii*3 + 1]] << " " << vertex[indice[iii*3 + 2]]); } diff --git a/src/org/atriasoft/gale/resource/ResourceManager.java b/src/org/atriasoft/gale/resource/ResourceManager.java index 0357a8a..a290994 100644 --- a/src/org/atriasoft/gale/resource/ResourceManager.java +++ b/src/org/atriasoft/gale/resource/ResourceManager.java @@ -14,14 +14,14 @@ public class ResourceManager { private boolean exiting = false; /** - * @brief initialize the internal variable + * initialize the internal variable */ public ResourceManager() { } /** - * @brief special end of application + * special end of application */ public void applicationExiting() { contextHasBeenDestroyed(); @@ -41,7 +41,7 @@ public class ResourceManager { } /** - * @brief This is to inform the resources manager that we have no more openGl context ... + * This is to inform the resources manager that we have no more openGl context ... */ public void contextHasBeenDestroyed() { for (final Resource it : this.resourceList) { @@ -54,7 +54,7 @@ public class ResourceManager { } /** - * @brief display in the log all the resources loaded ... + * display in the log all the resources loaded ... */ public void display() { Log.info("Resources loaded : "); @@ -97,7 +97,7 @@ public class ResourceManager { } /** - * @brief Reload all resources from files, and send there in openGL card if needed. + * Reload all resources from files, and send there in openGL card if needed. * @note If file is reference at THEMEXXX:///filename if the Theme change the file will reload the newOne */ public void reLoadResources() { @@ -120,12 +120,12 @@ public class ResourceManager { } /** - * @brief Uninitiamize the resource manager, free all resources previously requested + * Uninitiamize the resource manager, free all resources previously requested * @note when not free == > generate warning, because the segfault can appear after... */ //public ~Manager(); /** - * @brief remove all resources (un-init) out of the destructor (due to the system implementation) + * remove all resources (un-init) out of the destructor (due to the system implementation) */ public void unInit() { display(); @@ -138,7 +138,7 @@ public class ResourceManager { } /** - * @brief Call by the system to send all the needed data on the graphic card chen they change ... + * Call by the system to send all the needed data on the graphic card chen they change ... * @param object The resources that might be updated */ public void update(final Resource object) { @@ -154,15 +154,15 @@ public class ResourceManager { } /** - * @brief Call by the system chen the openGL Context has been unexpectially removed == > This reload all the texture, VBO and other .... + * Call by the system chen the openGL Context has been unexpectially removed == > This reload all the texture, VBO and other .... */ public void updateContext() { - if (this.exiting == true) { + if (this.exiting) { Log.error("Request update after application EXIT ..."); return; } // TODO Check the number of call this ... Log.info("update open-gl context ... "); - if (this.contextHasBeenRemoved == true) { + if (this.contextHasBeenRemoved) { // need to update all ... this.contextHasBeenRemoved = false; this.resourceListToUpdate.clear(); @@ -173,7 +173,7 @@ public class ResourceManager { for (final Resource it : this.resourceList) { if (jjj == it.getResourceLevel()) { //Log.debug("Update context named : " + lresourceList[iii].getName()); - if (it.updateContext() == false) { + if (!it.updateContext()) { // Lock error ==> postponned this.resourceListToUpdate.add(it); } @@ -193,7 +193,7 @@ public class ResourceManager { Log.verbose(" updateContext level (U) : " + jjj + "/" + (MAX_RESOURCE_LEVEL - 1)); for (final Resource it : resourceListToUpdate) { if (jjj == it.getResourceLevel()) { - if (it.updateContext() == false) { + if (!it.updateContext()) { // Lock error ==> postponned this.resourceListToUpdate.add(it); } diff --git a/src/org/atriasoft/gale/resource/ResourceProgram.java b/src/org/atriasoft/gale/resource/ResourceProgram.java index e5f94fc..f470c4a 100644 --- a/src/org/atriasoft/gale/resource/ResourceProgram.java +++ b/src/org/atriasoft/gale/resource/ResourceProgram.java @@ -19,22 +19,19 @@ import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL40; class ProgAttributeElement { - public String name; //!< Name of the element - public int elementId; //!< openGl Id if this element == > can not exist ==> @ref m_isLinked - public boolean isAttribute; //!< true if it was an attribute element, otherwite it was an uniform - public boolean isLinked; //!< if this element does not exist this is false + public String name; // !< Name of the element + public int elementId; // !< openGl Id if this element == > can not exist ==> @ref m_isLinked + public boolean isAttribute; // !< true if it was an attribute element, otherwite it was an uniform + public boolean isLinked; // !< if this element does not exist this is false }; public class ResourceProgram extends Resource { static final boolean DEBUG = false; // TODO externalize this ... - + public static ResourceProgram create(final Uri uriVertexShader, final Uri uriFragmentShader) { ResourceProgram resource; - Resource resource2 = null; final String name = uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue(); - if (name.isEmpty() == false && name != "---") { - resource2 = getManager().localKeep(name); - } + Resource resource2 = getManager().localKeep(name); if (resource2 != null) { if (resource2 instanceof ResourceProgram) { resource2.keep(); @@ -47,50 +44,55 @@ public class ResourceProgram extends Resource { getManager().localAdd(resource); return resource; } - + public static FloatBuffer storeDataInFloatBuffer(final float[] data) { final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length); buffer.put(data); buffer.flip(); return buffer; } - + public static FloatBuffer storeDataInFloatBufferColor(final List data) { final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.size() * 4); for (int iii = 0; iii < data.size(); iii++) { - buffer.put(iii * 3, data.get(iii).r); - buffer.put(iii * 3 + 1, data.get(iii).g); - buffer.put(iii * 3 + 2, data.get(iii).b); - buffer.put(iii * 3 + 3, data.get(iii).a); + buffer.put(iii * 3, data.get(iii).r()); + buffer.put(iii * 3 + 1, data.get(iii).g()); + buffer.put(iii * 3 + 2, data.get(iii).b()); + buffer.put(iii * 3 + 3, data.get(iii).a()); } buffer.flip(); return buffer; } - + public static FloatBuffer storeDataInFloatBufferVector3f(final List data) { final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.size() * 3); for (int iii = 0; iii < data.size(); iii++) { - buffer.put(iii * 3, data.get(iii).x); - buffer.put(iii * 3 + 1, data.get(iii).y); - buffer.put(iii * 3 + 2, data.get(iii).z); + buffer.put(iii * 3, data.get(iii).x()); + buffer.put(iii * 3 + 1, data.get(iii).y()); + buffer.put(iii * 3 + 2, data.get(iii).z()); } buffer.flip(); return buffer; } - - private boolean exist = false; //!< the file existed - private int program = 0; //!< openGL id of the current program + + private boolean exist = false; // !< the file existed + private int program = 0; // !< openGL id of the current program private ResourceShader shaderVertex = null; private ResourceShader shaderFragment = null; - - private final List elementList = new ArrayList<>(); //!< List of all the attribute requested by the user - private final List listOfVBOUsed = new ArrayList<>(); //!< retain the list of VBO used to disable it when unuse program ... - // private boolean hasTexture = false; //!< A texture has been set to the current shader - // private boolean hasTexture1 = false; //!< A texture has been set to the current shader - + + private final List elementList = new ArrayList<>(); // !< List of all the attribute requested + // by the user + private final List listOfVBOUsed = new ArrayList<>(); // !< retain the list of VBO used to disable it when + // unuse program ... + private boolean hasTexture = false; // !< A texture has been set to the + // current shader + private boolean hasTexture1 = false; // !< A texture has been set to the + // current shader + /** - * @brief Contructor of an opengl Program. - * @param uri Uri of the file + * Contructor of an opengl Program. + * @param uriVertexShader Uri of the file + * @param uriFragmentShader Uri of the file */ protected ResourceProgram(final Uri uriVertexShader, final Uri uriFragmentShader) { super(uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue()); @@ -110,22 +112,23 @@ public class ResourceProgram extends Resource { } else { Log.debug("Add shader on program : " + uriFragmentShader + "frag"); } - if (OpenGL.hasContext() == true) { + if (OpenGL.hasContext()) { updateContext(); } else { getManager().update(this); } } - + public void bindAttribute(final int attribute, final String variableName) { - if (this.exist == false) { + if (!this.exist) { return; } OpenGL.programBindAttribute(this.program, attribute, variableName); } - + /** - * @brief Check If an Id is valid in the shader or not (sometime the shader have not some attribute, then we need to display some error) + * Check If an Id is valid in the shader or not (sometime the shader have + * not some attribute, then we need to display some error) * @return idElem Id of the Attribute that might be sended. * @return true The id is valid, false otherwise */ @@ -135,9 +138,9 @@ public class ResourceProgram extends Resource { } return this.elementList.get(idElem).isLinked; } - + /** - * @brief Destructor, remove the current Program. + * Destructor, remove the current Program. */ @Override public void cleanUp() { @@ -151,35 +154,38 @@ public class ResourceProgram extends Resource { this.shaderVertex = null; } this.elementList.clear(); - // this.hasTexture = false; - // this.hasTexture1 = false; + this.hasTexture = false; + this.hasTexture1 = false; } - + private float[] convertInFloat(final List data) { final float[] out = new float[data.size() * 3]; for (int iii = 0; iii < data.size(); iii++) { - out[iii * 3] = data.get(iii).x; - out[iii * 3 + 1] = data.get(iii).y; - out[iii * 3 + 2] = data.get(iii).z; + out[iii * 3] = data.get(iii).x(); + out[iii * 3 + 1] = data.get(iii).y(); + out[iii * 3 + 2] = data.get(iii).z(); } return out; } - - // private void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data) { - // int vboID = GL15.glGenBuffers(); - // vbos.add(vboID); - // OpenGL.bindBuffer(vboID); - // FloatBuffer buffer = storeDataInFloatBuffer(data); - // GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); - // GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0, 0); - // GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); - // } - + + // private void storeDataInAttributeList(int attributeNumber, int + // coordinateSize, float[] data) { + // int vboID = GL15.glGenBuffers(); + // vbos.add(vboID); + // OpenGL.bindBuffer(vboID); + // FloatBuffer buffer = storeDataInFloatBuffer(data); + // GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); + // GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, + // false, 0, 0); + // GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + // } + /** - * @brief User request an attribute on this program. + * User request an attribute on this program. * @note The attribute is send to the fragment shaders * @param elementName Name of the requested attribute. - * @return An abstract ID of the current attribute (this value is all time availlable, even if the program will be reloaded) + * @return An abstract ID of the current attribute (this value is all time + * availlable, even if the program will be reloaded) */ public int getAttribute(final String elementName) { // check if it exist previously : @@ -191,18 +197,20 @@ public class ResourceProgram extends Resource { final ProgAttributeElement tmp = new ProgAttributeElement(); tmp.name = elementName; tmp.isAttribute = true; - if (OpenGL.hasContext() == false) { + if (!OpenGL.hasContext()) { getManager().update(this); tmp.elementId = -1; tmp.isLinked = false; - } else if (this.exist == true) { + } else if (this.exist) { tmp.elementId = OpenGL.programGetAttributeLocation(this.program, tmp.name); tmp.isLinked = true; if (tmp.elementId < 0) { - Log.warning(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\"" + tmp.name + "\") = " + tmp.elementId); + Log.warning(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\"" + + tmp.name + "\") = " + tmp.elementId); tmp.isLinked = false; } else { - Log.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\"" + tmp.name + "\") = " + tmp.elementId); + Log.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\"" + + tmp.name + "\") = " + tmp.elementId); } } else { // program is not loaded ==> just local reister ... @@ -212,18 +220,20 @@ public class ResourceProgram extends Resource { this.elementList.add(tmp); return this.elementList.size() - 1; } - - // public void sendAttribute(int idElem, etk::Vector> data) { - // sendAttribute(idElem, 4/*r,g,b,a*/, data[0]); - // } - // public void sendAttribute(int idElem, etk::Vector data) { - // sendAttribute(idElem, 1, data[0]); - // } + + // public void sendAttribute(int idElem, etk::Vector> data) { + // sendAttribute(idElem, 4/*r,g,b,a*/, data[0]); + // } + // public void sendAttribute(int idElem, etk::Vector data) { + // sendAttribute(idElem, 1, data[0]); + // } /** - * @brief User request an Uniform on this program. - * @note uniform value is availlable for all the fragment shader in the program (only one value for all) + * User request an Uniform on this program. + * @note uniform value is availlable for all the fragment shader in the program + * (only one value for all) * @param elementName Name of the requested uniform. - * @return An abstract ID of the current uniform (this value is all time availlable, even if the program will be reloaded) + * @return An abstract ID of the current uniform (this value is all time + * availlable, even if the program will be reloaded) */ public int getUniform(final String elementName) { // check if it exist previously : @@ -235,18 +245,20 @@ public class ResourceProgram extends Resource { final ProgAttributeElement tmp = new ProgAttributeElement(); tmp.name = elementName; tmp.isAttribute = false; - if (OpenGL.hasContext() == false) { + if (!OpenGL.hasContext()) { getManager().update(this); tmp.elementId = -1; tmp.isLinked = false; - } else if (this.exist == true) { + } else if (this.exist) { tmp.elementId = OpenGL.programGetUniformLocation(this.program, tmp.name); tmp.isLinked = true; if (tmp.elementId < 0) { - Log.warning(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\"" + tmp.name + "\") = " + tmp.elementId); + Log.warning(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\"" + + tmp.name + "\") = " + tmp.elementId); tmp.isLinked = false; } else { - Log.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\"" + tmp.name + "\") = " + tmp.elementId); + Log.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\"" + + tmp.name + "\") = " + tmp.elementId); } } else { // program is not loaded ==> just local reister ... @@ -256,57 +268,40 @@ public class ResourceProgram extends Resource { this.elementList.add(tmp); return this.elementList.size() - 1; } - + /** - * @brief Relode the shader from the file. used when a request of resouces reload is done. - * @note this is really usefull when we tested the new themes or shader developpements. - */ + * Relode the shader from the file. used when a request of resouces + * reload is done. + * @note this is really usefull when we tested the new themes or shader + * developpements. + */ @Override public void reload() { - /* TODO ... - etk::file file(this.name, etk::FILETYPEDATA); - if (file.Exist() == false) { - Log.error("File does not Exist :"" + file + "\""); - return; - } - - int fileSize = file.size(); - if (fileSize == 0) { - Log.error("This file is empty : " + file); - return; - } - if (file.fOpenRead() == false) { - Log.error("Can not open the file : " + file); - return; - } - // remove previous data ... - if (this.fileData != null) { - del ete[] this.fileData; - this.fileData = 0; - } - // allocate data - this.fileData = ne w char[fileSize+5]; - if (this.fileData == null) { - Log.error("Error Memory allocation size=" + fileSize); - return; - } - memset(this.fileData, 0, (fileSize+5)*sizeof(char)); - // load data from the file : - file.fRead(this.fileData, 1, fileSize); - // close the file: - file.fClose(); - */ + /* + * TODO ... etk::file file(this.name, etk::FILETYPEDATA); if (file.Exist() == + * false) { Log.error("File does not Exist :"" + file + "\""); return; } + * + * int fileSize = file.size(); if (fileSize == 0) { + * Log.error("This file is empty : " + file); return; } if (file.fOpenRead() == + * false) { Log.error("Can not open the file : " + file); return; } // remove + * previous data ... if (this.fileData != null) { del ete[] this.fileData; + * this.fileData = 0; } // allocate data this.fileData = ne w char[fileSize+5]; + * if (this.fileData == null) { Log.error("Error Memory allocation size=" + + * fileSize); return; } memset(this.fileData, 0, (fileSize+5)*sizeof(char)); // + * load data from the file : file.fRead(this.fileData, 1, fileSize); // close + * the file: file.fClose(); + */ // now change the OGL context ... removeContext(); updateContext(); } - + /** - * @brief remove the data from the opengl context. + * remove the data from the opengl context. */ @Override public void removeContext() { - if (this.exist == true) { + if (this.exist) { OpenGL.programRemove(this.program); this.program = 0; this.exist = false; @@ -316,117 +311,130 @@ public class ResourceProgram extends Resource { } } } - + /** - * @brief Special android spec! It inform us that all context is removed and after notify us... + * Special android spec! It inform us that all context is removed and + * after notify us... */ @Override public void removeContextToLate() { - + this.exist = false; this.program = 0; } - + /** - * @brief Send attribute table to the specified ID attribute (not send if does not really exist in the openGL program). - * @param idElem Id of the Attribute that might be sent. - * @param nbElement Specifies the number of elements that are to be modified. - * @param pointer Pointer on the data that might be sent. - * @param jumpBetweenSample Number of byte to jump between 2 vertex (this permit to interlace informations) + * Send attribute table to the specified ID attribute (not send if does + * not really exist in the openGL program). + * @param idElem Id of the Attribute that might be sent. + * @param nbElement Specifies the number of elements that are to be + * modified. + * @param data Pointer on the data that might be sent. + * @param jumpBetweenSample Number of byte to jump between 2 vertex (this permit + * to interlace informations) */ - // public void sendAttribute3fv(int idElem, float[] data) { - // if (!this.exist) { - // return; - // } - // if ( idElem < 0 - // || (long)idElem > this.elementList.size()) { - // Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - // return; - // } - // if (this.elementList.get(idElem).isLinked == false) { - // return; - // } - // FloatBuffer buffer = storeDataInFloatBuffer(data); - // //GL40.glBindVertexArray(this.elementList.get(idElem).elementId); - // Log.error("[" + this.elementList.get(idElem).name + "] send " + data.length + " element"); - // GL40.glVertexAttribPointer( - // this.elementList.get(idElem).elementId, - // data.length, - // GL40.GL_FLOAT, - // false, - // 0, - // buffer); - // //checkGlError("glVertexAttribPointer", LINE, idElem); - // GL40.glEnableVertexAttribArray(this.elementList.get(idElem).elementId); - // //checkGlError("glEnableVertexAttribArray", LINE, idElem); - // } - //// public void sendAttribute(int idElem, etk::Vector data) { - //// sendAttribute(idElem, 2/*u,v / x,y*/, data[0]); - //// } - // public void sendAttribute(int idElem, List data) { - // sendAttribute3fv(idElem, convertInFloat(data)); - // } - public void sendAttribute(final int idElem, final int nbElement, final FloatBuffer data, final int jumpBetweenSample) { - if (this.exist == false) { + // public void sendAttribute3fv(int idElem, float[] data) { + // if (!this.exist) { + // return; + // } + // if ( idElem < 0 + // || (long)idElem > this.elementList.size()) { + // Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + // + "]"); + // return; + // } + // if (this.elementList.get(idElem).isLinked == false) { + // return; + // } + // FloatBuffer buffer = storeDataInFloatBuffer(data); + // //GL40.glBindVertexArray(this.elementList.get(idElem).elementId); + // Log.error("[" + this.elementList.get(idElem).name + "] send " + data.length + + // " element"); + // GL40.glVertexAttribPointer( + // this.elementList.get(idElem).elementId, + // data.length, + // GL40.GL_FLOAT, + // false, + // 0, + // buffer); + // //checkGlError("glVertexAttribPointer", LINE, idElem); + // GL40.glEnableVertexAttribArray(this.elementList.get(idElem).elementId); + // //checkGlError("glEnableVertexAttribArray", LINE, idElem); + // } + //// public void sendAttribute(int idElem, etk::Vector data) { + //// sendAttribute(idElem, 2/*u,v / x,y*/, data[0]); + //// } + // public void sendAttribute(int idElem, List data) { + // sendAttribute3fv(idElem, convertInFloat(data)); + // } + public void sendAttribute(final int idElem, final int nbElement, final FloatBuffer data, + final int jumpBetweenSample) { + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (this.elementList.get(idElem).isLinked == false) { + if (!this.elementList.get(idElem).isLinked) { return; } - //GL40.glBindVertexArray(this.elementList.get(idElem).elementId); - //Log.error("[" + this.elementList.get(idElem).name + "] send " + 3 + " element"); - GL40.glVertexAttribPointer(this.elementList.get(idElem).elementId, nbElement, GL40.GL_FLOAT, false, jumpBetweenSample * 4, /* 4 is the size of float in the generic system...*/ + // GL40.glBindVertexArray(this.elementList.get(idElem).elementId); + // Log.error("[" + this.elementList.get(idElem).name + "] send " + 3 + " + // element"); + GL40.glVertexAttribPointer(this.elementList.get(idElem).elementId, nbElement, GL40.GL_FLOAT, false, + jumpBetweenSample * 4, /* 4 is the size of float in the generic system... */ data); - //checkGlError("glVertexAttribPointer", LINE, idElem); + // checkGlError("glVertexAttribPointer", LINE, idElem); GL40.glEnableVertexAttribArray(this.elementList.get(idElem).elementId); - //checkGlError("glEnableVertexAttribArray", LINE, idElem); + // checkGlError("glEnableVertexAttribArray", LINE, idElem); } - + /** - * @brief Send attribute table to the spefified ID attribure (not send if does not really exist in the openGL program). - * @param idElem Id of the Attribute that might be sended. - * @param vbo Reference on the buffer to send. - * @param index Reference on the buffer to send. - * @param jumpBetweenSample Number of byte to jump between 2 vertex (this permit to enterlace informations) - * @param offset offset of start the elements send. + * Send attribute table to the spefified ID attribure (not send if does + * not really exist in the openGL program). + * @param idElem Id of the Attribute that might be sended. + * @param vbo Reference on the buffer to send. + * @param index Reference on the buffer to send. */ - // public void sendAttributePointer(int idElem, - // ResourceVirtualArrayObject vbo, - // int index, - // int coordinateSize, - // float[] data){ - // - // if (!this.exist) { - // return; - // } - // if ( idElem < 0 - // || (long)idElem > this.elementList.size()) { - // Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - // return; - // } - // if (this.elementList.get(idElem).isLinked == false) { - // return; - // } - // // check error of the VBO goog enought ... - // if (vbo.getElementSize(index) <= 0) { - // Log.error("Can not bind a VBO Buffer with an element size of : " + vbo.getElementSize(index) + " named=" + vbo.getName()); - // return; - // } - // - // Log.verbose("[" + this.elementList.get(idElem).name + "] send " + vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + " VBOindex=" + index); - // OpenGL.bindBuffer(vbo.getGLID(index)); - // Log.verbose(" id=" + this.elementList.get(idElem).elementId); - // Log.verbose(" eleme size=" + vbo.getElementSize(index)); - // OpenGL.bufferData(data, Usage.staticDraw); - // OpenGL.vertexAttribPointerFloat(this.elementList.get(idElem).elementId, vbo.getElementSize(index)); // Pointer on the buffer - // OpenGL.unbindBuffer(); - // //glEnableVertexAttribArray(this.elementList.get(idElem).elementId); - // this.listOfVBOUsed.add(this.elementList.get(idElem).elementId); - // } + // public void sendAttributePointer(int idElem, + // ResourceVirtualArrayObject vbo, + // int index, + // int coordinateSize, + // float[] data){ + // + // if (!this.exist) { + // return; + // } + // if ( idElem < 0 + // || (long)idElem > this.elementList.size()) { + // Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + // + "]"); + // return; + // } + // if (this.elementList.get(idElem).isLinked == false) { + // return; + // } + // // check error of the VBO goog enought ... + // if (vbo.getElementSize(index) <= 0) { + // Log.error("Can not bind a VBO Buffer with an element size of : " + + // vbo.getElementSize(index) + " named=" + vbo.getName()); + // return; + // } + // + // Log.verbose("[" + this.elementList.get(idElem).name + "] send " + + // vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + " + // VBOindex=" + index); + // OpenGL.bindBuffer(vbo.getGLID(index)); + // Log.verbose(" id=" + this.elementList.get(idElem).elementId); + // Log.verbose(" eleme size=" + vbo.getElementSize(index)); + // OpenGL.bufferData(data, Usage.staticDraw); + // OpenGL.vertexAttribPointerFloat(this.elementList.get(idElem).elementId, + // vbo.getElementSize(index)); // Pointer on the buffer + // OpenGL.unbindBuffer(); + // //glEnableVertexAttribArray(this.elementList.get(idElem).elementId); + // this.listOfVBOUsed.add(this.elementList.get(idElem).elementId); + // } public void sendAttributePointer(final int idElem, final ResourceVirtualBufferObject vbo, final int index) { final int jumpBetweenSample = 0; final int offset = 0; @@ -437,13 +445,14 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (this.elementList.get(idElem).isLinked == false) { + if (!this.elementList.get(idElem).isLinked) { return; } - - Log.verbose("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getGL_ID(index) + " VBOindex=" + index); - GL20.glBindBuffer(GL20.GL_ARRAY_BUFFER, vbo.getGL_ID(index)); - //checkGlError("glBindBuffer", __LINE__, _idElem); + + Log.verbose("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(index) + " VBOindex=" + + index); + GL20.glBindBuffer(GL20.GL_ARRAY_BUFFER, vbo.getOpenGlId(index)); + // checkGlError("glBindBuffer", __LINE__, _idElem); Log.verbose(" id=" + this.elementList.get(idElem).elementId); Log.verbose(" jump sample=" + jumpBetweenSample); Log.verbose(" offset=" + offset); @@ -453,176 +462,226 @@ public class ResourceProgram extends Resource { false, // take our values as-is 0, // no extra data between each position 0); // Pointer on the buffer - //checkGlError("glVertexAttribPointer", __LINE__, _idElem); + // checkGlError("glVertexAttribPointer", __LINE__, _idElem); GL20.glEnableVertexAttribArray(this.elementList.get(idElem).elementId); this.listOfVBOUsed.add(this.elementList.get(idElem).elementId); - //checkGlError("glEnableVertexAttribArray", __LINE__, _idElem); + // checkGlError("glEnableVertexAttribArray", __LINE__, _idElem); } - + + /** + * set the testure Id on the specify uniform element. + * @param idElem Id of the uniform that might be sended. + * @param textureOpenGlID Real openGL texture ID + */ + public void setTexture0(final int idElem, final int textureOpenGlID) { + if (!this.exist) { + return; + } + if (idElem < 0 || (long) idElem > this.elementList.size()) { + return; + } + if (!this.elementList.get(idElem).isLinked) { + return; + } + OpenGL.activeTexture(0); + // set the textureID + OpenGL.bindTexture2D(textureOpenGlID); + // set the texture on the uniform attribute + uniformInt(this.elementList.get(idElem).elementId, /* GLTEXTURE */0); + this.hasTexture = true; + } + + public void setTexture1(final int idElem, final int textureOpenGlID) { + if (!this.exist) { + return; + } + if (idElem < 0 || (long) idElem > this.elementList.size()) { + return; + } + if (!this.elementList.get(idElem).isLinked) { + return; + } + OpenGL.activeTexture(1); + // set the textureID + OpenGL.bindTexture2D(textureOpenGlID); + // set the texture on the uniform attribute + uniformInt(this.elementList.get(idElem).elementId, /* GLTEXTURE */0); + this.hasTexture1 = true; + } + public void uniformColor(final int idElem, final Color value) { - if (this.exist == false) { + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformColor(this.elementList.get(idElem).elementId, value); } - + /** - * @brief Send 1 float uniform element to the spefified ID (not send if does not really exist in the openGL program) + * Send 1 float uniform element to the spefified ID (not send if does not + * really exist in the openGL program) * @param idElem Id of the uniform that might be sended. * @param value1 Value to send at the Uniform */ public void uniformFloat(final int idElem, final float value1) { - if (this.exist == false) { + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1); } - + /** - * @brief Send 2 float uniform element to the spefified ID (not send if does not really exist in the openGL program) + * Send 2 float uniform element to the spefified ID (not send if does not + * really exist in the openGL program) * @param idElem Id of the uniform that might be sended. * @param value1 Value to send at the Uniform * @param value2 Value to send at the Uniform */ public void uniformFloat(final int idElem, final float value1, final float value2) { - - if (this.exist == false) { + + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2); } - + /** - * @brief Send 3 float uniform element to the spefified ID (not send if does not really exist in the openGL program) + * Send 3 float uniform element to the spefified ID (not send if does not + * really exist in the openGL program) * @param idElem Id of the uniform that might be sended. * @param value1 Value to send at the Uniform * @param value2 Value to send at the Uniform * @param value3 Value to send at the Uniform */ public void uniformFloat(final int idElem, final float value1, final float value2, final float value3) { - - if (this.exist == false) { + + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2, value3); } - + /** - * @brief Send 4 float uniform element to the spefified ID (not send if does not really exist in the openGL program) + * Send 4 float uniform element to the spefified ID (not send if does not + * really exist in the openGL program) * @param idElem Id of the uniform that might be sended. * @param value1 Value to send at the Uniform * @param value2 Value to send at the Uniform * @param value3 Value to send at the Uniform * @param value4 Value to send at the Uniform */ - public void uniformFloat(final int idElem, final float value1, final float value2, final float value3, final float value4) { - - if (this.exist == false) { + public void uniformFloat(final int idElem, final float value1, final float value2, final float value3, + final float value4) { + + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2, value3, value4); } - + /** - * @brief Send 1 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program) + * Send 1 signed integer uniform element to the spefified ID (not send if + * does not really exist in the openGL program) * @param idElem Id of the uniform that might be sended. * @param value1 Value to send at the Uniform */ public void uniformInt(final int idElem, final int value1) { - - if (this.exist == false) { + + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1); } - + /** - * @brief Send 2 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program) + * Send 2 signed integer uniform element to the spefified ID (not send if + * does not really exist in the openGL program) * @param idElem Id of the uniform that might be sended. * @param value1 Value to send at the Uniform * @param value2 Value to send at the Uniform */ public void uniformInt(final int idElem, final int value1, final int value2) { - - if (this.exist == false) { + + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2); } - + /** - * @brief Send 3 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program) + * Send 3 signed integer uniform element to the spefified ID (not send if + * does not really exist in the openGL program) * @param idElem Id of the uniform that might be sended. * @param value1 Value to send at the Uniform * @param value2 Value to send at the Uniform * @param value3 Value to send at the Uniform */ public void uniformInt(final int idElem, final int value1, final int value2, final int value3) { - - if (this.exist == false) { + + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2, value3); } - + /** - * @brief Send 4 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program) + * Send 4 signed integer uniform element to the spefified ID (not send if + * does not really exist in the openGL program) * @param idElem Id of the uniform that might be sended. * @param value1 Value to send at the Uniform * @param value2 Value to send at the Uniform @@ -630,177 +689,137 @@ public class ResourceProgram extends Resource { * @param value4 Value to send at the Uniform */ public void uniformInt(final int idElem, final int value1, final int value2, final int value3, final int value4) { - - if (this.exist == false) { + + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2, value3, value4); } - + /** - * @brief Send a uniform element to the spefified ID (not send if does not really exist in the openGL program) - * @param idElem Id of the uniform that might be sended. - * @param matrix Matrix that might be sended. - * @param transpose Transpose the matrix (needed all the taime in the normal openGl access (only not done in the openGL-ES2 due to the fact we must done it ourself) + * Send a uniform element to the spefified ID (not send if does not + * really exist in the openGL program) + * @param idElem Id of the uniform that might be sended. + * @param matrix Matrix that might be sended. + * @param transpose Transpose the matrix (needed all the taime in the normal + * openGl access (only not done in the openGL-ES2 due to the + * fact we must done it ourself) */ public void uniformMatrix(final int idElem, final Matrix4f matrix) { uniformMatrix(idElem, matrix, true); } - - public void uniformMatrix(final int idElem, final Matrix4f matrix, final boolean transpose/*=true*/) { - if (this.exist == false) { + + public void uniformMatrix(final int idElem, final Matrix4f matrix, final boolean transpose/* =true */) { + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } - //Log.error("[" + this.elementList.get(idElem).name + "] send 1 matrix"); - // note : Android des not supported the transposition of the matrix, then we will done it oursef: + // Log.error("[" + this.elementList.get(idElem).name + "] send 1 matrix"); + // note : Android des not supported the transposition of the matrix, then we + // will done it oursef: /* - if (transpose == true) { - Matrix4f tmp = matrix; - tmp.transpose(); - programLoadUniformMatrix(this.elementList.get(idElem).elementId, tmp.mat); - } else { - programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix.mat); - } - */ + * if (transpose == true) { Matrix4f tmp = matrix; tmp.transpose(); + * programLoadUniformMatrix(this.elementList.get(idElem).elementId, tmp.mat); } + * else { programLoadUniformMatrix(this.elementList.get(idElem).elementId, + * matrix.mat); } + */ OpenGL.programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix, transpose); } - + public void uniformVector(final int idElem, final Vector2f value) { - if (this.exist == false) { + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value); } - + public void uniformVector(final int idElem, final Vector2i value) { - if (this.exist == false) { + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value); } - + public void uniformVector(final int idElem, final Vector3f value) { - if (this.exist == false) { + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value); } - + public void uniformVector(final int idElem, final Vector3i value) { - if (this.exist == false) { + if (!this.exist) { return; } if (idElem < 0 || (long) idElem > this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); return; } - if (false == this.elementList.get(idElem).isLinked) { + if (!this.elementList.get(idElem).isLinked) { return; } OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value); } - - // /** - // * @brief set the testure Id on the specify uniform element. - // * @param idElem Id of the uniform that might be sended. - // * @param textureOpenGlID Real openGL texture ID - // */ - // public void setTexture0(int idElem, int textureOpenGlID){ - // - // if (!this.exist) { - // return; - // } - // if ( idElem < 0 - // || (long)idElem > this.elementList.size()) { - // return; - // } - // if (this.elementList.get(idElem).isLinked == false) { - // return; - // } - // OpenGL.activeTexture(GL13.GL_TEXTURE0); - // // set the textureID - // GL13.glBindTexture(GL13.GL_TEXTURE_2D, textureOpenGlID); - // // set the texture on the uniform attribute - // GL20.glUniform1i(this.elementList.get(idElem).elementId, /*GLTEXTURE*/0); - // this.hasTexture = true; - // } - // public void setTexture1(int idElem, int textureOpenGlID) { - // if (!this.exist) { - // return; - // } - // if ( idElem < 0 - // || (long)idElem > this.elementList.size()) { - // return; - // } - // if (this.elementList.get(idElem).isLinked == false) { - // return; - // } - // OpenGL.activeTexture(GL13.GL_TEXTURE1); - // // set the textureID - // GL13.glBindTexture(GL13.GL_TEXTURE_2D, textureOpenGlID); - // // set the texture on the uniform attribute - // GL20.glUniform1i(this.elementList.get(idElem).elementId, /*GLTEXTURE*/1); - // this.hasTexture1 = true; - // } + /** - * @brief Stop the processing of this program + * Stop the processing of this program */ public void unUse() { - //Log.verbose("Will UN-use program : " + this.program); - - if (this.exist == false) { + // Log.verbose("Will UN-use program : " + this.program); + + if (!this.exist) { return; } for (final Integer it : this.listOfVBOUsed) { GL20.glDisableVertexAttribArray(it); } this.listOfVBOUsed.clear(); - // no need to disable program == > this only generate perturbation on speed ... + // no need to disable program == > this only generate perturbation on speed ... OpenGL.programUse(-1); } - + /** - * @brief This load/reload the data in the opengl context, needed when removed previously. + * This load/reload the data in the opengl context, needed when removed + * previously. */ @Override public boolean updateContext() { - if (this.exist == true) { - // Do nothing == > too dangerous ... + if (this.exist) { + // Do nothing == > too dangerous ... } else { // create the Shader Log.debug("Create the Program ...'" + this.name + "'"); @@ -815,13 +834,14 @@ public class ResourceProgram extends Resource { if (this.shaderFragment != null) { OpenGL.programAttach(this.program, this.shaderFragment.getGLID()); } - + OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, "in_position"); - OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, "tin_extureCoords"); + OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, + "tin_extureCoords"); OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_NORMALS, "in_normal"); OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_COLORS, "in_colors"); - - if (OpenGL.programCompile(this.program) == false) { + + if (!OpenGL.programCompile(this.program)) { Log.error("Could not compile'PROGRAM':'" + this.name + "'"); OpenGL.programRemove(this.program); return true; @@ -829,23 +849,27 @@ public class ResourceProgram extends Resource { // now get the old attribute requested priviously ... long iii = 0; for (final ProgAttributeElement it : this.elementList) { - if (it.isAttribute == true) { + if (it.isAttribute) { it.elementId = OpenGL.programGetAttributeLocation(this.program, it.name); it.isLinked = true; if (it.elementId < 0) { - Log.warning(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId); + Log.warning(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + + "\") = " + it.elementId); it.isLinked = false; } else { - Log.debug(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId); + Log.debug(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + + "\") = " + it.elementId); } } else { it.elementId = OpenGL.programGetUniformLocation(this.program, it.name); it.isLinked = true; if (it.elementId < 0) { - Log.warning(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId); + Log.warning(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + + "\") = " + it.elementId); it.isLinked = false; } else { - Log.debug(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId); + Log.debug(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + + "\") = " + it.elementId); } } iii++; @@ -855,14 +879,15 @@ public class ResourceProgram extends Resource { } return true; } - + /** - * @brief Request the processing of this program + * Request the processing of this program */ public void use() { - //Log.verbose("Will use program : " + this.program); - // event if it was 0 == > set it to prevent other use of the previous shader display ... + // Log.verbose("Will use program : " + this.program); + // event if it was 0 == > set it to prevent other use of the previous shader + // display ... OpenGL.programUse(this.program); } - + } diff --git a/src/org/atriasoft/gale/resource/ResourceShader.java b/src/org/atriasoft/gale/resource/ResourceShader.java index 60380fd..c3966f1 100644 --- a/src/org/atriasoft/gale/resource/ResourceShader.java +++ b/src/org/atriasoft/gale/resource/ResourceShader.java @@ -11,7 +11,7 @@ public class ResourceShader extends Resource { ResourceShader resource; Resource resource2; final String name = uriShader.getValue(); - if (name.isEmpty() == false && name != "---") { + if (!name.isEmpty() && !name.equals("---")) { resource2 = getManager().localKeep(name); } else { Log.error("Can not create a shader without a filaname"); @@ -26,23 +26,18 @@ public class ResourceShader extends Resource { return null; } resource = new ResourceShader(uriShader); - if (resource == null) { - Log.error("allocation error of a resource : " + name); - return null; - } getManager().localAdd(resource); return resource; } private boolean exist = false; //!< The shader file existed and has been loaded - private final String fileData = ""; //!< A copy of the data loaded from the file (usefull only when opengl context is removed) private int shader = -1; //!< opengl id of this element private final ShaderType type; //!< Type of the current shader(vertex/fragment) private final Uri uri; /** - * @brief Contructor of an opengl Shader - * @param filename Standard file name format. see @ref etk::FSNode + * Constructor of an opengl Shader + * @param uri Standard file name format. see @ref etk::FSNode */ protected ResourceShader(final Uri uri) { super(uri); @@ -64,7 +59,7 @@ public class ResourceShader extends Resource { } /** - * @brief Destructor, remove the current Shader + * Destructor, remove the current Shader */ @Override public void cleanUp() { @@ -73,7 +68,7 @@ public class ResourceShader extends Resource { }; /** - * @brief get the opengl reference id of this shader. + * get the opengl reference id of this shader. * @return The opengl id. */ public int getGLID() { @@ -81,7 +76,7 @@ public class ResourceShader extends Resource { }; /** - * @brief get the opengl type of this shader. + * get the opengl type of this shader. * @return The type of this loaded shader. */ public ShaderType getShaderType() { @@ -89,14 +84,16 @@ public class ResourceShader extends Resource { } /** - * @brief Relode the shader from the file. used when a request of resouces reload is done. - * @note this is really usefull when we tested the new themes or shader developpements. + * Reloaded the shader from the file. used when a request of resources reload is done. + * @note this is really useful when we tested the new themes or shader developments. */ @Override public void reload() { - Log.verbose("load shader:\n-----------------------------------------------------------------\n" + this.fileData + "\n-----------------------------------------------------------------"); + //!< A copy of the data loaded from the file (useful only when opengl context is removed) + String fileData = ""; + Log.verbose("load shader:\n-----------------------------------------------------------------\n" + fileData + "\n-----------------------------------------------------------------"); // now change the OGL context ... - if (OpenGL.hasContext() == true) { + if (OpenGL.hasContext()) { Log.debug("OGL : load SHADER '" + this.name + "' ==> call update context (direct)"); removeContext(); updateContext(); @@ -110,11 +107,11 @@ public class ResourceShader extends Resource { } /** - * @brief remove the data from the opengl context. + * remove the data from the opengl context. */ @Override public void removeContext() { - if (true == this.exist) { + if (this.exist) { OpenGL.shaderRemove(this.shader); this.shader = -1; this.exist = false; @@ -122,7 +119,7 @@ public class ResourceShader extends Resource { } /** - * @brief Special android spec! It inform us that all context is removed and after notify us... + * Special android spec! It inform us that all context is removed and after notify us... */ @Override public void removeContextToLate() { @@ -131,14 +128,12 @@ public class ResourceShader extends Resource { } /** - * @brief This load/reload the data in the opengl context, needed when removed previously. + * This load/reload the data in the opengl context, needed when removed previously. */ @Override public boolean updateContext() { - if (this.exist == true) { - // Do nothing == > too dangerous ... - } else { - this.shader = OpenGL.shaderLoad(this.uri.get(), this.type); + if (!this.exist) { + this.shader = OpenGL.shaderLoad(this.uri, this.type); // create the Shader if (this.shader < 0) { return true; diff --git a/src/org/atriasoft/gale/resource/ResourceTexture.java b/src/org/atriasoft/gale/resource/ResourceTexture.java index d097896..8166dd7 100644 --- a/src/org/atriasoft/gale/resource/ResourceTexture.java +++ b/src/org/atriasoft/gale/resource/ResourceTexture.java @@ -32,7 +32,7 @@ public class ResourceTexture extends Resource { ResourceTexture resource; Resource resource2; final String name = uriTexture.getValue(); - if (name.isEmpty() == false && name != "---") { + if (!name.isEmpty() && !name.equals("---")) { resource2 = getManager().localKeep(name); } else { Log.error("Can not create a shader without a filaname"); @@ -48,14 +48,14 @@ public class ResourceTexture extends Resource { } resource = new ResourceTexture(uriTexture, textureUnit); final ImageRawData decodedData = ImageLoader.decodePngFile(uriTexture); - resource.setTexture(decodedData.getBuffer(), new Vector2i(decodedData.getWidth(), decodedData.getHeight()), (decodedData.isHasAlpha() == true ? TextureColorMode.rgba : TextureColorMode.rgb), + resource.setTexture(decodedData.getBuffer(), new Vector2i(decodedData.getWidth(), decodedData.getHeight()), (decodedData.isHasAlpha() ? TextureColorMode.rgba : TextureColorMode.rgb), textureUnit); resource.flush(); return resource; } /** - * @brief get the next power 2 if the input + * get the next power 2 if the input * @param value Value that we want the next power of 2 * @return result value */ @@ -105,7 +105,7 @@ public class ResourceTexture extends Resource { } public void bindForRendering(final int idTexture) { - if (this.loaded == false) { + if (!this.loaded) { return; } GL13.glActiveTexture(textureIdBinding[idTexture]); @@ -142,7 +142,7 @@ public class ResourceTexture extends Resource { @Override public synchronized void removeContext() { - if (this.loaded == true) { + if (this.loaded) { // Request remove texture ... Log.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId); // TODO Check if we are in the correct thread @@ -161,14 +161,13 @@ public class ResourceTexture extends Resource { this.data = data; this.size = size; this.textureUnit = textureUnit; - this.endPointSize.x = size.x; - this.endPointSize.y = size.y; + this.endPointSize = new Vector2f(size.x(), size.y()); this.dataColorSpace = dataColorSpace; flush(); } public void unBindForRendering() { - if (this.loaded == false) { + if (!this.loaded) { return; } if (this.dataColorSpace == TextureColorMode.rgb) { @@ -180,7 +179,7 @@ public class ResourceTexture extends Resource { // Gale internal API: @Override public boolean updateContext() { - if (this.loaded == true) { + if (this.loaded) { return true; } // Request a new texture at openGl : @@ -192,9 +191,9 @@ public class ResourceTexture extends Resource { GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); Log.info("TEXTURE: add [" + getId() + "]=" + this.size + " OGlId=" + this.texId); if (this.dataColorSpace == TextureColorMode.rgb) { - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.size.x, this.size.y, 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, this.data); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, this.data); } else { - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.size.x, this.size.y, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, this.data); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, this.data); } // generate multi-texture mapping GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); diff --git a/src/org/atriasoft/gale/resource/ResourceVirtualArrayObject.java b/src/org/atriasoft/gale/resource/ResourceVirtualArrayObject.java index 48ceaa3..4a68754 100644 --- a/src/org/atriasoft/gale/resource/ResourceVirtualArrayObject.java +++ b/src/org/atriasoft/gale/resource/ResourceVirtualArrayObject.java @@ -76,10 +76,6 @@ public class ResourceVirtualArrayObject extends Resource { int vertexCount = -1; - /** - * @brief ructor of this VBO. - * @param accesMode Acces mode : ??? - */ protected ResourceVirtualArrayObject(final float[] positions, final float[] colors, final float[] textureCoordinates, final float[] normals, final int[] indices, final int vertexCount) { super(); this.resourceLevel = 3; @@ -93,7 +89,7 @@ public class ResourceVirtualArrayObject extends Resource { } public void bindForRendering() { - if (this.exist == false) { + if (!this.exist) { return; } GL30.glBindVertexArray(this.vaoID); @@ -113,7 +109,7 @@ public class ResourceVirtualArrayObject extends Resource { } private void bindIndicesBuffer(final int[] indices) { - final int vboId = OpenGL.glGenBuffers(); + final int vboId = OpenGL.genBuffers(); this.vbo.add(vboId); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboId); final IntBuffer buffer = storeDataInIntBuffer(indices); @@ -121,7 +117,7 @@ public class ResourceVirtualArrayObject extends Resource { } /** - * @brief Destructor of this VBO. + * Destructor of this VBO. */ @Override public void cleanUp() { @@ -129,7 +125,7 @@ public class ResourceVirtualArrayObject extends Resource { } /** - * @brief clear buffers + * clear buffers */ public void clear() { //Log.verbose(" Clear: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.get(0).length + ")"); @@ -143,7 +139,7 @@ public class ResourceVirtualArrayObject extends Resource { } /** - * @brief Send the data to the graphic card. + * Send the data to the graphic card. */ public void flush() { // request to the manager to be call at the next update ... @@ -152,7 +148,7 @@ public class ResourceVirtualArrayObject extends Resource { } /** - * @brief get the real openGL ID. + * get the real openGL ID. * @return the Ogl id reference of this VBO. */ public int getGLID() { @@ -185,7 +181,7 @@ public class ResourceVirtualArrayObject extends Resource { } /** - * @brief Relode the shader from the file. used when a request of resouces reload is done. + * Relode the shader from the file. used when a request of resouces reload is done. * @note this is really usefull when we tested the new themes or shader developpements. */ @Override @@ -195,23 +191,21 @@ public class ResourceVirtualArrayObject extends Resource { } /** - * @brief remove the data from the opengl context. + * remove the data from the opengl context. */ @Override public void removeContext() { - - if (this.exist == true) { + if (this.exist) { // OpenGL.deleteBuffers(this.vbo); this.exist = false; } } /** - * @brief Special android spec! It inform us that all context is removed and after notify us... + * Special android spec! It inform us that all context is removed and after notify us... */ @Override public void removeContextToLate() { - this.exist = false; // for (int iii=0; iii ALLOCATE new handle"); // Allocate and assign a Vertex Array Object to our handle loadToVAO(); diff --git a/src/org/atriasoft/gale/resource/ResourceVirtualBufferObject.java b/src/org/atriasoft/gale/resource/ResourceVirtualBufferObject.java index 0e00f09..bbd5373 100644 --- a/src/org/atriasoft/gale/resource/ResourceVirtualBufferObject.java +++ b/src/org/atriasoft/gale/resource/ResourceVirtualBufferObject.java @@ -5,6 +5,8 @@ */ package org.atriasoft.gale.resource; +import java.util.Arrays; + import org.atriasoft.etk.Color; import org.atriasoft.etk.math.Vector2f; import org.atriasoft.etk.math.Vector3f; @@ -13,7 +15,7 @@ import org.atriasoft.gale.backend3d.OpenGL.Usage; import org.atriasoft.gale.internal.Log; /** - * @brief ResourceVirtualBufferObject is a specific resources for opengl, this load the data directly in the graphic card ad keep these inside + * ResourceVirtualBufferObject is a specific resources for opengl, this load the data directly in the graphic card ad keep these inside */ public class ResourceVirtualBufferObject extends Resource { @@ -26,14 +28,14 @@ public class ResourceVirtualBufferObject extends Resource { private final Object[] buffer; //!< data that is availlable in the VBO system ... /** - * @brief Constructor of this VBO. - * @param[in] accesMode Acces mode : ??? + * Constructor of this VBO. + * @param accesMode Acces mode : ??? */ - protected ResourceVirtualBufferObject(final int _number) { + protected ResourceVirtualBufferObject(final int number) { super(); - this.vbo = new int[_number]; // 0 - this.buffer = new Object[_number]; - Log.debug("OGL : load VBO count=\"" + _number + "\""); + this.vbo = new int[number]; // 0 + this.buffer = new Object[number]; + Log.debug("OGL : load VBO count=\"" + number + "\""); this.resourceLevel = 3; } @@ -63,18 +65,16 @@ public class ResourceVirtualBufferObject extends Resource { } /** - * @brief clear buffers + * clear buffers */ public void clear() { Log.verbose(" Clear: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")"); // DO not clear the this.vbo indexed in the graphic cards ... - for (int iii = 0; iii < this.buffer.length; iii++) { - this.buffer[iii] = null; - } + Arrays.fill(this.buffer, null); } /** - * @brief Send the data to the graphic card. + * Send the data to the graphic card. */ public synchronized void flush() { // request to the manager to be call at the next update ... @@ -103,15 +103,15 @@ public class ResourceVirtualBufferObject extends Resource { } /** - * @brief get the real openGL ID. + * get the real openGL ID. * @return the Ogl id reference of this VBO. */ - public int getGL_ID(final int _id) { - return this.vbo[_id]; + public int getOpenGlId(final int id) { + return this.vbo[id]; } /** - * @brief Relode the shader from the file. used when a request of resouces reload is done. + * Relode the shader from the file. used when a request of resouces reload is done. * @note this is really usefull when we tested the new themes or shader developpements. */ @Override @@ -121,29 +121,27 @@ public class ResourceVirtualBufferObject extends Resource { } /** - * @brief remove the data from the opengl context. + * remove the data from the opengl context. */ @Override public synchronized void removeContext() { - if (this.exist == true) { + if (this.exist) { OpenGL.deleteBuffers(this.vbo); this.exist = false; } } /** - * @brief Special android spec! It inform us that all context is removed and after notify us... + * Special android spec! It inform us that all context is removed and after notify us... */ @Override public synchronized void removeContextToLate() { this.exist = false; - for (int iii = 0; iii < this.vbo.length; iii++) { - this.vbo[iii] = 0; - } + Arrays.fill(this.vbo, 0); } /** - * @brief get the data from the graphic card. + * get the data from the graphic card. */ public void retreiveData() { Log.error("TODO ... "); @@ -170,7 +168,7 @@ public class ResourceVirtualBufferObject extends Resource { } /** - * @brief This load/reload the data in the opengl context, needed when removed previously. + * This load/reload the data in the opengl context, needed when removed previously. */ @Override public synchronized boolean updateContext() { @@ -182,7 +180,7 @@ public class ResourceVirtualBufferObject extends Resource { return false; } */ - if (this.exist == false) { + if (!this.exist) { Log.debug(" ==> ALLOCATE new handle"); // Allocate and assign a Vertex Array Object to our handle OpenGL.genBuffers(this.vbo); diff --git a/src/org/atriasoft/gale/test/sample1/Sample1Application.java b/src/org/atriasoft/gale/test/sample1/Sample1Application.java index 872051a..f038ad5 100644 --- a/src/org/atriasoft/gale/test/sample1/Sample1Application.java +++ b/src/org/atriasoft/gale/test/sample1/Sample1Application.java @@ -51,10 +51,6 @@ public class Sample1Application extends Application { }; // this is the properties of the buffer requested : "r"/"w" + "-" + buffer type "f"=float "i"=integer this.verticesVBO = ResourceVirtualArrayObject.create(vertices, colors, indices); - if (this.verticesVBO == null) { - Log.error("can not instanciate VBO ..."); - return; - } // TO facilitate some debugs we add a name of the VBO: this.verticesVBO.setName("[VBO] of basic SAMPLE"); // update all the VBO elements ... @@ -69,7 +65,7 @@ public class Sample1Application extends Application { // set the basic openGL view port: (position drawed in the windows) OpenGL.setViewPort(new Vector2f(0,0), size); // Clear all the stacked matrix ... - OpenGL.setBasicMatrix(Matrix4f.identity()); + OpenGL.setBasicMatrix(Matrix4f.IDENTITY); // clear background Color bgColor = new Color(0.0f, 1.0f, 1.0f, 0.75f); OpenGL.clearColor(bgColor); diff --git a/src/org/atriasoft/gale/test/sample2/Sample2Application.java b/src/org/atriasoft/gale/test/sample2/Sample2Application.java index b9ec054..f47773b 100644 --- a/src/org/atriasoft/gale/test/sample2/Sample2Application.java +++ b/src/org/atriasoft/gale/test/sample2/Sample2Application.java @@ -92,10 +92,6 @@ public class Sample2Application extends Application { }; // this is the properties of the buffer requested : "r"/"w" + "-" + buffer type "f"=float "i"=integer this.verticesVBO = ResourceVirtualArrayObject.create(vertices, textureCoords, null, indices); - if (this.verticesVBO == null) { - Log.error("can not instanciate VBO ..."); - return; - } // TO facilitate some debugs we add a name of the VBO: this.verticesVBO.setName("[VBO] of basic SAMPLE"); // update all the VBO elements ... @@ -119,7 +115,7 @@ public class Sample2Application extends Application { // set the basic openGL view port: (position drawed in the windows) OpenGL.setViewPort(new Vector2f(0,0), size); // Clear all the stacked matrix ... - OpenGL.setBasicMatrix(Matrix4f.identity()); + OpenGL.setBasicMatrix(Matrix4f.IDENTITY); // clear background Color bgColor = new Color(0.0f, 1.0f, 1.0f, 0.75f); OpenGL.enable(OpenGL.Flag.flag_depthTest); @@ -143,12 +139,12 @@ public class Sample2Application extends Application { // set Matrix : translation/positionMatrix Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix(); - Matrix4f transforamtionMatrix = Matrix4f.identity(); - transforamtionMatrix.multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,-1))); - transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(1,0,0),this.angleX)); - transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(0,1,0),this.angleY)); - transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(0,0,1),this.angleZ)); - Matrix4f viewMatrix = OpenGL.getCameraMatrix().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(0,0,-2))); + Matrix4f transforamtionMatrix = Matrix4f.IDENTITY; + transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,-1))); + transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(1,0,0),this.angleX)); + transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(0,1,0),this.angleY)); + transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(0,0,1),this.angleZ)); + Matrix4f viewMatrix = OpenGL.getCameraMatrix().multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,-2))); //Matrix4f tmpMatrix = projMatrix * camMatrix; this.verticesVBO.bindForRendering(); this.oGLprogram.uniformMatrix(this.oGLMatrixView, viewMatrix); diff --git a/src/org/atriasoft/gale/tools/ImageLoader.java b/src/org/atriasoft/gale/tools/ImageLoader.java index 2118cbe..f66b0bc 100644 --- a/src/org/atriasoft/gale/tools/ImageLoader.java +++ b/src/org/atriasoft/gale/tools/ImageLoader.java @@ -1,6 +1,5 @@ package org.atriasoft.gale.tools; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; @@ -11,39 +10,39 @@ import de.matthiasmann.twl.utils.PNGDecoder; import de.matthiasmann.twl.utils.PNGDecoder.Format; public class ImageLoader { + public static ImageRawData decodePngFile(final Uri filename) { + ByteBuffer buf = null; + int tWidth = 0; + int tHeight = 0; + boolean hasAlpha = false; + try { + // Open the PNG file as an InputStream + final InputStream in = Uri.getStream(filename); + // Link the PNG decoder to this stream + final PNGDecoder decoder = new PNGDecoder(in); + // Get the width and height of the texture + tWidth = decoder.getWidth(); + tHeight = decoder.getHeight(); + hasAlpha = decoder.hasAlpha(); + // Decode the PNG file in a ByteBuffer + if (hasAlpha) { + buf = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight()); + //decoder.decodeFlipped(buf, decoder.getWidth() * 4, Format.RGBA); + decoder.decode(buf, decoder.getWidth() * 4, Format.RGBA); + } else { + buf = ByteBuffer.allocateDirect(3 * decoder.getWidth() * decoder.getHeight()); + //decoder.decodeFlipped(buf, decoder.getWidth() * 4, Format.RGBA); + decoder.decode(buf, decoder.getWidth() * 3, Format.RGB); + } + buf.flip(); + in.close(); + } catch (final IOException e) { + e.printStackTrace(); + System.err.println("try to load texture " + filename + ", didn't work"); + System.exit(-1); + } + return new ImageRawData(buf, tWidth, tHeight, hasAlpha); + } + private ImageLoader() {} - - public static ImageRawData decodePngFile(Uri filename) { - ByteBuffer buf = null; - int tWidth = 0; - int tHeight = 0; - boolean hasAlpha = false; - try { - // Open the PNG file as an InputStream - InputStream in = new FileInputStream(filename.get()); - // Link the PNG decoder to this stream - PNGDecoder decoder = new PNGDecoder(in); - // Get the width and height of the texture - tWidth = decoder.getWidth(); - tHeight = decoder.getHeight(); - hasAlpha = decoder.hasAlpha(); - // Decode the PNG file in a ByteBuffer - if (hasAlpha == true) { - buf = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight()); - //decoder.decodeFlipped(buf, decoder.getWidth() * 4, Format.RGBA); - decoder.decode(buf, decoder.getWidth() * 4, Format.RGBA); - } else { - buf = ByteBuffer.allocateDirect(3 * decoder.getWidth() * decoder.getHeight()); - //decoder.decodeFlipped(buf, decoder.getWidth() * 4, Format.RGBA); - decoder.decode(buf, decoder.getWidth() * 3, Format.RGB); - } - buf.flip(); - in.close(); - } catch (IOException e) { - e.printStackTrace(); - System.err.println("try to load texture " + filename + ", didn't work"); - System.exit(-1); - } - return new ImageRawData(buf, tWidth, tHeight, hasAlpha); - } } diff --git a/test/src/test/atriasoft/gale/TestBasicLog.java b/test/src/test/atriasoft/gale/TestBasicLog.java index 552868f..e2a5ca4 100644 --- a/test/src/test/atriasoft/gale/TestBasicLog.java +++ b/test/src/test/atriasoft/gale/TestBasicLog.java @@ -13,10 +13,9 @@ import java.util.List; import io.scenarium.logger.Logger; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Order; -//import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; @TestMethodOrder(OrderAnnotation.class)