[FEAT] use Maven a build system root tool

This commit is contained in:
Edouard DUPIN 2024-06-07 09:28:33 +02:00
parent adb11eaeb3
commit 423f488740
29 changed files with 1479 additions and 1276 deletions

View File

@ -1,101 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="**/__*" kind="src" path="src">
<classpathentry including="**/*.java" kind="src" output="out/maven/classes" path="src">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="resources"/>
<classpathentry including="**/*.java" kind="src" output="out/eclipse/classes-test" path="test/src">
<classpathentry kind="src" output="out/maven/test-classes" path="test/src">
<attributes>
<attribute name="test" value="true"/>
<attribute name="optional" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-14">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl3-awt-0.1.7.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/pngdecoder.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-assimp.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-assimp-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-glfw.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-glfw-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-jawt.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-opengl.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-stb.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-stb-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-opengl-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/atriasoft-io-gami">
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-21">
<attributes>
<attribute name="module" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/atriasoft-etk">
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="module" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="out/eclipse/classes"/>
<classpathentry kind="output" path="out/maven/classes"/>
</classpath>

View File

@ -1,9 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>atriasoft-gale</name>
<name>gale</name>
<comment></comment>
<projects>
<project>atriasoft-gale</project>
</projects>
<buildSpec>
<buildCommand>
@ -12,24 +11,13 @@
</arguments>
</buildCommand>
<buildCommand>
<name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
<filteredResources>
<filter>
<id>1646149232195</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View File

