diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..47edc61 --- /dev/null +++ b/.classpath @@ -0,0 +1,805 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..53b0976 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + jege + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cf1ab25 --- /dev/null +++ b/LICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/src/guis/GuiRenderer.java b/src/guis/GuiRenderer.java index 7819c84..8b468e0 100644 --- a/src/guis/GuiRenderer.java +++ b/src/guis/GuiRenderer.java @@ -29,13 +29,9 @@ public class GuiRenderer { GL30.glBindVertexArray(quad.getVaoID()); GL20.glEnableVertexAttribArray(0); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glDisable(GL11.GL_DEPTH_TEST); - //OpenGL.enable(OpenGL.Flag.flag_blend); - //GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - //OpenGL.enable(OpenGL.Flag.flag_cullFace); - //OpenGL.enable(OpenGL.Flag.flag_back); + OpenGL.enable(OpenGL.Flag.flag_blend); + OpenGL.enable(OpenGL.Flag.flag_cullFace); + OpenGL.enable(OpenGL.Flag.flag_back); for (GuiTexture gui: guis) { GL13.glActiveTexture(GL13.GL_TEXTURE0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, gui.getTexture()); @@ -45,11 +41,9 @@ public class GuiRenderer { GL11.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, quad.getVertexCount()); } - //OpenGL.disable(OpenGL.Flag.flag_blend); - //OpenGL.disable(OpenGL.Flag.flag_cullFace); - //OpenGL.disable(OpenGL.Flag.flag_back); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_DEPTH_TEST); + OpenGL.disable(OpenGL.Flag.flag_blend); + OpenGL.disable(OpenGL.Flag.flag_cullFace); + OpenGL.disable(OpenGL.Flag.flag_back); GL20.glDisableVertexAttribArray(0); GL30.glBindVertexArray(0); diff --git a/src/guis/GuiShader.java b/src/guis/GuiShader.java index 07ac72c..4aebe51 100644 --- a/src/guis/GuiShader.java +++ b/src/guis/GuiShader.java @@ -7,8 +7,8 @@ import shaders.ShaderProgram; public class GuiShader extends ShaderProgram { - private static final String VERTEX_FILE = "src/guis/guiVertexShader.txt"; - private static final String FRAGMENT_FILE = "src/guis/guiFragmentShader.txt"; + private static final String VERTEX_FILE = "src/guis/gui.vert"; + private static final String FRAGMENT_FILE = "src/guis/gui.frag"; private int location_transformationMatrix; diff --git a/src/guis/guiFragmentShader.txt b/src/guis/gui.frag similarity index 100% rename from src/guis/guiFragmentShader.txt rename to src/guis/gui.frag diff --git a/src/guis/guiVertexShader.txt b/src/guis/gui.vert similarity index 100% rename from src/guis/guiVertexShader.txt rename to src/guis/gui.vert diff --git a/src/org/atriaSoft/etk/ThreadAbstract.java b/src/org/atriaSoft/etk/ThreadAbstract.java new file mode 100644 index 0000000..5a81936 --- /dev/null +++ b/src/org/atriaSoft/etk/ThreadAbstract.java @@ -0,0 +1,61 @@ +package org.atriaSoft.etk; + +public abstract class ThreadAbstract { + // thread section: + private boolean threadStopRequested = false; + private Thread threadInstance = null; + private final String threadName; + public ThreadAbstract(String name) { + this.threadName = name; + } + + public void threadStart() { + System.out.println("INFO: Start the thread : " + this.threadName); + if (threadInstance != null) { + threadStop(); + } + threadStopRequested = false; + threadInstance = new Thread() { + public void run() { + threadRun(); + } + }; + threadInstance.setName(threadName); + threadInstance.start(); + } + + private void threadRun() { + System.out.println("INFO: Thread Start: " + threadName); + birth(); + while (threadStopRequested == false) { + try { + runPeriodic(); + } catch (Exception eee) { + eee.printStackTrace(); + } + } + death(); + System.out.println("INFO: Thread Stop: " + threadName); + } + protected abstract void birth(); + protected abstract void runPeriodic(); + protected abstract void death(); + + public void threadStop() { + if (threadStopRequested == true) { + return; + } + threadStopRequested = true; + if (threadInstance == null) { + return; + } + threadInstance.interrupt(); + try { + threadInstance.join(); + } catch (InterruptedException eee) { + // nothing to do + } + threadInstance = null; + } + +} diff --git a/src/org/atriaSoft/etk/Uri.java b/src/org/atriaSoft/etk/Uri.java index d8643a7..d77e207 100644 --- a/src/org/atriaSoft/etk/Uri.java +++ b/src/org/atriaSoft/etk/Uri.java @@ -24,7 +24,7 @@ public class Uri { } public String getPath() { - String[] ret = value.split(":",1); + String[] ret = value.split(":",2); return genericMap.get(ret[0]) + "/" + ret[1]; } public String get() { diff --git a/src/org/atriaSoft/etk/math/Matrix3f.java b/src/org/atriaSoft/etk/math/Matrix3f.java index 7d43982..aba82bd 100644 --- a/src/org/atriaSoft/etk/math/Matrix3f.java +++ b/src/org/atriaSoft/etk/math/Matrix3f.java @@ -1,5 +1,7 @@ package org.atriaSoft.etk.math; +import java.util.Arrays; + public class Matrix3f { public float[] mat = new float[3*3]; //!< matrix data /** diff --git a/src/org/atriaSoft/etk/math/Matrix4f.java b/src/org/atriaSoft/etk/math/Matrix4f.java index 5f5c54f..fc1d02d 100644 --- a/src/org/atriaSoft/etk/math/Matrix4f.java +++ b/src/org/atriaSoft/etk/math/Matrix4f.java @@ -139,7 +139,7 @@ public class Matrix4f { * @brief Operator*= Multiplication an other matrix with this one * @param[in] obj Reference on the external object */ - public void multiply(Matrix4f obj) { + public Matrix4f multiply(Matrix4f obj) { // output Matrix float[] matrixOut = new float[16]; for(int xxx=0; xxx<4 ; xxx++) { @@ -155,6 +155,10 @@ public class Matrix4f { for(int iii=0; iii<4*4 ; iii++) { this.mat[iii] = matrixOut[iii]; } + return this; + } + public Matrix4f multiply_new(Matrix4f obj) { + return this.clone().multiply(obj); } /** * @brief Operator* apply matrix on a vector @@ -169,7 +173,7 @@ public class Matrix4f { /** * @brief Transpose the current matix (usefull for OpenGL display) */ - public void transpose() { + public Matrix4f transpose() { float tmpVal = this.mat[1]; this.mat[1] = this.mat[4]; this.mat[4] = tmpVal; @@ -193,13 +197,20 @@ public class Matrix4f { tmpVal = this.mat[11]; this.mat[11] = this.mat[14]; this.mat[14] = tmpVal; + return this; + } + public Matrix4f transpose_new() { + return this.clone().transpose(); } /** * @brief Scale the current Matrix. * @param[in] vect Scale vector to apply. */ - public void scale(Vector3f vect) { - scale(vect.x, vect.y, vect.z); + public Matrix4f scale(Vector3f vect) { + return scale(vect.x, vect.y, vect.z); + } + public Matrix4f scale_new(Vector3f vect) { + return this.clone().scale(vect.x, vect.y, vect.z); } /** * @brief Scale the current Matrix. @@ -207,34 +218,49 @@ public class Matrix4f { * @param[in] sy Scale Y value to apply. * @param[in] sz Scale Z value to apply. */ - public void scale(float sx, float sy, float sz) { + public Matrix4f scale(float sx, float sy, float sz) { this.mat[0] *= sx; this.mat[1] *= sy; this.mat[2] *= sz; this.mat[4] *= sx; this.mat[5] *= sy; this.mat[6] *= sz; this.mat[8] *= sx; this.mat[9] *= sy; this.mat[10] *= sz; + return this; + } + public Matrix4f scale_new(float sx, float sy, float sz) { + return this.clone().scale(sx, sy, sz); } /** * @brief Scale the current Matrix in all direction with 1 value. * @param[in] scale Scale XYZ value to apply. */ - public void scale(float scale) { - scale(scale, scale, scale); + public Matrix4f scale(float scale) { + return scale(scale, scale, scale); + } + public Matrix4f scale_new(float scale) { + return this.clone().scale(scale, scale, scale); } /** * @brief Makes a rotation matrix about an arbitrary axis. * @param[in] vect vector to apply the angle. * @param[in] angleRad angle to apply. */ - public void rotate(Vector3f vect, float angleRad) { + public Matrix4f rotate(Vector3f vect, float angleRad) { Matrix4f tmpMat = createMatrixRotate(vect, angleRad); - this.multiply(tmpMat); + return this.multiply(tmpMat); + } + public Matrix4f rotate_new(Vector3f vect, float angleRad) { + Matrix4f tmpMat = createMatrixRotate(vect, angleRad); + return this.multiply_new(tmpMat); } /** * @brief Makes a translation of the matrix * @param[in] vect Translation to apply. */ - public void translate(Vector3f vect) { + public Matrix4f translate(Vector3f vect) { Matrix4f tmpMat = createMatrixTranslate(vect); - this.multiply(tmpMat); + return this.multiply(tmpMat); + } + public Matrix4f translate_new(Vector3f vect) { + Matrix4f tmpMat = createMatrixTranslate(vect); + return this.multiply_new(tmpMat); } /** * @brief Computes a cofactor. Used for matrix inversion. @@ -267,7 +293,7 @@ public class Matrix4f { * @note The determinant must be != 0, otherwithe the matrix can't be inverted. * @return The inverted matrix. */ - public Matrix4f invert() { + public Matrix4f invert_new() { float det = determinant(); if(Math.abs(det) < (1.0e-7f)) { // The matrix is not invertible! Singular case! diff --git a/src/org/atriaSoft/etk/math/Quaternion.java b/src/org/atriaSoft/etk/math/Quaternion.java index 2b75cfd..bc8d931 100644 --- a/src/org/atriaSoft/etk/math/Quaternion.java +++ b/src/org/atriaSoft/etk/math/Quaternion.java @@ -1,5 +1,7 @@ package org.atriaSoft.etk.math; +import java.util.Arrays; + public class Quaternion { public float x; public float y; @@ -645,4 +647,8 @@ public class Quaternion { public Quaternion clone() { return new Quaternion(this); } + @Override + public String toString() { + return "Quaternion(" + this.x + "," + this.y + "," + this.z + "," + this.w + ")"; + } } diff --git a/src/org/atriaSoft/etk/math/Transform3D.java b/src/org/atriaSoft/etk/math/Transform3D.java index 17bd58f..e76c612 100644 --- a/src/org/atriaSoft/etk/math/Transform3D.java +++ b/src/org/atriaSoft/etk/math/Transform3D.java @@ -104,4 +104,8 @@ public class Transform3D { public Transform3D clone() { return new Transform3D(this); } + @Override + public String toString() { + return "Transform3D(" + this.position + " & " + this.orientation + ")"; + } } diff --git a/src/org/atriaSoft/etk/math/Vector2f.java b/src/org/atriaSoft/etk/math/Vector2f.java index 0838cb5..6e64149 100644 --- a/src/org/atriaSoft/etk/math/Vector2f.java +++ b/src/org/atriaSoft/etk/math/Vector2f.java @@ -10,6 +10,9 @@ public class Vector2f { this.x = 0; this.y = 0; } + public static Vector2f zero() { + return new Vector2f(0,0); + } /** * @brief Constructor from scalars * @param[in] xxx X value @@ -355,4 +358,8 @@ public class Vector2f { public Vector2f clone() { return new Vector2f(this); } + @Override + public String toString() { + return "Vector2f(" + this.x + "," + this.y + ")"; + } } diff --git a/src/org/atriaSoft/etk/math/Vector2i.java b/src/org/atriaSoft/etk/math/Vector2i.java index 845b8d6..e8adede 100644 --- a/src/org/atriaSoft/etk/math/Vector2i.java +++ b/src/org/atriaSoft/etk/math/Vector2i.java @@ -355,4 +355,8 @@ public class Vector2i { public Vector2i clone() { return new Vector2i(this); } + @Override + public String toString() { + return "Vector2i(" + this.x + "," + this.y + ")"; + } } diff --git a/src/org/atriaSoft/etk/math/Vector3f.java b/src/org/atriaSoft/etk/math/Vector3f.java index 2dae9a8..4dd413b 100644 --- a/src/org/atriaSoft/etk/math/Vector3f.java +++ b/src/org/atriaSoft/etk/math/Vector3f.java @@ -500,4 +500,8 @@ public class Vector3f { public static Vector3f zero() { return new Vector3f(0,0,0); } + @Override + public String toString() { + return "Vector3f(" + this.x + "," + this.y + "," + this.z + ")"; + } } diff --git a/src/org/atriaSoft/etk/math/Vector3i.java b/src/org/atriaSoft/etk/math/Vector3i.java index 0950c12..9be9ace 100644 --- a/src/org/atriaSoft/etk/math/Vector3i.java +++ b/src/org/atriaSoft/etk/math/Vector3i.java @@ -469,4 +469,8 @@ public class Vector3i { public static Vector3i zero() { return new Vector3i(0,0,0); } + @Override + public String toString() { + return "Vector3i(" + this.x + "," + this.y + "," + this.z + ")"; + } } diff --git a/src/org/atriaSoft/gale/Application.java b/src/org/atriaSoft/gale/Application.java index 46110ba..318bdb4 100644 --- a/src/org/atriaSoft/gale/Application.java +++ b/src/org/atriaSoft/gale/Application.java @@ -1,189 +1,283 @@ package org.atriaSoft.gale; +import org.atriaSoft.etk.Uri; +import org.atriaSoft.etk.math.Vector2f; +import org.atriaSoft.gale.context.ClipboardList; +import org.atriaSoft.gale.context.Context; +import org.atriaSoft.gale.context.Cursor; +import org.atriaSoft.gale.key.Keyboard; +import org.atriaSoft.gale.key.Special; +import org.atriaSoft.gale.key.Status; +import org.atriaSoft.gale.key.Type; + public class Application { - private boolean m_canDraw; - private boolean m_needRedraw; - private String m_title; - private Uri m_iconName; - private Cursor m_cursor; + public boolean canDraw = false; + private boolean needRedraw = true; + private String title = "gale"; + private Uri iconName = new Uri(""); + private Cursor cursor = Cursor.arrow; + private Orientation orientation = Orientation.screenAuto; + Vector2f windowsSize = new Vector2f(800,600); public Application() { - Log.verbose("Constructor Gale Application") + Log.verbose("Constructor Gale Application"); } /** * @brief The application is created. - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onCreate(gale::Context& _context); + public void onCreate(Context context) { + Log.verbose("Create Gale Application"); + } /** * @brief The application is started. - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onStart(gale::Context& _context); + public void onStart(Context context){ + Log.verbose("Start Gale Application"); + } /** * @brief The application is resumed (now visible). - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onResume(gale::Context& _context); + public void onResume(Context context){ + Log.verbose("Start Gale Application"); + } /** * @brief call application to precalculate drawing. - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onRegenerateDisplay(gale::Context& _context); + public void onRegenerateDisplay(Context context) { + Log.verbose("Regenerate Gale Application"); + markDrawingIsNeeded(); + } + /** * @brief Real draw of the application - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onDraw(gale::Context& _context); + public void onDraw(Context context) { + Log.verbose("draw Gale Application"); + } /** * @brief The application is Hide / not visible. - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onPause(gale::Context& _context); + public void onPause(Context context) { + Log.verbose("Pause Gale Application"); + } /** * @brief The application is stopped. - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onStop(gale::Context& _context); + public void onStop(Context context) { + Log.verbose("Stop Gale Application"); + } /** * @brief The application is removed (call destructor just adter it.). - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onDestroy(gale::Context& _context); + public void onDestroy(Context context) { + Log.verbose("Destroy Gale Application"); + } /** * @brief The user request application removing. - * @param[in] _context Current gale context. + * @param[in] context Current gale context. */ - public void onKillDemand(gale::Context& _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)) - * @param[in] _value value to return on the program + * @param[in] value value to return on the program */ - public void exit(int32_t _value); + public void exit(int value) { + Log.verbose("Exit Requested " + value); + Gale.getContext().stop(); + } - public void markDrawingIsNeeded(); - public boolean isDrawingNeeded(); + public void markDrawingIsNeeded() { + this.needRedraw = true; + } + public boolean isDrawingNeeded() { + boolean tmp = this.needRedraw; + this.needRedraw = false; + return tmp; + } /** * @brief Get touch/mouse/... event. - * @param[in] _type Type of pointer event - * @param[in] _pointerID Pointer id of the touch event. - * @param[in] _pos Position of the event (can be <0 if out of window). - * @param[in] _state Key state (up/down/move) + * @param[in] type Type of pointer event + * @param[in] pointerID Pointer id of the touch event. + * @param[in] pos Position of the event (can be <0 if out of window). + * @param[in] state Key state (up/down/move) */ - public void onPointer(enum gale::key::type _type, - int32_t _pointerID, - const vec2& _pos, - gale::key::status _state); + public void onPointer(Type type, + int pointerID, + Vector2f pos, + Status state) { + + } /** * @brief Get keyborad value input. - * @param[in] _special Current special key status (ctrl/alt/shift ...). - * @param[in] _type Type of the event. - * @param[in] _value Unicode value of the char pushed (viable only if _type==gale::key::keyboard::character). - * @param[in] _state State of the key (up/down/upRepeate/downRepeate) + * @param[in] special Current special key status (ctrl/alt/shift ...). + * @param[in] type Type of the event. + * @param[in] value Unicode value of the char pushed (viable only if type==gale::key::keyboard::character). + * @param[in] state State of the key (up/down/upRepeate/downRepeate) */ - public void onKeyboard(const gale::key::Special& _special, - enum gale::key::keyboard _type, - char32_t _value, - gale::key::status _state); + public void onKeyboard(Special special, + Keyboard type, + Character value, + Status state) { + + } /** * @brief Show the virtal keyboard (if possible : only on iOs/Android) */ - public void keyboardShow(); + 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(); + 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[in] _size New size of the window. + * @param[in] size New size of the window. */ - public void onResize(const ivec2& _size); + public void onResize(Vector2f size) { + + } /** * @brief Set the size of the window (if possible: Android and Ios does not support it) - * @param[in] _size New size of the window. + * @param[in] size New size of the window. * @return */ - public void setSize(const vec2& _size); + 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 vec2 getSize() const; + public Vector2f getSize() { + return windowsSize; + } /** * @brief Event generated when user change the position of the window. - * @param[in] _size New position of the window. + * @param[in] size New position of the window. */ - public void onMovePosition(const vec2& _size); + public void onMovePosition(Vector2f size) { + + } /** * @brief Set the position of the window (if possible: Android and Ios does not support it) - * @param[in] _size New position of the window. + * @param[in] size New position of the window. */ - public void setPosition(const vec2& _size); + public void setPosition(Vector2f size) { + + } /** * @brief Get the position of the window. * @return Current position of the window. */ - public vec2 getPosition() const; + public Vector2f getPosition() { + return new Vector2f(0,0); + } /** * @brief Set the title of the application - * @param[in] _title New title to set at the application (if possible: Android and Ios does not support it) + * @param[in] title New title to set at the application (if possible: Android and Ios does not support it) */ - public void setTitle(const etk::String& _title); + 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 etk::String getTitle(); + public String getTitle() { + return this.title; + } /** * @brief set the Icon of the application. - * @param[in] _iconFile File name icon (.bmp/.png). + * @param[in] iconFile File name icon (.bmp/.png). */ - public void setIcon(const etk::Uri& _iconFile); + 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 const etk::Uri& getIcon(); + public Uri getIcon() { + return this.iconName; + } /** * @brief Set the cursor type. - * @param[in] _newCursor Selected cursor. + * @param[in] newCursor Selected cursor. */ - public void setCursor(enum gale::context::cursor _newCursor); + public void setCursor(Cursor newCursor) { + Gale.getContext().setCursor(this.cursor); + } /** * @brief Get the cursor type. * @return the current cursor. */ - public enum gale::context::cursor getCursor(); - /** - * @brief Open an URL on an internal brother. - * @param[in] _url URL to open. - */ - public void openURL(const etk::String& _url); - - private Orientation m_orientation; - + public Cursor getCursor() { + return this.cursor; + } /** * @brief set the screen orientation (if possible : only on iOs/Android) - * @param[in] _orientation New orientation. + * @param[in] orientation New orientation. */ - public void setOrientation(Orientation _orientation); + public void setOrientation(Orientation orientation) { + this.orientation = orientation; + Gale.getContext().forceOrientation(this.orientation); + } /** * @brief get the screen orientation (if possible : only on iOs/Android) * @return Current orientation. */ - public Orientation getOrientation(); + public Orientation getOrientation() { + return this.orientation; + } + /** * @brief A clipboard data is back (apear after a request of a new clipboard). - * @param[in] _clipboardId Id of the clipboard. + * @param[in] clipboardId Id of the clipboard. */ - public void onClipboardEvent(ClipboardList _clipboardId); + public void onClipboardEvent(ClipboardList clipboardId) { + + } + /** * @brief Call every time a draw is called (not entirely periodic, but faster at we can ... - * @param[in] _time Current time of the call; + * @param[in] time Current time of the call; */ - public void onPeriod(const echrono::Clock& _time) {}; + public void onPeriod(long time) {}; } diff --git a/src/org/atriaSoft/gale/Gale.java b/src/org/atriaSoft/gale/Gale.java index dc1fa79..adc8643 100644 --- a/src/org/atriaSoft/gale/Gale.java +++ b/src/org/atriaSoft/gale/Gale.java @@ -1,5 +1,8 @@ package org.atriaSoft.gale; +import org.atriaSoft.gale.context.Context; +import org.atriaSoft.gale.context.LWJGL.ContextLWJGL; + public class Gale { /** * @brief This is the only one things the User might done in his main(); @@ -13,25 +16,30 @@ public class Gale { * @param[in] _argv Standard argv * @return normal error int for the application error management */ - int run(Application application, String arg[]) { + public static int run(Application application, String arg[]) { //etk::init(_argc, _argv); Context context = null; String request = ""; - context = ContextLWJGL.create(_application, arg); + context = ContextLWJGL.create(application, arg); if (context == null) { Log.error("Can not allocate the interface of the GUI ..."); return -1; } - return context->run(); + return context.run(); } /** * @brief get GALE version * @return The string that describe gale version */ - String getVersion() { + public static String getVersion() { return "J-0.5"; } + + public static Context getContext() { + // TODO Auto-generated method stub + return Context.getContext(); + } } diff --git a/src/org/atriaSoft/gale/backend3d/OpenGL.java b/src/org/atriaSoft/gale/backend3d/OpenGL.java index f11c55a..2a3c2f6 100644 --- a/src/org/atriaSoft/gale/backend3d/OpenGL.java +++ b/src/org/atriaSoft/gale/backend3d/OpenGL.java @@ -3,6 +3,7 @@ package org.atriaSoft.gale.backend3d; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; +import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -11,12 +12,14 @@ import java.util.Map; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import org.atriaSoft.etk.math.Matrix4f; import org.atriaSoft.etk.math.Vector2f; import org.atriaSoft.etk.math.Vector2i; import org.atriaSoft.etk.math.Vector3f; +import org.atriaSoft.etk.math.Vector3i; import org.atriaSoft.etk.Color; import org.atriaSoft.gale.Log; @@ -43,7 +46,7 @@ public class OpenGL { } private static List matrixList = new ArrayList(); - private static Matrix4f matrixCamera; + private static Matrix4f matrixCamera = new Matrix4f(); private static int programId = 0; // We map all the flag, but not all is supported by all platform... @@ -80,7 +83,7 @@ public class OpenGL { flag_fog, flag_back }; - enum RenderMode { + public enum RenderMode { point, line, lineStrip, //!< Not supported in GALE (TODO : Later) @@ -113,6 +116,12 @@ public class OpenGL { private static boolean flagsStatesChange = false; private static Map flagsStates = new HashMap(); + public enum Usage { + streamDraw, + staticDraw, + dynamicDraw + } + public static Map convertUsage; static { flagsStates.put(Flag.flag_blend, new StateFlag()); flagsStates.put(Flag.flag_clipDistanceI, new StateFlag()); @@ -175,6 +184,10 @@ public class OpenGL { // basicFlag.put(Flag.flag_alphaTest, GLALPHATEST); // basicFlag.put(Flag.flag_fog, GLFOG); basicFlag.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 void clearFlagState() { for (Map.Entry elem: flagsStates.entrySet()) { @@ -316,10 +329,10 @@ public class OpenGL { 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("========================"); } /** @@ -329,12 +342,12 @@ public class OpenGL { } public static void setViewPort( Vector2i start, Vector2i stop){ - Log.info("setViewport " + start + " " + stop); + //Log.info("setViewport " + start + " " + stop); GL11.glViewport(start.x, start.y, stop.x, stop.y); checkGlError("glViewport"); } public static void setViewPort( Vector2f start, Vector2f stop){ - Log.info("setViewport " + start + " " + stop); + //Log.info("setViewport " + start + " " + stop); GL11.glViewport((int)start.x, (int)start.y, (int)stop.x, (int)stop.y); checkGlError("glViewport"); } @@ -535,61 +548,62 @@ public class OpenGL { } -// public static boolean genBuffers(List buffers) { -// if (buffers.size() == 0) { -// Log.warning("try to generate vector buffer with size 0"); -// return true; -// } -// Log.info("Create N=" + buffers.size() + " Buffer"); -// glGenBuffers(buffers.size(), &buffers[0]); -// checkGlError("glGenBuffers"); -// boolean hasError = false; -// for (sizet iii=0; iii rtfm ..."); } commandLine.parse(args); - GALE_INFO(" == > Gale system init (BEGIN)"); + Log.info(" == > Gale system init (BEGIN)"); // create thread to manage real periodic event - //this.periodicThread = ememory::makeShared(this); + this.periodicThread = new PeriodicThread(this); // By default we set 2 themes (1 color and 1 shape ...) : - //etk::theme::setNameDefault("GUI", "shape/square/"); - //etk::theme::setNameDefault("COLOR", "color/black/"); + //theme::setNameDefault("GUI", "shape/square/"); + //theme::setNameDefault("COLOR", "color/black/"); // parse the debug level: - for(int iii=0; iii{ Application appl = _context.getApplication(); if (appl == null) { return; @@ -121,63 +145,80 @@ public class Context { // force a recalculation requestUpdateSize(); - // release the curent interface : - unLockContext(); - GALE_INFO(" == > Gale system init (END)"); + Log.info(" == > Gale system init (END)"); } /** * @brief StartProcessing (2nd thread). * @note to call when all the Context is started */ public void start2ndThreadProcessing() { - // set the curent interface: + // set the current interface: lockContext(); - this.periodicThread.start(); - ethread::sleepMilliSeconds((1)); - // release the curent interface: + this.periodicThread.threadStart(); + try { + Thread.sleep(1); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // release the current interface: unLockContext(); } // simulation area: - protected boolean this.simulationActive; - protected etk::Uri this.simulationUri; - protected etk::io::Interface> this.simulationFile; - private echrono::Steady this.previousDisplayTime; // this is to limit framerate ... in case... - private etk::Fifo > this.msgSystem; - private boolean this.displayFps; - private gale::context::Fps this.FpsSystemEvent; - private gale::context::Fps this.FpsSystemContext; - private gale::context::Fps this.FpsSystem; - private gale::context::Fps this.FpsFlush; + private long previousDisplayTime; // this is to limit framerate ... in case... + private Vector msgSystem = new Vector(); + private boolean displayFps = false; + private Fps FpsSystemEvent = new Fps("SystemEvent", displayFps); + private Fps FpsSystemContext = new Fps("SystemContext", displayFps); + private Fps FpsSystem = new Fps("System", displayFps); + private Fps FpsFlush = new Fps("Flush", displayFps); + + + + private synchronized void postAction(ActionToDoInAsyncLoop data) { + msgSystem.addElement(data); + notify(); + //Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object. + } + + // Called by Consumer + public synchronized ActionToDoInAsyncLoop getAction() { + notify(); + while (msgSystem.size() == 0) { + try { + wait(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return null; + }//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep. + } + ActionToDoInAsyncLoop message = (ActionToDoInAsyncLoop) msgSystem.firstElement(); + msgSystem.removeElement(message); + return message; + } /** * @brief Processing all the event arrived ... (commoly called in draw function) */ public void processEvents() { int nbEvent = 0; //Log.debug(" ******** Event " << this.msgSystem.count()); - while (this.msgSystem.count() > 0) { + while (this.msgSystem.size() > 0) { nbEvent++; //Log.verbose(" [" << nbEvent << "] event ..."); - etk::Function func; - { - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.wait(func); - } + ActionToDoInAsyncLoop func = getAction(); if (func == null) { continue; } - func(*this); + func.run(this); } } - public void postAction(etk::Function _action) { - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.post(_action); - } // gale::Context::~Context() { -// GALE_INFO(" == > Gale system Un-Init (BEGIN)"); -// this.periodicThread.stop(); +// Log.info(" == > Gale system Un-Init (BEGIN)"); +// this.periodicThread.threadStart(); // getResourcesManager().applicationExiting(); // // TODO : Clean the message list ... -// // set the curent interface: +// // set the current interface: // lockContext(); // // clean all widget and sub widget with their resources: // //this.objectManager.cleanInternalRemoved(); @@ -193,116 +234,94 @@ public class Context { // //this.objectManager.cleanInternalRemoved(); // this.resourceManager.cleanInternalRemoved(); // -// GALE_INFO("List of all widget of this context must be equal at 0 ==> otherwise some remove is missing"); +// Log.info("List of all widget of this context must be equal at 0 ==> otherwise some remove is missing"); // //this.objectManager.displayListObject(); // // Resource is an lower element as objects ... // this.resourceManager.unInit(); // // now All must be removed !!! // //this.objectManager.unInit(); -// // release the curent interface : +// // release the current interface : // unLockContext(); -// GALE_INFO(" == > Gale system Un-Init (END)"); +// Log.info(" == > Gale system Un-Init (END)"); // if (this.simulationActive == true) { // // in simulation case: // this.simulationFile.close(); // } // } - public void OS_SetInput( gale::key::type _type, - gale::key::status _status, - int _pointerID, - vec2 _pos){ - if (this.simulationActive == true) { - this.simulationFile.puts(etk::toString(echrono::Steady::now())); - this.simulationFile.puts(":INPUT:"); - this.simulationFile.puts(etk::toString(_type)); - this.simulationFile.puts(":"); - this.simulationFile.puts(etk::toString(_status)); - this.simulationFile.puts(":"); - this.simulationFile.puts(etk::toString(_pointerID)); - this.simulationFile.puts(":"); - this.simulationFile.puts(etk::toString(_pos)); - this.simulationFile.puts("\n"); - } - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.post([_type, _status, _pointerID, _pos](gale::Context _context){ - Application> appl = _context.getApplication(); + public void OS_SetInput( Type type, + Status status, + int pointerID, + Vector2f pos){ + postAction((context)->{ + Application appl = context.getApplication(); if (appl == null) { return; } - appl.onPointer(_type, - _pointerID, - _pos, - _status); + appl.onPointer(type, + pointerID, + pos, + status); }); } - public void OS_setKeyboard( gale::key::Special _special, - gale::key::keyboard _type, - gale::key::status _state, - boolean _isARepeateKey = false, - char32_t _char = u32char::Null){ - if (_isARepeateKey == true) { - if (_state == gale::key::status::down) { - _state = gale::key::status::downRepeate; + public void OS_setKeyboard( Special special, + Keyboard type, + Status state, + boolean isARepeateKey, + Character charValue) { + Status tmpState = state; + if (isARepeateKey == true) { + if (tmpState == Status.down) { + tmpState = Status.downRepeate; } else { - _state = gale::key::status::upRepeate; + tmpState = Status.upRepeate; } } - if (this.simulationActive == true) { - this.simulationFile.puts(etk::toString(echrono::Steady::now())); - this.simulationFile.puts(":KEYBOARD:"); - this.simulationFile.puts(etk::toString(_special)); - this.simulationFile.puts(":"); - this.simulationFile.puts(etk::toString(_type)); - this.simulationFile.puts(":"); - this.simulationFile.puts(etk::toString(_state)); - this.simulationFile.puts(":"); - this.simulationFile.puts(etk::toString(uint64_t(_char))); - this.simulationFile.puts("\n"); - } - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.post([_special, _type, _state, _char](gale::Context _context){ - Application> appl = _context.getApplication(); + OS_setKeyboard2(special, type, state, charValue); + } + public void OS_setKeyboard2( Special special, + Keyboard type, + Status state, + Character charValue){ + postAction((context)->{ + Application appl = context.getApplication(); if (appl == null) { return; } - appl.onKeyboard(_special, - _type, - _char, - _state); + appl.onKeyboard(special, + type, + charValue, + state); }); } /** * @brief The current context is suspended */ public void OS_Suspend(){ - // set the curent interface : + // set the current interface : lockContext(); - GALE_INFO("OS_Suspend..."); - this.previousDisplayTime = echrono::Steady(); - #if 0 - if (this.windowsCurrent != null) { - this.windowsCurrent.onStateSuspend(); - } - #endif - // release the curent interface : + Log.info("OS_Suspend..."); + this.previousDisplayTime = 0; + +// if (this.windowsCurrent != null) { +// this.windowsCurrent.onStateSuspend(); +// } + // release the current interface : unLockContext(); } /** * @brief The current context is resumed */ public void OS_Resume(){ - // set the curent interface : + // set the current interface : lockContext(); - GALE_INFO("OS_Resume..."); - this.previousDisplayTime = echrono::Steady::now(); + Log.info("OS_Resume..."); + this.previousDisplayTime = System.currentTimeMillis(); // TODO : this.objectManager.timeCallResume(this.previousDisplayTime); - #if 0 - if (this.windowsCurrent != null) { - this.windowsCurrent.onStateResume(); - } - #endif - // release the curent interface : +// if (this.windowsCurrent != null) { +// this.windowsCurrent.onStateResume(); +// } + // release the current interface : unLockContext(); } @@ -310,75 +329,58 @@ public class Context { * @brief The current context is set in foreground (framerate is maximum speed) */ public void OS_Foreground(){ - // set the curent interface : + // set the current interface : lockContext(); - GALE_INFO("OS_Foreground..."); - #if 0 - if (this.windowsCurrent != null) { - this.windowsCurrent.onStateForeground(); - } - #endif - // release the curent interface : + Log.info("OS_Foreground..."); + +// if (this.windowsCurrent != null) { +// this.windowsCurrent.onStateForeground(); +// } + // release the current interface : unLockContext(); } /** * @brief The current context is set in background (framerate is slowing down (max fps)/5 # 4fps) */ public void OS_Background(){ - // set the curent interface : + // set the current interface : lockContext(); - GALE_INFO("OS_Background..."); - #if 0 - if (this.windowsCurrent != null) { - this.windowsCurrent.onStateBackground(); - } - #endif - // release the curent interface : + Log.info("OS_Background..."); +// if (this.windowsCurrent != null) { +// this.windowsCurrent.onStateBackground(); +// } + // release the current interface : unLockContext(); } public void requestUpdateSize() { - if (this.simulationActive == true) { - this.simulationFile.puts(etk::toString(echrono::Steady::now())); - this.simulationFile.puts(":RECALCULATE_SIZE\n"); - } - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.post([](gale::Context _context){ + postAction((context)->{ //Log.debug("Receive MSG : THREAD_RESIZE"); - _context.forceRedrawAll(); + context.forceRedrawAll(); }); } // return true if a flush is needed - public boolean OS_Draw(boolean _displayEveryTime){ - if (this.simulationActive == true) { - this.simulationFile.puts(etk::toString(echrono::Steady::now())); - this.simulationFile.puts(":DRAW:"); - this.simulationFile.puts(etk::toString(_displayEveryTime)); - this.simulationFile.puts("\n"); - } - { - static int countMemeCheck = 0; - if (countMemeCheck++ >= 10*16) { - countMemeCheck = 0; - ETK_MEM_SHOW_LOG(true); - } + private static int countMemeCheck = 0; + public boolean OS_Draw(boolean displayEveryTime) { + if (countMemeCheck++ >= 10*16) { + countMemeCheck = 0; } //Log.verbose("Call draw"); - echrono::Steady currentTime = echrono::Steady::now(); + long currentTime = System.currentTimeMillis(); //echrono::Time currentTime2 = echrono::Time::now(); //Log.warning("Time = " << currentTime << " " << currentTime2); // TODO : Review this ... // this is to prevent the multiple display at the a high frequency ... - #if ( !defined(__TARGET_OS__Windows) \ - & !defined(__TARGET_OS__Android)) - if(currentTime - this.previousDisplayTime < echrono::milliseconds(8)) { - ethread::sleepMilliSeconds((1)); - return false; + if(currentTime - this.previousDisplayTime < 8) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - #endif + return false; + } this.previousDisplayTime = currentTime; - - gale::openGL::threadHasContext(); - + OpenGL.threadHasContext(); // process the events if (this.displayFps == true) { this.FpsSystemEvent.tic(); @@ -401,26 +403,26 @@ public class Context { if (this.application != null) { // Redraw all needed elements //Log.debug("Regenerate Display"); - this.application.onRegenerateDisplay(*this); + this.application.onRegenerateDisplay(this); needRedraw = this.application.isDrawingNeeded(); } if (this.displayFps == true) { this.FpsSystemEvent.incrementCounter(); this.FpsSystemEvent.toc(); } - // release the curent interface : + // release the current interface : unLockContext(); } boolean hasDisplayDone = false; //! drawing section: { // Lock openGl context: - gale::openGL::lock(); + OpenGL.lock(); if (this.displayFps == true) { this.FpsSystemContext.tic(); } if( needRedraw == true - || _displayEveryTime == true) { + || displayEveryTime == true) { //Log.debug(" ==> real Draw"); lockContext(); this.resourceManager.updateContext(); @@ -435,12 +437,12 @@ public class Context { } if (this.application != null) { if( needRedraw == true - || _displayEveryTime == true) { + || displayEveryTime == true) { this.FpsSystem.incrementCounter(); - // set the curent interface : + // set the current interface : lockContext(); if (this.application.canDraw == true) { - this.application.onDraw(*this); + this.application.onDraw(this); } unLockContext(); hasDisplayDone = true; @@ -451,17 +453,17 @@ public class Context { this.FpsFlush.tic(); } if (hasDisplayDone == true) { - //GALE_INFO("lklklklklk " << _displayEveryTime); + //Log.info("lklklklklk " << _displayEveryTime); if (this.displayFps == true) { this.FpsFlush.incrementCounter(); } - gale::openGL::flush(); + OpenGL.flush(); } if (this.displayFps == true) { this.FpsFlush.toc(); } // release open GL Context - gale::openGL::unLock(); + OpenGL.unLock(); } if (this.displayFps == true) { this.FpsSystemEvent.draw(); @@ -470,20 +472,20 @@ public class Context { this.FpsFlush.draw(); } { - // set the curent interface: + // set the current interface: lockContext(); // release open GL Context - gale::openGL::lock(); + OpenGL.lock(); // while The Gui is drawing in OpenGl, we do some not realTime things this.resourceManager.updateContext(); // release open GL Context - gale::openGL::unLock(); + OpenGL.unLock(); // TODO : this.objectManager.cleanInternalRemoved(); this.resourceManager.cleanInternalRemoved(); - // release the curent interface: + // release the current interface: unLockContext(); } - gale::openGL::threadHasNoMoreContext(); + OpenGL.threadHasNoMoreContext(); return hasDisplayDone; } /** @@ -502,114 +504,101 @@ public class Context { * @brief The OS Inform that the Window has been killed */ public void OS_Stop(){ - // set the curent interface : + // set the current interface : lockContext(); - GALE_INFO("OS_Stop..."); + Log.info("OS_Stop..."); if (this.application == null) { stop(); return; } - this.application.onKillDemand(*this); - // release the curent interface : + this.application.onKillDemand(this); + // release the current interface : unLockContext(); - + } /** * @brief The application request that the Window will be killed */ public void stop() { Log.warning("stop: NOT implemented for this platform..."); } - protected ivec2 this.windowsSize; //!< current size of the system + protected Vector2f windowsSize; //!< current size of the system /** * @brief get the current windows size * @return the current size ... */ - public ivec2 getSize() { + public Vector2f getSize() { return this.windowsSize; }; /** * @brief The OS inform that the current windows has change his size. * @param[in] _size new size of the windows. */ - public void OS_Resize( vec2 _size){ + public void OS_Resize( Vector2f _size){ if (this.windowsSize == _size) { return; } // TODO : Better in the thread ... ==> but generate some init error ... - gale::Dimension::setPixelWindowsSize(_size); - if (this.simulationActive == true) { - this.simulationFile.puts(etk::toString(echrono::Steady::now())); - this.simulationFile.puts(":RESIZE:"); - this.simulationFile.puts(etk::toString(_size)); - this.simulationFile.puts("\n"); - } - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.post([_size](gale::Context _context){ - Log.debug("Receive MSG : THREAD_RESIZE : " << _context.windowsSize << " ==> " << _size); - _context.windowsSize = _size; - gale::Dimension::setPixelWindowsSize(_context.windowsSize); + //gale::Dimension::setPixelWindowsSize(_size); + postAction((context) -> { + Log.debug("Receive MSG : THREAD_RESIZE : " + context.windowsSize + " ==> " + _size); + context.windowsSize = _size; + //gale::Dimension::setPixelWindowsSize(_context.windowsSize); // call application inside .. - _context.forceRedrawAll(); + context.forceRedrawAll(); }); } /** - * @brief The application request a change of his curent size. + * @brief The application request a change of his current size. * @param[in] _size new Requested size of the windows. */ - public void setSize( vec2 _size){ - GALE_INFO("setSize: NOT implemented ..."); + public void setSize( Vector2f _size){ + Log.info("setSize: NOT implemented ..."); }; /** * @brief The application request a change of his current size force the fullscreen mode. * @param[in] _status status of the fullscreen mode. */ public void setFullScreen(boolean _status){ - GALE_INFO("setFullScreen: NOT implemented ..."); + Log.info("setFullScreen: NOT implemented ..."); }; - protected ivec2 this.windowsPos; //!< current size of the system + protected Vector2f windowsPos; //!< current size of the system /** * @brief The OS inform that the current windows has change his position. * @param[in] _pos New position of the Windows. */ - public void OS_Move( vec2 _pos){ - if (this.windowsPos == _pos) { + public void OS_Move( Vector2f _pos){ + if (this.windowsPos.isEqual(_pos)) { return; } - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.post([_pos](gale::Context _context){ - Log.debug("Receive MSG : THREAD_MOVE : " << _context.windowsPos << " ==> " << _pos); - _context.windowsPos = _pos; - Application> appl = _context.getApplication(); + postAction((context) -> { + Log.debug("Receive MSG : THREAD_MOVE : " + context.windowsPos + " ==> " + _pos); + context.windowsPos = _pos; + Application appl = context.getApplication(); if (appl == null) { return; } - appl.onMovePosition(_context.windowsPos); + appl.onMovePosition(context.windowsPos); }); } /** * @brief The Application request that the current windows will change his position. * @param[in] _pos New position of the Windows requested. */ - public void setPos( vec2 _pos){ - GALE_INFO("setPos: NOT implemented ..."); + public void setPos( Vector2f _pos){ + Log.info("setPos: NOT implemented ..."); } /** * @brief The Application request the current position of the windows. * @return Turrent position of the Windows. */ - public vec2 getPos(){ + public Vector2f getPos(){ return this.windowsPos; } /** * @brief The OS inform that the Windows is now Hidden. */ public void OS_Hide() { - if (this.simulationActive == true) { - this.simulationFile.puts(etk::toString(echrono::Steady::now())); - this.simulationFile.puts(":VIEW:false\n"); - } - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.post([](gale::Context _context){ + postAction((context) -> { /* Application> appl = _context.getApplication(); if (appl == null) { @@ -620,24 +609,20 @@ public class Context { _char, _state); */ - GALE_TODO("HIDE ... "); + Log.todo("HIDE ... "); }); } /** * @brief The Application request that the Windows will be Hidden. */ public void hide(){ - GALE_INFO("hide: NOT implemented ..."); + Log.info("hide: NOT implemented ..."); }; /** * @brief The OS inform that the Windows is now visible. */ public void OS_Show(){ - if (this.simulationActive == true) { - this.simulationFile.puts(etk::toString(echrono::Steady::now())); - this.simulationFile.puts(":VIEW:true\n"); - } - this.msgSystem.post([](gale::Context _context){ + postAction((context) -> { /* Application> appl = _context.getApplication(); if (appl == null) { @@ -648,14 +633,14 @@ public class Context { _char, _state); */ - GALE_TODO("SHOW ... "); + Log.todo("SHOW ... "); }); } /** * @brief The Application request that the Windows will be visible. */ public void show(){ - GALE_INFO("show: NOT implemented ..."); + Log.info("show: NOT implemented ..."); } /** * @brief Redraw all the windows @@ -670,20 +655,20 @@ public class Context { * @brief display the virtal keyboard (for touch system only) */ public void keyboardShow(){ - GALE_INFO("keyboardShow: NOT implemented ..."); + Log.info("keyboardShow: NOT implemented ..."); } /** * @brief Hide the virtal keyboard (for touch system only) */ public void keyboardHide(){ - GALE_INFO("keyboardHide: NOT implemented ..."); + Log.info("keyboardHide: NOT implemented ..."); } /** * @brief Inform the Gui that we want to have a copy of the clipboard * @param[in] _clipboardID ID of the clipboard (STD/SELECTION) only apear here */ - public void clipBoardGet( gale::context::clipBoard::clipboardListe _clipboardID){ + public void clipBoardGet( ClipboardList _clipboardID){ // just transmit an event , we have the data in the system OS_ClipBoardArrive(_clipboardID); } @@ -691,17 +676,16 @@ public class Context { * @brief Inform the Gui that we are the new owner of the clipboard * @param[in] _clipboardID ID of the clipboard (STD/SELECTION) only apear here */ - public void clipBoardSet( gale::context::clipBoard::clipboardListe _clipboardID){ + public void clipBoardSet( ClipboardList _clipboardID){ // nothing to do, data is already copyed in the GALE clipborad center } /** * @brief Call by the OS when a clipboard arrive to US (previously requested by a widget) * @param[in] Id of the clipboard */ - public void OS_ClipBoardArrive( gale::context::clipBoard::clipboardListe _clipboardID) { - ethread::RecursiveLock lock(this.mutex); - this.msgSystem.post([_clipboardID](gale::Context _context){ - Application appl = _context.getApplication(); + public void OS_ClipBoardArrive( ClipboardList _clipboardID) { + postAction((context) -> { + Application appl = context.getApplication(); if (appl != null) { appl.onClipboardEvent(_clipboardID); } @@ -712,7 +696,7 @@ public class Context { * @param[in] title New desired title */ public void setTitle( String _title){ - GALE_INFO("setTitle: NOT implemented ..."); + Log.info("setTitle: NOT implemented ..."); } /** * @brief Open an URL on an eternal brother. @@ -723,7 +707,7 @@ public class Context { * @brief force the screen orientation (availlable on portable elements ... * @param[in] _orientation Selected orientation. */ - public void forceOrientation( gale::orientation _orientation) { }; + public void forceOrientation(Orientation _orientation) { }; /** * @brief get all Keyboard event from the X system (like many time use of META) * @param[in] _status "true" if all the event will be get, false if we want only ours. @@ -734,7 +718,7 @@ public class Context { * @param[in] _status "true" if all the event will be get, false if we want only ours. * @param[in] _forcedPosition the position where the mouse might be reset at every events ... */ - public void grabPointerEvents(boolean _status, vec2 _forcedPosition) { }; + public void grabPointerEvents(boolean _status, Vector2f _forcedPosition) { }; /** * @brief set the cursor display type. * @param[in] _newCursor selected new cursor. @@ -742,9 +726,9 @@ public class Context { public void setCursor( Cursor _newCursor) { }; /** * @brief set the Icon of the program - * @param[in] _inputFile new filename icon of the curent program. + * @param[in] _inputFile new filename icon of the current program. */ - public void setIcon(etk::Uri _inputFile) { }; + public void setIcon(Uri _inputFile) { }; /** * @brief Enable or Disable the decoration on the Windows (availlable only on Desktop) * @param[in] _status "true" to enable decoration / false otherwise diff --git a/src/org/atriaSoft/gale/context/LWJGL/ContextLWJGL.java b/src/org/atriaSoft/gale/context/LWJGL/ContextLWJGL.java new file mode 100644 index 0000000..7180f63 --- /dev/null +++ b/src/org/atriaSoft/gale/context/LWJGL/ContextLWJGL.java @@ -0,0 +1,388 @@ +package org.atriaSoft.gale.context.LWJGL; + +import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks; +import static org.lwjgl.glfw.GLFW.GLFW_FALSE; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_A; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_D; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_Q; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_S; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_SPACE; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_W; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_Z; +import static org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_LEFT; +import static org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_RIGHT; +import static org.lwjgl.glfw.GLFW.GLFW_PRESS; +import static org.lwjgl.glfw.GLFW.GLFW_RELEASE; +import static org.lwjgl.glfw.GLFW.GLFW_RESIZABLE; +import static org.lwjgl.glfw.GLFW.GLFW_TRUE; +import static org.lwjgl.glfw.GLFW.GLFW_VISIBLE; +import static org.lwjgl.glfw.GLFW.glfwCreateWindow; +import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints; +import static org.lwjgl.glfw.GLFW.glfwDestroyWindow; +import static org.lwjgl.glfw.GLFW.glfwGetPrimaryMonitor; +import static org.lwjgl.glfw.GLFW.glfwGetVideoMode; +import static org.lwjgl.glfw.GLFW.glfwGetWindowSize; +import static org.lwjgl.glfw.GLFW.glfwInit; +import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent; +import static org.lwjgl.glfw.GLFW.glfwPollEvents; +import static org.lwjgl.glfw.GLFW.glfwSetCursorPosCallback; +import static org.lwjgl.glfw.GLFW.glfwSetErrorCallback; +import static org.lwjgl.glfw.GLFW.glfwSetKeyCallback; +import static org.lwjgl.glfw.GLFW.glfwSetMouseButtonCallback; +import static org.lwjgl.glfw.GLFW.glfwSetScrollCallback; +import static org.lwjgl.glfw.GLFW.glfwSetWindowPos; +import static org.lwjgl.glfw.GLFW.glfwSetWindowShouldClose; +import static org.lwjgl.glfw.GLFW.glfwShowWindow; +import static org.lwjgl.glfw.GLFW.glfwSwapBuffers; +import static org.lwjgl.glfw.GLFW.glfwSwapInterval; +import static org.lwjgl.glfw.GLFW.glfwTerminate; +import static org.lwjgl.glfw.GLFW.glfwWindowHint; +import static org.lwjgl.glfw.GLFW.glfwWindowShouldClose; +import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; +import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT; +import static org.lwjgl.opengl.GL11.glClear; +import static org.lwjgl.opengl.GL11.glClearColor; +import static org.lwjgl.opengl.GL11.glViewport; +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.system.MemoryUtil.NULL; + +import java.nio.IntBuffer; + +import org.atriaSoft.etk.math.Vector2f; +import org.atriaSoft.gale.Application; +import org.atriaSoft.gale.Fps; +import org.atriaSoft.gale.context.Context; +import org.atriaSoft.gale.key.Special; +import org.lwjgl.Version; +import org.lwjgl.glfw.GLFWErrorCallback; +import org.lwjgl.glfw.GLFWVidMode; +import org.lwjgl.opengl.GL; +import org.lwjgl.system.MemoryStack; + +import renderEngine.DisplayManagerDraw; + +public class ContextLWJGL extends Context { + + private static final int WIDTH = 800; + private static final int HEIGHT = 600; + 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 Special guiKeyBoardMode = new Special(); + + public ContextLWJGL(Application application, String[] args) { + super(application, args); + System.out.println("Hello LWJGL " + Version.getVersion() + "!"); + + initWindows(); + // This line is critical for LWJGL's interoperation with GLFW's + // OpenGL context, or any context that is managed externally. + // LWJGL detects the context that is current in the current thread, + // creates the GLCapabilities instance and makes the OpenGL + // bindings available for use. + GL.createCapabilities(); + // Set the clear color + glClearColor(0.0f, 1.0f, 0.0f, 0.0f); + glViewport(0, 0, (int)application.getSize().x, (int)application.getSize().y); + start2ndThreadProcessing(); + } + + + public void setDrawer(DisplayManagerDraw drawer) { + this.drawer = drawer; + } + +// public static Vector2f getSize() { +// return new Vector2f(WIDTH, HEIGHT); +// } + + + public void unInit() { + + // Free the window callbacks and destroy the window + glfwFreeCallbacks(window); + glfwDestroyWindow(window); + + // Terminate GLFW and free the error callback + glfwTerminate(); + glfwSetErrorCallback(null).free(); + } + private static boolean valueS = false; + private static boolean valueZ = false; + private static boolean valueQ = false; + private static boolean valueD = false; + private static boolean valueA = false; + private static boolean valueW = false; + private static boolean valueSPACE = false; + public static boolean isKeyDown(char value) { + if (value == 's') { + return valueS; + } + if (value == 'z') { + return valueZ; + } + if (value == 'q') { + return valueQ; + } + if (value == 'd') { + return valueD; + } + if (value == 'w') { + return valueW; + } + if (value == 'a') { + return valueA; + } + if (value == ' ') { + return valueSPACE; + } + return false; + } + + private void initWindows() { + // Setup an error callback. The default implementation + // will print the error message in System.err. + GLFWErrorCallback.createPrint(System.err).set(); + + // Initialize GLFW. Most GLFW functions will not work before doing this. + if ( !glfwInit() ) { + throw new IllegalStateException("Unable to initialize GLFW"); + } + // Configure GLFW + glfwDefaultWindowHints(); // optional, the current window hints are already the default + glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation + glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable + + // Create the window + window = glfwCreateWindow((int)application.getSize().x, (int)application.getSize().y, application.getTitle(), NULL, NULL); + if ( window == 0 ) { + throw new RuntimeException("Failed to create the GLFW window"); + } + // Setup a key callback. It will be called every time a key is pressed, repeated or released. + // https://www.glfw.org/docs/latest/input_guide.html + glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> { + if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE ) { + glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop + } + if ( key == GLFW_KEY_Z ) { + if (action == GLFW_PRESS ) { + System.out.println("Key Z is pressed"); + valueZ = true; + } else if (action == GLFW_RELEASE ) { + System.out.println("Key Z is release"); + valueZ = false; + } + } + if ( key == GLFW_KEY_S ) { + if (action == GLFW_PRESS ) { + System.out.println("Key S is pressed"); + valueS = true; + } else if (action == GLFW_RELEASE ) { + System.out.println("Key S is release"); + valueS = false; + } + } + if ( key == GLFW_KEY_Q ) { + if (action == GLFW_PRESS ) { + System.out.println("Key Q is pressed"); + valueQ = true; + } else if (action == GLFW_RELEASE ) { + System.out.println("Key Q is release"); + valueQ = false; + } + } + if ( key == GLFW_KEY_D ) { + if (action == GLFW_PRESS ) { + System.out.println("Key D is pressed"); + valueD = true; + } else if (action == GLFW_RELEASE ) { + System.out.println("Key D is release"); + valueD = false; + } + } + if ( key == GLFW_KEY_A ) { + if (action == GLFW_PRESS ) { + System.out.println("Key A is pressed"); + valueA = true; + } else if (action == GLFW_RELEASE ) { + System.out.println("Key A is release"); + valueA = false; + } + } + if ( key == GLFW_KEY_W ) { + if (action == GLFW_PRESS ) { + System.out.println("Key W is pressed"); + valueW = true; + } else if (action == GLFW_RELEASE ) { + System.out.println("Key W is release"); + valueW = false; + } + } + if ( key == GLFW_KEY_SPACE ) { + if (action == GLFW_PRESS ) { + System.out.println("Key SPACE is pressed"); + valueSPACE = true; + } else if (action == GLFW_RELEASE ) { + System.out.println("Key SPACE is release"); + valueSPACE = false; + } + } + }); + + glfwSetCursorPosCallback(window, (window, xpos, ypos) -> { + currentMousePositionX = xpos; + currentMousePositionY = ypos; + + }); + + glfwSetMouseButtonCallback(window, (window, button, action, mods) -> { + if (button == GLFW_MOUSE_BUTTON_RIGHT) { + if (action == GLFW_PRESS) { + rightButtonStateDown = true; + } else if (action == GLFW_RELEASE) { + rightButtonStateDown = false; + } + } else if (button == GLFW_MOUSE_BUTTON_LEFT) { + if (action == GLFW_PRESS) { + leftButtonStateDown = true; + } else if (action == GLFW_RELEASE) { + leftButtonStateDown = false; + } + } + }); + + glfwSetScrollCallback(window, (window, xoffset, yoffset) -> { + whellOffsetY += yoffset; + whellOffsetX += xoffset; + }); + + + // Get the thread stack and push a new frame + try ( MemoryStack stack = stackPush() ) { + IntBuffer pWidth = stack.mallocInt(1); // int* + IntBuffer pHeight = stack.mallocInt(1); // int* + + // Get the window size passed to glfwCreateWindow + glfwGetWindowSize(window, pWidth, pHeight); + + // Get the resolution of the primary monitor + GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); + + // Center the window + glfwSetWindowPos( + window, + (vidmode.width() - pWidth.get(0)) / 2, + (vidmode.height() - pHeight.get(0)) / 2 + ); + } // the stack frame is popped automatically + + // Make the OpenGL context current + glfwMakeContextCurrent(window); + // Enable v-sync + glfwSwapInterval(1); + + // Make the window visible + glfwShowWindow(window); + + lastFrameTime = getCurrentTime(); + + } + + + public static float getFrameTimeSecconds() { + return delta; + } + + private static long getCurrentTime() { + return System.currentTimeMillis(); + } + + + public static boolean isButtonRightDown() { + return rightButtonStateDown; + } + public static boolean isButtonLeftDown() { + return leftButtonStateDown; + } + + + public static float getDX() { + return (float) (currentMousePositionX-lastMousePositionX); + } + public static float getDY() { + return (float) (currentMousePositionY-lastMousePositionY); + } + + + public static float getDWheel() { + // TODO Auto-generated method stub + return (float) whellOffsetY; + } + + @Override + public int run() { + // 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(); + */ + OS_Draw(true); + glfwSwapBuffers(window); // swap the color buffers + glfwPollEvents(); + /* + if (specialEventThatNeedARedraw == true) { + X11_INFO("specialEventThatNeedARedraw = " << specialEventThatNeedARedraw); + } + hasDisplay = OS_Draw(specialEventThatNeedARedraw); + if (hasDisplay == true) { + // 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 static Context create(Application application, String[] arg) { + // TODO Auto-generated method stub + return new ContextLWJGL(application, arg); + } + +} diff --git a/src/org/atriaSoft/gale/resource/Resource.java b/src/org/atriaSoft/gale/resource/Resource.java index 1864334..df4124c 100644 --- a/src/org/atriaSoft/gale/resource/Resource.java +++ b/src/org/atriaSoft/gale/resource/Resource.java @@ -4,15 +4,14 @@ import java.util.ArrayList; import java.util.List; import org.atriaSoft.etk.Uri; -import org.atriaSoft.gale.Gale; import org.atriaSoft.gale.Log; import org.atriaSoft.gale.context.Context; -public class Resource { +public abstract class Resource { protected static int MAXRESOURCELEVEL = 5; private static int idGenerated = 0; protected long uid = 0; //!< unique ID definition - protected int count = 0; + protected int count = 1; protected int resourceLevel = MAXRESOURCELEVEL-1; //!< Level of the resource ==> for update priority [0..5] 0 must be update first. protected String name; //!< name of the resource ... protected boolean resourceHasBeenInit = false; //!< Know if the init function has bben called @@ -20,34 +19,32 @@ public class Resource { /** * @brief generic protected contructor (use factory to create this class) */ - Resource() { + protected Resource() { this.uid = idGenerated++; this.addResourceType("gale::Resource"); - } - /** - * @brief Initialisation of the class and previous classes. - * @param[in] name Name of the resource. - * @param[in] uri Uri of the resource. - */ - protected void init() { this.resourceHasBeenInit = true; } - //! @previous - protected void init( String name) { + protected Resource(String name) { this.resourceHasBeenInit = true; this.name = name; } - //! @previous - protected void init( Uri uri) { + protected Resource( Uri uri) { this.resourceHasBeenInit = true; - this.name = uri.get(); + this.name = uri.getValue(); } public void keep() { this.count++; } - public void retease() { - this.count--; + public int getCount() { + return this.count; } + public void release() { + this.count--; + if (this.count == 0) { + + } + } + public abstract void cleanUp(); public long getId() { return this.uid; } diff --git a/src/org/atriaSoft/gale/resource/ResourceManager.java b/src/org/atriaSoft/gale/resource/ResourceManager.java index f7f6fa1..5ff92ce 100644 --- a/src/org/atriaSoft/gale/resource/ResourceManager.java +++ b/src/org/atriaSoft/gale/resource/ResourceManager.java @@ -3,15 +3,20 @@ package org.atriaSoft.gale.resource; import java.util.ArrayList; import java.util.List; +import org.atriaSoft.gale.Log; + public class ResourceManager { private List resourceList = new ArrayList(); private List resourceListToUpdate = new ArrayList(); private boolean contextHasBeenRemoved = true; private boolean exiting = false; + private final int MAXRESOURCELEVEL = 9; /** * @brief initialize the internal variable */ - public Manager(); + public ResourceManager() { + + } /** * @brief Uninitiamize the resource manager, free all resources previously requested * @note when not free == > generate warning, because the segfault can appear after... @@ -21,20 +26,13 @@ public class ResourceManager { * @brief remove all resources (un-init) out of the destructor (due to the system implementation) */ public void unInit() { - ethread::RecursiveLock lock(this.mutex); display(); this.resourceListToUpdate.clear(); // remove all resources ... - auto it(this.resourceList.begin()); - while(it != this.resourceList.end()) { - gale::Resource> tmpRessource = (*it).lock(); - if (tmpRessource != null) { - Log.warning("Find a resource that is not removed : [" + tmpRessource.getId() + "]" - + "=\"" + tmpRessource.getName() + "\" " - + tmpRessource.useCount() + " elements"); - } - this.resourceList.erase(it); - it = this.resourceList.begin(); + for(Resource it : this.resourceList) { + Log.warning("Find a resource that is not removed : [" + it.getId() + "]" + + "='" + it.getName() + "' " + + it.getCount() + " elements"); } this.resourceList.clear(); } @@ -44,15 +42,11 @@ public class ResourceManager { public void display(){ Log.info("Resources loaded : "); // remove all resources ... - ethread::RecursiveLock lock(this.mutex); - for (auto it : this.resourceList) { - gale::Resource> tmpRessource = it.lock(); - if (tmpRessource != null) { - Log.info(" [" + tmpRessource.getId() + "]" - + tmpRessource.getType() - + "=\"" + tmpRessource.getName() + "\" " - + tmpRessource.useCount() + " elements"); - } + for(Resource it : this.resourceList) { + Log.info(" [" + it.getId() + "]" + + it.getType() + + "='" + it.getName() + "' " + + it.getCount() + " elements"); } Log.info("Resources ---"); } @@ -63,17 +57,13 @@ public class ResourceManager { public void reLoadResources() { Log.info("------------- Resources re-loaded -------------"); // remove all resources ... - ethread::RecursiveLock lock(this.mutex); - if (this.resourceList.size() != 0) { - for (long jjj=0; jjj tmpRessource = it.lock(); - if(tmpRessource != null) { - if (jjj == tmpRessource.getResourceLevel()) { - tmpRessource.reload(); - Log.info(" [" + tmpRessource.getId() + "]="+ tmpRessource.getType()); - } + for (long jjj=0; jjj 0) { + it.reload(); + Log.info(" [" + it.getId() + "]="+ it.getType()); } } } @@ -87,18 +77,16 @@ public class ResourceManager { * @brief Call by the system to send all the needed data on the graphic card chen they change ... * @param[in] object The resources that might be updated */ - public void update( gale::Resource> object) { - // chek if not added before - ethread::RecursiveLock lock(this.mutex); - for (auto it : this.resourceListToUpdate) { - if ( it != null - it == object) { + public void update(Resource object) { + // check if not added before + for (Resource it : this.resourceListToUpdate) { + if (it == object) { // just prevent some double add ... return; } } // add it ... - this.resourceListToUpdate.pushBack(object); + this.resourceListToUpdate.add(object); } /** * @brief Call by the system chen the openGL Context has been unexpectially removed == > This reload all the texture, VBO and other .... @@ -112,48 +100,37 @@ public class ResourceManager { if (this.contextHasBeenRemoved == true) { // need to update all ... this.contextHasBeenRemoved = false; - etk::Vector> resourceList; - { - ethread::RecursiveLock lock(this.mutex); - // Clean the update list - this.resourceListToUpdate.clear(); - resourceList = this.resourceList; - } - if (resourceList.size() != 0) { - for (long jjj=0; jjj tmpRessource = it.lock(); - if( tmpRessource != null - jjj == tmpRessource.getResourceLevel()) { - //Log.debug("Update context named : " + lresourceList[iii].getName()); - if (tmpRessource.updateContext() == false) { - // Lock error ==> postponned - ethread::RecursiveLock lock(this.mutex); - this.resourceListToUpdate.pushBack(tmpRessource); + this.resourceListToUpdate.clear(); + synchronized(this.resourceList) { + if (this.resourceList.size() != 0) { + for (long jjj=0; jjj postponned + this.resourceListToUpdate.add(it); + } } } } } } } else { - etk::Vector> resourceListToUpdate; - { - ethread::RecursiveLock lock(this.mutex); + List resourceListToUpdate = null; + synchronized(this.resourceListToUpdate) { resourceListToUpdate = this.resourceListToUpdate; - // Clean the update list - this.resourceListToUpdate.clear(); + this.resourceListToUpdate = new ArrayList(); } if (resourceListToUpdate.size() != 0) { for (long jjj=0; jjj postponned - this.resourceListToUpdate.pushBack(it); + this.resourceListToUpdate.add(it); } } } @@ -165,11 +142,9 @@ public class ResourceManager { * @brief This is to inform the resources manager that we have no more openGl context ... */ public void contextHasBeenDestroyed() { - ethread::RecursiveLock lock(this.mutex); - for (auto it : this.resourceList) { - gale::Resource> tmpRessource = it.lock(); - if (tmpRessource != null) { - tmpRessource.removeContextToLate(); + for (Resource it : this.resourceList) { + if (it.getCount() > 0) { + it.removeContextToLate(); } } // no context preent ... @@ -182,15 +157,13 @@ public class ResourceManager { contextHasBeenDestroyed(); this.exiting = true; } -public: // internal API to extent eResources in extern Soft public Resource localKeep(String filename) { Log.verbose("KEEP (DEFAULT) : file : '" + filename + "' in " + this.resourceList.size() + " resources"); - for (auto it : this.resourceList) { - gale::Resource> tmpRessource = it.lock(); - if (tmpRessource != null) { - if (tmpRessource.getName() == filename) { - return tmpRessource; + for (Resource it : this.resourceList) { + if (it != null) { + if (it.getName() == filename) { + return it; } } } @@ -203,12 +176,13 @@ public: public void cleanInternalRemoved() { //Log.info("remove object in Manager"); updateContext(); - for (auto it(this.resourceList.begin()); it!=this.resourceList.end(); ++it) { - if ((*it).expired() == true) { - this.resourceList.erase(it); - it = this.resourceList.begin(); - } - } + // TODO: ... +// for (auto it(this.resourceList.begin()); it!=this.resourceList.end(); ++it) { +// if ((*it).expired() == true) { +// this.resourceList.erase(it); +// it = this.resourceList.begin(); +// } +// } } } diff --git a/src/org/atriaSoft/gale/resource/ResourceProgram.java b/src/org/atriaSoft/gale/resource/ResourceProgram.java index 7c15489..3385ffe 100644 --- a/src/org/atriaSoft/gale/resource/ResourceProgram.java +++ b/src/org/atriaSoft/gale/resource/ResourceProgram.java @@ -1,11 +1,25 @@ package org.atriaSoft.gale.resource; import java.io.File; +import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.List; +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; +import org.atriaSoft.etk.math.Vector3f; +import org.atriaSoft.etk.math.Vector3i; import org.atriaSoft.gale.Log; +import org.atriaSoft.gale.backend3d.OpenGL; +import org.atriaSoft.gale.backend3d.OpenGL.Usage; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; @@ -19,9 +33,9 @@ class ProgAttributeElement { public class ResourceProgram extends Resource { static final boolean DEBUG = false; // TODO: externalize this ... private boolean exist = false; //!< the file existed - private long program = 0; //!< openGL id of the current program - private ResourceShader shaderVertex; - private ResourceShader shaderFragment; + private int program = 0; //!< openGL id of the current program + private ResourceShader shaderVertex = null; + private ResourceShader shaderFragment = null; private List elementList = new ArrayList(); //!< List of all the attribute requested by the user private 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 @@ -30,13 +44,10 @@ public class ResourceProgram extends Resource { * @brief Contructor of an opengl Program. * @param[in] uri Uri of the file */ - protected ResourceProgram() { - super(); + protected ResourceProgram(Uri uriVertexShader, Uri uriFragmentShader) { + super(uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue()); addResourceType("gale::resource::Program"); this.resourceLevel = 1; - } - protected void init(Uri uriVertexShader, Uri uriFragmentShader) { - super.init(uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue()); Log.debug("OGL : load PROGRAM '" + uriVertexShader + "' && '" + uriFragmentShader + "'"); shaderVertex = ResourceShader.create(uriVertexShader); if (shaderVertex == null) { @@ -61,13 +72,21 @@ public class ResourceProgram extends Resource { /** * @brief Destructor, remove the current Program. */ -// virtual ~Program() { -// this.shaderList.clear(); -// removeContext(); -// this.elementList.clear(); -// this.hasTexture = false; -// this.hasTexture1 = false; -// } + @Override + public void cleanUp() { + removeContext(); + if (this.shaderFragment != null) { + this.shaderFragment.release(); + this.shaderFragment = null; + } + if (this.shaderVertex != null) { + this.shaderVertex.release(); + this.shaderVertex = null; + } + this.elementList.clear(); + this.hasTexture = false; + this.hasTexture1 = false; + } /** * @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) * @return idElem Id of the Attribute that might be sended. @@ -101,7 +120,7 @@ public class ResourceProgram extends Resource { tmp.elementId = -1; tmp.isLinked = false; } else if (this.exist == true) { - tmp.elementId = OpenGL.program_getAttributeLocation(this.program, tmp.name); + 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); @@ -114,9 +133,21 @@ public class ResourceProgram extends Resource { tmp.elementId = -1; tmp.isLinked = false; } - this.elementList.pushBack(tmp); + this.elementList.add(tmp); return this.elementList.size()-1; } + private FloatBuffer storeDataInFloatBuffer(float[] data) { + FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length); + buffer.put(data); + buffer.flip(); + return buffer; + } + public void bindAttribute(int attribute, String variableName) { + if (this.exist == false) { + return; + } + OpenGL.programBindAttribute(program, attribute, variableName); + } /** * @brief Send attribute table to the spefified ID attribure (not send if does not really exist in the openGL program). * @param[in] idElem Id of the Attribute that might be sended. @@ -125,47 +156,89 @@ public class ResourceProgram extends Resource { * @param[in] jumpBetweenSample Number of byte to jump between 2 vertex (this permit to enterlace informations) * @param[in] offset offset of start the elements send. */ - public void sendAttributePointer(int idElem, - gale::resource::VirtualBufferObject> vbo, - int index, - int jumpBetweenSample=0, - int offset=0){ - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[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[idElem].name + "] send " + vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + " VBOindex=" + index); - glBindBuffer(GLARRAYBUFFER, vbo.getGLID(index)); - checkGlError("glBindBuffer", LINE, idElem); - Log.verbose(" id=" + this.elementList[idElem].elementId); - Log.verbose(" eleme size=" + vbo.getElementSize(index)); - Log.verbose(" jump sample=" + jumpBetweenSample); - Log.verbose(" offset=" + offset); - glVertexAttribPointer(this.elementList[idElem].elementId, // attribute ID of openGL - vbo.getElementSize(index), // number of elements per vertex, here (r,g,b,a) - GLFLOAT, // the type of each element - GLFALSE, // take our values as-is - jumpBetweenSample, // no extra data between each position - (GLvoid *)offset); // Pointer on the buffer - checkGlError("glVertexAttribPointer", LINE, idElem); - glEnableVertexAttribArray(this.elementList[idElem].elementId); - this.listOfVBOUsed.pushBack(this.elementList[idElem].elementId); - checkGlError("glEnableVertexAttribArray", LINE, idElem); - } +// public void sendAttributePointer(int idElem, +// ResourceVirtualArrayObject vbo, +// int index, +// int coordinateSize, +// float[] data){ +// +// if (this.exist == false) { +// 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 sendAttributePointer2(int idElem, +// ResourceVirtualArrayObject vbo, +// int index) { +// int jumpBetweenSample = 0; +// int offset = 0; +// if (this.exist == false) { +// return; +// } +// if ( idElem < 0 +// || 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 good enough ... +// 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("[" + elementList.get(idElem).name + "] send " + vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + " VBOindex=" + index); +// GL20.glBindBuffer(GL20.GL_ARRAY_BUFFER, vbo.getGLID(index)); +// //checkGlError("glBindBuffer", __LINE__, _idElem); +// Log.verbose(" id=" + elementList.get(idElem).elementId); +// Log.verbose(" eleme size=" + vbo.getElementSize(index)); +// Log.verbose(" jump sample=" + jumpBetweenSample); +// Log.verbose(" offset=" + offset); +// GL20.glVertexAttribPointer(elementList.get(idElem).elementId, // attribute ID of openGL +// vbo.getElementSize(index), // number of elements per vertex, here (r,g,b,a) +// GL11.GL_FLOAT, // the type of each element +// false, // take our values as-is +// 0, // no extra data between each position +// 0); // Pointer on the buffer +// //checkGlError("glVertexAttribPointer", __LINE__, _idElem); +// GL20.glEnableVertexAttribArray(elementList.get(idElem).elementId); +// listOfVBOUsed.add(elementList.get(idElem).elementId); +// //checkGlError("glEnableVertexAttribArray", __LINE__, _idElem); +// } + +// 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 Send attribute table to the spefified ID attribure (not send if does not really exist in the openGL program). * @param[in] idElem Id of the Attribute that might be sended. @@ -173,60 +246,59 @@ public class ResourceProgram extends Resource { * @param[in] pointer Pointer on the data that might be sended. * @param[in] jumpBetweenSample Number of byte to jump between 2 vertex (this permit to enterlace informations) */ - public void sendAttribute(int idElem, - int nbElement, - void* pointer, - int jumpBetweenSample=0) { - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[idElem].isLinked == false) { - return; - } - //Log.error("[" + this.elementList[idElem].name + "] send " + nbElement + " element"); - glVertexAttribPointer(this.elementList[idElem].elementId, // attribute ID of openGL - nbElement, // number of elements per vertex, here (r,g,b,a) - GLFLOAT, // the type of each element - GLFALSE, // take our values as-is - jumpBetweenSample, // no extra data between each position - pointer); // Pointer on the buffer - checkGlError("glVertexAttribPointer", LINE, idElem); - glEnableVertexAttribArray(this.elementList[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, etk::Vector data) { - sendAttribute(idElem, 3/*x,y,z,unused*/, data[0], 4*sizeof(btScalar)); - } - 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, +// int nbElement, +// void* pointer, +// int jumpBetweenSample=0) { +// +// if (this.exist == false) { +// 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; +// } +// //Log.error("[" + this.elementList.get(idElem).name + "] send " + nbElement + " element"); +// glVertexAttribPointer(this.elementList.get(idElem).elementId, // attribute ID of openGL +// nbElement, // number of elements per vertex, here (r,g,b,a) +// GLFLOAT, // the type of each element +// GLFALSE, // take our values as-is +// jumpBetweenSample, // no extra data between each position +// pointer); // Pointer on the buffer +// checkGlError("glVertexAttribPointer", LINE, idElem); +// 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, etk::Vector data) { +// sendAttribute(idElem, 3/*x,y,z,unused*/, data[0], 4*sizeof(btScalar)); +// } +// 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) * @param[in] 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) */ - public int getUniform( String elementName){ - + public int getUniform(String elementName){ // check if it exist previously : - for(long iii=0; iii value) { - uniform4f(idElem, value.r(), value.g(), value.b(), value.a()); + public void uniformColor(int idElem, Color value) { + if (this.exist == false) { + 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) { + return; + } + OpenGL.programLoadUniformColor(this.elementList.get(idElem).elementId, value); } /** @@ -291,7 +377,6 @@ public class ResourceProgram extends Resource { * @param[in] value1 Value to send at the Uniform */ public void uniform1f(int idElem, float value1){ - if (this.exist == false) { return; } @@ -299,11 +384,10 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (false == this.elementList[idElem].isLinked) { + if (false == this.elementList.get(idElem).isLinked) { return; } - glUniform1f(this.elementList[idElem].elementId, value1); - checkGlError("glUniform1f", LINE, idElem); + 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) @@ -320,11 +404,10 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (false == this.elementList[idElem].isLinked) { + if (false == this.elementList.get(idElem).isLinked) { return; } - glUniform2f(this.elementList[idElem].elementId, value1, value2); - checkGlError("glUniform2f", LINE, idElem); + 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) @@ -342,11 +425,10 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (false == this.elementList[idElem].isLinked) { + if (false == this.elementList.get(idElem).isLinked) { return; } - glUniform3f(this.elementList[idElem].elementId, value1, value2, value3); - checkGlError("glUniform3f", LINE, idElem); + 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) @@ -365,11 +447,10 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (false == this.elementList[idElem].isLinked) { + if (false == this.elementList.get(idElem).isLinked) { return; } - glUniform4f(this.elementList[idElem].elementId, value1, value2, value3, value4); - checkGlError("glUniform4f", LINE, idElem); + OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2, value3, value4); } /** @@ -386,11 +467,10 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (false == this.elementList[idElem].isLinked) { + if (false == this.elementList.get(idElem).isLinked) { return; } - glUniform1i(this.elementList[idElem].elementId, value1); - checkGlError("glUniform1i", LINE, idElem); + 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) @@ -407,11 +487,10 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (false == this.elementList[idElem].isLinked) { + if (false == this.elementList.get(idElem).isLinked) { return; } - glUniform2i(this.elementList[idElem].elementId, value1, value2); - checkGlError("glUniform2i", LINE, idElem); + 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) @@ -429,11 +508,10 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (false == this.elementList[idElem].isLinked) { + if (false == this.elementList.get(idElem).isLinked) { return; } - glUniform3i(this.elementList[idElem].elementId, value1, value2, value3); - checkGlError("glUniform3i", LINE, idElem); + 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) @@ -452,11 +530,10 @@ public class ResourceProgram extends Resource { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (false == this.elementList[idElem].isLinked) { + if (false == this.elementList.get(idElem).isLinked) { return; } - glUniform4i(this.elementList[idElem].elementId, value1, value2, value3, value4); - checkGlError("glUniform4i", LINE, idElem); + OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2, value3, value4); } /** @@ -465,122 +542,122 @@ public class ResourceProgram extends Resource { * @param[in] nbElement Number of element sended * @param[in] value Pointer on the data */ - public void uniform1fv(int idElem, int nbElement, float *value){ - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[idElem].isLinked == false) { - return; - } - if (nbElement == 0) { - Log.error("No element to send at open GL ..."); - return; - } - if (value == null) { - Log.error("null Input pointer to send at open GL ..."); - return; - } - glUniform1fv(this.elementList[idElem].elementId, nbElement, value); - checkGlError("glUniform1fv", LINE, idElem); - } +// public void uniform1fv(int idElem, int nbElement, float *value){ +// +// if (this.exist == false) { +// 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; +// } +// if (nbElement == 0) { +// Log.error("No element to send at open GL ..."); +// return; +// } +// if (value == null) { +// Log.error("null Input pointer to send at open GL ..."); +// return; +// } +// glUniform1fv(this.elementList.get(idElem).elementId, nbElement, value); +// checkGlError("glUniform1fv", LINE, idElem); +// } /** * @brief Send "Vector2f" uniform element to the spefified ID (not send if does not really exist in the openGL program) * @param[in] idElem Id of the uniform that might be sended. * @param[in] nbElement Number of element sended * @param[in] value Pointer on the data */ - public void uniform2fv(int idElem, int nbElement, float *value){ - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[idElem].isLinked == false) { - return; - } - if (nbElement == 0) { - Log.error("No element to send at open GL ..."); - return; - } - if (value == null) { - Log.error("null Input pointer to send at open GL ..."); - return; - } - glUniform2fv(this.elementList[idElem].elementId, nbElement, value); - checkGlError("glUniform2fv", LINE, idElem); - } +// public void uniform2fv(int idElem, int nbElement, float *value){ +// +// if (this.exist == false) { +// 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; +// } +// if (nbElement == 0) { +// Log.error("No element to send at open GL ..."); +// return; +// } +// if (value == null) { +// Log.error("null Input pointer to send at open GL ..."); +// return; +// } +// glUniform2fv(this.elementList.get(idElem).elementId, nbElement, value); +// checkGlError("glUniform2fv", LINE, idElem); +// } /** * @brief Send "Vector3f" uniform element to the spefified ID (not send if does not really exist in the openGL program) * @param[in] idElem Id of the uniform that might be sended. * @param[in] nbElement Number of element sended * @param[in] value Pointer on the data */ - public void uniform3fv(int idElem, int nbElement, float *value){ - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[idElem].isLinked == false) { - return; - } - if (nbElement == 0) { - Log.error("No element to send at open GL ..."); - return; - } - if (value == null) { - Log.error("null Input pointer to send at open GL ..."); - return; - } - Log.verbose("[" + this.elementList[idElem].name + "] send " + nbElement + " Vector3f"); - glUniform3fv(this.elementList[idElem].elementId, nbElement, value); - checkGlError("glUniform3fv", LINE, idElem); - } +// public void uniform3fv(int idElem, int nbElement, float *value){ +// +// if (this.exist == false) { +// 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; +// } +// if (nbElement == 0) { +// Log.error("No element to send at open GL ..."); +// return; +// } +// if (value == null) { +// Log.error("null Input pointer to send at open GL ..."); +// return; +// } +// Log.verbose("[" + this.elementList.get(idElem).name + "] send " + nbElement + " Vector3f"); +// glUniform3fv(this.elementList.get(idElem).elementId, nbElement, value); +// checkGlError("glUniform3fv", LINE, idElem); +// } /** * @brief Send "Vector4f" uniform element to the spefified ID (not send if does not really exist in the openGL program) * @param[in] idElem Id of the uniform that might be sended. * @param[in] nbElement Number of element sended * @param[in] value Pointer on the data */ - public void uniform4fv(int idElem, int nbElement, float *value){ - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[idElem].isLinked == false) { - return; - } - if (nbElement == 0) { - Log.error("No element to send at open GL ..."); - return; - } - if (value == null) { - Log.error("null Input pointer to send at open GL ..."); - return; - } - Log.verbose("[" + this.elementList[idElem].name + "] send " + nbElement + " Vector4f"); - glUniform4fv(this.elementList[idElem].elementId, nbElement, value); - checkGlError("glUniform4fv", LINE, idElem); - } +// public void uniform4fv(int idElem, int nbElement, float *value){ +// +// if (this.exist == false) { +// 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; +// } +// if (nbElement == 0) { +// Log.error("No element to send at open GL ..."); +// return; +// } +// if (value == null) { +// Log.error("null Input pointer to send at open GL ..."); +// return; +// } +// Log.verbose("[" + this.elementList.get(idElem).name + "] send " + nbElement + " Vector4f"); +// glUniform4fv(this.elementList.get(idElem).elementId, nbElement, value); +// checkGlError("glUniform4fv", LINE, idElem); +// } /** * @brief Send "ivec1" uniform element to the spefified ID (not send if does not really exist in the openGL program) @@ -588,137 +665,171 @@ public class ResourceProgram extends Resource { * @param[in] nbElement Number of element sended * @param[in] value Pointer on the data */ - public void uniform1iv(int idElem, int nbElement, int *value){ - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[idElem].isLinked == false) { - return; - } - if (nbElement == 0) { - Log.error("No element to send at open GL ..."); - return; - } - if (value == null) { - Log.error("null Input pointer to send at open GL ..."); - return; - } - glUniform1iv(this.elementList[idElem].elementId, nbElement, value); - checkGlError("glUniform1iv", LINE, idElem); - } +// public void uniform1iv(int idElem, int nbElement, int *value){ +// +// if (this.exist == false) { +// 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; +// } +// if (nbElement == 0) { +// Log.error("No element to send at open GL ..."); +// return; +// } +// if (value == null) { +// Log.error("null Input pointer to send at open GL ..."); +// return; +// } +// glUniform1iv(this.elementList.get(idElem).elementId, nbElement, value); +// checkGlError("glUniform1iv", LINE, idElem); +// } /** * @brief Send "Vector2i" uniform element to the spefified ID (not send if does not really exist in the openGL program) * @param[in] idElem Id of the Attribute that might be sended. * @param[in] nbElement Number of element sended * @param[in] value Pointer on the data */ - public void uniform2iv(int idElem, int nbElement, int *value){ - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[idElem].isLinked == false) { - return; - } - if (nbElement == 0) { - Log.error("No element to send at open GL ..."); - return; - } - if (value == null) { - Log.error("null Input pointer to send at open GL ..."); - return; - } - glUniform2iv(this.elementList[idElem].elementId, nbElement, value); - checkGlError("glUniform2iv", LINE, idElem); - } +// public void uniform2iv(int idElem, int nbElement, int *value){ +// +// if (this.exist == false) { +// 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; +// } +// if (nbElement == 0) { +// Log.error("No element to send at open GL ..."); +// return; +// } +// if (value == null) { +// Log.error("null Input pointer to send at open GL ..."); +// return; +// } +// glUniform2iv(this.elementList.get(idElem).elementId, nbElement, value); +// checkGlError("glUniform2iv", LINE, idElem); +// } /** * @brief Send "Vector3i" uniform element to the spefified ID (not send if does not really exist in the openGL program) * @param[in] idElem Id of the uniform that might be sended. * @param[in] nbElement Number of element sended * @param[in] value Pointer on the data */ - public void uniform3iv(int idElem, int nbElement, int *value){ - - if (this.exist == false) { - return; - } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { - Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); - return; - } - if (this.elementList[idElem].isLinked == false) { - return; - } - if (nbElement == 0) { - Log.error("No element to send at open GL ..."); - return; - } - if (value == null) { - Log.error("null Input pointer to send at open GL ..."); - return; - } - glUniform3iv(this.elementList[idElem].elementId, nbElement, value); - checkGlError("glUniform3iv", LINE, idElem); - } +// public void uniform3iv(int idElem, int nbElement, int *value){ +// +// if (this.exist == false) { +// 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; +// } +// if (nbElement == 0) { +// Log.error("No element to send at open GL ..."); +// return; +// } +// if (value == null) { +// Log.error("null Input pointer to send at open GL ..."); +// return; +// } +// glUniform3iv(this.elementList.get(idElem).elementId, nbElement, value); +// checkGlError("glUniform3iv", LINE, idElem); +// } /** * @brief Send "Vector4i" uniform element to the spefified ID (not send if does not really exist in the openGL program) * @param[in] idElem Id of the uniform that might be sended. * @param[in] nbElement Number of element sended * @param[in] value Pointer on the data */ - public void uniform4iv(int idElem, int nbElement, int *value){ - +// public void uniform4iv(int idElem, int nbElement, int *value){ +// +// if (this.exist == false) { +// 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; +// } +// if (nbElement == 0) { +// Log.error("No element to send at open GL ..."); +// return; +// } +// if (value == null) { +// Log.error("null Input pointer to send at open GL ..."); +// return; +// } +// glUniform4iv(this.elementList.get(idElem).elementId, nbElement, value); +// checkGlError("glUniform4iv", LINE, idElem); +// } + public void uniform2(int idElem, Vector2f value) { if (this.exist == false) { return; } - if ( idElem < 0 - || (long)idElem > this.elementList.size()) { + if (idElem<0 || (long)idElem>this.elementList.size()) { Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]"); return; } - if (this.elementList[idElem].isLinked == false) { + if (false == this.elementList.get(idElem).isLinked) { return; } - if (nbElement == 0) { - Log.error("No element to send at open GL ..."); - return; - } - if (value == null) { - Log.error("null Input pointer to send at open GL ..."); - return; - } - glUniform4iv(this.elementList[idElem].elementId, nbElement, value); - checkGlError("glUniform4iv", LINE, idElem); - } - public void uniform2(int idElem, Vector2f value) { - uniform2fv(idElem, 1, value.floats[0]); + OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value); }; public void uniform3(int idElem, Vector3f value) { - uniform3fv(idElem, 1, value.floats[0]); - }; - public void uniform4(int idElem, Vector4f value) { - uniform4fv(idElem, 1, value.floats[0]); + if (this.exist == false) { + 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) { + return; + } + OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value); }; public void uniform2(int idElem, Vector2i value) { - uniform2iv(idElem, 1, value.floats[0]); + if (this.exist == false) { + 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) { + return; + } + OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value); }; public void uniform3(int idElem, Vector3i value) { - uniform3iv(idElem, 1, value.floats[0]); - }; - public void uniform4(int idElem, Vector4i value) { - uniform4iv(idElem, 1, value.floats[0]); + if (this.exist == false) { + 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) { + return; + } + OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value); }; /** @@ -726,19 +837,15 @@ public class ResourceProgram extends Resource { */ public void use() { Log.verbose("Will use program : " + this.program); - #ifdef PROGRAMDISPLAYSPEED - gstartTime = gale::getTime(); - #endif // event if it was 0 == > set it to prevent other use of the previous shader display ... OpenGL.useProgram(this.program); - checkGlError("glUseProgram", LINE); } /** * @brief set the testure Id on the specify uniform element. * @param[in] idElem Id of the uniform that might be sended. * @param[in] textureOpenGlID Real openGL texture ID */ - public void setTexture0(int idElem, long textureOpenGlID){ + public void setTexture0(int idElem, int textureOpenGlID){ if (this.exist == false) { return; @@ -747,25 +854,17 @@ public class ResourceProgram extends Resource { || (long)idElem > this.elementList.size()) { return; } - if (this.elementList[idElem].isLinked == false) { + if (this.elementList.get(idElem).isLinked == false) { return; } - #if 0 - OpenGL.enable(GLTEXTURE2D); - checkGlError("glEnable", LINE); - #endif - OpenGL.activeTexture(GLTEXTURE0); - checkGlError("glActiveTexture", LINE, idElem); + OpenGL.activeTexture(GL13.GL_TEXTURE0); // set the textureID - glBindTexture(GLTEXTURE2D, textureOpenGlID); - checkGlError("glBindTexture", LINE, idElem); + GL13.glBindTexture(GL13.GL_TEXTURE_2D, textureOpenGlID); // set the texture on the uniform attribute - glUniform1i(this.elementList[idElem].elementId, /*GLTEXTURE*/0); - checkGlError("glUniform1i", LINE, idElem); + GL20.glUniform1i(this.elementList.get(idElem).elementId, /*GLTEXTURE*/0); this.hasTexture = true; } - public void setTexture1(int idElem, long textureOpenGlID){ - + public void setTexture1(int idElem, int textureOpenGlID) { if (this.exist == false) { return; } @@ -773,21 +872,14 @@ public class ResourceProgram extends Resource { || (long)idElem > this.elementList.size()) { return; } - if (this.elementList[idElem].isLinked == false) { + if (this.elementList.get(idElem).isLinked == false) { return; } - #if 0 - OpenGL.enable(GLTEXTURE2D); - checkGlError("glEnable", LINE); - #endif - OpenGL.activeTexture(GLTEXTURE1); - checkGlError("glActiveTexture", LINE, idElem); + OpenGL.activeTexture(GL13.GL_TEXTURE1); // set the textureID - glBindTexture(GLTEXTURE2D, textureOpenGlID); - checkGlError("glBindTexture", LINE, idElem); + GL13.glBindTexture(GL13.GL_TEXTURE_2D, textureOpenGlID); // set the texture on the uniform attribute - glUniform1i(this.elementList[idElem].elementId, /*GLTEXTURE*/1); - checkGlError("glUniform1i", LINE, idElem); + GL20.glUniform1i(this.elementList.get(idElem).elementId, /*GLTEXTURE*/1); this.hasTexture1 = true; } /** @@ -799,72 +891,55 @@ public class ResourceProgram extends Resource { if (this.exist == false) { return; } - for (auto it : this.listOfVBOUsed) { - glDisableVertexAttribArray(it); + for (Integer it : this.listOfVBOUsed) { + GL20.glDisableVertexAttribArray(it); } this.listOfVBOUsed.clear(); - #if 0 - if (this.hasTexture == true) { - OpenGL.disable(GLTEXTURE2D); - //checkGlError("glDisable", LINE); - this.hasTexture = false; - } - #endif // no need to disable program == > this only generate perturbation on speed ... OpenGL.useProgram(-1); - #ifdef PROGRAMDISPLAYSPEED - float localTime = (float)(gale::getTime() - gstartTime) / 1000.0f; - if (localTime>1) { - Log.error(" prog : " + localTime + "ms resource=\"" + this.name + "\""); - } else { - Log.debug(" prog : " + localTime + "ms resource=\"" + this.name + "\""); - } - #endif - checkGlError("glUseProgram", LINE); } + public static final int INDICE_VBO_POSITIONS = 0; + public static final int INDICE_VBO_TEXTURE_COORDINATES = 1; + public static final int INDICE_VBO_NORMALS = 2; + public static final int INDICE_VBO_COLORS = 3; + + /** * @brief This load/reload the data in the opengl context, needed when removed previously. */ public boolean updateContext(){ - ethread::RecursiveLock lock(this.mutex, true); - if (lock.tryLock() == false) { - //Lock error ==> try later ... - return false; - } if (this.exist == true) { // Do nothing == > too dangerous ... } else { // create the Shader - Log.debug("Create the Program ..."" + this.name + "\""); - this.program = OpenGL.program::create(); + Log.debug("Create the Program ...'" + this.name + "'"); + this.program = OpenGL.programCreate(); if (this.program < 0) { return true; } // first attach vertex shader, and after fragment shader - for (long iii=0; iii" + uriFragmentShader.getValue(); if (name.isEmpty() == false && name != "---") { resource2 = getManager().localKeep(name); @@ -999,13 +1044,7 @@ public class ResourceProgram extends Resource { Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)"); return null; } - resource = new ResourceProgram(_uri); - if (resource == null) { - Log.error("allocation error of a resource : " + name); - return null; - } - resource.init(_uri); - resource.keep(); + resource = new ResourceProgram(uriVertexShader, uriFragmentShader); if (resource.resourceHasBeenCorectlyInit() == false) { Log.critical("resource Is not correctly init : ResourceProgram" ); return null; diff --git a/src/org/atriaSoft/gale/resource/ResourceShader.java b/src/org/atriaSoft/gale/resource/ResourceShader.java index 810a467..c7b0ae5 100644 --- a/src/org/atriaSoft/gale/resource/ResourceShader.java +++ b/src/org/atriaSoft/gale/resource/ResourceShader.java @@ -1,147 +1,141 @@ package org.atriaSoft.gale.resource; -public class ResourceShader { +import org.atriaSoft.etk.Uri; +import org.atriaSoft.gale.Log; +import org.atriaSoft.gale.backend3d.OpenGL; +import org.atriaSoft.gale.backend3d.OpenGL.ShaderType; - private : - boolean this.exist; //!< The shader file existed and has been loaded - String this.fileData; //!< A copy of the data loaded from the file (usefull only when opengl context is removed) - long this.shader; //!< opengl id of this element - gale::openGL::shader::type this.type; //!< Type of the current shader(vertex/fragment) - protected: - /** - * @brief Contructor of an opengl Shader - * @param[in] filename Standard file name format. see @ref etk::FSNode - */ - Shader(): - gale::Resource(), - this.exist(false), - this.fileData(""), - this.shader(-1), - this.type(gale::openGL::shader::type::vertex) { - addResourceType("gale::Shader"); - this.resourceLevel = 0; - } - public: - void init( etk::Uri uri){ - ethread::RecursiveLock lock(this.mutex); - gale::Resource::init(uri.get()); - Log.debug("OGL : load SHADER '" + uri + "'"); - // load data from file "all the time ..." - - if (uri.getPath().getExtention() == "frag") { - this.type = gale::openGL::shader::type::fragment; - } else if (uri.getPath().getExtention() == "vert") { - this.type = gale::openGL::shader::type::vertex; - } else { - Log.error("File does not have extention \".vert\" for Vertex Shader or \".frag\" for Fragment Shader. but : \"" + uri + "\""); - return; - } - reload(); +public class ResourceShader extends Resource { + + private boolean exist = false; //!< The shader file existed and has been loaded + private 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[in] filename Standard file name format. see @ref etk::FSNode + */ + protected ResourceShader(Uri uri) { + super(uri); + this.uri = uri; + addResourceType("gale::Shader"); + this.resourceLevel = 0; + Log.debug("OGL : load SHADER '" + uri + "'"); + // load data from file "all the time ..." + + if (uri.get().endsWith(".frag")) { + this.type = ShaderType.fragment; + } else if (uri.get().endsWith(".vert")) { + this.type = ShaderType.vertex; + } else { + Log.error("File does not have extention '.vert' for Vertex Shader or '.frag' for Fragment Shader. but : \"" + uri + "\""); + this.type = ShaderType.vertex; + return; } - /** - * @brief Destructor, remove the current Shader - */ - virtual ~Shader(){ - ethread::RecursiveLock lock(this.mutex); - this.fileData.clear(); - gale::openGL::shader::remove(this.shader); + reload(); + } + /** + * @brief Destructor, remove the current Shader + */ + public void cleanUp() { + OpenGL.shaderRemove(this.shader); + this.exist = false; + } + /** + * @brief get the opengl reference id of this shader. + * @return The opengl id. + */ + public int getGLID() { + return this.shader; + }; + /** + * @brief get the opengl type of this shader. + * @return The type of this loaded shader. + */ + public ShaderType getShaderType() { + return this.type; + }; + /** + * @brief This load/reload the data in the opengl context, needed when removed previously. + */ + public boolean updateContext(){ + if (this.exist == true) { + // Do nothing == > too dangerous ... + } else { + this.shader = OpenGL.shaderLoad(this.uri.get(), type); + // create the Shader + if (this.shader < 0) { + return true; + } + this.exist = true; + } + return true; + } + /** + * @brief remove the data from the opengl context. + */ + public void removeContext(){ + if (true == this.exist) { + OpenGL.shaderRemove(this.shader); + this.shader = -1; this.exist = false; } - public: - /** - * @brief get the opengl reference id of this shader. - * @return The opengl id. - */ - long getGLID() { - return this.shader; - }; - /** - * @brief get the opengl type of this shader. - * @return The type of this loaded shader. - */ - gale::openGL::shader::type getShaderType() { - return this.type; - }; - /** - * @brief This load/reload the data in the opengl context, needed when removed previously. - */ - boolean updateContext(){ - ethread::RecursiveLock lock(this.mutex, true); - if (lock.tryLock() == false) { - //Lock error ==> try later ... - return false; - } - if (this.exist == true) { - // Do nothing == > too dangerous ... - } else { - // create the Shader - if (this.fileData.size() == 0) { - this.shader = -1; - return true; - } - Log.debug("Create Shader : '" + this.name + "'"); - this.shader = gale::openGL::shader::create(this.type); - if (this.shader < 0) { - Log.critical(" can not load shader"); - return true; - } else { - Log.debug("Compile shader with GLID=" + this.shader); - boolean ret = gale::openGL::shader::compile(this.shader, this.fileData); - if (ret == false) { - char * tmpShaderType = "FRAGMENT SHADER"; - if (this.type == gale::openGL::shader::type::vertex){ - tmpShaderType = "VERTEX SHADER"; - } - Log.critical("Could not compile '" + tmpShaderType + "' name='" + this.name + "'"); - return true; - } - } - this.exist = true; - } - return true; - } - /** - * @brief remove the data from the opengl context. - */ - void removeContext(){ - ethread::RecursiveLock lock(this.mutex); - if (true == this.exist) { - gale::openGL::shader::remove(this.shader); - this.exist = false; - } - } - /** - * @brief Special android spec! It inform us that all context is removed and after notify us... - */ - void removeContextToLate(){ - ethread::RecursiveLock lock(this.mutex); + } + /** + * @brief Special android spec! It inform us that all context is removed and after notify us... + */ + public void removeContextToLate(){ + this.exist = false; + this.shader = -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. + */ + public void reload() { + Log.verbose("load shader:\n-----------------------------------------------------------------\n" + this.fileData + "\n-----------------------------------------------------------------"); + // now change the OGL context ... + if (OpenGL.hasContext() == true) { + Log.debug("OGL : load SHADER '" + this.name + "' ==> call update context (direct)"); + removeContext(); + updateContext(); + } else { + Log.debug("OGL : load SHADER '" + this.name + "' ==> tagged has update context needed"); + // TODO : Check this, this is a leek ==> in the GPU ... really bad ... this.exist = false; this.shader = 0; + getManager().update(this); } - /** - * @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. - */ - void reload() { - ethread::RecursiveLock lock(this.mutex); - etk::Uri uri = this.name; - if (etk::uri::exist(uri) == false) { - Log.critical("File does not Exist : '" + uri + "' : path='" + uri.getPath() + "'"); - return; - } - etk::uri::readAll(uri, this.fileData); - Log.verbose("load shader:\n-----------------------------------------------------------------\n" + this.fileData + "\n-----------------------------------------------------------------"); - // now change the OGL context ... - if (gale::openGL::hasContext() == true) { - Log.debug("OGL : load SHADER '" + this.name + "' ==> call update context (direct)"); - removeContext(); - updateContext(); - } else { - Log.debug("OGL : load SHADER '" + this.name + "' ==> tagged has update context needed"); - // TODO : Check this, this is a leek ==> in the GPU ... really bad ... - this.exist = false; - this.shader = 0; - getManager().update(ememory::dynamicPointerCast(sharedFromThis())); - } + } + public static ResourceShader create(Uri uriShader) { + ResourceShader resource; + Resource resource2; + String name = uriShader.getValue(); + if (name.isEmpty() == false && name != "---") { + resource2 = getManager().localKeep(name); + } else { + Log.error("Can not create a shader without a filaname"); + return null; + } + if (resource2 != null) { + if (resource2 instanceof ResourceShader) { + resource2.keep(); + return (ResourceShader)resource2; } + Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)"); + return null; + } + resource = new ResourceShader(uriShader); + if (resource == null) { + Log.error("allocation error of a resource : " + name); + return null; + } + if (resource.resourceHasBeenCorectlyInit() == false) { + Log.critical("resource Is not correctly init : ResourceProgram" ); + return null; + } + getManager().localAdd(resource); + return resource; + } } diff --git a/src/org/atriaSoft/gale/resource/ResourceVirtualArrayObject.java b/src/org/atriaSoft/gale/resource/ResourceVirtualArrayObject.java new file mode 100644 index 0000000..18e9cd5 --- /dev/null +++ b/src/org/atriaSoft/gale/resource/ResourceVirtualArrayObject.java @@ -0,0 +1,212 @@ +package org.atriaSoft.gale.resource; + +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; + +import org.atriaSoft.etk.Color; +import org.atriaSoft.etk.math.Vector2f; +import org.atriaSoft.etk.math.Vector3f; +import org.atriaSoft.gale.Log; +import org.atriaSoft.gale.backend3d.OpenGL; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; + +import models.RawModel; + +public class ResourceVirtualArrayObject extends Resource { + private int vaoID = -1; + private boolean exist = false; //!< This data is availlable in the Graphic card + private List vbo = new ArrayList(); + float[] positions = null; + float[] colors = null; + float[] textureCoordinates = null; + float[] normals = null; + int[] indices = null; + int vertexCount = -1; + + private FloatBuffer storeDataInFloatBuffer(float[] data) { + FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length); + buffer.put(data); + buffer.flip(); + return buffer; + } + + private IntBuffer storeDataInIntBuffer(int[] data) { + IntBuffer buffer = BufferUtils.createIntBuffer(data.length); + buffer.put(data); + buffer.flip(); + return buffer; + } + + private void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data) { + int vboID = GL15.glGenBuffers(); + vbo.add(vboID); + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 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 bindIndicesBuffer(int[] indices) { + int vboId = GL15.glGenBuffers(); + vbo.add(vboId); + GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboId); + IntBuffer buffer = storeDataInIntBuffer(indices); + GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); + } + + private void createVAO() { + vaoID = GL30.glGenVertexArrays(); + GL30.glBindVertexArray(vaoID); + } + private void unbindVAO() { + GL30.glBindVertexArray(0); + } + + public void loadToVAO() { + createVAO(); + if (indices != null) { + Log.info("Set indices"); + bindIndicesBuffer(indices); + } + if (positions != null) { + Log.info("Set positions"); + storeDataInAttributeList(0, 3, positions); + } + if (textureCoordinates != null) { + Log.info("Set textureCoordinates"); + storeDataInAttributeList(1, 2, textureCoordinates); + } + if (normals != null) { + Log.info("Set normals"); + storeDataInAttributeList(2, 3, normals); + } + if (colors != null) { + Log.info("Set colors"); + storeDataInAttributeList(3, 4, colors); + } + unbindVAO(); + } + /** + * @brief ructor of this VBO. + * @param[in] accesMode Acces mode : ??? + */ + protected ResourceVirtualArrayObject(float[] positions, float[] colors, float[] textureCoordinates, float[] normals, int[] indices, int vertexCount) { + super(); + addResourceType("gale::VirtualBufferObject"); + this.resourceLevel = 3; + this.positions = positions; + this.colors = colors; + this.textureCoordinates = textureCoordinates; + this.normals = normals; + this.indices = indices; + this.vertexCount = vertexCount; + Log.debug("OGL: load VBO count"); + } + /** + * @brief Destructor of this VBO. + */ + @Override + public void cleanUp() { + removeContext(); + } + + /** + * @brief clear buffers + */ + public void clear() { + //Log.verbose(" Clear: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.get(0).length + ")"); + // DO not clear the this.vbo indexed in the graphic cards ... + + } + /** + * @brief get the real openGL ID. + * @return the Ogl id reference of this VBO. + */ + public int getGLID() { + return this.vaoID; + }; + + /** + * @brief Send the data to the graphic card. + */ + public void flush() { + // request to the manager to be call at the next update ... + getManager().update(this); + Log.verbose("Request flush of VBO: [" + getId() + "] '" + getName() + "'"); + } + /** + * @brief This load/reload the data in the opengl context, needed when removed previously. + */ + public boolean updateContext() { + //Log.verbose(" Start: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.get(0).length + ")"); + if (this.exist == false) { + Log.debug(" ==> ALLOCATE new handle"); + // Allocate and assign a Vertex Array Object to our handle + loadToVAO(); + } + this.exist = true; + Log.verbose(" Stop: [" + getId() + "] '" + getName() + "'"); + return true; + } + /** + * @brief remove the data from the opengl context. + */ + public void removeContext() { + + if (this.exist == true) { + //OpenGL.deleteBuffers(this.vbo); + this.exist = false; + } + } + /** + * @brief Special android spec! It inform us that all context is removed and after notify us... + */ + public void removeContextToLate() { + + this.exist = false; +// for (int iii=0; iii Init APPL (END)"); + } + @Override + public void onDraw(Context _context) { + this.angle += 0.01; + Log.info("==> appl Draw ..."); + Vector2f size = getSize(); + // 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()); + // clear background + Color bgColor = new Color(0.0f, 1.0f, 1.0f, 0.75f); + OpenGL.clearColor(bgColor); + // real clear request: + OpenGL.clear(OpenGL.ClearFlag.clearFlag_colorBuffer); + // create a local matrix environnement. + OpenGL.push(); + + Matrix4f tmpProjection = Matrix4f.createMatrixOrtho(-1, 1, -1, 1, -2, 2); + // set internal matrix system: + OpenGL.setMatrix(tmpProjection); + if (this.GLprogram == null) { + Log.info("No shader ..."); + return; + } + //EWOL_DEBUG(" display " + this.coord.size() + " elements" ); + this.GLprogram.use(); + + // set Matrix : translation/positionMatrix + Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix(); + Matrix4f transforamtionMatrix = Matrix4f.createMatrixRotate(new Vector3f(0,0,1),this.angle); + Matrix4f viewMatrix = OpenGL.getCameraMatrix(); + //Matrix4f tmpMatrix = projMatrix * camMatrix; + + this.GLprogram.uniformMatrix(this.GLMatrixView, viewMatrix); + this.GLprogram.uniformMatrix(this.GLMatrixTransformation, transforamtionMatrix); + this.GLprogram.uniformMatrix(this.GLMatrixProjection, projectionMatrix); + // position: + //this.GLprogram.sendAttributePointer2(this.GLPosition, this.verticesVBO, INDICE_VBO_VERTICES); + //glEnableVertexAttribArray + // color: + //this.GLprogram.sendAttributePointer2(this.GLColor, this.verticesVBO, INDICE_VBO_COLOR); + + GL30.glBindVertexArray(this.verticesVBO.getGLID()); + GL20.glEnableVertexAttribArray(INDICE_VBO_POSITIONS); + GL20.glEnableVertexAttribArray(INDICE_VBO_COLORS); + // Request the draw od the elements: + //OpenGL.drawArrays(OpenGL.RenderMode.triangle, 0, 3 /*number of points*/); + Log.warning("Draw 3 points"); + //GL11.glDrawElements(GL11.GL_TRIANGLES, 3 /*number of points*/, GL11.GL_UNSIGNED_INT, 0); + GL11.glDrawElements(GL11.GL_TRIANGLES, 3, GL11.GL_UNSIGNED_INT, 0); + + GL20.glDisableVertexAttribArray(INDICE_VBO_COLORS); + GL20.glDisableVertexAttribArray(INDICE_VBO_POSITIONS); + GL30.glBindVertexArray(0); + this.GLprogram.unUse(); + // Restore context of matrix + OpenGL.pop(); + this.markDrawingIsNeeded(); + } + @Override + public void onPointer(Type _type, + int _pointerID, + Vector2f _pos, + Status _state) { + /* + Log.info("input event: type=" + _type); + Log.info(" id=" + _pointerID); + Log.info(" pos=" + _pos); + Log.info(" state=" + _state); + */ + } + @Override + public void onKeyboard( Special _special, + Keyboard _type, + Character _value, + Status _state) { + Log.info("Keyboard event: special=" + _special); + Log.info(" type=" + _type); + Log.info(" value='" + _value + "'"); + Log.info(" state=" + _state); + } +} diff --git a/src/org/atriaSoft/gale/test/sample1/basic.frag b/src/org/atriaSoft/gale/test/sample1/basic.frag new file mode 100644 index 0000000..58f5960 --- /dev/null +++ b/src/org/atriaSoft/gale/test/sample1/basic.frag @@ -0,0 +1,13 @@ +#version 400 core + +#ifdef GL_ES +precision mediump float; +precision mediump int; +#endif + +// output: +varying vec4 f_color; + +void main(void) { + gl_FragColor = f_color; +} diff --git a/src/org/atriaSoft/gale/test/sample1/basic.vert b/src/org/atriaSoft/gale/test/sample1/basic.vert new file mode 100644 index 0000000..a4f2905 --- /dev/null +++ b/src/org/atriaSoft/gale/test/sample1/basic.vert @@ -0,0 +1,21 @@ +#version 400 core + +#ifdef GL_ES +precision mediump float; +precision mediump int; +#endif + +// Input: +attribute vec3 position; +attribute vec4 colors; +uniform mat4 EW_MatrixTransformation; +uniform mat4 EW_MatrixProjection; +uniform mat4 EW_MatrixView; + +// output: +varying vec4 f_color; + +void main(void) { + gl_Position = EW_MatrixProjection * EW_MatrixView * EW_MatrixTransformation * vec4(position, 1.0); + f_color = colors; +} diff --git a/src/org/atriaSoft/gale/test/sample1/sample_1.java b/src/org/atriaSoft/gale/test/sample1/sample_1.java new file mode 100644 index 0000000..a12afec --- /dev/null +++ b/src/org/atriaSoft/gale/test/sample1/sample_1.java @@ -0,0 +1,11 @@ +package org.atriaSoft.gale.test.sample1; + +import org.atriaSoft.etk.Uri; +import org.atriaSoft.gale.Gale; + +public class sample_1 { + public static void main(String[] args) { + Uri.setGroup("DATA", "src/org/atriaSoft/gale/test/sample1/"); + Gale.run(new MainApplication(), args); + } +} diff --git a/src/renderEngine/EntityRenderer.java b/src/renderEngine/EntityRenderer.java index afb39a4..fa2408f 100644 --- a/src/renderEngine/EntityRenderer.java +++ b/src/renderEngine/EntityRenderer.java @@ -32,10 +32,9 @@ public class EntityRenderer { shader.stop(); } public void render(Map> entities) { - //OpenGL.enable(OpenGL.Flag.flag_blend); - //GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - //OpenGL.enable(OpenGL.Flag.flag_cullFace); - //OpenGL.enable(OpenGL.Flag.flag_back); + OpenGL.enable(OpenGL.Flag.flag_blend); + OpenGL.enable(OpenGL.Flag.flag_cullFace); + OpenGL.enable(OpenGL.Flag.flag_back); for (TexturedModel model:entities.keySet()) { prepareTexturedModel(model); OpenGL.updateAllFlags(); @@ -47,9 +46,9 @@ public class EntityRenderer { } unbindTexturedModel(); } - //OpenGL.disable(OpenGL.Flag.flag_blend); - //OpenGL.disable(OpenGL.Flag.flag_cullFace); - //OpenGL.disable(OpenGL.Flag.flag_back); + OpenGL.disable(OpenGL.Flag.flag_blend); + OpenGL.disable(OpenGL.Flag.flag_cullFace); + OpenGL.disable(OpenGL.Flag.flag_back); } private void prepareTexturedModel(TexturedModel model) { @@ -60,10 +59,9 @@ public class EntityRenderer { GL20.glEnableVertexAttribArray(2); ModelTexture texture = model.getTexture(); shader.loadNumberOfRows(texture.getNumberOfRows()); - if (texture.isHasTransparency()) { - MasterRenderer.disableCulling(); - //OpenGL.disable(OpenGL.Flag.flag_cullFace); - //OpenGL.disable(OpenGL.Flag.flag_back); + if (texture.isHasTransparency() == false) { + OpenGL.enable(OpenGL.Flag.flag_cullFace); + OpenGL.enable(OpenGL.Flag.flag_back); } shader.loadFakeLightingVariable(texture.isUseFakeLighting()); shader.loadShineVariable(texture.getShineDamper(), texture.getReflectivity()); @@ -72,12 +70,11 @@ public class EntityRenderer { } private void unbindTexturedModel() { - MasterRenderer.enableCulling(); - //OpenGL.enable(OpenGL.Flag.flag_cullFace); - //OpenGL.enable(OpenGL.Flag.flag_back); - GL20.glDisableVertexAttribArray(0); - GL20.glDisableVertexAttribArray(1); + OpenGL.disable(OpenGL.Flag.flag_cullFace); + OpenGL.disable(OpenGL.Flag.flag_back); GL20.glDisableVertexAttribArray(2); + GL20.glDisableVertexAttribArray(1); + GL20.glDisableVertexAttribArray(0); GL30.glBindVertexArray(0); } diff --git a/src/renderEngine/MasterRenderer.java b/src/renderEngine/MasterRenderer.java index 2481b15..1b6b014 100644 --- a/src/renderEngine/MasterRenderer.java +++ b/src/renderEngine/MasterRenderer.java @@ -41,8 +41,7 @@ public class MasterRenderer { public MasterRenderer(Loader loader) { //enableCulling(); - //OpenGL.enable(OpenGL.Flag.flag_blend); - GL11.glEnable(GL11.GL_BLEND); + OpenGL.enable(OpenGL.Flag.flag_blend); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); createProjectionMatrix(); renderer = new EntityRenderer(shader, projectionMatrix); @@ -51,16 +50,12 @@ public class MasterRenderer { } public static void enableCulling() { - GL11.glEnable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BACK); - //OpenGL.enable(OpenGL.Flag.flag_cullFace); - //OpenGL.enable(OpenGL.Flag.flag_back); + OpenGL.enable(OpenGL.Flag.flag_cullFace); + OpenGL.enable(OpenGL.Flag.flag_back); } public static void disableCulling() { - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glDisable(GL11.GL_BACK); - //OpenGL.disable(OpenGL.Flag.flag_cullFace); - //OpenGL.disable(OpenGL.Flag.flag_back); + OpenGL.disable(OpenGL.Flag.flag_cullFace); + OpenGL.disable(OpenGL.Flag.flag_back); } public void render(List lights, Camera camera) { @@ -99,11 +94,9 @@ public class MasterRenderer { } public void prepare() { - //OpenGL.enable(OpenGL.Flag.flag_depthTest); - GL11.glEnable(GL11.GL_DEPTH_TEST); - //OpenGL.clear(OpenGL.ClearFlag.clearFlag_depthBuffer); - //OpenGL.clear(OpenGL.ClearFlag.clearFlag_colorBuffer); - GL11.glClear(GL11.GL_COLOR_BUFFER_BIT|GL11.GL_DEPTH_BUFFER_BIT); + OpenGL.enable(OpenGL.Flag.flag_depthTest); + OpenGL.clear(OpenGL.ClearFlag.clearFlag_depthBuffer); + OpenGL.clear(OpenGL.ClearFlag.clearFlag_colorBuffer); OpenGL.clearColor(SKY_COLOUR); } @@ -114,20 +107,8 @@ public class MasterRenderer { } private void createProjectionMatrix() { - //float aspectRatio = (float) Display.getWidth() / (float) Display.getHeight(); Vector2f windowsSize = DisplayManager.getSize(); float aspectRatio = windowsSize.x / windowsSize.y; -// float y_scale = (float) ((1f/Math.atan(Math.toRadians(FOV/2f))) * aspectRatio); -// float x_scale = y_scale / aspectRatio; -// float frustrum_length = FAR_PLANE - NEAR_PLANE; -// -// projectionMatrix = new Matrix4f(); -// projectionMatrix.m00 = x_scale; -// projectionMatrix.m11 = y_scale; -// projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustrum_length); -// projectionMatrix.m23 = -1;; -// projectionMatrix.m32 = -((2*FAR_PLANE * NEAR_PLANE) / frustrum_length); -// projectionMatrix.m33 = 0; projectionMatrix = Matrix4f.createMatrixPerspective(FOV, aspectRatio, NEAR_PLANE, FAR_PLANE); } diff --git a/src/renderEngine/TerrainRenderer.java b/src/renderEngine/TerrainRenderer.java index 21de4ef..22812d4 100644 --- a/src/renderEngine/TerrainRenderer.java +++ b/src/renderEngine/TerrainRenderer.java @@ -30,10 +30,9 @@ public class TerrainRenderer { } public void render(List terrains) { - //OpenGL.enable(OpenGL.Flag.flag_blend); - //GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - //OpenGL.enable(OpenGL.Flag.flag_cullFace); - //OpenGL.enable(OpenGL.Flag.flag_back); + OpenGL.enable(OpenGL.Flag.flag_blend); + OpenGL.enable(OpenGL.Flag.flag_cullFace); + OpenGL.enable(OpenGL.Flag.flag_back); for (Terrain terrain : terrains) { prepareTerrain(terrain); loadModelMatrix(terrain); @@ -42,9 +41,9 @@ public class TerrainRenderer { GL11.GL_UNSIGNED_INT, 0); unbindTexturedModel(); } - //OpenGL.disable(OpenGL.Flag.flag_blend); - //OpenGL.disable(OpenGL.Flag.flag_cullFace); - //OpenGL.disable(OpenGL.Flag.flag_back); + OpenGL.disable(OpenGL.Flag.flag_blend); + OpenGL.disable(OpenGL.Flag.flag_cullFace); + OpenGL.disable(OpenGL.Flag.flag_back); } private void prepareTerrain(Terrain terrain) { diff --git a/src/shaders/ShaderProgram.java b/src/shaders/ShaderProgram.java index f9d9f17..13ebf0b 100644 --- a/src/shaders/ShaderProgram.java +++ b/src/shaders/ShaderProgram.java @@ -22,7 +22,6 @@ public abstract class ShaderProgram { public ShaderProgram (String vertexFile, String fragmentFile) { - /* vertexShaderID = OpenGL.shaderLoad(vertexFile, OpenGL.ShaderType.vertex); fragmentShaderID = OpenGL.shaderLoad(fragmentFile, OpenGL.ShaderType.fragment); programID = OpenGL.programCreate(); @@ -31,50 +30,26 @@ public abstract class ShaderProgram { bindAttributes(); OpenGL.programCompile(programID); getAllUniformLocations(); - */ - vertexShaderID = loadShader(vertexFile, GL20.GL_VERTEX_SHADER); - fragmentShaderID = loadShader(fragmentFile, GL20.GL_FRAGMENT_SHADER); - programID = GL20.glCreateProgram(); - GL20.glAttachShader(programID, vertexShaderID); - GL20.glAttachShader(programID, fragmentShaderID); - bindAttributes(); - GL20.glLinkProgram(programID); - GL20.glValidateProgram(programID); - getAllUniformLocations(); } protected abstract void getAllUniformLocations(); -// protected abstract void setRenderFlags(); -// protected abstract void unSetRenderFlags(); protected int getUniformLocation(String uniformName) { - //return OpenGL.programGetUniformLocation(programID, uniformName); - return GL20.glGetUniformLocation(programID, uniformName); + return OpenGL.programGetUniformLocation(programID, uniformName); } public void start() { - //setRenderFlags(); - //OpenGL.useProgram(programID); - GL20.glUseProgram(programID); + OpenGL.useProgram(programID); } public void stop() { - //OpenGL.unUseProgram(programID); - //unSetRenderFlags(); - GL20.glUseProgram(0); + OpenGL.unUseProgram(programID); } public void cleanUp() { stop(); - /* OpenGL.programDetach(programID, fragmentShaderID); OpenGL.programDetach(programID, vertexShaderID); OpenGL.shaderRemove(vertexShaderID); OpenGL.shaderRemove(fragmentShaderID); OpenGL.programRemove(programID); - */ - GL20.glDetachShader(programID, vertexShaderID); - GL20.glDetachShader(programID, fragmentShaderID); - GL20.glDeleteShader(vertexShaderID); - GL20.glDeleteShader(fragmentShaderID); - GL20.glDeleteProgram(programID); } protected abstract void bindAttributes(); @@ -82,32 +57,4 @@ public abstract class ShaderProgram { protected void bindAttribute(int attribute, String variableName) { OpenGL.programBindAttribute(programID, attribute, variableName); } - - - - private static int loadShader(String file, int type) { - System.out.println("Load shader: '" + file + "'"); - StringBuilder shaderSource = new StringBuilder(); - try { - BufferedReader reader = new BufferedReader(new FileReader(file)); - String line; - while((line = reader.readLine()) != null) { - shaderSource.append(line).append("\n"); - } - reader.close(); - } catch(IOException e) { - System.err.println("Could not read the file!"); - e.printStackTrace(); - System.exit(-1); - } - int shaderID = GL20.glCreateShader(type); - GL20.glShaderSource(shaderID, shaderSource); - GL20.glCompileShader(shaderID); - if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { - System.out.println(GL20.glGetShaderInfoLog(shaderID, 500)); - System.out.println("Could not compile the shader"); - System.exit(-1); - } - return shaderID; - } } diff --git a/src/shaders/StaticShader.java b/src/shaders/StaticShader.java index b4ae52e..24a2a4c 100644 --- a/src/shaders/StaticShader.java +++ b/src/shaders/StaticShader.java @@ -14,8 +14,8 @@ import toolbox.Maths; public class StaticShader extends ShaderProgram { private static final int MAX_LIGHTS = 4; - private static final String VERTEX_FILE = "src/shaders/vertexShader.txt"; - private static final String FRAGMENT_FILE = "src/shaders/fragmentShader.txt"; + private static final String VERTEX_FILE = "src/shaders/static.vert"; + private static final String FRAGMENT_FILE = "src/shaders/static.frag"; private int location_transformationMatrix; private int location_projectionMatrix; diff --git a/src/shaders/TerrainShader.java b/src/shaders/TerrainShader.java index b246c8b..df0f3ad 100644 --- a/src/shaders/TerrainShader.java +++ b/src/shaders/TerrainShader.java @@ -13,8 +13,8 @@ import toolbox.Maths; public class TerrainShader extends ShaderProgram { private static final int MAX_LIGHTS = 4; - private static final String VERTEX_FILE = "src/shaders/terrainVertexShader.txt"; - private static final String FRAGMENT_FILE = "src/shaders/terrainFragmentShader.txt"; + private static final String VERTEX_FILE = "src/shaders/terrain.vert"; + private static final String FRAGMENT_FILE = "src/shaders/terrain.frag"; private int location_transformationMatrix; private int location_projectionMatrix; diff --git a/src/shaders/fragmentShader.txt b/src/shaders/static.frag similarity index 100% rename from src/shaders/fragmentShader.txt rename to src/shaders/static.frag diff --git a/src/shaders/vertexShader.txt b/src/shaders/static.vert similarity index 100% rename from src/shaders/vertexShader.txt rename to src/shaders/static.vert diff --git a/src/shaders/terrainFragmentShader.txt b/src/shaders/terrain.frag similarity index 100% rename from src/shaders/terrainFragmentShader.txt rename to src/shaders/terrain.frag diff --git a/src/shaders/terrainVertexShader.txt b/src/shaders/terrain.vert similarity index 100% rename from src/shaders/terrainVertexShader.txt rename to src/shaders/terrain.vert diff --git a/src/skybox/SkyboxRenderer.java b/src/skybox/SkyboxRenderer.java index d37d9af..506ea54 100644 --- a/src/skybox/SkyboxRenderer.java +++ b/src/skybox/SkyboxRenderer.java @@ -2,7 +2,6 @@ package skybox; import org.atriaSoft.etk.math.Matrix4f; -import org.atriaSoft.etk.math.Vector3f; import org.atriaSoft.gale.backend3d.OpenGL; import org.atriaSoft.etk.Color; import org.lwjgl.opengl.GL11; @@ -82,10 +81,9 @@ public class SkyboxRenderer { } public void render(Camera camera, Color colour) { - //OpenGL.enable(OpenGL.Flag.flag_blend); - //GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - //OpenGL.enable(OpenGL.Flag.flag_cullFace); - //OpenGL.enable(OpenGL.Flag.flag_back); + OpenGL.enable(OpenGL.Flag.flag_blend); + OpenGL.enable(OpenGL.Flag.flag_cullFace); + OpenGL.enable(OpenGL.Flag.flag_back); shader.start(); shader.loadViewMatrix(camera); @@ -99,9 +97,9 @@ public class SkyboxRenderer { GL30.glBindVertexArray(0); shader.stop(); - //OpenGL.disable(OpenGL.Flag.flag_blend); - //OpenGL.disable(OpenGL.Flag.flag_cullFace); - //OpenGL.disable(OpenGL.Flag.flag_back); + OpenGL.disable(OpenGL.Flag.flag_blend); + OpenGL.disable(OpenGL.Flag.flag_cullFace); + OpenGL.disable(OpenGL.Flag.flag_back); } private void bindTextures(){ diff --git a/src/skybox/SkyboxShader.java b/src/skybox/SkyboxShader.java index 54d0b5d..68bcd41 100644 --- a/src/skybox/SkyboxShader.java +++ b/src/skybox/SkyboxShader.java @@ -13,8 +13,8 @@ import toolbox.Maths; public class SkyboxShader extends ShaderProgram { - private static final String VERTEX_FILE = "src/skybox/skyboxVertexShader.txt"; - private static final String FRAGMENT_FILE = "src/skybox/skyboxFragmentShader.txt"; + private static final String VERTEX_FILE = "src/skybox/skybox.vert"; + private static final String FRAGMENT_FILE = "src/skybox/skybox.frag"; private static final float ROTATE_SPEED = 0.02f; diff --git a/src/skybox/skyboxFragmentShader.txt b/src/skybox/skybox.frag similarity index 100% rename from src/skybox/skyboxFragmentShader.txt rename to src/skybox/skybox.frag diff --git a/src/skybox/skyboxVertexShader.txt b/src/skybox/skybox.vert similarity index 100% rename from src/skybox/skyboxVertexShader.txt rename to src/skybox/skybox.vert