@ -33,14 +33,14 @@ def configure(target, my_module):
my_module.add_src_file([
'src/module-info.java',
'src/org/atriasoft/gale/TextureFilter.java',
'src/org/atriasoft/gale/internal/Log.java',
'src/org/atriasoft/gale/internal/LOGGER.java',
'src/org/atriasoft/gale/DisplayManagerDraw.java',
'src/org/atriasoft/gale/test/sample1/Sample1.java',
'src/org/atriasoft/gale/test/sample1/Sample1Application.java',
'src/org/atriasoft/gale/test/sample1/Log.java',
'src/org/atriasoft/gale/test/sample1/LOGGER.java',
'src/org/atriasoft/gale/test/sample2/Sample2Application.java',
'src/org/atriasoft/gale/test/sample2/Main.java',
'src/org/atriasoft/gale/test/sample2/Log.java',
'src/org/atriasoft/gale/test/sample2/LOGGER.java',
'src/org/atriasoft/gale/context/ClipboardList.java',
'src/org/atriasoft/gale/context/Cursor.java',
'src/org/atriasoft/gale/context/LWJG_AWT/ContextLWJGLAWT.java',

200
pom.xml Normal file
View File

@ -0,0 +1,200 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.atriasoft</groupId>
<artifactId>gale</artifactId>
<version>0.1.0</version>
<properties>
<maven.compiler.version>3.13.0</maven.compiler.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<maven.dependency.version>3.1.1</maven.dependency.version>
<lwjgl.version>3.3.3</lwjgl.version>
<lwjgl3-awt.version>0.1.8</lwjgl3-awt.version>
<lwjgl.natives>natives-linux-arm64</lwjgl.natives>
</properties>
<repositories>
<repository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</repository>
<snapshotRepository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</snapshotRepository>
</distributionManagement>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bom</artifactId>
<version>${lwjgl.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.atriasoft</groupId>
<artifactId>io-gami</artifactId>
<version>0.1.0</version>
</dependency>
<dependency>
<groupId>org.atriasoft</groupId>
<artifactId>png-decoder</artifactId>
<version>0.1.0</version>
</dependency>
<!-- generate with https://www.lwjgl.org/customize -->
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-assimp</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-jawt</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-stb</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-assimp</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-stb</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjglx</groupId>
<artifactId>lwjgl3-awt</artifactId>
<version>${lwjgl3-awt.version}</version>
</dependency>
<!-- Test tools section-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test/src</testSourceDirectory>
<directory>${project.basedir}/out/maven/</directory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<!--<encoding>${project.build.sourceEncoding}</encoding>-->
</configuration>
</plugin>
<!-- Create the source bundle -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- junit results -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<!-- Java-doc generation for stand-alone site -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<show>private</show>
<nohelp>true</nohelp>
</configuration>
</plugin>
</plugins>
</build>
<!-- Generate Java-docs As Part Of Project Reports -->
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<show>public</show>
</configuration>
</plugin>
</plugins>
</reporting>
</project>

View File

@ -12,10 +12,10 @@ open module org.atriasoft.gale {
exports org.atriasoft.gale.context.LWJG_AWT;
exports org.atriasoft.gale.key;
exports org.atriasoft.gale.resource;
requires transitive org.atriasoft.etk;
requires transitive org.atriasoft.egami;
requires transitive org.lwjgl;
requires transitive org.lwjgl.natives;
requires transitive org.lwjgl.glfw;
@ -27,10 +27,10 @@ open module org.atriasoft.gale {
requires transitive org.lwjgl.jawt;
requires transitive org.lwjgl.opengl;
requires transitive org.lwjgl.opengl.natives;
requires transitive java.desktop;
requires transitive org.atriasoft.pngdecoder;
requires transitive lwjgl3.awt;
requires org.atriasoft.reggol;
requires org.atriasoft.iogami;
requires org.slf4j;
}

View File

@ -4,15 +4,17 @@ import org.atriasoft.etk.Uri;
import org.atriasoft.gale.context.GaleContext;
//import org.atriasoft.gale.context.JOGL.ContextJOGL;
import org.atriasoft.gale.context.LWJG_AWT.ContextLWJGLAWT;
//import org.atriasoft.gale.context.LWJGL.ContextLWJGL;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Gale {
static final Logger LOGGER = LoggerFactory.getLogger(Gale.class);
public static GaleContext getContext() {
// TODO Auto-generated method stub
return GaleContext.getContext();
}
/**
* get GALE version
* @return The string that describe gale version
@ -20,16 +22,16 @@ public class Gale {
public static String getVersion() {
return "J-0.5";
}
public static void init() {
Uri.addLibrary("gale", Gale.class, "/resources/gale/");
}
/**
* This is the only one things the User might done in his main();
* @note To answare you before you ask the question, this is really simple:
* Due to the fect that the current system is multiple-platform, you "main"
* Does not exist in the android platform, then gale call other start
* Does not exist in the android platform, then gale call other start
* and stop function, to permit to have only one code
* @note The main can not be in the gale, due to the fact thet is an librairy
* @param _application just created instance of the applicationo
@ -41,17 +43,17 @@ public class Gale {
init();
//etk::init(_argc, _argv);
GaleContext context = null;
String request = "";
final String request = "";
//context = ContextLWJGL.create(application, arg);
//context = ContextJOGL.create(application, arg);
context = ContextLWJGLAWT.create(application, arg);
if (context == null) {
Log.error("Can not allocate the interface of the GUI ...");
LOGGER.error("Can not allocate the interface of the GUI ...");
return -1;
}
return context.run();
}
private Gale() {}
}

View File

@ -7,37 +7,39 @@ import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.gale.context.ClipboardList;
import org.atriasoft.gale.context.Cursor;
import org.atriasoft.gale.context.GaleContext;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GaleApplication {
static final Logger LOGGER = LoggerFactory.getLogger(GaleApplication.class);
private boolean needRedraw = true;
private String title = "gale";
private Uri iconName = null;
private final Cursor cursor = Cursor.arrow;
private Orientation orientation = Orientation.screenAuto;
private Vector2f windowsSize = new Vector2f(800, 600);
public GaleApplication() {
Log.verbose("Constructor Gale Application");
LOGGER.trace("Constructor Gale Application");
}
/**
* Exit the application (not availlable on IOs, ==> the user will not understand the comportement. He will think the application has crashed (Apple philosophie))
* @param value value to return on the program
*/
public void exit(final int value) {
Log.verbose("Exit Requested " + value);
LOGGER.trace("Exit Requested " + value);
Gale.getContext().stop();
}
public float getAspectRatio() {
return this.windowsSize.x() / this.windowsSize.y();
}
/**
* Get the cursor type.
* @return the current cursor.
@ -45,7 +47,7 @@ public class GaleApplication {
public Cursor getCursor() {
return this.cursor;
}
/**
* Get the current filename of the application.
* @return Filename of the icon.
@ -53,7 +55,7 @@ public class GaleApplication {
public Uri getIcon() {
return this.iconName;
}
/**
* get the screen orientation (if possible : only on iOs/Android)
* @return Current orientation.
@ -61,7 +63,7 @@ public class GaleApplication {
public Orientation getOrientation() {
return this.orientation;
}
/**
* Get the position of the window.
* @return Current position of the window.
@ -69,7 +71,7 @@ public class GaleApplication {
public Vector2f getPosition() {
return new Vector2f(0, 0);
}
/**
* Get the size of the window.
* @return Current size of the window.
@ -77,7 +79,7 @@ public class GaleApplication {
public Vector2f getSize() {
return this.windowsSize;
}
/**
* Get the current title of the application
* @return Current title
@ -85,13 +87,13 @@ public class GaleApplication {
public String getTitle() {
return this.title;
}
public boolean isDrawingNeeded() {
final boolean tmp = this.needRedraw;
this.needRedraw = false;
return tmp;
}
/**
* Hide the virtal keyboard (if possible : only on iOs/Android)
*/
@ -102,7 +104,7 @@ public class GaleApplication {
}
context.keyboardHide();
}
/**
* Show the virtal keyboard (if possible : only on iOs/Android)
*/
@ -113,43 +115,43 @@ public class GaleApplication {
}
context.keyboardShow();
}
public void markDrawingIsNeeded() {
this.needRedraw = true;
}
/**
* A clipboard data is back (apear after a request of a new clipboard).
* @param clipboardId Id of the clipboard.
*/
public void onClipboardEvent(final ClipboardList clipboardId) {
}
/**
* The application is created.
* @param context Current gale context.
*/
public void onCreate(final GaleContext context) {
Log.verbose("Create Gale Application");
LOGGER.trace("Create Gale Application");
}
/**
* The application is removed (call destructor just adter it.).
* @param context Current gale context.
*/
public void onDestroy(final GaleContext context) {
Log.verbose("Destroy Gale Application");
LOGGER.trace("Destroy Gale Application");
}
/**
* Real draw of the application
* @param context Current gale context.
*/
public void onDraw(final GaleContext context) {
Log.verbose("draw Gale Application");
LOGGER.trace("draw Gale Application");
}
/**
* Get keyborad value input.
* @param special Current special key status (ctrl/alt/shift ...).
@ -157,42 +159,46 @@ public class GaleApplication {
* @param value Unicode value of the char pushed (viable only if type==gale::key::keyboard::character).
* @param state State of the key (up/down/upRepeate/downRepeate)
*/
public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) {
public void onKeyboard(
final KeySpecial special,
final KeyKeyboard type,
final Character value,
final KeyStatus state) {
}
/**
* The user request application removing.
* @param context Current gale context.
*/
public void onKillDemand(final GaleContext context) {
Log.info("Gale request auto destroy ==> no applification specification");
LOGGER.info("Gale request auto destroy ==> no applification specification");
System.exit(0);
}
/**
* Event generated when user change the position of the window.
* @param size New position of the window.
*/
public void onMovePosition(final Vector2f size) {
}
/**
* The application is Hide / not visible.
* @param context Current gale context.
*/
public void onPause(final GaleContext context) {
Log.verbose("Pause Gale Application");
LOGGER.trace("Pause Gale Application");
}
/**
* Call when contrext finish process event in the buffer and add a latency of 10ms between calls
* @param clock Current time of the call;
* @param time time of the program in nanoseconds (monotonic) ==> need restart application approximately every 292 years
*/
public void onPeriod(final Clock clock, final long time) {}
/**
* Get touch/mouse/... event.
* @param type Type of pointer event
@ -200,56 +206,61 @@ public class GaleApplication {
* @param pos Position of the event (can be <0 if out of window).
* @param state Key state (up/down/move)
*/
public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) {
public void onPointer(
final KeySpecial special,
final KeyType type,
final int pointerID,
final Vector2f pos,
final KeyStatus state) {
}
/**
* call application to precalculate drawing.
* @param context Current gale context.
*/
public void onRegenerateDisplay(final GaleContext context) {
//Log.verbose("Regenerate Gale Application");
//LOGGER.trace("Regenerate Gale Application");
markDrawingIsNeeded();
}
/**
* Event generated when user change the size of the window.
* @param size New size of the window.
*/
public void onResize(final Vector2f size) {
if (size == null) {
Log.error("Try to set a null size ...");
LOGGER.error("Try to set a null size ...");
return;
}
this.windowsSize = size;
markDrawingIsNeeded();
}
/**
* The application is resumed (now visible).
* @param context Current gale context.
*/
public void onResume(final GaleContext context) {
Log.verbose("Start Gale Application");
LOGGER.trace("Start Gale Application");
}
/**
* The application is started.
* @param context Current gale context.
*/
public void onStart(final GaleContext context) {
Log.verbose("Start Gale Application");
LOGGER.trace("Start Gale Application");
}
/**
* The application is stopped.
* @param context Current gale context.
*/
public void onStop(final GaleContext context) {
Log.verbose("Stop Gale Application");
LOGGER.trace("Stop Gale Application");
}
/**
* Set the cursor type.
* @param newCursor Selected cursor.
@ -257,11 +268,11 @@ public class GaleApplication {
public void setCursor(final Cursor newCursor) {
Gale.getContext().setCursor(this.cursor);
}
void setForceRedraw() {
this.needRedraw = true;
}
/**
* set the Icon of the application.
* @param iconFile File name icon (.bmp/.png).
@ -270,7 +281,7 @@ public class GaleApplication {
this.iconName = iconFile;
Gale.getContext().setIcon(this.iconName);
}
/**
* set the screen orientation (if possible : only on iOs/Android)
* @param orientation New orientation.
@ -279,15 +290,15 @@ public class GaleApplication {
this.orientation = orientation;
Gale.getContext().forceOrientation(this.orientation);
}
/**
* Set the position of the window (if possible: Android and Ios does not support it)
* @param size New position of the window.
*/
public void setPosition(final Vector2f size) {
}
/**
* Set the size of the window (if possible: Android and Ios does not support it)
* @param size New size of the window.
@ -295,7 +306,7 @@ public class GaleApplication {
*/
public void setSize(final Vector2f size) {
if (size.x() <= 0 || size.y() <= 0) {
Log.error("Wrong windows size: " + size);
LOGGER.error("Wrong windows size: " + size);
}
final Vector2f oldSize = this.windowsSize;
this.windowsSize = size;
@ -306,12 +317,12 @@ public class GaleApplication {
context.setSize(size);
/* ==> change API ==> need the GUI notify the Windows that the size has change ????
if (!) {
Log.error("Can not set the size required by the user.");
LOGGER.error("Can not set the size required by the user.");
this.windowsSize = oldSize;
}
*/
}
/**
* Set the title of the application
* @param title New title to set at the application (if possible: Android and Ios does not support it)

View File

@ -25,15 +25,18 @@ import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.etk.math.Vector3i;
import org.atriasoft.etk.math.Vector4f;
import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OpenGL {
static final Logger LOGGER = LoggerFactory.getLogger(OpenGL.class);
public enum ClearFlag {
clearFlag_colorBuffer, // !< Indicates the buffers currently enabled for color writing.
clearFlag_depthBuffer, // !< Indicates the depth buffer.
@ -147,10 +150,13 @@ public class OpenGL {
streamDraw, staticDraw, dynamicDraw
}
private static final int[] TEXTURE_ID_BINDING = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2, GL13.GL_TEXTURE3, GL13.GL_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7,
GL13.GL_TEXTURE8, GL13.GL_TEXTURE9, GL13.GL_TEXTURE10, GL13.GL_TEXTURE11, GL13.GL_TEXTURE12, GL13.GL_TEXTURE13, GL13.GL_TEXTURE14, GL13.GL_TEXTURE15, GL13.GL_TEXTURE16, GL13.GL_TEXTURE17,
GL13.GL_TEXTURE18, GL13.GL_TEXTURE19, GL13.GL_TEXTURE20, GL13.GL_TEXTURE21, GL13.GL_TEXTURE22, GL13.GL_TEXTURE23, GL13.GL_TEXTURE24, GL13.GL_TEXTURE25, GL13.GL_TEXTURE26,
GL13.GL_TEXTURE27, GL13.GL_TEXTURE28, GL13.GL_TEXTURE29, GL13.GL_TEXTURE30, GL13.GL_TEXTURE31 };
private static final int[] TEXTURE_ID_BINDING = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2,
GL13.GL_TEXTURE3, GL13.GL_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7, GL13.GL_TEXTURE8,
GL13.GL_TEXTURE9, GL13.GL_TEXTURE10, GL13.GL_TEXTURE11, GL13.GL_TEXTURE12, GL13.GL_TEXTURE13,
GL13.GL_TEXTURE14, GL13.GL_TEXTURE15, GL13.GL_TEXTURE16, GL13.GL_TEXTURE17, GL13.GL_TEXTURE18,
GL13.GL_TEXTURE19, GL13.GL_TEXTURE20, GL13.GL_TEXTURE21, GL13.GL_TEXTURE22, GL13.GL_TEXTURE23,
GL13.GL_TEXTURE24, GL13.GL_TEXTURE25, GL13.GL_TEXTURE26, GL13.GL_TEXTURE27, GL13.GL_TEXTURE28,
GL13.GL_TEXTURE29, GL13.GL_TEXTURE30, GL13.GL_TEXTURE31 };
public static final int GL_RGB = GL11.GL_RGB;
@ -170,9 +176,11 @@ public class OpenGL {
private static Matrix4f matrixCamera = Matrix4f.IDENTITY;
private static int programId = 0;
private static final Map<RenderMode, Integer> CONVERT_RENDER_MODE = Map.of(RenderMode.POINT, GL11.GL_POINTS, RenderMode.LINE, GL11.GL_LINES, RenderMode.LINE_STRIP, GL11.GL_LINE_STRIP,
RenderMode.LINE_LOOP, GL11.GL_LINE_LOOP, RenderMode.TRIANGLE, GL11.GL_TRIANGLES, RenderMode.TRIANGLE_STRIP, GL11.GL_TRIANGLE_STRIP, RenderMode.TRIANGLE_FAN, GL11.GL_TRIANGLE_FAN,
RenderMode.QUAD, GL11.GL_QUADS, RenderMode.QUAD_STRIP, GL11.GL_QUAD_STRIP, RenderMode.POLYGON, GL11.GL_POLYGON);
private static final Map<RenderMode, Integer> CONVERT_RENDER_MODE = Map.of(RenderMode.POINT, GL11.GL_POINTS,
RenderMode.LINE, GL11.GL_LINES, RenderMode.LINE_STRIP, GL11.GL_LINE_STRIP, RenderMode.LINE_LOOP,
GL11.GL_LINE_LOOP, RenderMode.TRIANGLE, GL11.GL_TRIANGLES, RenderMode.TRIANGLE_STRIP,
GL11.GL_TRIANGLE_STRIP, RenderMode.TRIANGLE_FAN, GL11.GL_TRIANGLE_FAN, RenderMode.QUAD, GL11.GL_QUADS,
RenderMode.QUAD_STRIP, GL11.GL_QUAD_STRIP, RenderMode.POLYGON, GL11.GL_POLYGON);
private static final Map<Flag, Integer> BASIC_FLAG;
private static boolean flagsStatesChange = false;
@ -248,7 +256,8 @@ public class OpenGL {
OpenGL.convertUsage.put(Usage.dynamicDraw, GL15.GL_DYNAMIC_DRAW);
}
private static final Map<Long, Boolean> THREAD_HAS_CONTEXT = new HashMap<>();
private static final Map<ClearFlag, Integer> BASIC_FLAG_CLEAR = Map.of(ClearFlag.clearFlag_colorBuffer, GL11.GL_COLOR_BUFFER_BIT, ClearFlag.clearFlag_depthBuffer, GL11.GL_DEPTH_BUFFER_BIT,
private static final Map<ClearFlag, Integer> BASIC_FLAG_CLEAR = Map.of(ClearFlag.clearFlag_colorBuffer,
GL11.GL_COLOR_BUFFER_BIT, ClearFlag.clearFlag_depthBuffer, GL11.GL_DEPTH_BUFFER_BIT,
ClearFlag.clearFlag_stencilBuffer, GL11.GL_STENCIL_BUFFER_BIT);
/**
@ -260,7 +269,7 @@ public class OpenGL {
GL13.glActiveTexture(OpenGL.TEXTURE_ID_BINDING[textureID]);
OpenGL.checkGlError("glActiveTexture");
} else if (OpenGL.DEBUG) {
Log.error("try to bind texture with no program set");
LOGGER.error("try to bind texture with no program set");
}
}
@ -312,14 +321,14 @@ public class OpenGL {
// if (CHECKERROROPENGL) {
// boolean hasError = false;
// for (int error = GL11.glGetError(); error != null; error = GL11.glGetError()) {
// Log.error("after " + op + "():" + localLine + " glError(" + error + ")");
// LOGGER.error("after " + op + "():" + localLine + " glError(" + error + ")");
// hasError = true;
// }
// if (hasError) {
// Log.critical("plop");
// LOGGER.critical("plop");
// }
// for (GLint error = glGetError(); error; error = glGetError()) {
// Log.error("after " + op + "() glError (" + error + ")");
// LOGGER.error("after " + op + "() glError (" + error + ")");
// }
// }
}
@ -380,7 +389,7 @@ public class OpenGL {
public static boolean deleteBuffers(final int[] buffers) {
if (buffers.length == 0) {
Log.warning("try to delete vector buffer with size 0");
LOGGER.warn("try to delete vector buffer with size 0");
return true;
}
// TODO Check if we are in the correct thread
@ -406,15 +415,15 @@ public class OpenGL {
* @param flagID The flag requested
*/
public static void disable(final Flag flagID) {
// Log.info("Disable : " + flagID);
// LOGGER.info("Disable : " + flagID);
if (OpenGL.DIRECT_MODE) {
GL11.glDisable(OpenGL.BASIC_FLAG.get(flagID));
OpenGL.checkGlError("glDisable");
} else {
// Log.debug("Disable FLAGS = " + this.flagsStates);
// LOGGER.debug("Disable FLAGS = " + this.flagsStates);
OpenGL.FLAGS_STATES.get(flagID).mustBeSet = false;
OpenGL.flagsStatesChange = true;
// Log.debug(" == >" + this.flagsStates);
// LOGGER.debug(" == >" + this.flagsStates);
}
}
@ -442,35 +451,35 @@ public class OpenGL {
* @param flagID The flag requested
*/
public static void enable(final Flag flagID) {
// Log.info("Enable : " + flagID);
// LOGGER.info("Enable : " + flagID);
if (OpenGL.DIRECT_MODE) {
GL11.glEnable(OpenGL.BASIC_FLAG.get(flagID));
OpenGL.checkGlError("glEnable");
} else {
// Log.debug("Enable FLAGS = " + this.flagsStates);
// LOGGER.debug("Enable FLAGS = " + this.flagsStates);
OpenGL.FLAGS_STATES.get(flagID).mustBeSet = true;
OpenGL.flagsStatesChange = true;
// Log.debug(" == >" + this.flagsStates);
// LOGGER.debug(" == >" + this.flagsStates);
}
}
/**
*
*
*/
public static void finish() {
OpenGL.programId = -1;
}
/**
*
*
*/
public static void flush() {
OpenGL.programId = -1;
GL11.glFlush();
// checkGlError("glFlush");
// Log.info("========================" );
// Log.info("== FLUSH OPEN GL ==" );
// Log.info("========================");
// LOGGER.info("========================" );
// LOGGER.info("== FLUSH OPEN GL ==" );
// LOGGER.info("========================");
}
public static int genBuffers() {
@ -479,16 +488,16 @@ public class OpenGL {
public static boolean genBuffers(final int[] buffers) {
if (buffers.length == 0) {
Log.warning("try to generate vector buffer with size 0");
LOGGER.warn("try to generate vector buffer with size 0");
return true;
}
Log.info("Create N=" + buffers.length + " Buffer");
LOGGER.info("Create N=" + buffers.length + " Buffer");
GL15.glGenBuffers(buffers);
OpenGL.checkGlError("glGenBuffers");
boolean hasError = false;
for (int iii = 0; iii < buffers.length; iii++) {
if (buffers[iii] == 0) {
Log.error("[" + iii + "] error to create a buffer id=" + buffers[iii]);
LOGGER.error("[" + iii + "] error to create a buffer id=" + buffers[iii]);
hasError = true;
}
}
@ -510,7 +519,7 @@ public class OpenGL {
*/
public static Matrix4f getMatrix() {
if (OpenGL.MATRIX_LIST.size() == 0) {
Log.error("set matrix list is not corect size in the stack: 0");
LOGGER.error("set matrix list is not corect size in the stack: 0");
OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY);
}
return OpenGL.MATRIX_LIST.get(OpenGL.MATRIX_LIST.size() - 1);
@ -524,29 +533,63 @@ public class OpenGL {
return GL11.glGenTextures();
}
public static void glTexImage2D(final int level, final int internalFormat, final int width, final int height, final int border, final int format, final int sizeObject, final byte[] data) {
public static void glTexImage2D(
final int level,
final int internalFormat,
final int width,
final int height,
final int border,
final int format,
final int sizeObject,
final byte[] data) {
final ByteBuffer dataBuffer = ByteBuffer.allocateDirect(data.length);
for (int iii = 0; iii < data.length; iii++) {
dataBuffer.put(data[iii]);
for (final byte element : data) {
dataBuffer.put(element);
}
dataBuffer.flip();
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, level, internalFormat, width, height, border, format, sizeObject, dataBuffer);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, level, internalFormat, width, height, border, format, sizeObject,
dataBuffer);
}
public static void glTexImage2D(final int level, final int internalFormat, final int width, final int height, final int border, final int format, final int sizeObject, final ByteBuffer data) {
public static void glTexImage2D(
final int level,
final int internalFormat,
final int width,
final int height,
final int border,
final int format,
final int sizeObject,
final ByteBuffer data) {
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, level, internalFormat, width, height, border, format, sizeObject, data);
}
public static void glTexSubImage2D(final int level, final int xOffset, final int yOffset, final int width, final int height, final int format, final int sizeObject, final byte[] data) {
public static void glTexSubImage2D(
final int level,
final int xOffset,
final int yOffset,
final int width,
final int height,
final int format,
final int sizeObject,
final byte[] data) {
final ByteBuffer dataBuffer = ByteBuffer.allocateDirect(data.length);
for (int iii = 0; iii < data.length; iii++) {
dataBuffer.put(data[iii]);
for (final byte element : data) {
dataBuffer.put(element);
}
dataBuffer.flip();
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, xOffset, yOffset, width, height, format, sizeObject, dataBuffer);
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, xOffset, yOffset, width, height, format, sizeObject,
dataBuffer);
}
public static void glTexSubImage2D(final int level, final int xOffset, final int yOffset, final int width, final int height, final int format, final int sizeObject, final ByteBuffer data) {
public static void glTexSubImage2D(
final int level,
final int xOffset,
final int yOffset,
final int width,
final int height,
final int format,
final int sizeObject,
final ByteBuffer data) {
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, xOffset, yOffset, width, height, format, sizeObject, data);
}
@ -582,9 +625,9 @@ public class OpenGL {
* remove the current matrix and get the last one from the matrix stack.
*/
public static void pop() {
Log.verbose("Pop OpenGl Matrix: " + OpenGL.MATRIX_LIST.size());
LOGGER.trace("Pop OpenGl Matrix: " + OpenGL.MATRIX_LIST.size());
if (OpenGL.MATRIX_LIST.size() <= 1) {
Log.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
LOGGER.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
OpenGL.MATRIX_LIST.clear();
OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY);
OpenGL.matrixCamera = Matrix4f.IDENTITY;
@ -596,11 +639,11 @@ public class OpenGL {
public static boolean programAttach(final int prog, final int shader) {
if (prog < 0) {
Log.error("wrong program ID");
LOGGER.error("wrong program ID");
return false;
}
if (shader < 0) {
Log.error("wrong shader ID");
LOGGER.error("wrong shader ID");
return false;
}
GL20.glAttachShader(prog, shader);
@ -610,7 +653,7 @@ public class OpenGL {
public static void programBindAttribute(final int prog, final int attribute, final String variableName) {
if (prog < 0) {
Log.error("wrong program ID");
LOGGER.error("wrong program ID");
return;
}
GL20.glBindAttribLocation(prog, attribute, variableName);
@ -618,7 +661,7 @@ public class OpenGL {
public static boolean programCompile(final int prog) {
if (prog < 0) {
Log.error("wrong program ID");
LOGGER.error("wrong program ID");
return false;
}
GL20.glLinkProgram(prog);
@ -635,14 +678,14 @@ public class OpenGL {
// this.bufferDisplayError);
// char tmpLog[256];
// int idOut=0;
// Log.error("Could not compile 'PROGRAM':");
// LOGGER.error("Could not compile 'PROGRAM':");
// for (sizet iii=0; iii<LOGOGLINTERNALBUFFERLEN ; iii++) {
// tmpLog[idOut] = this.bufferDisplayError[iii];
// if ( tmpLog[idOut] == '\n'
// || tmpLog[idOut] == '\0'
// || idOut >= 256) {
// tmpLog[idOut] = '\0';
// Log.error(" == > " + tmpLog);
// LOGGER.error(" == > " + tmpLog);
// idOut=0;
// } else {
// idOut++;
@ -653,7 +696,7 @@ public class OpenGL {
// }
// if (idOut != 0) {
// tmpLog[idOut] = '\0';
// Log.error(" == > " + tmpLog);
// LOGGER.error(" == > " + tmpLog);
// }
// return false;
// }
@ -666,21 +709,21 @@ public class OpenGL {
public static int programCreate() {
final int programId = GL20.glCreateProgram();
if (programId == 0) {
Log.error("program creation return error ...");
LOGGER.error("program creation return error ...");
OpenGL.checkGlError("glCreateProgram");
return -1;
}
Log.debug("Create program with oglID=" + programId);
LOGGER.debug("Create program with oglID=" + programId);
return programId;
}
public static boolean programDetach(final int prog, final int shader) {
if (prog < 0) {
Log.error("wrong program ID");
LOGGER.error("wrong program ID");
return false;
}
if (shader < 0) {
Log.error("wrong shader ID");
LOGGER.error("wrong shader ID");
return false;
}
GL20.glDetachShader(prog, shader);
@ -690,17 +733,17 @@ public class OpenGL {
public static int programGetAttributeLocation(final int prog, final String name) {
if (prog < 0) {
Log.error("wrong program ID");
LOGGER.error("wrong program ID");
return -1;
}
if (name.length() == 0) {
Log.error("wrong name of attribure");
LOGGER.error("wrong name of attribure");
return -1;
}
final int val = GL20.glGetAttribLocation(prog, name);
if (val < 0) {
OpenGL.checkGlError("glGetAttribLocation");
Log.warning("glGetAttribLocation('" + name + "') = " + val);
LOGGER.warn("glGetAttribLocation('" + name + "') = " + val);
return -1;
}
return val;
@ -708,23 +751,23 @@ public class OpenGL {
public static int programGetUniformLocation(final int prog, final String name) {
if (prog < 0) {
Log.error("wrong program ID");
LOGGER.error("wrong program ID");
return -1;
}
if (name.length() == 0) {
Log.error("wrong name of uniform");
LOGGER.error("wrong name of uniform");
return -1;
}
final int val = GL20.glGetUniformLocation(prog, name);
if (val == GL11.GL_INVALID_VALUE) {
OpenGL.checkGlError("glGetUniformLocation");
Log.warning("glGetUniformLocation('" + name + "') = GL_INVALID_VALUE");
LOGGER.warn("glGetUniformLocation('" + name + "') = GL_INVALID_VALUE");
} else if (val == GL11.GL_INVALID_OPERATION) {
OpenGL.checkGlError("glGetUniformLocation");
Log.warning("glGetUniformLocation('" + name + "') = GL_INVALID_OPERATION");
LOGGER.warn("glGetUniformLocation('" + name + "') = GL_INVALID_OPERATION");
} else if (val < 0) {
OpenGL.checkGlError("glGetUniformLocation");
Log.warning("glGetUniformLocation('" + name + "') = " + val);
LOGGER.warn("glGetUniformLocation('" + name + "') = " + val);
}
return val;
}
@ -750,11 +793,20 @@ public class OpenGL {
GL20.glUniform2f(location, value, value2);
}
public static void programLoadUniformFloat(final int location, final float value, final float value2, final float value3) {
public static void programLoadUniformFloat(
final int location,
final float value,
final float value2,
final float value3) {
GL20.glUniform3f(location, value, value2, value3);
}
public static void programLoadUniformFloat(final int location, final float value, final float value2, final float value3, final float value4) {
public static void programLoadUniformFloat(
final int location,
final float value,
final float value2,
final float value3,
final float value4) {
GL20.glUniform4f(location, value, value2, value3, value4);
}
@ -770,7 +822,12 @@ public class OpenGL {
GL20.glUniform3i(location, value, value2, value3);
}
public static void programLoadUniformInt(final int location, final int value, final int value2, final int value3, final int value4) {
public static void programLoadUniformInt(
final int location,
final int value,
final int value2,
final int value3,
final int value4) {
GL20.glUniform4i(location, value, value2, value3, value4);
}
@ -818,7 +875,7 @@ public class OpenGL {
// public static void drawElements(RenderMode mode, List<Integer> indices) {
// if (this.programId >= 0) {
// updateAllFlags();
// //Log.debug("Request draw of " + indices.size() + "elements");
// //LOGGER.debug("Request draw of " + indices.size() + "elements");
// GL15.glDrawElements(convertRenderMode.get(mode), indices.size(),
// GL11.GL_UNSIGNED_INT);//, &indices[0]);
// checkGlError("glDrawElements");
@ -845,7 +902,7 @@ public class OpenGL {
* @param id Id of the program that might be used
*/
public static void programUse(final int id) {
// Log.verbose("USE prog : " + id);
// LOGGER.trace("USE prog : " + id);
// note : In normal openGL case, the system might call with the program ID and
// at the end with 0,
// here, we wrap this use to prevent over call of glUseProgram == > then we set
@ -867,9 +924,9 @@ public class OpenGL {
* store current matrix in the matrix stack.
*/
public static void push() {
Log.verbose("push OpenGl Matrix: " + OpenGL.MATRIX_LIST.size());
LOGGER.trace("push OpenGl Matrix: " + OpenGL.MATRIX_LIST.size());
if (OpenGL.MATRIX_LIST.size() == 0) {
Log.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
LOGGER.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY);
return;
}
@ -887,7 +944,8 @@ public class OpenGL {
}
reader.close();
} catch (final IOException e) {
Log.critical("Could not read the file!");
LOGGER.error("Could not read the file!");
System.exit(-1);
}
return fileSource;
}
@ -897,15 +955,17 @@ public class OpenGL {
try {
final InputStream inputStream = Uri.getStream(name);
if (inputStream == null) {
Log.critical("Could not read the file! " + name);
LOGGER.error("Could not read the file! " + name);
System.exit(-1);
}
final Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())));
final Reader reader = new BufferedReader(
new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())));
int c = 0;
while ((c = reader.read()) != -1) {
fileSource.append((char) c);
}
} catch (final IOException e) {
Log.error("Could not read the file! " + name);
LOGGER.error("Could not read the file! " + name);
e.printStackTrace();
System.exit(-1);
}
@ -914,7 +974,7 @@ public class OpenGL {
public static void reset() {
if (OpenGL.DIRECT_MODE) {
Log.error("TODO ...");
LOGGER.error("TODO ...");
} else {
OpenGL.clearFlagState();
OpenGL.programId = -1;
@ -938,7 +998,7 @@ public class OpenGL {
*/
public static void setBasicMatrix(final Matrix4f newOne) {
if (OpenGL.MATRIX_LIST.size() != 1) {
Log.error("matrix is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
LOGGER.error("matrix is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
}
OpenGL.MATRIX_LIST.clear();
OpenGL.MATRIX_LIST.add(newOne);
@ -965,7 +1025,7 @@ public class OpenGL {
*/
public static void setMatrix(final Matrix4f newOne) {
if (OpenGL.MATRIX_LIST.size() == 0) {
Log.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
LOGGER.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
OpenGL.MATRIX_LIST.add(newOne);
return;
}
@ -993,25 +1053,25 @@ public class OpenGL {
}
public static void setViewPort(final Vector2f start, final Vector2f stop) {
// Log.info("setViewport " + start + " " + stop);
// LOGGER.info("setViewport " + start + " " + stop);
GL11.glViewport((int) start.x(), (int) start.y(), (int) stop.x(), (int) stop.y());
OpenGL.checkGlError("glViewport");
}
public static void setViewPort(final Vector2i start, final Vector2i stop) {
// Log.info("setViewport " + start + " " + stop);
// LOGGER.info("setViewport " + start + " " + stop);
GL11.glViewport(start.x(), start.y(), stop.x(), stop.y());
OpenGL.checkGlError("glViewport");
}
public static void setViewPort(final Vector3f start, final Vector3f stop) {
// Log.info("setViewport " + start + " " + stop);
// LOGGER.info("setViewport " + start + " " + stop);
GL11.glViewport((int) start.x(), (int) start.y(), (int) stop.x(), (int) stop.y());
OpenGL.checkGlError("glViewport");
}
public static void setViewPort(final Vector3i start, final Vector3i stop) {
// Log.info("setViewport " + start + " " + stop);
// LOGGER.info("setViewport " + start + " " + stop);
GL11.glViewport(start.x(), start.y(), stop.x(), stop.y());
OpenGL.checkGlError("glViewport");
}
@ -1019,18 +1079,18 @@ public class OpenGL {
private static int shaderCreate(final ShaderType type) {
int shaderId = 0;
if (type == ShaderType.VERTEX) {
Log.verbose("create shader: VERTEX");
LOGGER.trace("create shader: VERTEX");
shaderId = GL20.glCreateShader(GL20.GL_VERTEX_SHADER);
} else if (type == ShaderType.FRAGMENT) {
Log.verbose("create shader: FRAGMENT");
LOGGER.trace("create shader: FRAGMENT");
shaderId = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER);
} else {
Log.error("create shader with wrong type ...");
LOGGER.error("create shader with wrong type ...");
return -1;
}
Log.verbose("create shader: ... (done)");
LOGGER.trace("create shader: ... (done)");
if (shaderId == 0) {
Log.error("glCreateShader return error ...");
LOGGER.error("glCreateShader return error ...");
OpenGL.checkGlError("glCreateShader");
return -1;
}
@ -1044,8 +1104,8 @@ public class OpenGL {
GL20.glShaderSource(shaderID, shaderSource);
GL20.glCompileShader(shaderID);
if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
Log.error(GL20.glGetShaderInfoLog(shaderID, 500));
Log.error("Could not compile the shader");
LOGGER.error(GL20.glGetShaderInfoLog(shaderID, 500));
LOGGER.error("Could not compile the shader");
return -1;
}
return shaderID;
@ -1061,7 +1121,7 @@ public class OpenGL {
}
public static FloatBuffer storeDataInFloatBuffer(final Color[] data) {
float[] tmpData = new float[data.length * 4];
final float[] tmpData = new float[data.length * 4];
for (int iii = 0; iii < data.length; iii++) {
tmpData[iii * 4] = data[iii].r();
tmpData[iii * 4 + 1] = data[iii].g();
@ -1098,7 +1158,7 @@ public class OpenGL {
}
public static FloatBuffer storeDataInFloatBuffer(final Vector2f[] data) {
float[] tmpData = new float[data.length * 2];
final float[] tmpData = new float[data.length * 2];
for (int iii = 0; iii < data.length; iii++) {
tmpData[iii * 2] = data[iii].x();
tmpData[iii * 2 + 1] = data[iii].y();
@ -1117,7 +1177,7 @@ public class OpenGL {
}
public static FloatBuffer storeDataInFloatBuffer(final Vector3f[] data) {
float[] tmpData = new float[data.length * 3];
final float[] tmpData = new float[data.length * 3];
for (int iii = 0; iii < data.length; iii++) {
tmpData[iii * 3] = data[iii].x();
tmpData[iii * 3 + 1] = data[iii].y();
@ -1140,7 +1200,7 @@ public class OpenGL {
}
/**
*
*
*/
public static void swap() {
@ -1198,11 +1258,11 @@ public class OpenGL {
if (value.current) {
GL11.glEnable(OpenGL.BASIC_FLAG.get(elem.getKey()));
OpenGL.checkGlError("glEnable");
// Log.info(" enable : " + elem.getKey() + " " + basicFlag.get(elem.getKey()));
// LOGGER.info(" enable : " + elem.getKey() + " " + basicFlag.get(elem.getKey()));
} else {
GL11.glDisable(OpenGL.BASIC_FLAG.get(elem.getKey()));
OpenGL.checkGlError("glDisable");
// Log.info(" disable : " + elem.getKey());
// LOGGER.info(" disable : " + elem.getKey());
}
}
}

View File

@ -3,31 +3,33 @@ package org.atriasoft.gale.context;
import java.util.ArrayList;
import java.util.List;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CommandLine {
private List<String> listArgs = new ArrayList<String>();
public void parse(String[] args) {
for (int iii=1 ; iii<args.length; iii++) {
Log.info("commandLine : '" + args[iii] + "'" );
listArgs.add(args[iii]);
static final Logger LOGGER = LoggerFactory.getLogger(CommandLine.class);
private final List<String> listArgs = new ArrayList<>();
public void parse(final String[] args) {
for (int iii = 1; iii < args.length; iii++) {
LOGGER.info("commandLine : '" + args[iii] + "'");
this.listArgs.add(args[iii]);
}
}
public int size() {
return listArgs.size();
return this.listArgs.size();
}
public String get(int id) {
return listArgs.get(id);
public String get(final int id) {
return this.listArgs.get(id);
}
public void add(String newElement) {
listArgs.add(newElement);
public void add(final String newElement) {
this.listArgs.add(newElement);
}
public void remove(int id) {
listArgs.remove(id);
public void remove(final int id) {
this.listArgs.remove(id);
}
}

View File

@ -14,12 +14,13 @@ import org.atriasoft.gale.Gale;
import org.atriasoft.gale.GaleApplication;
import org.atriasoft.gale.Orientation;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gale.resource.ResourceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
interface ActionToDoInAsyncLoop {
void run(GaleContext context);
@ -30,13 +31,14 @@ enum ApplicationState {
}
public abstract class GaleContext {
static final Logger LOGGER = LoggerFactory.getLogger(GaleContext.class);
protected static final int MAX_MANAGE_INPUT = 15;
private static final String STATIC_ID_RESIZE = "010__RESIZE";
private static final String STATIC_ID_REDRAW_ALL = "0100__REDRAW_ALL";
private static GaleContext globalContext = null;
// return true if a flush is needed
private static int countMemeCheck = 0;
/**
* From everyware in the program, we can get the context inteface.
* @return current reference on the instance.
@ -45,11 +47,11 @@ public abstract class GaleContext {
public static GaleContext getContext() {
return GaleContext.globalContext;
}
public static void setContext(final GaleContext context) {
GaleContext.globalContext = context;
}
protected ThreadAbstract periodicThread;
protected GaleApplication application; //!< Application handle
protected ApplicationState applicationState = ApplicationState.UNDEFINED; // state of the application
@ -58,7 +60,7 @@ public abstract class GaleContext {
// simulation area:
private long previousDisplayTime; // this is to limit framerate ... in case...
private final boolean displayFps = true;
private final Lock msgSystemAsyncLock = new ReentrantLock();
private final MessageSystem msgSystemAsync = new MessageSystem();
private final MessageSystem msgSystemGui = new MessageSystem();
@ -71,7 +73,7 @@ public abstract class GaleContext {
protected Vector2f windowsPos; //!< current size of the system
// note: in the current mode, the management is not able to synchronize it good..
private final boolean requestSynchronousProcessing = true; //!< this permit to process the event in the global GUI thread instead of the local processing thread.
public GaleContext(final GaleApplication application, final String[] args) {
// set a basic
this.application = application;
@ -79,17 +81,18 @@ public abstract class GaleContext {
GaleContext.setContext(this);
Thread.currentThread().setName("galeThread");
if (this.application == null) {
Log.critical("Can not start context with no Application ==> rtfm ...");
LOGGER.error("Can not start context with no Application ==> rtfm ...");
throw new RuntimeException("Can not start context with no Application ==> rtfm ...");
}
this.commandLine.parse(args);
Log.info(" == > Gale system init (BEGIN)");
LOGGER.info(" == > Gale system init (BEGIN)");
// create thread to manage real periodic event
this.periodicThread = new PeriodicThread(this);
// By default we set 2 themes (1 color and 1 shape ...) :
//theme::setNameDefault("GUI", "shape/square/");
//theme::setNameDefault("COLOR", "color/black/");
// parse the debug level:
// for(int iii=0; iii<this.commandLine.size(); ++iii) {
// if (this.commandLine.get(iii) == "--gale-fps") {
@ -97,13 +100,13 @@ public abstract class GaleContext {
// } else if ( this.commandLine.get(iii) == "-h"
// || this.commandLine.get(iii) == "--help"
// || startwith(this.commandLine.get(iii), "--gale")) {
// Log.print("gale - help : ");
// Log.print(" --gale-fps");
// Log.print(" Display the current fps of the display");
// Log.print(" -h/--help");
// Log.print(" Display this help");
// LOGGER.print("gale - help : ");
// LOGGER.print(" --gale-fps");
// LOGGER.print(" Display the current fps of the display");
// LOGGER.print(" -h/--help");
// LOGGER.print(" Display this help");
// if (startwith(this.commandLine.get(iii), "--gale")) {
// Log.error("gale unknow element in parameter: '" << this.commandLine.get(iii) << "'");
// LOGGER.error("gale unknow element in parameter: '" << this.commandLine.get(iii) << "'");
// // remove parameter ...
// } else {
// // this is a global help system does not remove it
@ -116,8 +119,8 @@ public abstract class GaleContext {
// --iii;
// }
//cout.setOutputFile(true);
Log.info("GALE v: {}", Gale.getVersion());
LOGGER.info("GALE v: {}", Gale.getVersion());
forceOrientation(Orientation.screenAuto);
postActionAsync(context -> {
final GaleApplication appl = context.getApplication();
@ -132,12 +135,12 @@ public abstract class GaleContext {
// this is done at the end to perform a full ended rendering.
context.requestUpdateSize();
});
// force a recalculation
//requestUpdateSize();
Log.info(" == > Gale system init (END)");
LOGGER.info(" == > Gale system init (END)");
}
/**
* Inform the Gui that we want to have a copy of the clipboard
* @param clipboardID ID of the clipboard (STD/SELECTION) only apear here
@ -146,7 +149,7 @@ public abstract class GaleContext {
// just transmit an event , we have the data in the system
operatingSystemClipBoardArrive(clipboardID);
}
/**
* Inform the Gui that we are the new owner of the clipboard
* @param clipboardID ID of the clipboard (STD/SELECTION) only apear here
@ -154,7 +157,7 @@ public abstract class GaleContext {
public void clipBoardSet(final ClipboardList clipboardID) {
// nothing to do, data is already copyed in the GALE clipborad center
}
/**
* force the screen orientation (availlable on portable elements ...
* @param orientation Selected orientation.
@ -164,11 +167,11 @@ public abstract class GaleContext {
context.forceOrientationThreadGUI(orientation);
});
}
protected void forceOrientationThreadGUI(final Orientation orientation) {
Log.todo("forceOrientation: not implemented");
LOGGER.info("TODO: forceOrientation: not implemented");
}
/**
* Redraw all the windows
*/
@ -181,12 +184,12 @@ public abstract class GaleContext {
}
this.application.onResize(this.windowsSize);
}
// Called by Consumer
public ActionToDoInAsyncLoop getAction() {
return this.msgSystemAsync.getElementWait();
}
public GaleApplication getApplication() {
return this.application;
/*
@ -199,15 +202,15 @@ public abstract class GaleContext {
}
*/
}
public CommandLine getCmd() {
return this.commandLine;
}
public boolean getFullScreen() {
return this.fullscreen;
}
/**
* The Application request the current position of the windows.
* @return Turrent position of the Windows.
@ -215,11 +218,11 @@ public abstract class GaleContext {
public Vector2f getPos() {
return this.windowsPos;
}
public ResourceManager getResourcesManager() {
return this.resourceManager;
}
/**
* get the current windows size
* @return the current size ...
@ -227,7 +230,7 @@ public abstract class GaleContext {
public Vector2f getSize() {
return this.windowsSize;
}
/**
* get all Keyboard event from the X system (like many time use of META)
* @param status "true" if all the event will be get, false if we want only ours.
@ -237,11 +240,11 @@ public abstract class GaleContext {
context.grabKeyboardEventsThreadGUI(status);
});
}
protected void grabKeyboardEventsThreadGUI(final boolean status) {
Log.info("grabKeyboardEvents: NOT implemented ...");
LOGGER.info("grabKeyboardEvents: NOT implemented ...");
}
/**
* get all Mouse/Touch events from the X system
* @param status "true" if all the event will be get, false if we want only ours.
@ -252,12 +255,12 @@ public abstract class GaleContext {
context.grabPointerEventsThreadGUI(status, forcedPosition);
});
}
protected void grabPointerEventsThreadGUI(final boolean status, final Vector2f forcedPosition) {
Log.info("grabPointerEvents: NOT implemented ...");
LOGGER.info("grabPointerEvents: NOT implemented ...");
}
/**
* The Application request that the Windows will be Hidden.
*/
@ -266,15 +269,15 @@ public abstract class GaleContext {
context.hideThreadGUI();
});
}
protected void hideThreadGUI() {
Log.info("hide: NOT implemented ...");
LOGGER.info("hide: NOT implemented ...");
}
public boolean isGrabPointerEvents() {
return false;
}
/**
* Hide the virtual keyboard (for touch system only)
*/
@ -283,11 +286,11 @@ public abstract class GaleContext {
context.keyboardHideThreadGUI();
});
}
protected void keyboardHideThreadGUI() {
Log.info("keyboardHide: NOT implemented ...");
LOGGER.info("keyboardHide: NOT implemented ...");
}
/**
* display the virtual keyboard (for touch system only)
*/
@ -296,11 +299,11 @@ public abstract class GaleContext {
context.keyboardShowThreadGUI();
});
}
protected void keyboardShowThreadGUI() {
Log.info("keyboardShow: NOT implemented ...");
LOGGER.info("keyboardShow: NOT implemented ...");
}
/**
* Open an URL on an eternal brother.
* @param url URL to open.
@ -310,25 +313,25 @@ public abstract class GaleContext {
context.openURLThreadGUI(url);
});
}
protected void openURLThreadGUI(final String url) {
Log.info("openURL: NOT implemented ...");
LOGGER.info("openURL: NOT implemented ...");
}
/**
* The current context is set in background (framerate is slowing down (max fps)/5 # 4fps)
*/
public void operatingSystemBackground() {
// set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemBackground...");
LOGGER.info("operatingSystemBackground...");
// if (this.windowsCurrent != null) {
// this.windowsCurrent.onStateBackground();
// }
// release the current interface :
}
}
/**
* Call by the OS when a clipboard arrive to US (previously requested by a widget)
* @param clipboardID of the clipboard
@ -341,14 +344,14 @@ public abstract class GaleContext {
}
});
}
public boolean operatingSystemDraw(final boolean displayEveryTime) {
if (GaleContext.countMemeCheck++ >= 10 * 16) {
GaleContext.countMemeCheck = 0;
}
Log.verbose("Call draw");
LOGGER.trace("Call draw");
final long currentTime = System.nanoTime();
//Log.warning("Time = " << currentTime << " " << currentTime2);
//LOGGER.warn("Time = " << currentTime << " " << currentTime2);
// TODO Review this ...
// this is to prevent the multiple display at the a high frequency ...
if (currentTime - this.previousDisplayTime < 8) {
@ -374,18 +377,18 @@ public abstract class GaleContext {
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
/*
Lock the event processing
Wait end of current processing
Display ...
Release the event processing
*/
if (this.application != null) {
if (this.applicationState == ApplicationState.RUNNING) {
// Redraw all needed elements
//Log.debug("Regenerate Display");
//LOGGER.debug("Regenerate Display");
this.application.onRegenerateDisplay(this);
needRedraw = this.application.isDrawingNeeded();
} else {
@ -407,7 +410,7 @@ public abstract class GaleContext {
this.fpsSystemContext.tic();
}
if (needRedraw || displayEveryTime) {
//Log.debug(" ==> real Draw");
//LOGGER.debug(" ==> real Draw");
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
this.resourceManager.updateContext();
}
@ -430,7 +433,7 @@ public abstract class GaleContext {
OpenGL.setViewPort(new Vector2f(0, 0), this.application.getSize());
final Color bgColor = new Color(0.8f, 0.5f, 0.8f, 1.0f);
OpenGL.clearColor(bgColor);
//Log.info("==> appl clear ==> not created ...");
//LOGGER.info("==> appl clear ==> not created ...");
}
}
hasDisplayDone = true;
@ -441,7 +444,7 @@ public abstract class GaleContext {
this.fpsFlush.tic();
}
if (hasDisplayDone) {
//Log.info("lklklklklk " << displayEveryTime);
//LOGGER.info("lklklklklk " << displayEveryTime);
if (this.displayFps) {
this.fpsFlush.incrementCounter();
}
@ -475,21 +478,21 @@ public abstract class GaleContext {
OpenGL.threadHasNoMoreContext();
return hasDisplayDone;
}
/**
* The current context is set in foreground (framerate is maximum speed)
*/
public void operatingSystemForeground() {
// set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemForeground...");
LOGGER.info("operatingSystemForeground...");
// if (this.windowsCurrent != null) {
// this.windowsCurrent.onStateForeground();
// }
}
}
/**
* The OS inform that the Windows is now Hidden.
*/
@ -505,10 +508,10 @@ public abstract class GaleContext {
char,
state);
*/
Log.todo("HIDE ... ");
LOGGER.info("TODO: HIDE ... ");
});
}
/**
* The OS inform that the current windows has change his position.
* @param pos New position of the Windows.
@ -518,7 +521,7 @@ public abstract class GaleContext {
return;
}
postActionAsync(context -> {
Log.debug("Receive MSG : THREADMOVE : {} ==> {}", context.windowsPos, pos);
LOGGER.debug("Receive MSG : THREADMOVE : {} ==> {}", context.windowsPos, pos);
context.windowsPos = pos;
final GaleApplication appl = context.getApplication();
if (appl == null) {
@ -527,27 +530,27 @@ public abstract class GaleContext {
appl.onMovePosition(context.windowsPos);
});
}
/**
* The OS inform that the openGL ext has been destroy == > use to automaticly reload the texture and other thinks ...
*/
public void operatingSystemOpenGlContextDestroy() {
this.resourceManager.contextHasBeenDestroyed();
}
/**
* The OS inform that the current windows has change his size.
* @param size new size of the windows.
*/
public void operatingSystemResize(final Vector2f size) {
Log.warning("Resize request={} previous={}", size, this.windowsSize);
LOGGER.warn("Resize request={} previous={}", size, this.windowsSize);
if (this.windowsSize.equals(size)) {
return;
}
// TODO Better in the thread ... ==> but generate some init error ...
//gale::Dimension::setPixelWindowsSize(size);
postActionAsync(GaleContext.STATIC_ID_RESIZE, context -> {
Log.error("Receive MSG : THREAD_RESIZE : {} ==> {}", context.windowsSize, size);
LOGGER.error("Receive MSG : THREAD_RESIZE : {} ==> {}", context.windowsSize, size);
context.windowsSize = size;
//gale::Dimension::setPixelWindowsSize(context.windowsSize);
final GaleApplication tmpAppl = context.getApplication();
@ -558,14 +561,14 @@ public abstract class GaleContext {
context.forceRedrawAll();
});
}
/**
* The current context is resumed
*/
public void operatingSystemResume() {
// set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemResume...");
LOGGER.info("operatingSystemResume...");
this.previousDisplayTime = System.currentTimeMillis();
// TODO this.objectManager.timeCallResume(this.previousDisplayTime);
// if (this.windowsCurrent != null) {
@ -573,9 +576,14 @@ public abstract class GaleContext {
// }
}
}
public void operatingSystemSetInput(final KeySpecial special, final KeyType type, final KeyStatus status, final int pointerID, final Vector2f pos) {
Log.verbose("Position motion: " + pos);
public void operatingSystemSetInput(
final KeySpecial special,
final KeyType type,
final KeyStatus status,
final int pointerID,
final Vector2f pos) {
LOGGER.trace("Position motion: " + pos);
postActionAsync(context -> {
final GaleApplication appl = context.getApplication();
if (appl == null) {
@ -584,12 +592,21 @@ public abstract class GaleContext {
appl.onPointer(special, type, pointerID, pos, status);
});
}
public void operatingSystemsetKeyboard(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final boolean isARepeateKey) {
public void operatingSystemsetKeyboard(
final KeySpecial special,
final KeyKeyboard type,
final KeyStatus state,
final boolean isARepeateKey) {
operatingSystemsetKeyboard(special, type, state, isARepeateKey, (char) 0);
}
public void operatingSystemsetKeyboard(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final boolean isARepeateKey, final Character charValue) {
public void operatingSystemsetKeyboard(
final KeySpecial special,
final KeyKeyboard type,
final KeyStatus state,
final boolean isARepeateKey,
final Character charValue) {
KeyStatus tmpState = state;
if (isARepeateKey) {
if (tmpState == KeyStatus.down) {
@ -600,8 +617,12 @@ public abstract class GaleContext {
}
operatingSystemsetKeyboard2(special, type, state, charValue);
}
public void operatingSystemsetKeyboard2(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final Character charValue) {
public void operatingSystemsetKeyboard2(
final KeySpecial special,
final KeyKeyboard type,
final KeyStatus state,
final Character charValue) {
postActionAsync(context -> {
final GaleApplication appl = context.getApplication();
if (appl == null) {
@ -610,7 +631,7 @@ public abstract class GaleContext {
appl.onKeyboard(special, type, charValue, state);
});
}
/**
* The OS inform that the Windows is now visible.
*/
@ -626,17 +647,17 @@ public abstract class GaleContext {
char,
state);
*/
Log.todo("SHOW ... ");
LOGGER.info("TODO: SHOW ... ");
});
}
/**
* The OS Inform that the Window has been killed
*/
public void operatingSystemStop() {
// set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemStop...");
LOGGER.info("operatingSystemStop...");
if (this.application == null) {
stop();
return;
@ -644,22 +665,22 @@ public abstract class GaleContext {
this.application.onKillDemand(this);
}
}
/**
* The current context is suspended
*/
public void operatingSystemSuspend() {
// set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemSuspend...");
LOGGER.info("operatingSystemSuspend...");
this.previousDisplayTime = 0;
// if (this.windowsCurrent != null) {
// this.windowsCurrent.onStateSuspend();
// }
}
}
protected void postActionAsync(final ActionToDoInAsyncLoop data) {
if (this.requestSynchronousProcessing) {
this.msgSystemGui.addElement(data);
@ -668,7 +689,7 @@ public abstract class GaleContext {
}
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
}
protected void postActionAsync(final String uniqueID, final ActionToDoInAsyncLoop data) {
if (this.requestSynchronousProcessing) {
this.msgSystemGui.addElement(uniqueID, data);
@ -677,12 +698,12 @@ public abstract class GaleContext {
}
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
}
protected void postActionToGui(final ActionToDoInAsyncLoop data) {
this.msgSystemGui.addElement(data);
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
}
/**
* Processing all the event arrived ... (commonly called in draw function)
*/
@ -693,7 +714,7 @@ public abstract class GaleContext {
try {
int nbEvent = 0;
while (this.msgSystemAsync.getSize() > 0) {
Log.verbose(" [" + nbEvent + "] event ...");
LOGGER.trace(" [" + nbEvent + "] event ...");
nbEvent++;
final ActionToDoInAsyncLoop func = this.msgSystemAsync.getElementWait();
if (func == null) {
@ -702,12 +723,13 @@ public abstract class GaleContext {
func.run(this);
}
} catch (final Exception e) {
Log.critical("Catch exception in main event Loop ...", e);
LOGGER.error("Catch exception in main event Loop ...", e);
throw e;
} finally {
this.msgSystemAsyncLock.unlock();
}
}
/**
* Process event in the GUI thread ==> prevent dead lock on the global GUI interface
*/
@ -724,14 +746,15 @@ public abstract class GaleContext {
func.run(this);
}
} catch (final Exception e) {
Log.critical("Catch exception in main event Loop ...", e);
LOGGER.error("Catch exception in main event Loop ...", e);
throw e;
} finally {
this.msgSystemAsyncLock.unlock();
}
}
// gale::Context::~Context() {
// Log.info(" == > Gale system Un-Init (BEGIN)");
// LOGGER.info(" == > Gale system Un-Init (BEGIN)");
// this.periodicThread.threadStart();
// getResourcesManager().applicationExiting();
// // TODO Clean the message list ...
@ -751,7 +774,7 @@ public abstract class GaleContext {
// //this.objectManager.cleanInternalRemoved();
// this.resourceManager.cleanInternalRemoved();
//
// Log.info("List of all widget of this context must be equal at 0 ==> otherwise some remove is missing");
// LOGGER.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();
@ -759,7 +782,7 @@ public abstract class GaleContext {
// //this.objectManager.unInit();
// // release the current interface :
// unLockContext();
// Log.info(" == > Gale system Un-Init (END)");
// LOGGER.info(" == > Gale system Un-Init (END)");
// if (this.simulationActive) {
// // in simulation case:
// this.simulationFile.close();
@ -767,25 +790,25 @@ public abstract class GaleContext {
// }
public void requestUpdateSize() {
postActionAsync(this.STATIC_ID_REDRAW_ALL, context -> {
//Log.debug("Receive MSG : THREADRESIZE");
//LOGGER.debug("Receive MSG : THREADRESIZE");
context.forceRedrawAll();
});
}
/**
* reset event management for the IO like Input ou Mouse or keyborad
*/
public void resetIOEvent() {
// TODO this.input.newLayerSet();
}
/**
* Internal API to run the processing of the event loop ...
* @return The Exit value of the program
* @note INTERNAL API
*/
public abstract int run();
/**
* set the cursor display type.
* @param newCursor selected new cursor.
@ -795,11 +818,11 @@ public abstract class GaleContext {
context.setCursorThreadGUI(newCursor);
});
}
public void setCursorThreadGUI(final Cursor newCursor) {
Log.info("setCursor: NOT implemented ...");
LOGGER.info("setCursor: NOT implemented ...");
}
/**
* The application request a change of his current size force the fullscreen mode.
* @param status status of the fullscreen mode.
@ -810,11 +833,11 @@ public abstract class GaleContext {
context.setFullScreenThreadGUI(status);
});
}
protected void setFullScreenThreadGUI(final boolean status) {
Log.info("setFullScreen: NOT implemented ...");
LOGGER.info("setFullScreen: NOT implemented ...");
}
/**
* set the Icon of the program
* @param inputFile new filename icon of the current program.
@ -824,11 +847,11 @@ public abstract class GaleContext {
context.setIconThreadGUI(inputFile);
});
}
public void setIconThreadGUI(final Uri inputFile) {
Log.info("setIcon: NOT implemented ...");
LOGGER.info("setIcon: NOT implemented ...");
}
/**
* The Application request that the current windows will change his position.
* @param pos New position of the Windows requested.
@ -838,11 +861,11 @@ public abstract class GaleContext {
context.setPosThreadGUI(pos);
});
}
protected void setPosThreadGUI(final Vector2f pos) {
Log.info("setPos: NOT implemented ...");
LOGGER.info("setPos: NOT implemented ...");
}
/**
* The application request a change of his current size.
* @param size new Requested size of the windows.
@ -852,11 +875,11 @@ public abstract class GaleContext {
context.setSizeThreadGUI(size);
});
}
protected void setSizeThreadGUI(final Vector2f size) {
Log.info("setSize: NOT implemented ...");
LOGGER.info("setSize: NOT implemented ...");
}
/**
* set the new title of the windows
* @param title New desired title
@ -866,15 +889,15 @@ public abstract class GaleContext {
context.setTitleThreadGUI(title);
});
}
/**
* set the new title of the windows
* @param title New desired title
*/
protected void setTitleThreadGUI(final String title) {
Log.info("setTitle: NOT implemented ...");
LOGGER.info("setTitle: NOT implemented ...");
}
/**
* Enable or Disable the decoration on the Windows (availlable only on Desktop)
* @param status "true" to enable decoration / false otherwise
@ -884,11 +907,11 @@ public abstract class GaleContext {
context.setWindowsDecorationThreadGUI(status);
});
}
protected void setWindowsDecorationThreadGUI(final boolean status) {
Log.info("setWindowsDecoration: NOT implemented ...");
LOGGER.info("setWindowsDecoration: NOT implemented ...");
}
/**
* The Application request that the Windows will be visible.
*/
@ -897,11 +920,11 @@ public abstract class GaleContext {
context.showThreadGUI();
});
}
public void showThreadGUI() {
Log.info("show: NOT implemented ...");
LOGGER.info("show: NOT implemented ...");
}
/**
* StartProcessing (2nd thread).
* @note to call when all the Context is started
@ -918,12 +941,12 @@ public abstract class GaleContext {
}
}
}
/**
* The application request that the Window will be killed
*/
public void stop() {
Log.warning("stop: NOT implemented for this platform...");
LOGGER.warn("stop: NOT implemented for this platform...");
}
}

View File

@ -31,7 +31,6 @@ import org.atriasoft.gale.DisplayManagerDraw;
import org.atriasoft.gale.Fps;
import org.atriasoft.gale.GaleApplication;
import org.atriasoft.gale.context.GaleContext;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus;
@ -45,10 +44,12 @@ import org.lwjgl.opengl.awt.AWTGLCanvas;
//import org.lwjgl.opengl.GL;
//import org.lwjgl.system.MemoryStack;
import org.lwjgl.opengl.awt.GLData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.atriasoft.reggol.Logger;
public class ContextLWJGLAWT extends GaleContext implements MouseListener, MouseMotionListener, KeyListener, MouseWheelListener {
public class ContextLWJGLAWT extends GaleContext
implements MouseListener, MouseMotionListener, KeyListener, MouseWheelListener {
static final Logger LOGGER = LoggerFactory.getLogger(ContextLWJGLAWT.class);
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int MAX_MANAGE_INPUT = 15;
@ -57,36 +58,36 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
private static float delta;
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;
public static GaleContext create(final GaleApplication application, final String[] arg) {
// TODO Auto-generated method stub
return new ContextLWJGLAWT(application, arg);
}
private static long getCurrentTime() {
return System.currentTimeMillis();
}
public static float getFrameTimeSecconds() {
return ContextLWJGLAWT.delta;
}
private final boolean[] inputIsPressed = new boolean[ContextLWJGLAWT.MAX_MANAGE_INPUT];
private Vector2f decoratedWindowsSize = Vector2f.ZERO;
private Vector2f cursorPos = Vector2f.ZERO;
private final Vector2f cursorSize = Vector2f.ZERO;
private final Fps fps = new Fps("Main Loop", true);
private DisplayManagerDraw drawer = null;
// The window handle
private final long window = 0;
@ -94,14 +95,14 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
// Generic UI properties
private JFrame frame;
private GLData glData;
private AWTGLCanvas canvas;
private Robot robot = null;
private final List<Integer> pressedKey = new ArrayList<>();
private Boolean isInitialized = false;
public ContextLWJGLAWT(final GaleApplication application, final String[] args) {
super(application, args);
System.out.println("Hello JOGL !");
@ -109,7 +110,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
start2ndThreadProcessing();
this.isInitialized = true;
}
private int getUniqueIndex(final KeyEvent e) {
int internalKeyValue = e.getKeyCode();
if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) {
@ -123,7 +124,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
}
return internalKeyValue;
}
@Override
protected void grabPointerEventsThreadGUI(final boolean status, final Vector2f forcedPosition) {
if (status) {
@ -139,14 +140,15 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
showCursor();
}
}
private void hideCursor() {
final int[] pixels = new int[16 * 16];
final Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
final Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor");
final Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0),
"invisiblecursor");
this.frame.setCursor(transparentCursor);
}
private void initWindows() {
this.frame = new JFrame("Gale base");
this.frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
@ -158,19 +160,21 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
this.frame.add(this.canvas = new AWTGLCanvas(this.glData) {
@Override
public void initGL() {
System.out.println("OpenGL version: " + this.effective.majorVersion + "." + this.effective.minorVersion + " (Profile: " + this.effective.profile + ")");
System.out.println("OpenGL version: " + this.effective.majorVersion + "." + this.effective.minorVersion
+ " (Profile: " + this.effective.profile + ")");
GL.createCapabilities();
GL11.glClearColor(0.3f, 0.4f, 0.5f, 1);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
@Override
public void paintGL() {
final long startRender = System.currentTimeMillis();
//Log.warning("Draw ... ");
//LOGGER.warn("Draw ... ");
final int w = getWidth();
final int h = getHeight();
if (ContextLWJGLAWT.this.decoratedWindowsSize.x() != w || ContextLWJGLAWT.this.decoratedWindowsSize.y() != h) {
if (ContextLWJGLAWT.this.decoratedWindowsSize.x() != w
|| ContextLWJGLAWT.this.decoratedWindowsSize.y() != h) {
ContextLWJGLAWT.this.decoratedWindowsSize = new Vector2f(w, h);
final Rectangle bounds = ContextLWJGLAWT.this.canvas.getBounds();
final Vector2f tmpWindowsSize = new Vector2f(bounds.width, bounds.height);
@ -178,9 +182,11 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
}
operatingSystemDraw(true);
swapBuffers();
/*
if (Logger.isCriticalOccured()) {
ContextLWJGLAWT.this.frame.dispose();
}
*/
// Process event from the GUI (specific events...
processEventsGui();
/*
@ -204,21 +210,21 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
this.canvas.addKeyListener(this);
this.canvas.addMouseWheelListener(this);
this.frame.transferFocus();
ContextLWJGLAWT.lastFrameTime = ContextLWJGLAWT.getCurrentTime();
}
@Override
public boolean isGrabPointerEvents() {
return this.robot != null;
}
public void keyEvent(final KeyEvent e, final boolean pressed, final boolean thisIsAReapeateKey) {
//Log.info("event " + thisIsAReapeateKey + " " + e.getKeyCode() + " " + e);
//LOGGER.info("event " + thisIsAReapeateKey + " " + e.getKeyCode() + " " + e);
boolean find = true;
KeyKeyboard keyInput = KeyKeyboard.UNKNOWN;
//Log.error("keyboard input " + e.getWhen() + " " + e.getKeyCode() + " " + e.getKeyLocation());
//LOGGER.error("keyboard input " + e.getWhen() + " " + e.getKeyCode() + " " + e.getKeyLocation());
switch (e.getKeyCode()) {
//case 328: // keypad
case KeyEvent.VK_UP:
@ -362,38 +368,48 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
find = false;
if (this.guiKeyBoardMode.getNumLock()) {
if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.');
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.');
}
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.');
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.');
} else {
if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F);
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F);
}
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F);
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F);
}
break;
case KeyEvent.VK_TAB: // special case for TAB
find = false;
if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09);
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09);
}
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09);
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09);
break;
default:
find = false;
if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar());
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar());
}
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar());
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar());
}
if (find) {
if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey);
operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (!pressed ? KeyStatus.down : KeyStatus.up),
thisIsAReapeateKey);
}
operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey);
operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (pressed ? KeyStatus.down : KeyStatus.up),
thisIsAReapeateKey);
}
}
@Override
public void keyPressed(final KeyEvent e) {
final int internalKeyValue = getUniqueIndex(e);
@ -403,7 +419,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
}
keyEvent(e, true, index != -1);
}
@Override
public void keyReleased(final KeyEvent e) {
final int internalKeyValue = getUniqueIndex(e);
@ -413,60 +429,60 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
}
keyEvent(e, false, false);
}
@Override
public void keyTyped(final KeyEvent e) {
// not needed with my model ...
//Log.info(" typed " + e.getKeyChar() + " " + e);
//LOGGER.info(" typed " + e.getKeyChar() + " " + e);
}
@Override
public void mouseClicked(final MouseEvent e) {
// System.out.println(e.getX());
// System.out.println(e.getY());
Log.info("Mouse clicked:" + e.getX() + " " + e.getY());
LOGGER.info("Mouse clicked:" + e.getX() + " " + e.getY());
}
@Override
public void mouseDragged(final MouseEvent e) {
//Log.error("mouse drag ... " + e);
//LOGGER.error("mouse drag ... " + e);
mouseMoved(e);
}
@Override
public void mouseEntered(final MouseEvent e) {
// TODO Auto-generated method stub
//Log.info("Mouse entered:" + e.getX() + " " + e.getY());
//LOGGER.info("Mouse entered:" + e.getX() + " " + e.getY());
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.enter, 0, this.cursorPos);
}
@Override
public void mouseExited(final MouseEvent e) {
// TODO Auto-generated method stub
//Log.info("Mouse exited:" + e.getX() + " " + e.getY());
//LOGGER.info("Mouse exited:" + e.getX() + " " + e.getY());
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.leave, 0, this.cursorPos);
//this.frame.mouseMove(e, 200, 200);
}
@Override
public void mouseMoved(final MouseEvent e) {
Log.verbose("Mouse moved:" + e.getX() + " " + e.getY() + " " + e);
LOGGER.trace("Mouse moved:" + e.getX() + " " + e.getY() + " " + e);
if (this.robot != null) {
final Rectangle bounds = this.frame.getBounds();
//Log.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize);
//LOGGER.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize);
final float refPosX = bounds.x + bounds.width / 2.0f;
final float refPosY = bounds.y + bounds.height / 2.0f;
if (e.getXOnScreen() == (int) refPosX && e.getYOnScreen() == (int) refPosY) {
this.cursorPos = Vector2f.ZERO;
return;
}
//Log.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize);
//LOGGER.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize);
this.cursorPos = new Vector2f(-(e.getXOnScreen() - refPosX), (e.getYOnScreen() - refPosY));
//this.cursorPos = new Vector2f(-(e.getXOnScreen() - refPosX), refPosY);
this.robot.mouseMove((int) refPosX, (int) refPosY);
Log.info("delta moved:" + this.cursorPos);
LOGGER.info("delta moved:" + this.cursorPos);
} else {
// TODO use real size ... !!!!
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() + (this.cursorSize.y() - e.getY()));
@ -475,7 +491,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
boolean findOne = false;
for (int iii = 0; iii < ContextLWJGLAWT.MAX_MANAGE_INPUT; iii++) {
if (this.inputIsPressed[iii]) {
//Log.debug("X11 event: bt=" << iii << " " << event.type << " = \"MotionNotify\" (" << m_cursorEventX << "," << m_cursorEventY << ")");
//LOGGER.debug("X11 event: bt=" << iii << " " << event.type << " = \"MotionNotify\" (" << m_cursorEventX << "," << m_cursorEventY << ")");
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.move, iii, this.cursorPos);
findOne = true;
}
@ -485,10 +501,10 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.move, 0, this.cursorPos);
}
}
@Override
public void mousePressed(final MouseEvent e) {
Log.info("Mouse pressed:" + e.getX() + " " + e.getY());
LOGGER.info("Mouse pressed:" + e.getX() + " " + e.getY());
final int button = e.getButton();
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
if (button < ContextLWJGLAWT.MAX_MANAGE_INPUT) {
@ -496,11 +512,11 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
}
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.down, button, this.cursorPos);
}
@Override
public void mouseReleased(final MouseEvent e) {
//Log.info("Mouse release:" + e.getX() + " " + e.getY());
// Log.info("mouse value: GLFW_RELEASE" + action + " bt=" + button);
//LOGGER.info("Mouse release:" + e.getX() + " " + e.getY());
// LOGGER.info("mouse value: GLFW_RELEASE" + action + " bt=" + button);
final int button = e.getButton();
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
if (button < ContextLWJGLAWT.MAX_MANAGE_INPUT) {
@ -508,10 +524,10 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
}
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, button, this.cursorPos);
}
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
//Log.info("wheel_event : " + e);
//LOGGER.info("wheel_event : " + e);
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
if (e.getWheelRotation() < 0) {
this.inputIsPressed[5] = true;
@ -525,7 +541,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, 4, this.cursorPos);
}
}
@Override
public int run() {
final Runnable renderLoop = new Runnable() {
@ -545,7 +561,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
}
};
SwingUtilities.invokeLater(renderLoop);
// while (canvas != null && canvas.isValid()) {
// canvas.render();
// try {
@ -555,7 +571,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
// e.printStackTrace();
// }
// }
// Run the rendering loop until the user has attempted to close
// the window or has pressed the ESCAPE key.
// while ( !glfwWindowShouldClose(window) ) {
@ -597,11 +613,11 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
//System.exit(0);
return 0;
}
public void setDrawer(final DisplayManagerDraw drawer) {
this.drawer = drawer;
}
@Override
public void setFullScreenThreadGUI(final boolean status) {
super.setFullScreen(status);
@ -613,24 +629,24 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
this.frame.setUndecorated(false);
}
}
@Override
public void setIconThreadGUI(final Uri inputFile) {
}
/****************************************************************************************/
@Override
public void setTitleThreadGUI(final String title) {
this.frame.setTitle(title);
}
private void showCursor() {
this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void unInit() {
}
}

View File

@ -4,40 +4,42 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageSystem {
static final Logger LOGGER = LoggerFactory.getLogger(MessageSystem.class);
private final Vector<ActionToDoInAsyncLoop> data = new Vector<>();
private final Map<String, ActionToDoInAsyncLoop> dataSingle = new HashMap<>();
public synchronized void addElement(final ActionToDoInAsyncLoop data2) {
this.data.addElement(data2);
notifyAll();
}
public synchronized void addElement(final String uniqueID, final ActionToDoInAsyncLoop data2) {
this.dataSingle.put(uniqueID, data2);
notifyAll();
}
protected synchronized ActionToDoInAsyncLoop getElementSingle() {
//Log.warning("+++++++++++++++++++++++++++++++++ getElement()");
//LOGGER.warn("+++++++++++++++++++++++++++++++++ getElement()");
final Map.Entry<String, ActionToDoInAsyncLoop> entry = this.dataSingle.entrySet().iterator().next();
final String key = entry.getKey();
final ActionToDoInAsyncLoop message = entry.getValue();
this.dataSingle.remove(key);
//Log.warning("+++++++++++++++++++++++++++++++++ getElement() ===> done " + message);
//LOGGER.warn("+++++++++++++++++++++++++++++++++ getElement() ===> done " + message);
return message;
}
protected synchronized ActionToDoInAsyncLoop getElementVector() {
//Log.warning("+++++++++++++++++++++++++++++++++ getElement()");
//LOGGER.warn("+++++++++++++++++++++++++++++++++ getElement()");
final ActionToDoInAsyncLoop message = this.data.firstElement();
this.data.removeElement(message);
//Log.warning("+++++++++++++++++++++++++++++++++ getElement() ===> done " + message);
//LOGGER.warn("+++++++++++++++++++++++++++++++++ getElement() ===> done " + message);
return message;
}
public synchronized ActionToDoInAsyncLoop getElementWait() {
if (this.data.isEmpty() && this.dataSingle.isEmpty()) {
try {
@ -56,11 +58,11 @@ public class MessageSystem {
}
return null;
}
public synchronized int getSize() {
Log.verbose("------------------------------------------------------------");
Log.verbose("-- nb message: {} + {}", this.data.size(), this.dataSingle.size());
Log.verbose("------------------------------------------------------------");
LOGGER.trace("------------------------------------------------------------");
LOGGER.trace("-- nb message: {} + {}", this.data.size(), this.dataSingle.size());
LOGGER.trace("------------------------------------------------------------");
return this.data.size() + this.dataSingle.size();
}
}

View File

@ -4,29 +4,31 @@ import java.time.Clock;
import org.atriasoft.etk.ThreadAbstract;
import org.atriasoft.gale.GaleApplication;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PeriodicThread extends ThreadAbstract {
static final Logger LOGGER = LoggerFactory.getLogger(PeriodicThread.class);
private final GaleContext context;
public PeriodicThread(final GaleContext context) {
super("GaleAsync");
this.context = context;
}
@Override
protected void birth() {
// TODO Auto-generated method stub
}
@Override
protected void death() {
// TODO Auto-generated method stub
}
@Override
protected void runPeriodic() {
Log.verbose("----------------------------- [START] -----------------------------------");
LOGGER.trace("----------------------------- [START] -----------------------------------");
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
@ -37,15 +39,15 @@ public class PeriodicThread extends ThreadAbstract {
// Keep global clock to process events
final Clock clock = Clock.systemUTC();
final long time = System.nanoTime();
///synchronized (this.context) {
this.context.processEventsAsync(clock, time);
// call all the application for periodic request (the application manage multiple instance )...
final GaleApplication appl = this.context.getApplication();
//Log.verbose("Call application : " + appl);
//LOGGER.trace("Call application : " + appl);
if (appl != null) {
appl.onPeriod(clock, time);
}
Log.verbose("----------------------------- [ END ] -----------------------------------");
LOGGER.trace("----------------------------- [ END ] -----------------------------------");
}
}

View File

@ -1,76 +0,0 @@
package org.atriasoft.gale.internal;
import org.atriasoft.reggol.LogLevel;
import org.atriasoft.reggol.Logger;
public class Log {
private static final boolean FORCE_ALL = false;
private static final String LIB_NAME = "gale";
private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME);
private static final boolean PRINT_CRITICAL = Logger.getNeedPrint(LIB_NAME, LogLevel.CRITICAL);
private static final boolean PRINT_ERROR = Logger.getNeedPrint(LIB_NAME, LogLevel.ERROR);
private static final boolean PRINT_WARNING = Logger.getNeedPrint(LIB_NAME, LogLevel.WARNING);
private static final boolean PRINT_INFO = Logger.getNeedPrint(LIB_NAME, LogLevel.INFO);
private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG);
private static final boolean PRINT_VERBOSE = Logger.getNeedPrint(LIB_NAME, LogLevel.VERBOSE);
private static final boolean PRINT_TODO = Logger.getNeedPrint(LIB_NAME, LogLevel.TODO);
private static final boolean PRINT_PRINT = Logger.getNeedPrint(LIB_NAME, LogLevel.PRINT);
public static void critical(final Exception e, final String data) {
e.printStackTrace();
if (PRINT_CRITICAL || FORCE_ALL) {
Logger.critical(LIB_NAME_DRAW, data + " : " + e.getMessage());
}
}
public static void critical(final String data, final Object... objects) {
if (PRINT_CRITICAL || FORCE_ALL) {
Logger.critical(LIB_NAME_DRAW, data, objects);
}
}
public static void debug(final String data, final Object... objects) {
if (PRINT_DEBUG || FORCE_ALL) {
Logger.debug(LIB_NAME_DRAW, data, objects);
}
}
public static void error(final String data, final Object... objects) {
if (PRINT_ERROR || FORCE_ALL) {
Logger.error(LIB_NAME_DRAW, data, objects);
}
}
public static void info(final String data, final Object... objects) {
if (PRINT_INFO || FORCE_ALL) {
Logger.info(LIB_NAME_DRAW, data, objects);
}
}
public static void print(final String data, final Object... objects) {
if (PRINT_PRINT || FORCE_ALL) {
Logger.print(LIB_NAME_DRAW, data, objects);
}
}
public static void todo(final String data, final Object... objects) {
if (PRINT_TODO || FORCE_ALL) {
Logger.todo(LIB_NAME_DRAW, data, objects);
}
}
public static void verbose(final String data, final Object... objects) {
if (PRINT_VERBOSE || FORCE_ALL) {
Logger.verbose(LIB_NAME_DRAW, data, objects);
}
}
public static void warning(final String data, final Object... objects) {
if (PRINT_WARNING || FORCE_ALL) {
Logger.warning(LIB_NAME_DRAW, data, objects);
}
}
private Log() {}
}

View File

@ -2,25 +2,27 @@ package org.atriasoft.gale.resource;
import org.atriasoft.etk.Uri;
import org.atriasoft.gale.context.GaleContext;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Resource {
static final Logger LOGGER = LoggerFactory.getLogger(Resource.class);
protected static final String NO_NAME_RESOURCE = "---";
protected static final int MAXRESOURCELEVEL = 5;
private static int idGenerated = 10;
/**
* Get the current resource Manager
*/
protected static ResourceManager getManager() {
return GaleContext.getContext().getResourcesManager();
}
protected long uid = -1; //!< unique ID definition
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 = NO_NAME_RESOURCE; //!< name of the resource ...
/**
* generic protected contructor (use factory to create this class)
*/
@ -28,7 +30,7 @@ public abstract class Resource {
this.uid = idGenerated++;
getManager().localAdd(this);
}
protected Resource(final String name) {
if (name == null) {
this.name = "---";
@ -37,7 +39,7 @@ public abstract class Resource {
}
getManager().localAdd(this);
}
protected Resource(final Uri uri) {
if (uri == null) {
this.name = "---";
@ -46,17 +48,17 @@ public abstract class Resource {
}
getManager().localAdd(this);
}
public abstract void cleanUp();
public int getCount() {
return this.count;
}
public long getId() {
return this.uid;
}
/**
* get the resource name
* @return The requested name
@ -64,7 +66,7 @@ public abstract class Resource {
public String getName() {
return this.name;
}
/**
* Get the current resource level;
* @return value in [0..5]
@ -72,40 +74,40 @@ public abstract class Resource {
public int getResourceLevel() {
return this.resourceLevel;
}
public void keep() {
this.count++;
}
public void release() {
this.count--;
if (this.count == 0) {
}
}
/**
* User request the reload of all resources (usefull when the file depend on DATA:GUI:xxx ...
*/
public void reload() {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
LOGGER.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
}
/**
* The current OpenGl context is removing ==> remove yout own system data
*/
public void removeContext() {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
LOGGER.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
}
/**
* The notification of the Context removing is too late, we have no more acces on the OpenGl context (thank you Android).
* Just update your internal state
*/
public void removeContextToLate() {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
LOGGER.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
}
/**
* get the resource name
* @param name The name to set.
@ -113,7 +115,7 @@ public abstract class Resource {
public void setName(final String name) {
this.name = name;
}
/**
* Call when need to send data on the harware (openGL)
* @note This is done asynchronously with the create of the Resource.
@ -121,7 +123,7 @@ public abstract class Resource {
* @return false The context is not updated
*/
public boolean updateContext() {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
LOGGER.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
return true;
}
}

View File

@ -9,27 +9,31 @@ import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Matrix4f;
import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceColored3DObject extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceColored3DObject.class);
public static ResourceColored3DObject create() {
final ResourceColored3DObject resource = new ResourceColored3DObject();
getManager().localAdd(resource);
return resource;
}
private final ResourceProgram program;
private int oGLPosition;
private int oGLColor;
private int oGLMatrixTransformation;
private int oGLMatrixProjection;
private int oGLMatrixView;
protected ResourceColored3DObject() {
// get the shader resource :
this.oGLPosition = 0;
this.program = ResourceProgram.create(new Uri("DATA", "simple3D.vert", "gale"), new Uri("DATA", "simple3D.frag", "gale"));
this.program = ResourceProgram.create(new Uri("DATA", "simple3D.vert", "gale"),
new Uri("DATA", "simple3D.frag", "gale"));
if (this.program != null) {
this.oGLMatrixTransformation = this.program.getUniform("in_matrixTransformation");
this.oGLMatrixProjection = this.program.getUniform("in_matrixProjection");
@ -38,13 +42,13 @@ public class ResourceColored3DObject extends Resource {
this.oGLColor = this.program.getUniform("in_colors");
}
}
@Override
public void cleanUp() {
// TODO Auto-generated method stub
}
private float[] convertInFloat(final List<Vector3f> data) {
final float[] out = new float[data.size() * 3];
for (int iii = 0; iii < data.size(); iii++) {
@ -54,13 +58,17 @@ public class ResourceColored3DObject extends Resource {
}
return out;
}
public void draw(final List<Vector3f> vertices, final Color color, final boolean updateDepthBuffer, final boolean depthtest) {
public void draw(
final List<Vector3f> vertices,
final Color color,
final boolean updateDepthBuffer,
final boolean depthtest) {
if (vertices.size() <= 0) {
return;
}
if (this.program == null) {
Log.error("No shader ...");
LOGGER.error("No shader ...");
return;
}
if (depthtest) {
@ -69,7 +77,7 @@ public class ResourceColored3DObject extends Resource {
OpenGL.setDeathMask(false);
}
}
//Log.debug(" display " << this.coord.size() << " elements" );
//LOGGER.debug(" display " << this.coord.size() << " elements" );
this.program.use();
final Matrix4f projectionMatrix = OpenGL.getMatrix();
final Matrix4f viewMatrix = OpenGL.getCameraMatrix();
@ -101,13 +109,18 @@ public class ResourceColored3DObject extends Resource {
OpenGL.disable(OpenGL.Flag.flag_depthTest);
}
}
public void draw(final List<Vector3f> vertices, final Color color, final Matrix4f transformationMatrix, final boolean updateDepthBuffer, final boolean depthtest) {
public void draw(
final List<Vector3f> vertices,
final Color color,
final Matrix4f transformationMatrix,
final boolean updateDepthBuffer,
final boolean depthtest) {
if (vertices.size() <= 0) {
return;
}
if (this.program == null) {
Log.error("No shader ...");
LOGGER.error("No shader ...");
return;
}
if (depthtest) {
@ -116,7 +129,7 @@ public class ResourceColored3DObject extends Resource {
OpenGL.setDeathMask(false);
}
}
//Log.debug(" display " << this.coord.size() << " elements" );
//LOGGER.debug(" display " << this.coord.size() << " elements" );
this.program.use();
// set Matrix: translation/positionMatrix
final Matrix4f projectionMatrix = OpenGL.getMatrix();
@ -128,7 +141,7 @@ public class ResourceColored3DObject extends Resource {
final FloatBuffer buffer = storeDataInFloatBuffer(convertInFloat(vertices));
this.program.sendAttribute(this.oGLPosition, 3, buffer, 3);
// color :
//Log.info("color= " + color + " " + this.oGLPosition);
//LOGGER.info("color= " + color + " " + this.oGLPosition);
this.program.uniformColor(this.oGLColor, color);
if (color.a() < 1.0f) {
OpenGL.enable(OpenGL.Flag.flag_blend);
@ -146,29 +159,35 @@ public class ResourceColored3DObject extends Resource {
OpenGL.disable(OpenGL.Flag.flag_depthTest);
}
}
public void drawCapsule(final float radius, final float size, int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) {
public void drawCapsule(
final float radius,
final float size,
int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>();
lats = lats / 2 * 2;
// center to border (TOP)
float offset = size * 0.5f;
for (int iii = lats / 2 + 1; iii <= lats; ++iii) {
final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats);
final float z0 = radius * (float) Math.sin(lat0);
final float zr0 = radius * (float) Math.cos(lat0);
final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats);
final float z1 = radius * (float) Math.sin(lat1);
final float zr1 = radius * (float) Math.cos(lat1);
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
float x = (float) Math.cos(lng);
float y = (float) Math.sin(lng);
final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1 + offset);
final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0 + offset);
lng = 2 * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng);
y = (float) Math.sin(lng);
@ -177,7 +196,7 @@ public class ResourceColored3DObject extends Resource {
tmpVertices.add(v1);
tmpVertices.add(v2);
tmpVertices.add(v3);
tmpVertices.add(v1);
tmpVertices.add(v3);
tmpVertices.add(v4);
@ -186,24 +205,24 @@ public class ResourceColored3DObject extends Resource {
// Cylinder
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final float z = size * 0.5f;
float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, z);
final Vector3f v2b = new Vector3f(x, y, -z);
lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius;
final Vector3f v3 = new Vector3f(x, y, z);
final Vector3f v3b = new Vector3f(x, y, -z);
tmpVertices.add(v2);
tmpVertices.add(v3);
tmpVertices.add(v3b);
tmpVertices.add(v2);
tmpVertices.add(v3b);
tmpVertices.add(v2b);
@ -214,18 +233,18 @@ public class ResourceColored3DObject extends Resource {
final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats);
final float z0 = radius * (float) Math.sin(lat0);
final float zr0 = radius * (float) Math.cos(lat0);
final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats);
final float z1 = radius * (float) Math.sin(lat1);
final float zr1 = radius * (float) Math.cos(lat1);
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
float x = (float) Math.cos(lng);
float y = (float) Math.sin(lng);
final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1 + offset);
final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0 + offset);
lng = 2 * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng);
y = (float) Math.sin(lng);
@ -234,7 +253,7 @@ public class ResourceColored3DObject extends Resource {
tmpVertices.add(v1);
tmpVertices.add(v2);
tmpVertices.add(v3);
tmpVertices.add(v1);
tmpVertices.add(v3);
tmpVertices.add(v4);
@ -242,18 +261,24 @@ public class ResourceColored3DObject extends Resource {
}
draw(tmpVertices, tmpColor, transformationMatrix, true, true);
}
public void drawCone(final float radius, final float size, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) {
public void drawCone(
final float radius,
final float size,
final int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>();
// center to border (TOP)
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final Vector3f v1 = new Vector3f(0.0f, 0.0f, -size / 2);
float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, size / 2);
lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius;
@ -265,13 +290,13 @@ public class ResourceColored3DObject extends Resource {
// center to border (BUTTOM)
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final Vector3f v1 = new Vector3f(0.0f, 0.0f, size / 2);
float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, size / 2);
lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius;
@ -282,67 +307,86 @@ public class ResourceColored3DObject extends Resource {
}
draw(tmpVertices, tmpColor, transformationMatrix, true, true);
}
public void drawCubeLine(final Vector3f min, final Vector3f max, final Color color, final Matrix4f transformationMatrix, final boolean updateDepthBuffer, final boolean depthtest) {
public void drawCubeLine(
final Vector3f min,
final Vector3f max,
final Color color,
final Matrix4f transformationMatrix,
final boolean updateDepthBuffer,
final boolean depthtest) {
final List<Vector3f> vertices = new ArrayList<>();
vertices.add(new Vector3f(min.x(), min.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), max.z()));
vertices.add(new Vector3f(max.x(), min.y(), max.z()));
vertices.add(new Vector3f(min.x(), min.y(), max.z()));
vertices.add(new Vector3f(min.x(), min.y(), max.z()));
vertices.add(new Vector3f(min.x(), min.y(), min.z()));
vertices.add(new Vector3f(min.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), max.y(), max.z()));
vertices.add(new Vector3f(max.x(), max.y(), max.z()));
vertices.add(new Vector3f(min.x(), max.y(), max.z()));
vertices.add(new Vector3f(min.x(), max.y(), max.z()));
vertices.add(new Vector3f(min.x(), max.y(), min.z()));
vertices.add(new Vector3f(min.x(), min.y(), min.z()));
vertices.add(new Vector3f(min.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), min.z()));
vertices.add(new Vector3f(max.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), max.z()));
vertices.add(new Vector3f(max.x(), max.y(), max.z()));
vertices.add(new Vector3f(min.x(), min.y(), max.z()));
vertices.add(new Vector3f(min.x(), max.y(), max.z()));
drawLine(vertices, color, transformationMatrix, updateDepthBuffer, depthtest);
}
public void drawCylinder(final float radius, final float size, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) {
public void drawCylinder(
final float radius,
final float size,
final int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor) {
drawCylinder(radius, size, lats, longs, transformationMatrix, tmpColor, true, true);
}
public void drawCylinder(final float radius, final float size, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor, final boolean updateDepthBuffer,
public void drawCylinder(
final float radius,
final float size,
final int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor,
final boolean updateDepthBuffer,
final boolean depthtest) {
final List<Vector3f> tmpVertices = new ArrayList<>();
// center to border (TOP)
// center to border (TOP)
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final float z = size * 0.5f;
final Vector3f v1 = new Vector3f(0.0f, 0.0f, z);
float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, z);
lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius;
@ -354,24 +398,24 @@ public class ResourceColored3DObject extends Resource {
// Cylinder
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final float z = size * 0.5f;
float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, z);
final Vector3f v2b = new Vector3f(x, y, -z);
lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius;
final Vector3f v3 = new Vector3f(x, y, z);
final Vector3f v3b = new Vector3f(x, y, -z);
tmpVertices.add(v2);
tmpVertices.add(v3);
tmpVertices.add(v3b);
tmpVertices.add(v2);
tmpVertices.add(v3b);
tmpVertices.add(v2b);
@ -379,14 +423,14 @@ public class ResourceColored3DObject extends Resource {
// center to border (BUTTOM)
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final float z = size * -0.5f;
final Vector3f v1 = new Vector3f(0.0f, 0.0f, z);
float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, z);
lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius;
@ -397,13 +441,18 @@ public class ResourceColored3DObject extends Resource {
}
draw(tmpVertices, tmpColor, transformationMatrix, updateDepthBuffer, depthtest);
}
public void drawLine(final List<Vector3f> vertices, final Color color, final Matrix4f transformationMatrix, final boolean updateDepthBuffer, final boolean depthtest) {
public void drawLine(
final List<Vector3f> vertices,
final Color color,
final Matrix4f transformationMatrix,
final boolean updateDepthBuffer,
final boolean depthtest) {
if (vertices.size() <= 0) {
return;
}
if (this.program == null) {
Log.error("No shader ...");
LOGGER.error("No shader ...");
return;
}
if (depthtest) {
@ -412,7 +461,7 @@ public class ResourceColored3DObject extends Resource {
OpenGL.setDeathMask(false);
}
}
//Log.debug(" display " << this.coord.size() << " elements" );
//LOGGER.debug(" display " << this.coord.size() << " elements" );
this.program.use();
// set Matrix: translation/positionMatrix
final Matrix4f projectionMatrix = OpenGL.getMatrix();
@ -441,35 +490,40 @@ public class ResourceColored3DObject extends Resource {
OpenGL.disable(OpenGL.Flag.flag_depthTest);
}
}
public void drawSphere(final float radius, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) {
public void drawSphere(
final float radius,
final int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>();
for (int iii = 0; iii <= lats; ++iii) {
final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats);
final float z0 = radius * (float) Math.sin(lat0);
final float zr0 = radius * (float) Math.cos(lat0);
final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats);
final float z1 = radius * (float) Math.sin(lat1);
final float zr1 = radius * (float) Math.cos(lat1);
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
float x = (float) Math.cos(lng);
float y = (float) Math.sin(lng);
final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1);
final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0);
lng = 2 * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng);
y = (float) Math.sin(lng);
final Vector3f v2 = new Vector3f(x * zr1, y * zr1, z1);
final Vector3f v3 = new Vector3f(x * zr0, y * zr0, z0);
tmpVertices.add(v1);
tmpVertices.add(v2);
tmpVertices.add(v3);
tmpVertices.add(v1);
tmpVertices.add(v3);
tmpVertices.add(v4);
@ -477,12 +531,15 @@ public class ResourceColored3DObject extends Resource {
}
draw(tmpVertices, tmpColor, transformationMatrix, true, true);
}
public void drawSquare(final Vector3f size, final Matrix4f transformationMatrix, final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>();
final int[] indices = { 0, 1, 2, 3, 2, 1, 4, 0, 6, 6, 0, 2, 5, 1, 4, 4, 1, 0, 7, 3, 1, 7, 1, 5, 5, 4, 7, 7, 4, 6, 7, 2, 3, 7, 6, 2 };
final Vector3f[] vertices = { new Vector3f(size.x(), size.y(), size.z()), new Vector3f(-size.x(), size.y(), size.z()), new Vector3f(size.x(), -size.y(), size.z()),
new Vector3f(-size.x(), -size.y(), size.z()), new Vector3f(size.x(), size.y(), -size.z()), new Vector3f(-size.x(), size.y(), -size.z()), new Vector3f(size.x(), -size.y(), -size.z()),
final int[] indices = { 0, 1, 2, 3, 2, 1, 4, 0, 6, 6, 0, 2, 5, 1, 4, 4, 1, 0, 7, 3, 1, 7, 1, 5, 5, 4, 7, 7, 4,
6, 7, 2, 3, 7, 6, 2 };
final Vector3f[] vertices = { new Vector3f(size.x(), size.y(), size.z()),
new Vector3f(-size.x(), size.y(), size.z()), new Vector3f(size.x(), -size.y(), size.z()),
new Vector3f(-size.x(), -size.y(), size.z()), new Vector3f(size.x(), size.y(), -size.z()),
new Vector3f(-size.x(), size.y(), -size.z()), new Vector3f(size.x(), -size.y(), -size.z()),
new Vector3f(-size.x(), -size.y(), -size.z()) };
tmpVertices.clear();
for (int iii = 0; iii < 36; iii += 3) {
@ -495,33 +552,47 @@ public class ResourceColored3DObject extends Resource {
}
draw(tmpVertices, tmpColor, transformationMatrix, true, true);
}
public void drawTriangle(final Vector3f p1, final Vector3f p2, final Vector3f p3, final Matrix4f transformationMatrix, final Color tmpColor) {
public void drawTriangle(
final Vector3f p1,
final Vector3f p2,
final Vector3f p3,
final Matrix4f transformationMatrix,
final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>();
tmpVertices.add(p1);
tmpVertices.add(p2);
tmpVertices.add(p3);
//Log.info("display " << tmpVertices.size() << " vertices form " << indice.size());
//LOGGER.info("display " << tmpVertices.size() << " vertices form " << indice.size());
draw(tmpVertices, tmpColor, transformationMatrix, true, true);
}
public void drawTriangles(final List<Vector3f> vertex, final List<Integer> indice, final Matrix4f transformationMatrix, final Color tmpColor) {
public void drawTriangles(
final List<Vector3f> vertex,
final List<Integer> indice,
final Matrix4f transformationMatrix,
final Color tmpColor) {
drawTriangles(vertex, indice, transformationMatrix, tmpColor, new Vector3f(0.0f, 0.0f, 0.1f));
}
public void drawTriangles(final List<Vector3f> vertex, final List<Integer> indice, final Matrix4f transformationMatrix, final Color tmpColor, final Vector3f offset) {
public void drawTriangles(
final List<Vector3f> vertex,
final List<Integer> indice,
final Matrix4f transformationMatrix,
final Color tmpColor,
final Vector3f offset) {
final List<Vector3f> tmpVertices = new ArrayList<>();
for (int iii = 0; iii < indice.size() / 3; ++iii) {
tmpVertices.add(vertex.get(indice.get(iii * 3 + 0)).add(offset));
tmpVertices.add(vertex.get(indice.get(iii * 3 + 1)).add(offset));
tmpVertices.add(vertex.get(indice.get(iii * 3 + 2)).add(offset));
//Log.info(" indices " << indice[iii*3 + 0] << " " << indice[iii*3 + 1] << " " << indice[iii*3 + 2]);
//Log.info(" triangle " << vertex[indice[iii*3 + 0]] << " " << vertex[indice[iii*3 + 1]] << " " << vertex[indice[iii*3 + 2]]);
//LOGGER.info(" indices " << indice[iii*3 + 0] << " " << indice[iii*3 + 1] << " " << indice[iii*3 + 2]);
//LOGGER.info(" triangle " << vertex[indice[iii*3 + 0]] << " " << vertex[indice[iii*3 + 1]] << " " << vertex[indice[iii*3 + 2]]);
}
//Log.info("display " << tmpVertices.size() << " vertices form " << indice.size());
//LOGGER.info("display " << tmpVertices.size() << " vertices form " << indice.size());
draw(tmpVertices, tmpColor, transformationMatrix, true, true);
}
private FloatBuffer storeDataInFloatBuffer(final float[] data) {
final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data);

View File

@ -4,22 +4,24 @@ import java.util.ArrayList;
import java.util.List;
import org.atriasoft.etk.Uri;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceManager {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceManager.class);
private static final int MAX_RESOURCE_LEVEL = 9;
private final List<Resource> resourceList = new ArrayList<>();
private List<Resource> resourceListToUpdate = new ArrayList<>();
private boolean contextHasBeenRemoved = true;
private boolean exiting = false;
/**
* initialize the internal variable
*/
public ResourceManager() {
}
/**
* special end of application
*/
@ -27,9 +29,9 @@ public class ResourceManager {
contextHasBeenDestroyed();
this.exiting = true;
}
public synchronized void cleanInternalRemoved() {
//Log.info("remove object in Manager");
//LOGGER.info("remove object in Manager");
updateContext();
// TODO ...
// for (auto it(this.resourceList.begin()); it!=this.resourceList.end(); ++it) {
@ -39,7 +41,7 @@ public class ResourceManager {
// }
// }
}
/**
* This is to inform the resources manager that we have no more openGl context ...
*/
@ -54,33 +56,34 @@ public class ResourceManager {
// no context preent ...
this.contextHasBeenRemoved = true;
}
/**
* display in the log all the resources loaded ...
*/
public synchronized void display() {
Log.info("Resources loaded : ");
LOGGER.info("Resources loaded : ");
// remove all resources ...
synchronized (this.resourceList) {
for (final Resource it : this.resourceList) {
Log.info(" [" + it.getId() + "]" + it.getClass().getCanonicalName() + "='" + it.getName() + "' " + it.getCount() + " elements");
LOGGER.info(" [" + it.getId() + "]" + it.getClass().getCanonicalName() + "='" + it.getName() + "' "
+ it.getCount() + " elements");
}
}
Log.info("Resources ---");
LOGGER.info("Resources ---");
}
public synchronized void localAdd(final Resource object) {
// add at the end if no slot is free
synchronized (this.resourceList) {
this.resourceList.add(object);
}
}
// internal API to extent eResources in extern Soft
public synchronized Resource localKeep(final String filename) {
synchronized (this.resourceList) {
Log.verbose("KEEP (DEFAULT) : file : '" + filename + "' in " + this.resourceList.size() + " resources");
LOGGER.trace("KEEP (DEFAULT) : file : '" + filename + "' in " + this.resourceList.size() + " resources");
for (final Resource it : this.resourceList) {
if (it == null) {
continue;
@ -88,7 +91,7 @@ public class ResourceManager {
if (it.getName() == null) {
continue;
}
//Log.verbose("compare : " + filename + " ==???== " + it.getName());
//LOGGER.trace("compare : " + filename + " ==???== " + it.getName());
if (it.getName().contentEquals(Resource.NO_NAME_RESOURCE)) {
continue;
}
@ -99,27 +102,27 @@ public class ResourceManager {
}
return null;
}
public synchronized Resource localKeep(final Uri uri) {
// TODO Auto-generated method stub
return localKeep(uri.toString());
}
/**
* Reload all resources from files, and send there in openGL card if needed.
* @note If file is reference at THEMEXXX:///filename if the Theme change the file will reload the newOne
*/
public synchronized void reLoadResources() {
Log.info("------------- Resources re-loaded -------------");
LOGGER.info("------------- Resources re-loaded -------------");
// remove all resources ...
for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) {
Log.info(" Reload level : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1));
LOGGER.info(" Reload level : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1));
synchronized (this.resourceList) {
for (final Resource it : this.resourceList) {
if (jjj == it.getResourceLevel()) {
if (it.getCount() > 0) {
it.reload();
Log.info(" [" + it.getId() + "]=" + it.getClass().getCanonicalName());
LOGGER.info(" [" + it.getId() + "]=" + it.getClass().getCanonicalName());
}
}
}
@ -127,9 +130,9 @@ public class ResourceManager {
}
// TODO UNderstand why it is set here ...
//gale::requestUpdateSize();
Log.info("------------- Resources -------------");
LOGGER.info("------------- Resources -------------");
}
/**
* Uninitiamize the resource manager, free all resources previously requested
* @note when not free == > generate warning, because the segfault can appear after...
@ -144,12 +147,13 @@ public class ResourceManager {
// remove all resources ...
synchronized (this.resourceList) {
for (final Resource it : this.resourceList) {
Log.warning("Find a resource that is not removed : [" + it.getId() + "]" + "='" + it.getName() + "' " + it.getCount() + " elements");
LOGGER.warn("Find a resource that is not removed : [" + it.getId() + "]" + "='" + it.getName() + "' "
+ it.getCount() + " elements");
}
this.resourceList.clear();
}
}
/**
* Call by the system to send all the needed data on the graphic card chen they change ...
* @param object The resources that might be updated
@ -167,16 +171,16 @@ public class ResourceManager {
this.resourceListToUpdate.add(object);
}
}
/**
* Call by the system chen the openGL Context has been unexpectially removed == > This reload all the texture, VBO and other ....
*/
public void updateContext() {
if (this.exiting) {
Log.error("Request update after application EXIT ...");
LOGGER.error("Request update after application EXIT ...");
return;
}
// TODO Check the number of call this ... Log.info("update open-gl context ... ");
// TODO Check the number of call this ... LOGGER.info("update open-gl context ... ");
if (this.contextHasBeenRemoved) {
// need to update all ...
this.contextHasBeenRemoved = false;
@ -186,10 +190,11 @@ public class ResourceManager {
synchronized (this.resourceList) {
if (this.resourceList.size() != 0) {
for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) {
Log.verbose(" updateContext level (D) : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1));
LOGGER.trace(" updateContext level (D) : " + jjj + "/"
+ (ResourceManager.MAX_RESOURCE_LEVEL - 1));
for (final Resource it : this.resourceList) {
if (jjj == it.getResourceLevel()) {
//Log.debug("Update context named : " + lresourceList[iii].getName());
//LOGGER.debug("Update context named : " + lresourceList[iii].getName());
if (!it.updateContext()) {
// Lock error ==> postponned
synchronized (this.resourceListToUpdate) {
@ -209,7 +214,8 @@ public class ResourceManager {
}
if (resourceListToUpdate.size() != 0) {
for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) {
Log.verbose(" updateContext level (U) : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1));
LOGGER.trace(
" updateContext level (U) : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1));
for (final Resource it : resourceListToUpdate) {
if (jjj == it.getResourceLevel()) {
if (!it.updateContext()) {
@ -222,5 +228,5 @@ public class ResourceManager {
}
}
}
}

View File

@ -13,12 +13,12 @@ import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.etk.math.Vector3i;
import org.atriasoft.etk.math.Vector4f;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ProgAttributeElement {
public String name; // !< Name of the element
@ -28,18 +28,20 @@ class ProgAttributeElement {
}
public class ResourceProgram extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceProgram.class);
static final boolean DEBUG = false; // TODO externalize this ...
public static ResourceProgram create(final Uri uriVertexShader, final Uri uriFragmentShader) {
ResourceProgram resource;
final String name = uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue();
Resource resource2 = Resource.getManager().localKeep(name);
final Resource resource2 = Resource.getManager().localKeep(name);
if (resource2 != null) {
if (resource2 instanceof ResourceProgram) {
resource2.keep();
return (ResourceProgram) resource2;
}
Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
LOGGER.error("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null;
}
resource = new ResourceProgram(uriVertexShader, uriFragmentShader);
@ -99,19 +101,19 @@ public class ResourceProgram extends Resource {
protected ResourceProgram(final Uri uriVertexShader, final Uri uriFragmentShader) {
super(uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue());
this.resourceLevel = 1;
Log.debug("OGL : load PROGRAM '" + uriVertexShader + "' && '" + uriFragmentShader + "'");
LOGGER.debug("OGL : load PROGRAM '" + uriVertexShader + "' && '" + uriFragmentShader + "'");
this.shaderVertex = ResourceShader.create(uriVertexShader);
if (this.shaderVertex == null) {
Log.error("Error while getting a specific shader filename: " + uriVertexShader);
LOGGER.error("Error while getting a specific shader filename: " + uriVertexShader);
return;
}
Log.debug("Add shader on program: '" + uriFragmentShader + "'");
LOGGER.debug("Add shader on program: '" + uriFragmentShader + "'");
this.shaderFragment = ResourceShader.create(uriFragmentShader);
if (this.shaderFragment == null) {
Log.error("Error while getting a specific shader filename: " + uriFragmentShader);
LOGGER.error("Error while getting a specific shader filename: " + uriFragmentShader);
return;
}
Log.debug("Add shader on program : " + uriFragmentShader + "frag");
LOGGER.debug("Add shader on program : " + uriFragmentShader + "frag");
if (OpenGL.hasContext()) {
updateContext();
} else {
@ -131,14 +133,15 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
return;
}
Log.error("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(vboId) + " VBOindex=" + vboId);
LOGGER.error("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(vboId)
+ " VBOindex=" + vboId);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo.getOpenGlId(vboId));
GL20.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
this.listOfVBOUsed.add(this.elementList.get(idElem).elementId);
@ -223,10 +226,12 @@ public class ResourceProgram extends Resource {
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);
LOGGER.warn(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\""
+ tmp.name + "\") = " + tmp.elementId);
tmp.isLinked = false;
} else {
Log.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\"" + tmp.name + "\") = " + tmp.elementId);
LOGGER.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\""
+ tmp.name + "\") = " + tmp.elementId);
}
} else {
// program is not loaded ==> just local reister ...
@ -269,10 +274,12 @@ public class ResourceProgram extends Resource {
tmp.elementId = OpenGL.programGetUniformLocation(this.program, tmp.name);
tmp.isLinked = true;
if (tmp.elementId < 0) {
Log.warning(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\"" + tmp.name + "\") = " + tmp.elementId);
LOGGER.warn(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\""
+ tmp.name + "\") = " + tmp.elementId);
tmp.isLinked = false;
} else {
Log.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\"" + tmp.name + "\") = " + tmp.elementId);
LOGGER.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\""
+ tmp.name + "\") = " + tmp.elementId);
}
} else {
// program is not loaded ==> just local reister ...
@ -293,14 +300,14 @@ public class ResourceProgram extends Resource {
public void reload() {
/*
* TODO ... etk::file file(this.name, etk::FILETYPEDATA); if (file.Exist() ==
* false) { Log.error("File does not Exist :"" + file + "\""); return; }
*
* false) { LOGGER.error("File does not Exist :"" + file + "\""); return; }
*
* int fileSize = file.size(); if (fileSize == 0) {
* Log.error("This file is empty : " + file); return; } if (file.fOpenRead() ==
* false) { Log.error("Can not open the file : " + file); return; } // remove
* LOGGER.error("This file is empty : " + file); return; } if (file.fOpenRead() ==
* false) { LOGGER.error("Can not open the file : " + file); return; } // remove
* previous data ... if (this.fileData != null) { del ete[] this.fileData;
* this.fileData = 0; } // allocate data this.fileData = ne w char[fileSize+5];
* if (this.fileData == null) { Log.error("Error Memory allocation size=" +
* if (this.fileData == null) { LOGGER.error("Error Memory allocation size=" +
* fileSize); return; } memset(this.fileData, 0, (fileSize+5)*sizeof(char)); //
* load data from the file : file.fRead(this.fileData, 1, fileSize); // close
* the file: file.fClose();
@ -353,7 +360,7 @@ public class ResourceProgram extends Resource {
// }
// if ( idElem < 0
// || (long)idElem > this.elementList.size()) {
// Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1)
// LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1)
// + "]");
// return;
// }
@ -362,7 +369,7 @@ public class ResourceProgram extends Resource {
// }
// FloatBuffer buffer = storeDataInFloatBuffer(data);
// //GL40.glBindVertexArray(this.elementList.get(idElem).elementId);
// Log.error("[" + this.elementList.get(idElem).name + "] send " + data.length +
// LOGGER.error("[" + this.elementList.get(idElem).name + "] send " + data.length +
// " element");
// GL40.glVertexAttribPointer(
// this.elementList.get(idElem).elementId,
@ -381,21 +388,26 @@ public class ResourceProgram extends Resource {
// public void sendAttribute(int idElem, List<Vector3f> data) {
// sendAttribute3fv(idElem, convertInFloat(data));
// }
public void sendAttribute(final int idElem, final int nbElement, final FloatBuffer data, final int jumpBetweenSample) {
public void sendAttribute(
final int idElem,
final int nbElement,
final FloatBuffer data,
final int jumpBetweenSample) {
if (!this.exist) {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
return;
}
// GL40.glBindVertexArray(this.elementList.get(idElem).elementId);
// Log.error("[" + this.elementList.get(idElem).name + "] send " + 3 + "
// LOGGER.error("[" + this.elementList.get(idElem).name + "] send " + 3 + "
// element");
GL20.glVertexAttribPointer(this.elementList.get(idElem).elementId, nbElement, GL11.GL_FLOAT, false, jumpBetweenSample * 4, /* 4 is the size of float in the generic system... */
GL20.glVertexAttribPointer(this.elementList.get(idElem).elementId, nbElement, GL11.GL_FLOAT, false,
jumpBetweenSample * 4, /* 4 is the size of float in the generic system... */
data);
// checkGlError("glVertexAttribPointer", LINE, idElem);
GL20.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
@ -420,7 +432,7 @@ public class ResourceProgram extends Resource {
// }
// if ( idElem < 0
// || (long)idElem > this.elementList.size()) {
// Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1)
// LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1)
// + "]");
// return;
// }
@ -429,17 +441,17 @@ public class ResourceProgram extends Resource {
// }
// // 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 : " +
// LOGGER.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 " +
// LOGGER.trace("[" + 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));
// LOGGER.trace(" id=" + this.elementList.get(idElem).elementId);
// LOGGER.trace(" eleme size=" + vbo.getElementSize(index));
// OpenGL.bufferData(data, Usage.staticDraw);
// OpenGL.vertexAttribPointerFloat(this.elementList.get(idElem).elementId,
// vbo.getElementSize(index)); // Pointer on the buffer
@ -454,19 +466,20 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
return;
}
Log.verbose("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(index) + " VBOindex=" + index);
LOGGER.trace("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(index)
+ " VBOindex=" + index);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo.getOpenGlId(index));
// checkGlError("glBindBuffer", __LINE__, _idElem);
Log.verbose(" id=" + this.elementList.get(idElem).elementId);
Log.verbose(" jump sample=" + jumpBetweenSample);
Log.verbose(" offset=" + offset);
LOGGER.trace(" id=" + this.elementList.get(idElem).elementId);
LOGGER.trace(" jump sample=" + jumpBetweenSample);
LOGGER.trace(" offset=" + offset);
GL20.glVertexAttribPointer(this.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
@ -525,7 +538,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -539,7 +552,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -547,6 +560,7 @@ public class ResourceProgram extends Resource {
}
OpenGL.programLoadUniformColorRGB(this.elementList.get(idElem).elementId, value);
}
/**
* Send 1 float uniform element to the spefified ID (not send if does not
* really exist in the openGL program)
@ -558,7 +572,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -580,7 +594,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -603,7 +617,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -621,13 +635,18 @@ public class ResourceProgram extends Resource {
* @param value3 Value to send at the Uniform
* @param value4 Value to send at the Uniform
*/
public void uniformFloat(final int idElem, final float value1, final float value2, final float value3, final float value4) {
public void uniformFloat(
final int idElem,
final float value1,
final float value2,
final float value3,
final float value4) {
if (!this.exist) {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -648,7 +667,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -670,7 +689,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -693,7 +712,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -717,7 +736,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -744,13 +763,13 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
return;
}
// Log.error("[" + this.elementList.get(idElem).name + "] send 1 matrix");
// LOGGER.error("[" + this.elementList.get(idElem).name + "] send 1 matrix");
// note : Android des not supported the transposition of the matrix, then we
// will done it oursef:
/*
@ -762,13 +781,12 @@ public class ResourceProgram extends Resource {
OpenGL.programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix, transpose);
}
public void uniformVector(final int idElem, final Vector2f value) {
if (!this.exist) {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -782,7 +800,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -796,7 +814,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -810,7 +828,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -824,7 +842,7 @@ public class ResourceProgram extends Resource {
return;
}
if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return;
}
if (!this.elementList.get(idElem).isLinked) {
@ -837,7 +855,7 @@ public class ResourceProgram extends Resource {
* Stop the processing of this program
*/
public void unUse() {
// Log.verbose("Will UN-use program : " + this.program);
// LOGGER.trace("Will UN-use program : " + this.program);
if (!this.exist) {
return;
@ -860,7 +878,7 @@ public class ResourceProgram extends Resource {
// Do nothing == > too dangerous ...
} else {
// create the Shader
Log.debug("Create the Program ...'" + this.name + "'");
LOGGER.debug("Create the Program ...'" + this.name + "'");
this.program = OpenGL.programCreate();
if (this.program < 0) {
return true;
@ -874,12 +892,13 @@ public class ResourceProgram extends Resource {
}
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, "in_position");
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, "in_extureCoords");
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES,
"in_extureCoords");
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_NORMALS, "in_normal");
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_COLORS, "in_colors");
if (!OpenGL.programCompile(this.program)) {
Log.error("Could not compile'PROGRAM':'" + this.name + "'");
LOGGER.error("Could not compile'PROGRAM':'" + this.name + "'");
OpenGL.programRemove(this.program);
return true;
}
@ -890,19 +909,23 @@ public class ResourceProgram extends Resource {
it.elementId = OpenGL.programGetAttributeLocation(this.program, it.name);
it.isLinked = true;
if (it.elementId < 0) {
Log.warning(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId);
LOGGER.warn(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name
+ "\") = " + it.elementId);
it.isLinked = false;
} else {
Log.debug(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId);
LOGGER.debug(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name
+ "\") = " + it.elementId);
}
} else {
it.elementId = OpenGL.programGetUniformLocation(this.program, it.name);
it.isLinked = true;
if (it.elementId < 0) {
Log.warning(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId);
LOGGER.warn(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name
+ "\") = " + it.elementId);
it.isLinked = false;
} else {
Log.debug(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId);
LOGGER.debug(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name
+ "\") = " + it.elementId);
}
}
iii++;
@ -917,7 +940,7 @@ public class ResourceProgram extends Resource {
* Request the processing of this program
*/
public void use() {
// Log.verbose("Will use program : " + this.program);
// LOGGER.trace("Will use program : " + this.program);
// event if it was 0 == > set it to prevent other use of the previous shader
// display ...
OpenGL.programUse(this.program);

View File

@ -3,9 +3,11 @@ package org.atriasoft.gale.resource;
import org.atriasoft.etk.Uri;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.ShaderType;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceShader extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceShader.class);
public static ResourceShader create(final Uri uriShader) {
ResourceShader resource;
@ -14,7 +16,7 @@ public class ResourceShader extends Resource {
if (!name.isEmpty() && !name.equals("---")) {
resource2 = getManager().localKeep(name);
} else {
Log.error("Can not create a shader without a filaname");
LOGGER.error("Can not create a shader without a filaname");
return null;
}
if (resource2 != null) {
@ -22,7 +24,8 @@ public class ResourceShader extends Resource {
resource2.keep();
return (ResourceShader) resource2;
}
Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
LOGGER.error("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null;
}
resource = new ResourceShader(uriShader);
@ -43,7 +46,7 @@ public class ResourceShader extends Resource {
super(uri);
this.uri = uri;
this.resourceLevel = 0;
Log.debug("OGL : load SHADER '" + uri + "'");
LOGGER.debug("OGL : load SHADER '" + uri + "'");
// load data from file "all the time ..."
if (uri.get().endsWith(".frag")) {
@ -51,7 +54,9 @@ public class ResourceShader extends Resource {
} 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 + "\"");
LOGGER.error(
"File does not have extention '.vert' for Vertex Shader or '.frag' for Fragment Shader. but : \""
+ uri + "\"");
this.type = ShaderType.VERTEX;
return;
}
@ -90,15 +95,16 @@ public class ResourceShader extends Resource {
@Override
public void reload() {
//!< A copy of the data loaded from the file (useful only when opengl context is removed)
String fileData = "";
Log.verbose("load shader:\n-----------------------------------------------------------------\n" + fileData + "\n-----------------------------------------------------------------");
final String fileData = "";
LOGGER.trace("load shader:\n-----------------------------------------------------------------\n" + fileData
+ "\n-----------------------------------------------------------------");
// now change the OGL context ...
if (OpenGL.hasContext()) {
Log.debug("OGL : load SHADER '" + this.name + "' ==> call update context (direct)");
LOGGER.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");
LOGGER.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;

View File

@ -6,29 +6,35 @@ import org.atriasoft.egami.ImageByteRGBA;
import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.tools.ImageLoader;
import org.atriasoft.gale.tools.ImageRawData;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Deprecated
public class ResourceTexture extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceTexture.class);
public enum TextureColorMode {
rgb, //!< red/green/blue data
rgba //!< red/green/blue/alpha data
}
private static int[] textureIdBinding = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2, GL13.GL_TEXTURE3, GL13.GL_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7,
GL13.GL_TEXTURE8, GL13.GL_TEXTURE9, GL13.GL_TEXTURE10, GL13.GL_TEXTURE11, GL13.GL_TEXTURE12, GL13.GL_TEXTURE13, GL13.GL_TEXTURE14, GL13.GL_TEXTURE15, GL13.GL_TEXTURE16, GL13.GL_TEXTURE17,
GL13.GL_TEXTURE18, GL13.GL_TEXTURE19, GL13.GL_TEXTURE20, GL13.GL_TEXTURE21, GL13.GL_TEXTURE22, GL13.GL_TEXTURE23, GL13.GL_TEXTURE24, GL13.GL_TEXTURE25, GL13.GL_TEXTURE26,
GL13.GL_TEXTURE27, GL13.GL_TEXTURE28, GL13.GL_TEXTURE29, GL13.GL_TEXTURE30, GL13.GL_TEXTURE31 };;
private static int[] textureIdBinding = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2, GL13.GL_TEXTURE3,
GL13.GL_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7, GL13.GL_TEXTURE8, GL13.GL_TEXTURE9,
GL13.GL_TEXTURE10, GL13.GL_TEXTURE11, GL13.GL_TEXTURE12, GL13.GL_TEXTURE13, GL13.GL_TEXTURE14,
GL13.GL_TEXTURE15, GL13.GL_TEXTURE16, GL13.GL_TEXTURE17, GL13.GL_TEXTURE18, GL13.GL_TEXTURE19,
GL13.GL_TEXTURE20, GL13.GL_TEXTURE21, GL13.GL_TEXTURE22, GL13.GL_TEXTURE23, GL13.GL_TEXTURE24,
GL13.GL_TEXTURE25, GL13.GL_TEXTURE26, GL13.GL_TEXTURE27, GL13.GL_TEXTURE28, GL13.GL_TEXTURE29,
GL13.GL_TEXTURE30, GL13.GL_TEXTURE31 };;
public static ResourceTexture createFromPng(final Uri uriTexture) {
return createFromPng(uriTexture, 1);
}
public static ResourceTexture createFromPng(final Uri uriTexture, final int textureUnit) {
ResourceTexture resource;
Resource resource2;
@ -36,7 +42,7 @@ public class ResourceTexture extends Resource {
if (!name.isEmpty() && !name.equals("---")) {
resource2 = getManager().localKeep(name);
} else {
Log.error("Can not create a shader without a filaname");
LOGGER.error("Can not create a shader without a filaname");
return null;
}
if (resource2 != null) {
@ -44,14 +50,15 @@ public class ResourceTexture extends Resource {
resource2.keep();
return (ResourceTexture) resource2;
}
Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
LOGGER.error("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null;
}
resource = new ResourceTexture(uriTexture, textureUnit);
final ImageRawData decodedData = ImageLoader.decodePngFile(uriTexture);
ImageByteRGBA img = new ImageByteRGBA(decodedData.getWidth(), decodedData.getHeight());
ByteBuffer mlklmklm = decodedData.getBuffer();
byte[] elemData = new byte[mlklmklm.remaining()];
final ImageByteRGBA img = new ImageByteRGBA(decodedData.getWidth(), decodedData.getHeight());
final ByteBuffer mlklmklm = decodedData.getBuffer();
final byte[] elemData = new byte[mlklmklm.remaining()];
mlklmklm.get(elemData);
if (decodedData.isHasAlpha()) {
for (int yyy = 0; yyy < decodedData.getHeight(); yyy++) {
@ -65,18 +72,19 @@ public class ResourceTexture extends Resource {
} else {
for (int yyy = 0; yyy < decodedData.getHeight(); yyy++) {
for (int xxx = 0; xxx < decodedData.getWidth(); xxx++) {
img.setAByte(xxx, yyy, (byte)0xFF);
img.setAByte(xxx, yyy, (byte) 0xFF);
img.setRByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 0]);
img.setGByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 1]);
img.setBByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 2]);
}
}
}
resource.setTexture(img, new Vector2i(decodedData.getWidth(), decodedData.getHeight()), (decodedData.isHasAlpha() ? TextureColorMode.rgba : TextureColorMode.rgb), textureUnit);
resource.setTexture(img, new Vector2i(decodedData.getWidth(), decodedData.getHeight()),
(decodedData.isHasAlpha() ? TextureColorMode.rgba : TextureColorMode.rgb), textureUnit);
resource.flush();
return resource;
}
/**
* get the next power 2 if the input
* @param value Value that we want the next power of 2
@ -90,10 +98,11 @@ public class ResourceTexture extends Resource {
}
val *= 2;
}
Log.critical("impossible CASE....");
LOGGER.error("impossible CASE....");
System.exit(-1);
return val;
}
protected int texId = -1; //!< openGl textureID.
// some image are not square == > we need to sqared it to prevent some openGl api error the the displayable size is not all the time 0.0 . 1.0.
protected Vector2i endPointSize = new Vector2i(-1, -1);
@ -109,16 +118,14 @@ public class ResourceTexture extends Resource {
private TextureColorMode dataColorSpace = TextureColorMode.rgb;
// number of lines and colomns in the texture (multiple texturing in a single texture)
private int textureUnit = 0;
protected ResourceTexture() {
super();
}
protected ResourceTexture() {}
protected ResourceTexture(final Uri filename, final int textureUnit) {
super(filename.toString() + "__" + textureUnit);
this.textureUnit = textureUnit;
}
public void bindForRendering(final int idTexture) {
if (!this.loaded) {
return;
@ -130,49 +137,53 @@ public class ResourceTexture extends Resource {
OpenGL.enable(OpenGL.Flag.flag_back);
}
}
@Override
public void cleanUp() {
removeContext();
}
// Flush the data to send it at the openGl system
public synchronized void flush() {
// request to the manager to be call at the next update ...
Log.verbose("Request UPDATE of Element");
LOGGER.trace("Request UPDATE of Element");
getManager().update(this);
}
public Vector2i getOpenGlSize() {
return this.size;
};
public int getRendererId() {
return this.texId;
}
public Vector2i getUsableSize() {
return this.endPointSize;
}
@Override
public synchronized void removeContext() {
if (this.loaded) {
// Request remove texture ...
Log.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
LOGGER.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
// TODO Check if we are in the correct thread
OpenGL.glDeleteTextures(this.texId);
this.loaded = false;
}
}
@Override
public synchronized void removeContextToLate() {
this.loaded = false;
this.texId = -1;
}
public void setTexture(final ImageByteRGBA data, final Vector2i size, final TextureColorMode dataColorSpace, final int textureUnit) {
public void setTexture(
final ImageByteRGBA data,
final Vector2i size,
final TextureColorMode dataColorSpace,
final int textureUnit) {
this.data = data;
this.size = size;
this.textureUnit = textureUnit;
@ -180,7 +191,7 @@ public class ResourceTexture extends Resource {
this.dataColorSpace = dataColorSpace;
flush();
}
public void unBindForRendering() {
if (!this.loaded) {
return;
@ -190,7 +201,7 @@ public class ResourceTexture extends Resource {
OpenGL.disable(OpenGL.Flag.flag_back);
}
}
// Gale internal API:
@Override
public boolean updateContext() {
@ -201,24 +212,26 @@ public class ResourceTexture extends Resource {
this.texId = GL11.glGenTextures();
GL13.glActiveTexture(this.textureUnit);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.texId);
// All RGB bytes are aligned to each other and each component is 1 byte
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
Log.info("TEXTURE: add [" + getId() + "]=" + this.size + " OGlId=" + this.texId);
LOGGER.info("TEXTURE: add [" + getId() + "]=" + this.size + " OGlId=" + this.texId);
if (this.dataColorSpace == TextureColorMode.rgb) {
OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, this.data.getRaw());
//The local image has not RGB but only RGBA data ...
OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE,
this.data.getRaw());
//The local image has not RGB but only RGBA data ...
//OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, this.data.getRaw());
} else {
OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, this.data.getRaw());
OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE,
this.data.getRaw());
}
// generate multi-texture mapping
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
// Setup the ST coordinate system
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
// Setup what to do when the texture has to be scaled
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);

View File

@ -12,59 +12,64 @@ import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.gale.TextureFilter;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceTexture2 extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceTexture2.class);
public enum TextureColorMode {
rgb, // !< red/green/blue data
rgba // !< red/green/blue/alpha data
}
public static ResourceTexture2 create() {
Log.verbose("KEEP: Resource Texture Dynamic: ");
LOGGER.trace("KEEP: Resource Texture Dynamic: ");
return new ResourceTexture2();
}
public static ResourceTexture2 create(final Uri uri) {
Log.verbose("KEEP: Resource Texture: " + uri);
LOGGER.trace("KEEP: Resource Texture: " + uri);
final Resource object2 = Resource.getManager().localKeep(uri);
if (object2 != null) {
if (object2 instanceof ResourceTexture2 tmpp) {
if (object2 instanceof final ResourceTexture2 tmpp) {
return tmpp;
}
Log.critical("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
LOGGER.error("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null;
}
Log.verbose("CREATE: new Texture: " + uri);
LOGGER.trace("CREATE: new Texture: " + uri);
return new ResourceTexture2(uri);
}
public static ResourceTexture2 createNamed(final String uri) {
Log.verbose("KEEP: Resource Texture Named: " + uri);
LOGGER.trace("KEEP: Resource Texture Named: " + uri);
final Resource object2 = Resource.getManager().localKeep(uri);
if (object2 != null) {
if (object2 instanceof ResourceTexture2 tmpp) {
if (object2 instanceof final ResourceTexture2 tmpp) {
return tmpp;
}
Log.critical("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
LOGGER.error("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null;
}
Log.debug("CREATE: new Texture Named: " + uri);
LOGGER.debug("CREATE: new Texture Named: " + uri);
return new ResourceTexture2(uri);
}
/*
* public static ResourceTexture2 createFromPng(final Uri uriTexture) { return
* createFromPng(uriTexture, 1); }
*
*
* public static ResourceTexture2 createFromPng(final Uri uriTexture, final int
* textureUnit) { ResourceTexture2 resource; Resource resource2; final String
* name = uriTexture.getValue(); if (name.isEmpty() == false && name != "---") {
* resource2 = getManager().localKeep(name); } else {
* Log.error("Can not create a shader without a filaname"); return null; } if
* LOGGER.error("Can not create a shader without a filaname"); return null; } if
* (resource2 != null) { if (resource2 instanceof ResourceTexture2) {
* resource2.keep(); return (ResourceTexture2) resource2; }
* Log.critical("Request resource file : '" + name +
* LOGGER.critical("Request resource file : '" + name +
* "' With the wrong type (dynamic cast error)"); return null; } resource = new
* ResourceTexture2(uriTexture, textureUnit); final ImageRawData decodedData =
* ImageLoader.decodePngFile(uriTexture);
@ -133,7 +138,7 @@ public class ResourceTexture2 extends Resource {
// Flush the data to send it at the openGl system
public synchronized void flush() {
// request to the manager to be call at the next update ...
Log.verbose("Request UPDATE of Element");
LOGGER.trace("Request UPDATE of Element");
Resource.getManager().update(this);
}
@ -158,7 +163,7 @@ public class ResourceTexture2 extends Resource {
public synchronized void removeContext() {
if (this.loaded) {
// Request remove texture ...
Log.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
LOGGER.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
// TODO Check if we are in the correct thread
OpenGL.glDeleteTextures(this.texId);
this.loaded = false;
@ -177,16 +182,16 @@ public class ResourceTexture2 extends Resource {
* @param image Image to set.
*/
public synchronized void set(final ImageByte image) {
Log.debug("Set a new image in a texture:");
Log.debug(" size=" + image.getSize());
LOGGER.debug("Set a new image in a texture:");
LOGGER.debug(" size=" + image.getSize());
this.data = image;
this.realImageSize = this.data.getSize();
// Disable compatibility size for embended ...
// final Vector2i compatibilityHWSize = new Vector2i(Tools.nextP2(this.realImageSize.x()), Tools.nextP2(this.realImageSize.y()));
// if (!this.realImageSize.equals(compatibilityHWSize)) {
// Log.warning("RESIZE Image for HArwareCompatibility:" + this.realImageSize + " => " + compatibilityHWSize);
// this.data.resize(compatibilityHWSize.x(), compatibilityHWSize.y());
// }
// Disable compatibility size for embended ...
// final Vector2i compatibilityHWSize = new Vector2i(Tools.nextP2(this.realImageSize.x()), Tools.nextP2(this.realImageSize.y()));
// if (!this.realImageSize.equals(compatibilityHWSize)) {
// LOGGER.warn("RESIZE Image for HArwareCompatibility:" + this.realImageSize + " => " + compatibilityHWSize);
// this.data.resize(compatibilityHWSize.x(), compatibilityHWSize.y());
// }
flush();
}
@ -225,7 +230,7 @@ public class ResourceTexture2 extends Resource {
@Override
public synchronized boolean updateContext() {
Log.verbose("updateContext [START]");
LOGGER.trace("updateContext [START]");
//final Steady tic = Steady.now();
/*
* TODO : use unlockable synchronized ... if (lock.tryLock() == false) { //Lock
@ -234,8 +239,9 @@ public class ResourceTexture2 extends Resource {
final int typeObject = this.data.hasAlpha() ? OpenGL.GL_RGBA : OpenGL.GL_RGB;
final int sizeObject = OpenGL.GL_UNSIGNED_BYTE;
if (this.loaded) {
if (this.lastTypeObject != typeObject || this.lastSizeObject != sizeObject || !this.lastSize.equals(this.data.getSize())) {
Log.warning("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
if (this.lastTypeObject != typeObject || this.lastSizeObject != sizeObject
|| !this.lastSize.equals(this.data.getSize())) {
LOGGER.warn("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
OpenGL.glDeleteTextures(this.texId);
this.loaded = false;
}
@ -246,9 +252,11 @@ public class ResourceTexture2 extends Resource {
this.lastSize = this.data.getSize();
this.lastTypeObject = typeObject;
this.lastSizeObject = sizeObject;
Log.debug("TEXTURE: add [" + getId() + "]=" + this.data.getSize() + "=>" + this.data.getGPUSize() + " OGlId=" + this.texId + " type=" + this.data.getClass().getCanonicalName());
LOGGER.debug("TEXTURE: add [" + getId() + "]=" + this.data.getSize() + "=>" + this.data.getGPUSize()
+ " OGlId=" + this.texId + " type=" + this.data.getClass().getCanonicalName());
} else {
Log.debug("TEXTURE: update [" + getId() + "]=" + this.data.getSize() + "=>" + this.data.getGPUSize() + " OGlId=" + this.texId + " type=" + this.data.getClass().getCanonicalName());
LOGGER.debug("TEXTURE: update [" + getId() + "]=" + this.data.getSize() + "=>" + this.data.getGPUSize()
+ " OGlId=" + this.texId + " type=" + this.data.getClass().getCanonicalName());
}
// in all case we set the texture properties :
// TODO check error ???
@ -268,7 +276,7 @@ public class ResourceTexture2 extends Resource {
}
// glPixelStorei(GLUNPACKALIGNMENT,1);
//final Steady toc1 = Steady.now();
//Log.verbose(" BIND ==> " + toc1.less(tic));
//LOGGER.trace(" BIND ==> " + toc1.less(tic));
// egami::store(this.data, String("~/texture") + etk::toString(getId()) + ".bmp");
if (!this.loaded) {
OpenGL.glTexImage2D(0, // Level
@ -289,7 +297,7 @@ public class ResourceTexture2 extends Resource {
// now the data is loaded
this.loaded = true;
// final Steady toc = Steady.now();
// Log.error(" updateContext [STOP] ==> " + (toc - toc1));
// LOGGER.error(" updateContext [STOP] ==> " + (toc - toc1));
return true;
}

View File

@ -4,12 +4,14 @@ import org.atriasoft.egami.ImageByte;
import org.atriasoft.etk.Tools;
import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.iogami.IOgami;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// TODO : Change tis file name ...
public class ResourceTextureFile extends ResourceTexture2 {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceTextureFile.class);
public static Vector2i sizeAuto = new Vector2i(-1, -1);
public static Vector2i sizeDefault = Vector2i.ZERO;
@ -32,24 +34,24 @@ public class ResourceTextureFile extends ResourceTexture2 {
* @return pointer on the resource or null if an error occured.
*/
public static ResourceTextureFile create(final Uri uri, final Vector2i inSize, final Vector2i sizeRegister) {
Log.verbose("KEEP: TextureFile: '" + uri + "' size=" + inSize + " sizeRegister=" + sizeRegister);
LOGGER.trace("KEEP: TextureFile: '" + uri + "' size=" + inSize + " sizeRegister=" + sizeRegister);
Vector2i size = inSize;
if (uri == null) {
return new ResourceTextureFile();
}
if (size.x() == 0) {
size = size.withX(-1);
// Log.error("Error Request the image size.x() =0 ???");
// LOGGER.error("Error Request the image size.x() =0 ???");
}
if (size.y() == 0) {
size = size.withY(-1);
// Log.error("Error Request the image size.y() =0 ???");
// LOGGER.error("Error Request the image size.y() =0 ???");
}
if (!uri.getExtention().toLowerCase().contentEquals("svg")) {
size = ResourceTextureFile.sizeAuto;
}
if (size.x() > 0 && size.y() > 0) {
Log.verbose(" == > specific size : " + size);
LOGGER.trace(" == > specific size : " + size);
size = new Vector2i(Tools.nextP2(size.x()), Tools.nextP2(size.y()));
if (!sizeRegister.equals(ResourceTextureFile.sizeAuto)) {
if (!sizeRegister.equals(ResourceTextureFile.sizeDefault)) {
@ -59,19 +61,20 @@ public class ResourceTextureFile extends ResourceTexture2 {
}
}
Log.verbose("KEEP: TextureFile: '" + uri + "' new size=" + size);
LOGGER.trace("KEEP: TextureFile: '" + uri + "' new size=" + size);
final Resource object2 = Resource.getManager().localKeep(uri.toString());
if (object2 != null) {
if (object2 instanceof ResourceTextureFile out) {
if (object2 instanceof final ResourceTextureFile out) {
object2.keep();
return out;
}
Log.critical("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
LOGGER.error("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null;
}
Log.debug("CREATE: TextureFile: '" + uri + "' size=" + size);
LOGGER.debug("CREATE: TextureFile: '" + uri + "' size=" + size);
// need to crate a new one ...
ResourceTextureFile object = new ResourceTextureFile(uri.toString(), uri, size);
final ResourceTextureFile object = new ResourceTextureFile(uri.toString(), uri, size);
Resource.getManager().localAdd(object);
return object;
}
@ -80,10 +83,10 @@ public class ResourceTextureFile extends ResourceTexture2 {
protected ResourceTextureFile(final String genName, final Uri uri, final Vector2i size) {
super(genName);
Log.debug("create a new resource::Image : genName=" + genName + " uri=" + uri + " size=" + size);
LOGGER.debug("create a new resource::Image : genName=" + genName + " uri=" + uri + " size=" + size);
final ImageByte tmp = IOgami.load(uri, size);
if (tmp == null) {
Log.error("Can not load the file : " + uri);
LOGGER.error("Can not load the file : " + uri);
return;
}
set(tmp);

View File

@ -12,99 +12,118 @@ import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.RenderMode;
import org.atriasoft.gale.backend3d.OpenGL.Usage;
import org.atriasoft.gale.internal.Log;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import models.RawModel;
public class ResourceVirtualArrayObject extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceVirtualArrayObject.class);
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;
public static int[] convertIntegers(final List<Integer> integers) {
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
final int[] ret = new int[integers.size()];
final Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++) {
ret[i] = iterator.next().intValue();
}
return ret;
}
public static ResourceVirtualArrayObject create(final float[] positions, final float[] colors, final float[] textureCoordinates, final float[] normals, final int[] indices) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors, textureCoordinates, normals, indices, indices.length);
public static ResourceVirtualArrayObject create(
final float[] positions,
final float[] colors,
final float[] textureCoordinates,
final float[] normals,
final int[] indices) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors,
textureCoordinates, normals, indices, indices.length);
Resource.getManager().localAdd(resource);
return resource;
}
public static ResourceVirtualArrayObject create(final float[] positions, final float[] textureCoordinates, final float[] normals, final int[] indices) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, textureCoordinates, normals, indices, indices.length);
public static ResourceVirtualArrayObject create(
final float[] positions,
final float[] textureCoordinates,
final float[] normals,
final int[] indices) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, textureCoordinates,
normals, indices, indices.length);
Resource.getManager().localAdd(resource);
return resource;
}
public static ResourceVirtualArrayObject create(final float[] positions, final float[] colors, final int[] indices) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors, null, null, indices, indices.length);
public static ResourceVirtualArrayObject create(
final float[] positions,
final float[] colors,
final int[] indices) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors, null, null,
indices, indices.length);
Resource.getManager().localAdd(resource);
return resource;
}
public static ResourceVirtualArrayObject create(final float[] positions, final int dimentions) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, null, null, null, positions.length / dimentions);
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, null, null, null,
positions.length / dimentions);
Resource.getManager().localAdd(resource);
return resource;
}
public static ResourceVirtualArrayObject createDynamic() {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject();
Resource.getManager().localAdd(resource);
return resource;
}
public static FloatBuffer storeDataInFloatBuffer(final float[] data) {
final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
public static IntBuffer storeDataInIntBuffer(final int[] data) {
final IntBuffer buffer = BufferUtils.createIntBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
private boolean dynamic = false;
private int vaoID = -1;
private boolean exist = false; //!< This data is availlable in the Graphic card
private final List<Integer> vbo = new ArrayList<>();
Object positions = null;
Object colors = null;
Object textureCoordinates = null;
Object normals = null;
int[] indices = null;
int vertexCount = -1;
protected ResourceVirtualArrayObject() {
this.resourceLevel = 3;
this.dynamic = true;
Log.debug("OGL: load VBO count (dynamic)");
LOGGER.debug("OGL: load VBO count (dynamic)");
}
protected ResourceVirtualArrayObject(final float[] positions, final float[] colors, final float[] textureCoordinates, final float[] normals, final int[] indices, final int vertexCount) {
protected ResourceVirtualArrayObject(final float[] positions, final float[] colors,
final float[] textureCoordinates, final float[] normals, final int[] indices, final int vertexCount) {
this.resourceLevel = 3;
this.positions = positions;
this.colors = colors;
@ -112,9 +131,9 @@ public class ResourceVirtualArrayObject extends Resource {
this.normals = normals;
this.indices = indices;
this.vertexCount = vertexCount;
Log.debug("OGL: load VBO count");
LOGGER.debug("OGL: load VBO count");
}
public void bindForRendering() {
if (!this.exist) {
return;
@ -122,7 +141,7 @@ public class ResourceVirtualArrayObject extends Resource {
GL30.glBindVertexArray(this.vaoID);
if (this.positions != null) {
GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS);
//Log.info("unbind POSITION");
//LOGGER.info("unbind POSITION");
}
if (this.textureCoordinates != null) {
GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES);
@ -134,7 +153,7 @@ public class ResourceVirtualArrayObject extends Resource {
GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_COLORS);
}
}
private void bindIndicesBuffer(final int[] indices) {
final int vboId = OpenGL.genBuffers();
this.vbo.add(vboId);
@ -146,7 +165,7 @@ public class ResourceVirtualArrayObject extends Resource {
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
}
}
/**
* Destructor of this VBO.
*/
@ -154,12 +173,12 @@ public class ResourceVirtualArrayObject extends Resource {
public void cleanUp() {
removeContext();
}
/**
* clear buffers
*/
public void clear() {
//Log.verbose(" Clear: [" + getId() + "] '" + getName() + "' (size=" + buffer.get(0).length + ")");
//LOGGER.trace(" Clear: [" + getId() + "] '" + getName() + "' (size=" + buffer.get(0).length + ")");
this.positions = null;
this.colors = null;
this.textureCoordinates = null;
@ -167,22 +186,22 @@ public class ResourceVirtualArrayObject extends Resource {
this.indices = null;
this.vertexCount = -1;
}
private void createVAO() {
Log.verbose("create VAO...");
LOGGER.trace("create VAO...");
this.vaoID = GL30.glGenVertexArrays();
GL30.glBindVertexArray(this.vaoID);
}
/**
* Send the data to the graphic card.
*/
public void flush() {
// request to the manager to be call at the next update ...
Resource.getManager().update(this);
Log.verbose("Request flush of VAO: [" + getId() + "] '" + getName() + "'");
LOGGER.trace("Request flush of VAO: [" + getId() + "] '" + getName() + "'");
}
/**
* get the real openGL ID.
* @return the Ogl id reference of this VBO.
@ -190,63 +209,65 @@ public class ResourceVirtualArrayObject extends Resource {
public int getGLID() {
return this.vaoID;
}
public int getVertexCount() {
return this.vertexCount;
}
public void loadAgainToVAO() {
GL30.glBindVertexArray(this.vaoID);
Log.verbose("push VAO: [" + getId() + "] '" + getName() + "'");
LOGGER.trace("push VAO: [" + getId() + "] '" + getName() + "'");
if (this.indices != null) {
Log.verbose("Set indices");
LOGGER.trace("Set indices");
bindIndicesBuffer(this.indices);
}
if (this.positions != null) {
Log.verbose("Set positions");
LOGGER.trace("Set positions");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, 3, this.positions);
}
if (this.textureCoordinates != null) {
Log.verbose("Set textureCoordinates");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, 2, this.textureCoordinates);
LOGGER.trace("Set textureCoordinates");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, 2,
this.textureCoordinates);
}
if (this.normals != null) {
Log.verbose("Set normals");
LOGGER.trace("Set normals");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_NORMALS, 3, this.normals);
}
if (this.colors != null) {
Log.verbose("Set colors");
LOGGER.trace("Set colors");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_COLORS, 4, this.colors);
}
unbindVAO();
}
public void loadToVAO() {
createVAO();
Log.verbose("push VAO: [" + getId() + "] '" + getName() + "'");
LOGGER.trace("push VAO: [" + getId() + "] '" + getName() + "'");
if (this.indices != null) {
Log.verbose("Set indices");
LOGGER.trace("Set indices");
bindIndicesBuffer(this.indices);
}
if (this.positions != null) {
Log.verbose("Set positions");
LOGGER.trace("Set positions");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, 3, this.positions);
}
if (this.textureCoordinates != null) {
Log.verbose("Set textureCoordinates");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, 2, this.textureCoordinates);
LOGGER.trace("Set textureCoordinates");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, 2,
this.textureCoordinates);
}
if (this.normals != null) {
Log.verbose("Set normals");
LOGGER.trace("Set normals");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_NORMALS, 3, this.normals);
}
if (this.colors != null) {
Log.verbose("Set colors");
LOGGER.trace("Set colors");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_COLORS, 4, this.colors);
}
unbindVAO();
}
/**
* 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.
@ -256,7 +277,7 @@ public class ResourceVirtualArrayObject extends Resource {
removeContext();
updateContext();
}
/**
* remove the data from the opengl context.
*/
@ -267,7 +288,7 @@ public class ResourceVirtualArrayObject extends Resource {
this.exist = false;
}
}
/**
* Special android spec! It inform us that all context is removed and after notify us...
*/
@ -278,84 +299,84 @@ public class ResourceVirtualArrayObject extends Resource {
// this.vbo[iii] = 0;
// }
}
public void render(final RenderMode mode) {
Log.verbose("request rendering indices : " + this.vertexCount);
LOGGER.trace("request rendering indices : " + this.vertexCount);
OpenGL.drawElements(mode, this.vertexCount);
}
public void render(final RenderMode mode, final int start, final int stop) {
OpenGL.drawArrays(mode, start, stop);
}
public void renderArrays(final RenderMode mode) {
Log.verbose("request rendering direct : " + this.vertexCount);
LOGGER.trace("request rendering direct : " + this.vertexCount);
OpenGL.drawArrays(mode, 0, this.vertexCount);
}
public void setColors(final Color[] colors) {
this.colors = colors;
}
public void setColors(final float[] colors) {
this.colors = colors;
}
public void setColors(final List<Color> colors) {
setColors(colors.toArray(Color[]::new));
}
public void setIndices(final int[] indices) {
this.indices = indices;
}
public void setIndices(final List<Integer> indices) {
this.indices = ResourceVirtualArrayObject.convertIntegers(indices);
this.vertexCount = this.indices.length;
}
public void setNormals(final float[] normals) {
this.normals = normals;
}
public void setNormals(final List<Vector3f> normals) {
setNormals(normals.toArray(Vector3f[]::new));
}
public void setNormals(final Vector3f[] normals) {
this.normals = normals;
}
public void setPosition(final float[] positions) {
this.positions = positions;
}
public void setPosition(final List<Vector3f> outPosition) {
setPosition(outPosition.toArray(Vector3f[]::new));
}
public void setPosition(final Vector3f[] positions) {
this.positions = positions;
}
public void setTextureCoordinate(final float[] textureCoordinates) {
this.textureCoordinates = textureCoordinates;
}
public void setTextureCoordinate(final List<Vector2f> outTexturePosition) {
setTextureCoordinate(outTexturePosition.toArray(Vector2f[]::new));
}
public void setTextureCoordinate(final Vector2f[] textureCoordinates) {
this.textureCoordinates = textureCoordinates;
}
public void setVertexCount(final int vertexCount) {
this.vertexCount = vertexCount;
}
private void storeDataInAttributeList(final int attributeNumber, final int coordinateSize, final Object data) {
final int vboID = GL15.glGenBuffers();
this.vbo.add(vboID);
@ -365,23 +386,23 @@ public class ResourceVirtualArrayObject extends Resource {
usage = Usage.streamDraw;
}
// select the buffer to set data inside it ...
if (data instanceof float[] buffer) {
if (data instanceof final float[] buffer) {
OpenGL.bufferData(buffer, usage);
} else if (data instanceof int[] buffer) {
} else if (data instanceof final int[] buffer) {
OpenGL.bufferData(buffer, usage);
} else if (data instanceof Vector2f[] buffer) {
} else if (data instanceof final Vector2f[] buffer) {
OpenGL.bufferData(buffer, usage);
} else if (data instanceof Vector3f[] buffer) {
} else if (data instanceof final Vector3f[] buffer) {
OpenGL.bufferData(buffer, usage);
} else if (data instanceof Color[] buffer) {
} else if (data instanceof final Color[] buffer) {
OpenGL.bufferData(buffer, usage);
} else {
Log.error("Not managed VBO model : " + data.getClass().getCanonicalName());
LOGGER.error("Not managed VBO model : " + data.getClass().getCanonicalName());
}
GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0, 0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
public void unBindForRendering() {
if (!this.exist) {
return;
@ -400,33 +421,34 @@ public class ResourceVirtualArrayObject extends Resource {
}
GL30.glBindVertexArray(0);
}
private void unbindVAO() {
Log.verbose("Unbind VAO ...");
LOGGER.trace("Unbind VAO ...");
GL30.glBindVertexArray(0);
}
/**
* This load/reload the data in the opengl context, needed when removed previously.
*/
@Override
public boolean updateContext() {
Log.verbose(" Start: [" + getId() + "] '" + getName() + "' (size=" + this.vertexCount + ") ********************************");
LOGGER.trace(" Start: [" + getId() + "] '" + getName() + "' (size=" + this.vertexCount
+ ") ********************************");
if (!this.exist) {
Log.verbose(" ==> ALLOCATE new handle");
LOGGER.trace(" ==> ALLOCATE new handle");
// Allocate and assign a Vertex Array Object to our handle
loadToVAO();
} else {
// Update VAO (only for dynamic:
if (!this.dynamic) {
Log.error(" Request update a VAO with a static buffer !!!" + this.name);
LOGGER.error(" Request update a VAO with a static buffer !!!" + this.name);
}
loadAgainToVAO();
}
this.exist = true;
Log.verbose(" Stop: [" + getId() + "] '" + getName() + "'");
LOGGER.trace(" Stop: [" + getId() + "] '" + getName() + "'");
return true;
}
}

View File

@ -12,21 +12,23 @@ import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.Usage;
import org.atriasoft.gale.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ResourceVirtualBufferObject is a specific resources for opengl, this load the data directly in the graphic card ad keep these inside
*/
public class ResourceVirtualBufferObject extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceVirtualBufferObject.class);
public static ResourceVirtualBufferObject create(final int count) {
return new ResourceVirtualBufferObject(count);
}
private boolean exist = false; //!< This data is available in the Graphic card
private final int[] vbo; //!< openGl ID of this VBO
private final Object[] buffer; //!< data that is available in the VBO system ...
/**
* Constructor of this VBO.
* @param accesMode Access mode : ???
@ -34,10 +36,10 @@ public class ResourceVirtualBufferObject extends Resource {
protected ResourceVirtualBufferObject(final int number) {
this.vbo = new int[number]; // 0
this.buffer = new Object[number];
Log.debug("OGL : load VBO count=\"" + number + "\"");
LOGGER.debug("OGL : load VBO count=\"" + number + "\"");
this.resourceLevel = 3;
}
public int bufferSize(final int vboidcoord) {
if (this.buffer[vboidcoord] != null) {
// select the buffer to set data inside it ...
@ -53,35 +55,35 @@ public class ResourceVirtualBufferObject extends Resource {
} else if (this.buffer[vboidcoord] instanceof Color[]) {
return ((Color[]) (this.buffer[vboidcoord])).length;
} else {
Log.error("Not managed VBO model : " + this.buffer[vboidcoord].getClass().getCanonicalName());
LOGGER.error("Not managed VBO model : " + this.buffer[vboidcoord].getClass().getCanonicalName());
}
}
return 0;
}
@Override
public void cleanUp() {
// TODO Auto-generated method stub
}
/**
* clear buffers
*/
public void clear() {
Log.verbose(" Clear: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")");
LOGGER.trace(" Clear: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")");
// DO not clear the this.vbo indexed in the graphic cards ...
Arrays.fill(this.buffer, null);
}
/**
* Send the data to the graphic card.
*/
public synchronized void flush() {
// request to the manager to be call at the next update ...
Resource.getManager().update(this);
Log.verbose("Request flush of VBO: [" + getId() + "] '" + getName() + "'");
LOGGER.trace("Request flush of VBO: [" + getId() + "] '" + getName() + "'");
}
public int getElementSize(final int index) {
if (this.buffer[index] != null) {
// select the buffer to set data inside it ...
@ -97,12 +99,12 @@ public class ResourceVirtualBufferObject extends Resource {
} else if (this.buffer[index] instanceof Color[]) {
return 4;
} else {
Log.error("Not managed VBO model : " + this.buffer[index].getClass().getCanonicalName());
LOGGER.error("Not managed VBO model : " + this.buffer[index].getClass().getCanonicalName());
}
}
return 1;
}
/**
* get the real openGL ID.
* @return the Ogl id reference of this VBO.
@ -110,7 +112,7 @@ public class ResourceVirtualBufferObject extends Resource {
public int getOpenGlId(final int id) {
return this.vbo[id];
}
/**
* 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.
@ -120,7 +122,7 @@ public class ResourceVirtualBufferObject extends Resource {
removeContext();
updateContext();
}
/**
* remove the data from the opengl context.
*/
@ -131,7 +133,7 @@ public class ResourceVirtualBufferObject extends Resource {
this.exist = false;
}
}
/**
* Special android spec! It inform us that all context is removed and after notify us...
*/
@ -140,56 +142,58 @@ public class ResourceVirtualBufferObject extends Resource {
this.exist = false;
Arrays.fill(this.vbo, 0);
}
/**
* get the data from the graphic card.
*/
public void retreiveData() {
Log.error("TODO ... ");
LOGGER.error("TODO ... ");
}
public void setVboData(final int vboId, final Color[] data) {
this.buffer[vboId] = data;
}
public void setVboData(final int vboId, final float[] data) {
this.buffer[vboId] = data;
}
public void setVboData(final int vboId, final int[] data) {
this.buffer[vboId] = data;
}
public void setVboData(final int vboId, final Vector2f[] data) {
this.buffer[vboId] = data;
}
public void setVboData(final int vboId, final Vector3f[] data) {
this.buffer[vboId] = data;
}
/**
* This load/reload the data in the opengl context, needed when removed previously.
*/
@Override
public synchronized boolean updateContext() {
Log.verbose("updateContext (VBO Start: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")");
LOGGER.trace(
"updateContext (VBO Start: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")");
/*
if (lock.tryLock() == false) {
//Lock error ==> try later ...
Log.warning(" ==> Lock error on VBO");
LOGGER.warn(" ==> Lock error on VBO");
return false;
}
*/
if (!this.exist) {
Log.debug(" ==> ALLOCATE new handle");
LOGGER.debug(" ==> ALLOCATE new handle");
// Allocate and assign a Vertex Array Object to our handle
OpenGL.genBuffers(this.vbo);
}
this.exist = true;
for (int iii = 0; iii < this.vbo.length; iii++) {
if (this.buffer[iii] != null) {
Log.verbose("VBO : add [" + getId() + "]=" + this.buffer[iii].getClass().getCanonicalName() + "*sizeof(float) OGl_Id=" + this.vbo[iii]);
LOGGER.trace("VBO : add [" + getId() + "]=" + this.buffer[iii].getClass().getCanonicalName()
+ "*sizeof(float) OGl_Id=" + this.vbo[iii]);
OpenGL.bindBuffer(this.vbo[iii]);
// select the buffer to set data inside it ...
if (this.buffer[iii] instanceof float[]) {
@ -203,13 +207,13 @@ public class ResourceVirtualBufferObject extends Resource {
} else if (this.buffer[iii] instanceof Color[]) {
OpenGL.bufferData((Color[]) (this.buffer[iii]), Usage.streamDraw);
} else {
Log.error("Not managed VBO model : " + this.buffer[iii].getClass().getCanonicalName());
LOGGER.error("Not managed VBO model : " + this.buffer[iii].getClass().getCanonicalName());
}
}
}
// un-bind it to permet to have no error in the next display ...
OpenGL.unbindBuffer();
Log.verbose(" Stop: [" + getId() + "] '" + getName() + "'");
LOGGER.trace(" Stop: [" + getId() + "] '" + getName() + "'");
return true;
}
}

View File

@ -14,23 +14,26 @@ import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gale.resource.ResourceProgram;
import org.atriasoft.gale.resource.ResourceVirtualArrayObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Sample1Application extends GaleApplication {
static final Logger LOGGER = LoggerFactory.getLogger(Sample1Application.class);
//float[] vertices = { 0.2f, 0.1f, 0.0f, 0.3f, 0.4f, 0.0f, 0.1f, 0.4f, 0.0f };
private static final float[] VERTICES = { -0.5f, -0.5f, -1.0f, 0.0f, 0.5f, -1.0f, 0.5f, -0.5f, -1.0f };
private static final float[] COLORS = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, };
private static final int[] INDICES = { 0, 1, 2 };
private static final boolean TEST_STATIC_MODE = false;
private ResourceProgram oGLprogram;
private int oGLMatrixTransformation;
private int oGLMatrixProjection;
private int oGLMatrixView;
private float angle;
private ResourceVirtualArrayObject verticesVBO;
@Override
public void onCreate(final GaleContext context) {
//setSize(new Vector2f(800, 600));
@ -41,7 +44,7 @@ public class Sample1Application extends GaleApplication {
this.oGLMatrixProjection = this.oGLprogram.getUniform("in_matrixProjection");
this.oGLMatrixView = this.oGLprogram.getUniform("in_matrixView");
}
// this is the properties of the buffer requested : "r"/"w" + "-" + buffer type "f"=float "i"=integer
if (TEST_STATIC_MODE) {
this.verticesVBO = ResourceVirtualArrayObject.create(VERTICES, COLORS, INDICES);
@ -52,49 +55,49 @@ public class Sample1Application extends GaleApplication {
this.verticesVBO.setName("[VBO] of basic SAMPLE");
// update all the VBO elements ...
this.verticesVBO.flush();
Log.info("==> Init APPL (END)");
LOGGER.info("==> Init APPL (END)");
}
@Override
public void onDraw(final GaleContext context) {
this.angle += 0.01;
//Log.info("==> appl Draw ...");
Vector2f size = getSize();
//LOGGER.info("==> appl Draw ...");
final Vector2f size = getSize();
// set the basic openGL view port: (position drawed in the windows)
OpenGL.setViewPort(Vector2f.ZERO, size);
// Clear all the stacked matrix ...
OpenGL.setBasicMatrix(Matrix4f.IDENTITY);
// clear background
Color bgColor = Color.CYAN;
final Color bgColor = Color.CYAN;
OpenGL.clearColor(bgColor);
// real clear request:
OpenGL.clear(OpenGL.ClearFlag.clearFlag_colorBuffer);
// create a local matrix environment.
OpenGL.push();
Matrix4f tmpProjection = Matrix4f.createMatrixOrtho(-getAspectRatio(), getAspectRatio(), -1, 1, -50, 50);
final Matrix4f tmpProjection = Matrix4f.createMatrixOrtho(-getAspectRatio(), getAspectRatio(), -1, 1, -50, 50);
//Matrix4f tmpProjection = Matrix4f.IDENTITY;
// set internal matrix system:
OpenGL.setMatrix(tmpProjection);
if (this.oGLprogram == null) {
Log.info("No shader ...");
LOGGER.info("No shader ...");
return;
}
//EWOL_DEBUG(" display " + this.coord.size() + " elements" );
this.oGLprogram.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();
final Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix();
final Matrix4f transforamtionMatrix = Matrix4f.createMatrixRotate(new Vector3f(0, 0, 1), this.angle);
final Matrix4f viewMatrix = OpenGL.getCameraMatrix();
//Matrix4f tmpMatrix = projMatrix * camMatrix;
this.verticesVBO.bindForRendering();
this.oGLprogram.uniformMatrix(this.oGLMatrixView, viewMatrix);
this.oGLprogram.uniformMatrix(this.oGLMatrixProjection, projectionMatrix);
// Change the position for each element with the same pipeline you need to render ...
this.oGLprogram.uniformMatrix(this.oGLMatrixTransformation, transforamtionMatrix);
// Request the draw of the elements:
if (TEST_STATIC_MODE) {
this.verticesVBO.render(OpenGL.RenderMode.TRIANGLE);
@ -107,7 +110,7 @@ public class Sample1Application extends GaleApplication {
OpenGL.pop();
// mark to redraw the screen ==> demo only....
markDrawingIsNeeded();
if (!TEST_STATIC_MODE) {
this.verticesVBO.clear();
this.verticesVBO.setPosition(VERTICES);
@ -116,20 +119,29 @@ public class Sample1Application extends GaleApplication {
this.verticesVBO.flush();
}
}
@Override
public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) {
Log.info("Keyboard event: special=" + special);
Log.info(" type=" + type);
Log.info(" value='" + value + "'");
Log.info(" state=" + state);
public void onKeyboard(
final KeySpecial special,
final KeyKeyboard type,
final Character value,
final KeyStatus state) {
LOGGER.info("Keyboard event: special=" + special);
LOGGER.info(" type=" + type);
LOGGER.info(" value='" + value + "'");
LOGGER.info(" state=" + state);
}
@Override
public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) {
// Log.info("input event: type=" + type);
// Log.info(" id=" + pointerID);
// Log.info(" pos=" + pos);
// Log.info(" state=" + state);
public void onPointer(
final KeySpecial special,
final KeyType type,
final int pointerID,
final Vector2f pos,
final KeyStatus state) {
// LOGGER.info("input event: type=" + type);
// LOGGER.info(" id=" + pointerID);
// LOGGER.info(" pos=" + pos);
// LOGGER.info(" state=" + state);
}
}

View File

@ -15,8 +15,11 @@ import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gale.resource.ResourceProgram;
import org.atriasoft.gale.resource.ResourceTexture;
import org.atriasoft.gale.resource.ResourceVirtualArrayObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Sample2Application extends GaleApplication {
static final Logger LOGGER = LoggerFactory.getLogger(Sample2Application.class);
private ResourceProgram oGLprogram;
private int oGLMatrixTransformation;
private int oGLMatrixProjection;
@ -26,7 +29,7 @@ public class Sample2Application extends GaleApplication {
private float angleZ = 0;
private ResourceVirtualArrayObject verticesVBO;
private ResourceTexture texture;
@Override
public void onCreate(final GaleContext context) {
setSize(new Vector2f(800, 600));
@ -37,88 +40,88 @@ public class Sample2Application extends GaleApplication {
this.oGLMatrixView = this.oGLprogram.getUniform("in_matrixView");
}
//@formatter:off
float[] vertices = {
-0.5f,0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f,0.5f,-0.5f,
-0.5f,0.5f,0.5f,
-0.5f,-0.5f,0.5f,
0.5f,-0.5f,0.5f,
0.5f,0.5f,0.5f,
0.5f,0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f,-0.5f,0.5f,
0.5f,0.5f,0.5f,
-0.5f,0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,0.5f,
final float[] vertices = {
-0.5f,0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f,0.5f,-0.5f,
-0.5f,0.5f,0.5f,
-0.5f,-0.5f,0.5f,
0.5f,-0.5f,0.5f,
0.5f,0.5f,0.5f,
0.5f,0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f,-0.5f,0.5f,
0.5f,0.5f,0.5f,
-0.5f,0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,0.5f,
-0.5f,0.5f,0.5f,
-0.5f,0.5f,0.5f,
-0.5f,0.5f,-0.5f,
0.5f,0.5f,-0.5f,
0.5f,0.5f,0.5f,
-0.5f,-0.5f,0.5f,
-0.5f,-0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f,-0.5f,0.5f
};
float[] textureCoords = {
0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0,
final float[] textureCoords = {
0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0
};
int[] indices = {
1,0,3, 1,3,2,
4,5,7, 7,5,6,
final int[] indices = {
1,0,3, 1,3,2,
4,5,7, 7,5,6,
9,8,11, 9,11,10,
12,13,15, 15,13,14,
12,13,15, 15,13,14,
17,16,19, 17,19,18,
20,21,23, 23,21,22
};
//@formatter:on
// this is the properties of the buffer requested : "r"/"w" + "-" + buffer type "f"=float "i"=integer
this.verticesVBO = ResourceVirtualArrayObject.create(vertices, textureCoords, null, indices);
// TO facilitate some debugs we add a name of the VBO:
this.verticesVBO.setName("[VBO] of basic SAMPLE");
// update all the VBO elements ...
this.verticesVBO.flush();
this.texture = ResourceTexture.createFromPng(new Uri("DATA", "tree_sample.png"));
if (this.texture == null) {
Log.error("can not instanciate Texture ...");
LOGGER.error("can not instanciate Texture ...");
return;
}
Log.info("==> Init APPL (END)");
LOGGER.info("==> Init APPL (END)");
}
@Override
public void onDraw(final GaleContext context) {
this.angleX += 0.001;
this.angleY += 0.005;
this.angleZ += 0.01;
//Log.info("==> appl Draw ...");
Vector2f size = getSize();
//Log.info("==> Windows size = " + size);
//LOGGER.info("==> appl Draw ...");
final Vector2f size = getSize();
//LOGGER.info("==> Windows size = " + size);
// 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);
final Color bgColor = new Color(0.0f, 1.0f, 1.0f, 0.75f);
OpenGL.enable(OpenGL.Flag.flag_depthTest);
OpenGL.clearColor(bgColor);
// real clear request:
@ -126,26 +129,30 @@ public class Sample2Application extends GaleApplication {
OpenGL.clear(OpenGL.ClearFlag.clearFlag_depthBuffer);
// create a local matrix environnement.
OpenGL.push();
//Matrix4f tmpProjection = Matrix4f.createMatrixOrtho(-getAspectRatio(), getAspectRatio(), -1, 1, -50, 50);
Matrix4f tmpProjection = Matrix4f.createMatrixPerspective(1.30f, getAspectRatio(), 1, 50);
final Matrix4f tmpProjection = Matrix4f.createMatrixPerspective(1.30f, getAspectRatio(), 1, 50);
// set internal matrix system:
OpenGL.setMatrix(tmpProjection);
if (this.oGLprogram == null) {
Log.info("No shader ...");
LOGGER.info("No shader ...");
return;
}
//EWOL_DEBUG(" display " + this.coord.size() + " elements" );
this.oGLprogram.use();
// set Matrix : translation/positionMatrix
Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix();
final Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix();
Matrix4f transforamtionMatrix = Matrix4f.IDENTITY;
transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, -1)));
transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(1, 0, 0), this.angleX));
transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(0, 1, 0), this.angleY));
transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(0, 0, 1), this.angleZ));
Matrix4f viewMatrix = OpenGL.getCameraMatrix().multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, -2)));
transforamtionMatrix = transforamtionMatrix
.multiply(Matrix4f.createMatrixRotate(new Vector3f(1, 0, 0), this.angleX));
transforamtionMatrix = transforamtionMatrix
.multiply(Matrix4f.createMatrixRotate(new Vector3f(0, 1, 0), this.angleY));
transforamtionMatrix = transforamtionMatrix
.multiply(Matrix4f.createMatrixRotate(new Vector3f(0, 0, 1), this.angleZ));
final Matrix4f viewMatrix = OpenGL.getCameraMatrix()
.multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, -2)));
//Matrix4f tmpMatrix = projMatrix * camMatrix;
this.verticesVBO.bindForRendering();
this.oGLprogram.uniformMatrix(this.oGLMatrixView, viewMatrix);
@ -157,7 +164,7 @@ public class Sample2Application extends GaleApplication {
OpenGL.updateAllFlags();
// Request the draw od the elements:
this.verticesVBO.render(OpenGL.RenderMode.TRIANGLE);
this.verticesVBO.unBindForRendering();
this.texture.unBindForRendering();
this.oGLprogram.unUse();
@ -165,20 +172,29 @@ public class Sample2Application extends GaleApplication {
OpenGL.pop();
markDrawingIsNeeded();
}
@Override
public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) {
Log.info("Keyboard event: special=" + special);
Log.info(" type=" + type);
Log.info(" value='" + value + "'");
Log.info(" state=" + state);
public void onKeyboard(
final KeySpecial special,
final KeyKeyboard type,
final Character value,
final KeyStatus state) {
LOGGER.info("Keyboard event: special=" + special);
LOGGER.info(" type=" + type);
LOGGER.info(" value='" + value + "'");
LOGGER.info(" state=" + state);
}
@Override
public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) {
// Log.info("input event: type=" + type);
// Log.info(" id=" + pointerID);
// Log.info(" pos=" + pos);
// Log.info(" state=" + state);
public void onPointer(
final KeySpecial special,
final KeyType type,
final int pointerID,
final Vector2f pos,
final KeyStatus state) {
// LOGGER.info("input event: type=" + type);
// LOGGER.info(" id=" + pointerID);
// LOGGER.info(" pos=" + pos);
// LOGGER.info(" state=" + state);
}
}

View File

@ -1,59 +0,0 @@
package test.atriasoft.gale;
import org.atriasoft.reggol.LogLevel;
import org.atriasoft.reggol.Logger;
public class Log {
private static final String LIB_NAME = "gale-test";
private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME);
private static final boolean PRINT_CRITICAL = Logger.getNeedPrint(LIB_NAME, LogLevel.CRITICAL);
private static final boolean PRINT_ERROR = Logger.getNeedPrint(LIB_NAME, LogLevel.ERROR);
private static final boolean PRINT_WARNING = Logger.getNeedPrint(LIB_NAME, LogLevel.WARNING);
private static final boolean PRINT_INFO = Logger.getNeedPrint(LIB_NAME, LogLevel.INFO);
private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG);
private static final boolean PRINT_VERBOSE = Logger.getNeedPrint(LIB_NAME, LogLevel.VERBOSE);
private static final boolean PRINT_TODO = Logger.getNeedPrint(LIB_NAME, LogLevel.TODO);
private static final boolean PRINT_PRINT = Logger.getNeedPrint(LIB_NAME, LogLevel.PRINT);
private Log() {}
public static void print(String data) {
if (PRINT_PRINT)
Logger.print(LIB_NAME_DRAW, data);
}
public static void critical(String data) {
if (PRINT_CRITICAL)
Logger.critical(LIB_NAME_DRAW, data);
}
public static void error(String data) {
if (PRINT_ERROR)
Logger.error(LIB_NAME_DRAW, data);
}
public static void warning(String data) {
if (PRINT_WARNING)
Logger.warning(LIB_NAME_DRAW, data);
}
public static void info(String data) {
if (PRINT_INFO)
Logger.info(LIB_NAME_DRAW, data);
}
public static void debug(String data) {
if (PRINT_DEBUG)
Logger.debug(LIB_NAME_DRAW, data);
}
public static void verbose(String data) {
if (PRINT_VERBOSE)
Logger.verbose(LIB_NAME_DRAW, data);
}
public static void todo(String data) {
if (PRINT_TODO)
Logger.todo(LIB_NAME_DRAW, data);
}
}

View File

@ -1,18 +0,0 @@
package test.atriasoft.gale;
import org.atriasoft.reggol.LogLevel;
import org.atriasoft.reggol.Logger;
public class Log2 {
private static final String LIB_NAME = "gale-test-2";
private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME);
private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG);
private Log2() {}
public static void debug(String data) {
if (PRINT_DEBUG)
Logger.debug(LIB_NAME_DRAW, data);
}
}

View File

@ -11,20 +11,18 @@ package test.atriasoft.gale;
import java.util.ArrayList;
import java.util.List;
import org.atriasoft.reggol.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(OrderAnnotation.class)
public class TestBasicLog {
// JUST keep a kanva ...
@Test
@Order(1)
public void aaFirstInitialisation() {
List<String> args = new ArrayList<>();
final List<String> args = new ArrayList<>();
args.add("--log-level=999");
args.add("--log-level=1");
args.add("--log-no-color");
@ -37,66 +35,6 @@ public class TestBasicLog {
args.add("--log-lib=sc-log-test");
args.add("--log-with-stupid-parameter=sdkfjsqdlkf");
args.add("--help");
Logger.init(args);
}
@Test
@Order(2)
public void bbSecondInitialisation() {
List<String> args = new ArrayList<>();
Logger.init(args);
}
@Test
@Order(3)
public void ccBasicLogCall() {
Log.print("Simple print");
Log.todo("Simple todo");
Log.error("Simple error");
Log.warning("Simple warning");
Log.info("Simple info");
Log.debug("Simple debug");
Log.verbose("Simple verbose");
}
// TODO REFACTO REMOVE this and set it in the Test of the logger.
public static String getAAAAAAA(int dfsdf) {
int hhh = 0;
for (int kkk = 0; kkk < dfsdf; kkk++)
for (int iii = 0; iii < 10000; iii++)
for (int jjj = 0; jjj < 100000; jjj++)
for (int lll = 0; lll < 100000; lll++)
hhh++;
return "kkk" + hhh;
}
public static void testLog() {
Log.print("test direct [START]");
// test de 10 secondes contre 0.0?? second quand le niveau n'est pas assez grand ...
long timeStart = System.currentTimeMillis();
for (int iii = 0; iii < 100000000; iii++)
Log2.debug("test direct");
long timeStop = System.currentTimeMillis();
Log.print("test direct [END] : " + timeStart + " to " + timeStop + " ==> delta=" + (timeStop - timeStart));
Log.print("test concat [START]");
// C'est très long dans les 2 cas ...
timeStart = System.currentTimeMillis();
for (int iii = 0; iii < 6; iii++)
Log2.debug("test concat: non fonctionnel, il applelle le get a chaque log ... " + getAAAAAAA(iii));
timeStop = System.currentTimeMillis();
Log.print("test concat [END] : " + timeStart + " to " + timeStop + " ==> delta=" + (timeStop - timeStart));
}
@Test
@Order(4)
public void ddTestSimpleLog() {
testLog();
}
@Test
@Order(4)
public void eeUsage() {
Logger.usage();
}
}